rpcrt4: Fix NdrGetBuffer to set the correct fields in the MIDL_STUB_MESSAGE structure.
[wine] / dlls / rpcrt4 / rpcrt4_main.c
1 /*
2  *  RPCRT4
3  *
4  * Copyright 2000 Huw D M Davies for CodeWeavers
5  *
6  * This library is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Lesser General Public
8  * License as published by the Free Software Foundation; either
9  * version 2.1 of the License, or (at your option) any later version.
10  *
11  * This library is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public
17  * License along with this library; if not, write to the Free Software
18  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
19  * 
20  * WINE RPC TODO's (and a few TODONT's)
21  *
22  * - Ove's decreasingly incomplete widl is an IDL compiler for wine.  For widl
23  *   to be wine's only IDL compiler, a fair bit of work remains to be done.
24  *   until then we have used some midl-generated stuff.  (What?)
25  *   widl currently doesn't generate stub/proxy files required by wine's (O)RPC
26  *   capabilities -- nor does it make those lovely format strings :(
27  *   The MS MIDL compiler does some really esoteric stuff.  Of course Ove has
28  *   started with the less esoteric stuff.  There are also lots of nice
29  *   comments in there if you want to flex your bison and help build this monster.
30  *
31  * - RPC has a quite featureful error handling mechanism; basically none of this is
32  *   implemented right now.  We also have deficiencies on the compiler side, where
33  *   wine's __TRY / __EXCEPT / __FINALLY macros are not even used for RpcTryExcept & co,
34  *   due to syntactic differences! (we can fix it with widl by using __TRY)
35  *
36  * - There are several different memory allocation schemes for MSRPC.
37  *   I don't even understand what they all are yet, much less have them
38  *   properly implemented.  Surely we are supposed to be doing something with
39  *   the user-provided allocation/deallocation functions, but so far,
40  *   I don't think we are doing this...
41  *
42  * - MSRPC provides impersonation capabilities which currently are not possible
43  *   to implement in wine.  At the very least we should implement the authorization
44  *   API's & gracefully ignore the irrelevant stuff (to an extent we already do).
45  *
46  * - Some transports are not yet implemented.  The existing transport implementations
47  *   are incomplete and may be bug-infested.
48  * 
49  * - The various transports that we do support ought to be supported in a more
50  *   object-oriented manner, as in DCE's RPC implementation, instead of cluttering
51  *   up the code with conditionals like we do now.
52  * 
53  * - Data marshalling: So far, only the beginnings of a full implementation
54  *   exist in wine.  NDR protocol itself is documented, but the MS API's to
55  *   convert data-types in memory into NDR are not.  This is challenging work,
56  *   and has supposedly been "at the top of Greg's queue" for several months now.
57  *
58  * - ORPC is RPC for OLE; once we have a working RPC framework, we can
59  *   use it to implement out-of-process OLE client/server communications.
60  *   ATM there is maybe a disconnect between the marshalling in the OLE DLLs
61  *   and the marshalling going on here [TODO: well, is there or not?]
62  * 
63  * - In-source API Documentation, at least for those functions which we have
64  *   implemented, but preferably for everything we can document, would be nice,
65  *   since some of this stuff is quite obscure.
66  *
67  * - Name services... [TODO: what about them]
68  *
69  * - Protocol Towers: Totally unimplemented.... I think.
70  *
71  * - Context Handle Rundown: whatever that is.
72  *
73  * - Nested RPC's: Totally unimplemented.
74  *
75  * - Statistics: we are supposed to be keeping various counters.  we aren't.
76  *
77  * - Async RPC: Unimplemented.
78  *
79  * - XML/http RPC: Somewhere there's an XML fiend that wants to do this! Betcha
80  *   we could use these as a transport for RPC's across computers without a
81  *   permissions and/or licensing crisis.
82  *
83  * - The NT "ports" API, aka LPC.  Greg claims this is on his radar.  Might (or
84  *   might not) enable users to get some kind of meaningful result out of
85  *   NT-based native rpcrt4's.  Commonly-used transport for self-to-self RPC's.
86  *
87  * - ...?  More stuff I haven't thought of.  If you think of more RPC todo's
88  *   drop me an e-mail <gmturner007@ameritech.net> or send a patch to the
89  *   wine-patches mailing list.
90  */
91
92 #include "config.h"
93
94 #include <stdarg.h>
95 #include <stdio.h>
96 #include <stdlib.h>
97 #include <string.h>
98
99 #include "windef.h"
100 #include "winerror.h"
101 #include "winbase.h"
102 #include "winuser.h"
103 #include "winnt.h"
104 #include "winternl.h"
105 #include "iptypes.h"
106 #include "iphlpapi.h"
107 #include "wine/unicode.h"
108 #include "rpc.h"
109
110 #include "ole2.h"
111 #include "rpcndr.h"
112 #include "rpcproxy.h"
113
114 #include "rpc_binding.h"
115 #include "rpcss_np_client.h"
116
117 #include "wine/debug.h"
118
119 WINE_DEFAULT_DEBUG_CHANNEL(rpc);
120
121 static UUID uuid_nil;
122 static HANDLE master_mutex;
123
124 HANDLE RPCRT4_GetMasterMutex(void)
125 {
126     return master_mutex;
127 }
128
129 static CRITICAL_SECTION uuid_cs;
130 static CRITICAL_SECTION_DEBUG critsect_debug =
131 {
132     0, 0, &uuid_cs,
133     { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
134       0, 0, { (DWORD_PTR)(__FILE__ ": uuid_cs") }
135 };
136 static CRITICAL_SECTION uuid_cs = { &critsect_debug, -1, 0, 0, 0, 0 };
137
138 static CRITICAL_SECTION threaddata_cs;
139 static CRITICAL_SECTION_DEBUG threaddata_cs_debug =
140 {
141     0, 0, &threaddata_cs,
142     { &threaddata_cs_debug.ProcessLocksList, &threaddata_cs_debug.ProcessLocksList },
143       0, 0, { (DWORD_PTR)(__FILE__ ": threaddata_cs") }
144 };
145 static CRITICAL_SECTION threaddata_cs = { &threaddata_cs_debug, -1, 0, 0, 0, 0 };
146
147 struct list threaddata_list = LIST_INIT(threaddata_list);
148
149 struct context_handle_list
150 {
151     struct context_handle_list *next;
152     NDR_SCONTEXT context_handle;
153 };
154
155 struct threaddata
156 {
157     struct list entry;
158     CRITICAL_SECTION cs;
159     DWORD thread_id;
160     RpcConnection *connection;
161     RpcBinding *server_binding;
162     struct context_handle_list *context_handle_list;
163 };
164
165 /***********************************************************************
166  * DllMain
167  *
168  * PARAMS
169  *     hinstDLL    [I] handle to the DLL's instance
170  *     fdwReason   [I]
171  *     lpvReserved [I] reserved, must be NULL
172  *
173  * RETURNS
174  *     Success: TRUE
175  *     Failure: FALSE
176  */
177
178 BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved)
179 {
180     struct threaddata *tdata;
181
182     switch (fdwReason) {
183     case DLL_PROCESS_ATTACH:
184         master_mutex = CreateMutexA( NULL, FALSE, RPCSS_MASTER_MUTEX_NAME);
185         if (!master_mutex)
186           ERR("Failed to create master mutex\n");
187         break;
188
189     case DLL_THREAD_DETACH:
190         tdata = NtCurrentTeb()->ReservedForNtRpc;
191         if (tdata)
192         {
193             EnterCriticalSection(&threaddata_cs);
194             list_remove(&tdata->entry);
195             LeaveCriticalSection(&threaddata_cs);
196
197             DeleteCriticalSection(&tdata->cs);
198             if (tdata->connection)
199                 ERR("tdata->connection should be NULL but is still set to %p\n", tdata->connection);
200             if (tdata->server_binding)
201                 ERR("tdata->server_binding should be NULL but is still set to %p\n", tdata->server_binding);
202             HeapFree(GetProcessHeap(), 0, tdata);
203         }
204         break;
205
206     case DLL_PROCESS_DETACH:
207         CloseHandle(master_mutex);
208         master_mutex = NULL;
209         break;
210     }
211
212     return TRUE;
213 }
214
215 /*************************************************************************
216  *           RpcStringFreeA   [RPCRT4.@]
217  *
218  * Frees a character string allocated by the RPC run-time library.
219  *
220  * RETURNS
221  *
222  *  S_OK if successful.
223  */
224 RPC_STATUS WINAPI RpcStringFreeA(RPC_CSTR* String)
225 {
226   HeapFree( GetProcessHeap(), 0, *String);
227
228   return RPC_S_OK;
229 }
230
231 /*************************************************************************
232  *           RpcStringFreeW   [RPCRT4.@]
233  *
234  * Frees a character string allocated by the RPC run-time library.
235  *
236  * RETURNS
237  *
238  *  S_OK if successful.
239  */
240 RPC_STATUS WINAPI RpcStringFreeW(RPC_WSTR* String)
241 {
242   HeapFree( GetProcessHeap(), 0, *String);
243
244   return RPC_S_OK;
245 }
246
247 /*************************************************************************
248  *           RpcRaiseException   [RPCRT4.@]
249  *
250  * Raises an exception.
251  */
252 void DECLSPEC_NORETURN WINAPI RpcRaiseException(RPC_STATUS exception)
253 {
254   /* shouldn't return */
255   RaiseException(exception, 0, 0, NULL);
256   ERR("handler continued execution\n");
257   ExitProcess(1);
258 }
259
260 /*************************************************************************
261  * UuidCompare [RPCRT4.@]
262  *
263  * PARAMS
264  *     UUID *Uuid1        [I] Uuid to compare
265  *     UUID *Uuid2        [I] Uuid to compare
266  *     RPC_STATUS *Status [O] returns RPC_S_OK
267  * 
268  * RETURNS
269  *    -1  if Uuid1 is less than Uuid2
270  *     0  if Uuid1 and Uuid2 are equal
271  *     1  if Uuid1 is greater than Uuid2
272  */
273 int WINAPI UuidCompare(UUID *Uuid1, UUID *Uuid2, RPC_STATUS *Status)
274 {
275   int i;
276
277   TRACE("(%s,%s)\n", debugstr_guid(Uuid1), debugstr_guid(Uuid2));
278
279   *Status = RPC_S_OK;
280
281   if (!Uuid1) Uuid1 = &uuid_nil;
282   if (!Uuid2) Uuid2 = &uuid_nil;
283
284   if (Uuid1 == Uuid2) return 0;
285
286   if (Uuid1->Data1 != Uuid2->Data1)
287     return Uuid1->Data1 < Uuid2->Data1 ? -1 : 1;
288
289   if (Uuid1->Data2 != Uuid2->Data2)
290     return Uuid1->Data2 < Uuid2->Data2 ? -1 : 1;
291
292   if (Uuid1->Data3 != Uuid2->Data3)
293     return Uuid1->Data3 < Uuid2->Data3 ? -1 : 1;
294
295   for (i = 0; i < 8; i++) {
296     if (Uuid1->Data4[i] < Uuid2->Data4[i])
297       return -1;
298     if (Uuid1->Data4[i] > Uuid2->Data4[i])
299       return 1;
300   }
301
302   return 0;
303 }
304
305 /*************************************************************************
306  * UuidEqual [RPCRT4.@]
307  *
308  * PARAMS
309  *     UUID *Uuid1        [I] Uuid to compare
310  *     UUID *Uuid2        [I] Uuid to compare
311  *     RPC_STATUS *Status [O] returns RPC_S_OK
312  *
313  * RETURNS
314  *     TRUE/FALSE
315  */
316 int WINAPI UuidEqual(UUID *Uuid1, UUID *Uuid2, RPC_STATUS *Status)
317 {
318   TRACE("(%s,%s)\n", debugstr_guid(Uuid1), debugstr_guid(Uuid2));
319   return !UuidCompare(Uuid1, Uuid2, Status);
320 }
321
322 /*************************************************************************
323  * UuidIsNil [RPCRT4.@]
324  *
325  * PARAMS
326  *     UUID *Uuid         [I] Uuid to compare
327  *     RPC_STATUS *Status [O] retuns RPC_S_OK
328  *
329  * RETURNS
330  *     TRUE/FALSE
331  */
332 int WINAPI UuidIsNil(UUID *Uuid, RPC_STATUS *Status)
333 {
334   TRACE("(%s)\n", debugstr_guid(Uuid));
335   if (!Uuid) return TRUE;
336   return !UuidCompare(Uuid, &uuid_nil, Status);
337 }
338
339  /*************************************************************************
340  * UuidCreateNil [RPCRT4.@]
341  *
342  * PARAMS
343  *     UUID *Uuid [O] returns a nil UUID
344  *
345  * RETURNS
346  *     RPC_S_OK
347  */
348 RPC_STATUS WINAPI UuidCreateNil(UUID *Uuid)
349 {
350   *Uuid = uuid_nil;
351   return RPC_S_OK;
352 }
353
354 /* Number of 100ns ticks per clock tick. To be safe, assume that the clock
355    resolution is at least 1000 * 100 * (1/1000000) = 1/10 of a second */
356 #define TICKS_PER_CLOCK_TICK 1000
357 #define SECSPERDAY  86400
358 #define TICKSPERSEC 10000000
359 /* UUID system time starts at October 15, 1582 */
360 #define SECS_15_OCT_1582_TO_1601  ((17 + 30 + 31 + 365 * 18 + 5) * SECSPERDAY)
361 #define TICKS_15_OCT_1582_TO_1601 ((ULONGLONG)SECS_15_OCT_1582_TO_1601 * TICKSPERSEC)
362
363 static void RPC_UuidGetSystemTime(ULONGLONG *time)
364 {
365     FILETIME ft;
366
367     GetSystemTimeAsFileTime(&ft);
368
369     *time = ((ULONGLONG)ft.dwHighDateTime << 32) | ft.dwLowDateTime;
370     *time += TICKS_15_OCT_1582_TO_1601;
371 }
372
373 /* Assume that a hardware address is at least 6 bytes long */ 
374 #define ADDRESS_BYTES_NEEDED 6
375
376 static RPC_STATUS RPC_UuidGetNodeAddress(BYTE *address)
377 {
378     int i;
379     DWORD status = RPC_S_OK;
380
381     ULONG buflen = sizeof(IP_ADAPTER_INFO);
382     PIP_ADAPTER_INFO adapter = HeapAlloc(GetProcessHeap(), 0, buflen);
383
384     if (GetAdaptersInfo(adapter, &buflen) == ERROR_BUFFER_OVERFLOW) {
385         HeapFree(GetProcessHeap(), 0, adapter);
386         adapter = HeapAlloc(GetProcessHeap(), 0, buflen);
387     }
388
389     if (GetAdaptersInfo(adapter, &buflen) == NO_ERROR) {
390         for (i = 0; i < ADDRESS_BYTES_NEEDED; i++) {
391             address[i] = adapter->Address[i];
392         }
393     }
394     /* We can't get a hardware address, just use random numbers.
395        Set the multicast bit to prevent conflicts with real cards. */
396     else {
397         for (i = 0; i < ADDRESS_BYTES_NEEDED; i++) {
398             address[i] = rand() & 0xff;
399         }
400
401         address[0] |= 0x01;
402         status = RPC_S_UUID_LOCAL_ONLY;
403     }
404
405     HeapFree(GetProcessHeap(), 0, adapter);
406     return status;
407 }
408
409 /*************************************************************************
410  *           UuidCreate   [RPCRT4.@]
411  *
412  * Creates a 128bit UUID.
413  *
414  * RETURNS
415  *
416  *  RPC_S_OK if successful.
417  *  RPC_S_UUID_LOCAL_ONLY if UUID is only locally unique.
418  *
419  *  FIXME: No compensation for changes across reloading
420  *         this dll or across reboots (e.g. clock going 
421  *         backwards and swapped network cards). The RFC
422  *         suggests using NVRAM for storing persistent 
423  *         values.
424  */
425 RPC_STATUS WINAPI UuidCreate(UUID *Uuid)
426 {
427     static int initialised, count;
428
429     ULONGLONG time;
430     static ULONGLONG timelast;
431     static WORD sequence;
432
433     static DWORD status;
434     static BYTE address[MAX_ADAPTER_ADDRESS_LENGTH];
435
436     EnterCriticalSection(&uuid_cs);
437
438     if (!initialised) {
439         RPC_UuidGetSystemTime(&timelast);
440         count = TICKS_PER_CLOCK_TICK;
441
442         sequence = ((rand() & 0xff) << 8) + (rand() & 0xff);
443         sequence &= 0x1fff;
444
445         status = RPC_UuidGetNodeAddress(address);
446         initialised = 1;
447     }
448
449     /* Generate time element of the UUID. Account for going faster
450        than our clock as well as the clock going backwards. */
451     while (1) {
452         RPC_UuidGetSystemTime(&time);
453         if (time > timelast) {
454             count = 0;
455             break;
456         }
457         if (time < timelast) {
458             sequence = (sequence + 1) & 0x1fff;
459             count = 0;
460             break;
461         }
462         if (count < TICKS_PER_CLOCK_TICK) {
463             count++;
464             break;
465         }
466     }
467
468     timelast = time;
469     time += count;
470
471     /* Pack the information into the UUID structure. */
472
473     Uuid->Data1  = (unsigned long)(time & 0xffffffff);
474     Uuid->Data2  = (unsigned short)((time >> 32) & 0xffff);
475     Uuid->Data3  = (unsigned short)((time >> 48) & 0x0fff);
476
477     /* This is a version 1 UUID */
478     Uuid->Data3 |= (1 << 12);
479
480     Uuid->Data4[0]  = sequence & 0xff;
481     Uuid->Data4[1]  = (sequence & 0x3f00) >> 8;
482     Uuid->Data4[1] |= 0x80;
483
484     Uuid->Data4[2] = address[0];
485     Uuid->Data4[3] = address[1];
486     Uuid->Data4[4] = address[2];
487     Uuid->Data4[5] = address[3];
488     Uuid->Data4[6] = address[4];
489     Uuid->Data4[7] = address[5];
490
491     LeaveCriticalSection(&uuid_cs);
492
493     TRACE("%s\n", debugstr_guid(Uuid));
494
495     return status;
496 }
497
498 /*************************************************************************
499  *           UuidCreateSequential   [RPCRT4.@]
500  *
501  * Creates a 128bit UUID.
502  *
503  * RETURNS
504  *
505  *  RPC_S_OK if successful.
506  *  RPC_S_UUID_LOCAL_ONLY if UUID is only locally unique.
507  *
508  */
509 RPC_STATUS WINAPI UuidCreateSequential(UUID *Uuid)
510 {
511    return UuidCreate(Uuid);
512 }
513
514
515 /*************************************************************************
516  *           UuidHash   [RPCRT4.@]
517  *
518  * Generates a hash value for a given UUID
519  *
520  * Code based on FreeDCE implementation
521  *
522  */
523 unsigned short WINAPI UuidHash(UUID *uuid, RPC_STATUS *Status)
524 {
525   BYTE *data = (BYTE*)uuid;
526   short c0 = 0, c1 = 0, x, y;
527   unsigned int i;
528
529   if (!uuid) data = (BYTE*)(uuid = &uuid_nil);
530
531   TRACE("(%s)\n", debugstr_guid(uuid));
532
533   for (i=0; i<sizeof(UUID); i++) {
534     c0 += data[i];
535     c1 += c0;
536   }
537
538   x = -c1 % 255;
539   if (x < 0) x += 255;
540
541   y = (c1 - c0) % 255;
542   if (y < 0) y += 255;
543
544   *Status = RPC_S_OK;
545   return y*256 + x;
546 }
547
548 /*************************************************************************
549  *           UuidToStringA   [RPCRT4.@]
550  *
551  * Converts a UUID to a string.
552  *
553  * UUID format is 8 hex digits, followed by a hyphen then three groups of
554  * 4 hex digits each followed by a hyphen and then 12 hex digits
555  *
556  * RETURNS
557  *
558  *  S_OK if successful.
559  *  S_OUT_OF_MEMORY if unsuccessful.
560  */
561 RPC_STATUS WINAPI UuidToStringA(UUID *Uuid, RPC_CSTR* StringUuid)
562 {
563   *StringUuid = HeapAlloc( GetProcessHeap(), 0, sizeof(char) * 37);
564
565   if(!(*StringUuid))
566     return RPC_S_OUT_OF_MEMORY;
567
568   if (!Uuid) Uuid = &uuid_nil;
569
570   sprintf( (char*)*StringUuid, "%08x-%04x-%04x-%02x%02x-%02x%02x%02x%02x%02x%02x",
571                  Uuid->Data1, Uuid->Data2, Uuid->Data3,
572                  Uuid->Data4[0], Uuid->Data4[1], Uuid->Data4[2],
573                  Uuid->Data4[3], Uuid->Data4[4], Uuid->Data4[5],
574                  Uuid->Data4[6], Uuid->Data4[7] );
575
576   return RPC_S_OK;
577 }
578
579 /*************************************************************************
580  *           UuidToStringW   [RPCRT4.@]
581  *
582  * Converts a UUID to a string.
583  *
584  *  S_OK if successful.
585  *  S_OUT_OF_MEMORY if unsuccessful.
586  */
587 RPC_STATUS WINAPI UuidToStringW(UUID *Uuid, RPC_WSTR* StringUuid)
588 {
589   char buf[37];
590
591   if (!Uuid) Uuid = &uuid_nil;
592
593   sprintf(buf, "%08x-%04x-%04x-%02x%02x-%02x%02x%02x%02x%02x%02x",
594                Uuid->Data1, Uuid->Data2, Uuid->Data3,
595                Uuid->Data4[0], Uuid->Data4[1], Uuid->Data4[2],
596                Uuid->Data4[3], Uuid->Data4[4], Uuid->Data4[5],
597                Uuid->Data4[6], Uuid->Data4[7] );
598
599   *StringUuid = RPCRT4_strdupAtoW(buf);
600
601   if(!(*StringUuid))
602     return RPC_S_OUT_OF_MEMORY;
603
604   return RPC_S_OK;
605 }
606
607 static const BYTE hex2bin[] =
608 {
609     0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,        /* 0x00 */
610     0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,        /* 0x10 */
611     0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,        /* 0x20 */
612     0,1,2,3,4,5,6,7,8,9,0,0,0,0,0,0,        /* 0x30 */
613     0,10,11,12,13,14,15,0,0,0,0,0,0,0,0,0,  /* 0x40 */
614     0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,        /* 0x50 */
615     0,10,11,12,13,14,15                     /* 0x60 */
616 };
617
618 /***********************************************************************
619  *              UuidFromStringA (RPCRT4.@)
620  */
621 RPC_STATUS WINAPI UuidFromStringA(RPC_CSTR s, UUID *uuid)
622 {
623     int i;
624
625     if (!s) return UuidCreateNil( uuid );
626
627     if (strlen((char*)s) != 36) return RPC_S_INVALID_STRING_UUID;
628
629     if ((s[8]!='-') || (s[13]!='-') || (s[18]!='-') || (s[23]!='-'))
630         return RPC_S_INVALID_STRING_UUID;
631
632     for (i=0; i<36; i++)
633     {
634         if ((i == 8)||(i == 13)||(i == 18)||(i == 23)) continue;
635         if (s[i] > 'f' || (!hex2bin[s[i]] && s[i] != '0')) return RPC_S_INVALID_STRING_UUID;
636     }
637
638     /* in form XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX */
639
640     uuid->Data1 = (hex2bin[s[0]] << 28 | hex2bin[s[1]] << 24 | hex2bin[s[2]] << 20 | hex2bin[s[3]] << 16 |
641                    hex2bin[s[4]] << 12 | hex2bin[s[5]]  << 8 | hex2bin[s[6]]  << 4 | hex2bin[s[7]]);
642     uuid->Data2 =  hex2bin[s[9]] << 12 | hex2bin[s[10]] << 8 | hex2bin[s[11]] << 4 | hex2bin[s[12]];
643     uuid->Data3 = hex2bin[s[14]] << 12 | hex2bin[s[15]] << 8 | hex2bin[s[16]] << 4 | hex2bin[s[17]];
644
645     /* these are just sequential bytes */
646     uuid->Data4[0] = hex2bin[s[19]] << 4 | hex2bin[s[20]];
647     uuid->Data4[1] = hex2bin[s[21]] << 4 | hex2bin[s[22]];
648     uuid->Data4[2] = hex2bin[s[24]] << 4 | hex2bin[s[25]];
649     uuid->Data4[3] = hex2bin[s[26]] << 4 | hex2bin[s[27]];
650     uuid->Data4[4] = hex2bin[s[28]] << 4 | hex2bin[s[29]];
651     uuid->Data4[5] = hex2bin[s[30]] << 4 | hex2bin[s[31]];
652     uuid->Data4[6] = hex2bin[s[32]] << 4 | hex2bin[s[33]];
653     uuid->Data4[7] = hex2bin[s[34]] << 4 | hex2bin[s[35]];
654     return RPC_S_OK;
655 }
656
657
658 /***********************************************************************
659  *              UuidFromStringW (RPCRT4.@)
660  */
661 RPC_STATUS WINAPI UuidFromStringW(RPC_WSTR s, UUID *uuid)
662 {
663     int i;
664
665     if (!s) return UuidCreateNil( uuid );
666
667     if (strlenW(s) != 36) return RPC_S_INVALID_STRING_UUID;
668
669     if ((s[8]!='-') || (s[13]!='-') || (s[18]!='-') || (s[23]!='-'))
670         return RPC_S_INVALID_STRING_UUID;
671
672     for (i=0; i<36; i++)
673     {
674         if ((i == 8)||(i == 13)||(i == 18)||(i == 23)) continue;
675         if (s[i] > 'f' || (!hex2bin[s[i]] && s[i] != '0')) return RPC_S_INVALID_STRING_UUID;
676     }
677
678     /* in form XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX */
679
680     uuid->Data1 = (hex2bin[s[0]] << 28 | hex2bin[s[1]] << 24 | hex2bin[s[2]] << 20 | hex2bin[s[3]] << 16 |
681                    hex2bin[s[4]] << 12 | hex2bin[s[5]]  << 8 | hex2bin[s[6]]  << 4 | hex2bin[s[7]]);
682     uuid->Data2 =  hex2bin[s[9]] << 12 | hex2bin[s[10]] << 8 | hex2bin[s[11]] << 4 | hex2bin[s[12]];
683     uuid->Data3 = hex2bin[s[14]] << 12 | hex2bin[s[15]] << 8 | hex2bin[s[16]] << 4 | hex2bin[s[17]];
684
685     /* these are just sequential bytes */
686     uuid->Data4[0] = hex2bin[s[19]] << 4 | hex2bin[s[20]];
687     uuid->Data4[1] = hex2bin[s[21]] << 4 | hex2bin[s[22]];
688     uuid->Data4[2] = hex2bin[s[24]] << 4 | hex2bin[s[25]];
689     uuid->Data4[3] = hex2bin[s[26]] << 4 | hex2bin[s[27]];
690     uuid->Data4[4] = hex2bin[s[28]] << 4 | hex2bin[s[29]];
691     uuid->Data4[5] = hex2bin[s[30]] << 4 | hex2bin[s[31]];
692     uuid->Data4[6] = hex2bin[s[32]] << 4 | hex2bin[s[33]];
693     uuid->Data4[7] = hex2bin[s[34]] << 4 | hex2bin[s[35]];
694     return RPC_S_OK;
695 }
696
697 /***********************************************************************
698  *              DllRegisterServer (RPCRT4.@)
699  */
700
701 HRESULT WINAPI DllRegisterServer( void )
702 {
703     FIXME( "(): stub\n" );
704     return S_OK;
705 }
706
707 static BOOL RPCRT4_StartRPCSS(void)
708 {
709     PROCESS_INFORMATION pi;
710     STARTUPINFOA si;
711     static char cmd[6];
712     BOOL rslt;
713
714     ZeroMemory(&pi, sizeof(PROCESS_INFORMATION));
715     ZeroMemory(&si, sizeof(STARTUPINFOA));
716     si.cb = sizeof(STARTUPINFOA);
717
718     /* apparently it's not OK to use a constant string below */
719     CopyMemory(cmd, "rpcss", 6);
720
721     /* FIXME: will this do the right thing when run as a test? */
722     rslt = CreateProcessA(
723         NULL,           /* executable */
724         cmd,            /* command line */
725         NULL,           /* process security attributes */
726         NULL,           /* primary thread security attributes */
727         FALSE,          /* inherit handles */
728         0,              /* creation flags */
729         NULL,           /* use parent's environment */
730         NULL,           /* use parent's current directory */
731         &si,            /* STARTUPINFO pointer */
732         &pi             /* PROCESS_INFORMATION */
733     );
734
735     if (rslt) {
736       CloseHandle(pi.hProcess);
737       CloseHandle(pi.hThread);
738     }
739
740     return rslt;
741 }
742
743 /***********************************************************************
744  *           RPCRT4_RPCSSOnDemandCall (internal)
745  * 
746  * Attempts to send a message to the RPCSS process
747  * on the local machine, invoking it if necessary.
748  * For remote RPCSS calls, use.... your imagination.
749  * 
750  * PARAMS
751  *     msg             [I] pointer to the RPCSS message
752  *     vardata_payload [I] pointer vardata portion of the RPCSS message
753  *     reply           [O] pointer to reply structure
754  *
755  * RETURNS
756  *     TRUE if successful
757  *     FALSE otherwise
758  */
759 BOOL RPCRT4_RPCSSOnDemandCall(PRPCSS_NP_MESSAGE msg, char *vardata_payload, PRPCSS_NP_REPLY reply)
760 {
761     HANDLE client_handle;
762     BOOL ret;
763     int i, j = 0;
764
765     TRACE("(msg == %p, vardata_payload == %p, reply == %p)\n", msg, vardata_payload, reply);
766
767     client_handle = RPCRT4_RpcssNPConnect();
768
769     while (INVALID_HANDLE_VALUE == client_handle) {
770         /* start the RPCSS process */
771         if (!RPCRT4_StartRPCSS()) {
772             ERR("Unable to start RPCSS process.\n");
773             return FALSE;
774         }
775         /* wait for a connection (w/ periodic polling) */
776         for (i = 0; i < 60; i++) {
777             Sleep(200);
778             client_handle = RPCRT4_RpcssNPConnect();
779             if (INVALID_HANDLE_VALUE != client_handle) break;
780         } 
781         /* we are only willing to try twice */
782         if (j++ >= 1) break;
783     }
784
785     if (INVALID_HANDLE_VALUE == client_handle) {
786         /* no dice! */
787         ERR("Unable to connect to RPCSS process!\n");
788         SetLastError(RPC_E_SERVER_DIED_DNE);
789         return FALSE;
790     }
791
792     /* great, we're connected.  now send the message */
793     ret = TRUE;
794     if (!RPCRT4_SendReceiveNPMsg(client_handle, msg, vardata_payload, reply)) {
795         ERR("Something is amiss: RPC_SendReceive failed.\n");
796         ret = FALSE;
797     }
798     CloseHandle(client_handle);
799
800     return ret;
801 }
802
803 #define MAX_RPC_ERROR_TEXT 256
804
805 /******************************************************************************
806  * DceErrorInqTextW   (rpcrt4.@)
807  *
808  * Notes
809  * 1. On passing a NULL pointer the code does bomb out.
810  * 2. The size of the required buffer is not defined in the documentation.
811  *    It appears to be 256.
812  * 3. The function is defined to return RPC_S_INVALID_ARG but I don't know
813  *    of any value for which it does.
814  * 4. The MSDN documentation currently declares that the second argument is
815  *    unsigned char *, even for the W version.  I don't believe it.
816  */
817 RPC_STATUS RPC_ENTRY DceErrorInqTextW (RPC_STATUS e, RPC_WSTR buffer)
818 {
819     DWORD count;
820     count = FormatMessageW (FORMAT_MESSAGE_FROM_SYSTEM |
821                 FORMAT_MESSAGE_IGNORE_INSERTS,
822                 NULL, e, 0, buffer, MAX_RPC_ERROR_TEXT, NULL);
823     if (!count)
824     {
825         count = FormatMessageW (FORMAT_MESSAGE_FROM_SYSTEM |
826                 FORMAT_MESSAGE_IGNORE_INSERTS,
827                 NULL, RPC_S_NOT_RPC_ERROR, 0, buffer, MAX_RPC_ERROR_TEXT, NULL);
828         if (!count)
829         {
830             ERR ("Failed to translate error\n");
831             return RPC_S_INVALID_ARG;
832         }
833     }
834     return RPC_S_OK;
835 }
836
837 /******************************************************************************
838  * DceErrorInqTextA   (rpcrt4.@)
839  */
840 RPC_STATUS RPC_ENTRY DceErrorInqTextA (RPC_STATUS e, RPC_CSTR buffer)
841 {
842     RPC_STATUS status;
843     WCHAR bufferW [MAX_RPC_ERROR_TEXT];
844     if ((status = DceErrorInqTextW (e, bufferW)) == RPC_S_OK)
845     {
846         if (!WideCharToMultiByte(CP_ACP, 0, bufferW, -1, (LPSTR)buffer, MAX_RPC_ERROR_TEXT,
847                 NULL, NULL))
848         {
849             ERR ("Failed to translate error\n");
850             status = RPC_S_INVALID_ARG;
851         }
852     }
853     return status;
854 }
855
856 /******************************************************************************
857  * I_RpcAllocate   (rpcrt4.@)
858  */
859 void * WINAPI I_RpcAllocate(unsigned int Size)
860 {
861     return HeapAlloc(GetProcessHeap(), 0, Size);
862 }
863
864 /******************************************************************************
865  * I_RpcFree   (rpcrt4.@)
866  */
867 void WINAPI I_RpcFree(void *Object)
868 {
869     HeapFree(GetProcessHeap(), 0, Object);
870 }
871
872 /******************************************************************************
873  * I_RpcMapWin32Status   (rpcrt4.@)
874  */
875 LONG WINAPI I_RpcMapWin32Status(RPC_STATUS status)
876 {
877     FIXME("(%ld): stub\n", status);
878     return 0;
879 }
880
881 /******************************************************************************
882  * RpcErrorStartEnumeration   (rpcrt4.@)
883  */
884 RPC_STATUS RPC_ENTRY RpcErrorStartEnumeration(RPC_ERROR_ENUM_HANDLE* EnumHandle)
885 {
886     FIXME("(%p): stub\n", EnumHandle);
887     return RPC_S_ENTRY_NOT_FOUND;
888 }
889
890 /******************************************************************************
891  * RpcMgmtSetCancelTimeout   (rpcrt4.@)
892  */
893 RPC_STATUS RPC_ENTRY RpcMgmtSetCancelTimeout(LONG Timeout)
894 {
895     FIXME("(%d): stub\n", Timeout);
896     return RPC_S_OK;
897 }
898
899 static struct threaddata *get_or_create_threaddata(void)
900 {
901     struct threaddata *tdata = NtCurrentTeb()->ReservedForNtRpc;
902     if (!tdata)
903     {
904         tdata = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*tdata));
905         if (!tdata) return NULL;
906
907         InitializeCriticalSection(&tdata->cs);
908         tdata->thread_id = GetCurrentThreadId();
909
910         EnterCriticalSection(&threaddata_cs);
911         list_add_tail(&threaddata_list, &tdata->entry);
912         LeaveCriticalSection(&threaddata_cs);
913
914         NtCurrentTeb()->ReservedForNtRpc = tdata;
915         return tdata;
916     }
917     return tdata;
918 }
919
920 void RPCRT4_SetThreadCurrentConnection(RpcConnection *Connection)
921 {
922     struct threaddata *tdata = get_or_create_threaddata();
923     if (!tdata) return;
924
925     EnterCriticalSection(&tdata->cs);
926     tdata->connection = Connection;
927     LeaveCriticalSection(&tdata->cs);
928 }
929
930 void RPCRT4_SetThreadCurrentCallHandle(RpcBinding *Binding)
931 {
932     struct threaddata *tdata = get_or_create_threaddata();
933     if (!tdata) return;
934
935     tdata->server_binding = Binding;
936 }
937
938 RpcBinding *RPCRT4_GetThreadCurrentCallHandle(void)
939 {
940     struct threaddata *tdata = get_or_create_threaddata();
941     if (!tdata) return NULL;
942
943     return tdata->server_binding;
944 }
945
946 void RPCRT4_PushThreadContextHandle(NDR_SCONTEXT SContext)
947 {
948     struct threaddata *tdata = get_or_create_threaddata();
949     struct context_handle_list *context_handle_list;
950
951     if (!tdata) return;
952
953     context_handle_list = HeapAlloc(GetProcessHeap(), 0, sizeof(*context_handle_list));
954     if (!context_handle_list) return;
955
956     context_handle_list->context_handle = SContext;
957     context_handle_list->next = tdata->context_handle_list;
958     tdata->context_handle_list = context_handle_list;
959 }
960
961 void RPCRT4_RemoveThreadContextHandle(NDR_SCONTEXT SContext)
962 {
963     struct threaddata *tdata = get_or_create_threaddata();
964     struct context_handle_list *current, *prev;
965
966     if (!tdata) return;
967
968     for (current = tdata->context_handle_list, prev = NULL; current; prev = current, current = current->next)
969     {
970         if (current->context_handle == SContext)
971         {
972             if (prev)
973                 prev->next = current->next;
974             else
975                 tdata->context_handle_list = current->next;
976             HeapFree(GetProcessHeap(), 0, current);
977             return;
978         }
979     }
980 }
981
982 NDR_SCONTEXT RPCRT4_PopThreadContextHandle(void)
983 {
984     struct threaddata *tdata = get_or_create_threaddata();
985     struct context_handle_list *context_handle_list;
986     NDR_SCONTEXT context_handle;
987
988     if (!tdata) return NULL;
989
990     context_handle_list = tdata->context_handle_list;
991     if (!context_handle_list) return NULL;
992     tdata->context_handle_list = context_handle_list->next;
993
994     context_handle = context_handle_list->context_handle;
995     HeapFree(GetProcessHeap(), 0, context_handle_list);
996     return context_handle;
997 }
998
999 /******************************************************************************
1000  * RpcCancelThread   (rpcrt4.@)
1001  */
1002 RPC_STATUS RPC_ENTRY RpcCancelThread(void* ThreadHandle)
1003 {
1004     DWORD target_tid;
1005     struct threaddata *tdata;
1006
1007     TRACE("(%p)\n", ThreadHandle);
1008
1009     target_tid = GetThreadId(ThreadHandle);
1010     if (!target_tid)
1011         return RPC_S_INVALID_ARG;
1012
1013     EnterCriticalSection(&threaddata_cs);
1014     LIST_FOR_EACH_ENTRY(tdata, &threaddata_list, struct threaddata, entry)
1015         if (tdata->thread_id == target_tid)
1016         {
1017             EnterCriticalSection(&tdata->cs);
1018             if (tdata->connection) rpcrt4_conn_cancel_call(tdata->connection);
1019             LeaveCriticalSection(&tdata->cs);
1020             break;
1021         }
1022     LeaveCriticalSection(&threaddata_cs);
1023
1024     return RPC_S_OK;
1025 }