rpcrt4: Fix a memory leak when freeing an association by deleting the critical section.
[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 threaddata
150 {
151     struct list entry;
152     CRITICAL_SECTION cs;
153     DWORD thread_id;
154     RpcConnection *connection;
155 };
156
157 /***********************************************************************
158  * DllMain
159  *
160  * PARAMS
161  *     hinstDLL    [I] handle to the DLL's instance
162  *     fdwReason   [I]
163  *     lpvReserved [I] reserved, must be NULL
164  *
165  * RETURNS
166  *     Success: TRUE
167  *     Failure: FALSE
168  */
169
170 BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved)
171 {
172     struct threaddata *tdata;
173
174     switch (fdwReason) {
175     case DLL_PROCESS_ATTACH:
176         master_mutex = CreateMutexA( NULL, FALSE, RPCSS_MASTER_MUTEX_NAME);
177         if (!master_mutex)
178           ERR("Failed to create master mutex\n");
179         break;
180
181     case DLL_THREAD_DETACH:
182         tdata = NtCurrentTeb()->ReservedForNtRpc;
183         if (tdata)
184         {
185             EnterCriticalSection(&threaddata_cs);
186             list_remove(&tdata->entry);
187             LeaveCriticalSection(&threaddata_cs);
188
189             DeleteCriticalSection(&tdata->cs);
190             if (tdata->connection)
191                 ERR("tdata->connection should be NULL but is still set to %p\n", tdata);
192             HeapFree(GetProcessHeap(), 0, tdata);
193         }
194
195     case DLL_PROCESS_DETACH:
196         CloseHandle(master_mutex);
197         master_mutex = NULL;
198         break;
199     }
200
201     return TRUE;
202 }
203
204 /*************************************************************************
205  *           RpcStringFreeA   [RPCRT4.@]
206  *
207  * Frees a character string allocated by the RPC run-time library.
208  *
209  * RETURNS
210  *
211  *  S_OK if successful.
212  */
213 RPC_STATUS WINAPI RpcStringFreeA(RPC_CSTR* String)
214 {
215   HeapFree( GetProcessHeap(), 0, *String);
216
217   return RPC_S_OK;
218 }
219
220 /*************************************************************************
221  *           RpcStringFreeW   [RPCRT4.@]
222  *
223  * Frees a character string allocated by the RPC run-time library.
224  *
225  * RETURNS
226  *
227  *  S_OK if successful.
228  */
229 RPC_STATUS WINAPI RpcStringFreeW(RPC_WSTR* String)
230 {
231   HeapFree( GetProcessHeap(), 0, *String);
232
233   return RPC_S_OK;
234 }
235
236 /*************************************************************************
237  *           RpcRaiseException   [RPCRT4.@]
238  *
239  * Raises an exception.
240  */
241 void WINAPI RpcRaiseException(RPC_STATUS exception)
242 {
243   /* FIXME: translate exception? */
244   RaiseException(exception, 0, 0, NULL);
245 }
246
247 /*************************************************************************
248  * UuidCompare [RPCRT4.@]
249  *
250  * PARAMS
251  *     UUID *Uuid1        [I] Uuid to compare
252  *     UUID *Uuid2        [I] Uuid to compare
253  *     RPC_STATUS *Status [O] returns RPC_S_OK
254  * 
255  * RETURNS
256  *    -1  if Uuid1 is less than Uuid2
257  *     0  if Uuid1 and Uuid2 are equal
258  *     1  if Uuid1 is greater than Uuid2
259  */
260 int WINAPI UuidCompare(UUID *Uuid1, UUID *Uuid2, RPC_STATUS *Status)
261 {
262   int i;
263
264   TRACE("(%s,%s)\n", debugstr_guid(Uuid1), debugstr_guid(Uuid2));
265
266   *Status = RPC_S_OK;
267
268   if (!Uuid1) Uuid1 = &uuid_nil;
269   if (!Uuid2) Uuid2 = &uuid_nil;
270
271   if (Uuid1 == Uuid2) return 0;
272
273   if (Uuid1->Data1 != Uuid2->Data1)
274     return Uuid1->Data1 < Uuid2->Data1 ? -1 : 1;
275
276   if (Uuid1->Data2 != Uuid2->Data2)
277     return Uuid1->Data2 < Uuid2->Data2 ? -1 : 1;
278
279   if (Uuid1->Data3 != Uuid2->Data3)
280     return Uuid1->Data3 < Uuid2->Data3 ? -1 : 1;
281
282   for (i = 0; i < 8; i++) {
283     if (Uuid1->Data4[i] < Uuid2->Data4[i])
284       return -1;
285     if (Uuid1->Data4[i] > Uuid2->Data4[i])
286       return 1;
287   }
288
289   return 0;
290 }
291
292 /*************************************************************************
293  * UuidEqual [RPCRT4.@]
294  *
295  * PARAMS
296  *     UUID *Uuid1        [I] Uuid to compare
297  *     UUID *Uuid2        [I] Uuid to compare
298  *     RPC_STATUS *Status [O] returns RPC_S_OK
299  *
300  * RETURNS
301  *     TRUE/FALSE
302  */
303 int WINAPI UuidEqual(UUID *Uuid1, UUID *Uuid2, RPC_STATUS *Status)
304 {
305   TRACE("(%s,%s)\n", debugstr_guid(Uuid1), debugstr_guid(Uuid2));
306   return !UuidCompare(Uuid1, Uuid2, Status);
307 }
308
309 /*************************************************************************
310  * UuidIsNil [RPCRT4.@]
311  *
312  * PARAMS
313  *     UUID *Uuid         [I] Uuid to compare
314  *     RPC_STATUS *Status [O] retuns RPC_S_OK
315  *
316  * RETURNS
317  *     TRUE/FALSE
318  */
319 int WINAPI UuidIsNil(UUID *Uuid, RPC_STATUS *Status)
320 {
321   TRACE("(%s)\n", debugstr_guid(Uuid));
322   if (!Uuid) return TRUE;
323   return !UuidCompare(Uuid, &uuid_nil, Status);
324 }
325
326  /*************************************************************************
327  * UuidCreateNil [RPCRT4.@]
328  *
329  * PARAMS
330  *     UUID *Uuid [O] returns a nil UUID
331  *
332  * RETURNS
333  *     RPC_S_OK
334  */
335 RPC_STATUS WINAPI UuidCreateNil(UUID *Uuid)
336 {
337   *Uuid = uuid_nil;
338   return RPC_S_OK;
339 }
340
341 /* Number of 100ns ticks per clock tick. To be safe, assume that the clock
342    resolution is at least 1000 * 100 * (1/1000000) = 1/10 of a second */
343 #define TICKS_PER_CLOCK_TICK 1000
344 #define SECSPERDAY  86400
345 #define TICKSPERSEC 10000000
346 /* UUID system time starts at October 15, 1582 */
347 #define SECS_15_OCT_1582_TO_1601  ((17 + 30 + 31 + 365 * 18 + 5) * SECSPERDAY)
348 #define TICKS_15_OCT_1582_TO_1601 ((ULONGLONG)SECS_15_OCT_1582_TO_1601 * TICKSPERSEC)
349
350 static void RPC_UuidGetSystemTime(ULONGLONG *time)
351 {
352     FILETIME ft;
353
354     GetSystemTimeAsFileTime(&ft);
355
356     *time = ((ULONGLONG)ft.dwHighDateTime << 32) | ft.dwLowDateTime;
357     *time += TICKS_15_OCT_1582_TO_1601;
358 }
359
360 /* Assume that a hardware address is at least 6 bytes long */ 
361 #define ADDRESS_BYTES_NEEDED 6
362
363 static RPC_STATUS RPC_UuidGetNodeAddress(BYTE *address)
364 {
365     int i;
366     DWORD status = RPC_S_OK;
367
368     ULONG buflen = sizeof(IP_ADAPTER_INFO);
369     PIP_ADAPTER_INFO adapter = HeapAlloc(GetProcessHeap(), 0, buflen);
370
371     if (GetAdaptersInfo(adapter, &buflen) == ERROR_BUFFER_OVERFLOW) {
372         HeapFree(GetProcessHeap(), 0, adapter);
373         adapter = HeapAlloc(GetProcessHeap(), 0, buflen);
374     }
375
376     if (GetAdaptersInfo(adapter, &buflen) == NO_ERROR) {
377         for (i = 0; i < ADDRESS_BYTES_NEEDED; i++) {
378             address[i] = adapter->Address[i];
379         }
380     }
381     /* We can't get a hardware address, just use random numbers.
382        Set the multicast bit to prevent conflicts with real cards. */
383     else {
384         for (i = 0; i < ADDRESS_BYTES_NEEDED; i++) {
385             address[i] = rand() & 0xff;
386         }
387
388         address[0] |= 0x01;
389         status = RPC_S_UUID_LOCAL_ONLY;
390     }
391
392     HeapFree(GetProcessHeap(), 0, adapter);
393     return status;
394 }
395
396 /*************************************************************************
397  *           UuidCreate   [RPCRT4.@]
398  *
399  * Creates a 128bit UUID.
400  *
401  * RETURNS
402  *
403  *  RPC_S_OK if successful.
404  *  RPC_S_UUID_LOCAL_ONLY if UUID is only locally unique.
405  *
406  *  FIXME: No compensation for changes across reloading
407  *         this dll or across reboots (e.g. clock going 
408  *         backwards and swapped network cards). The RFC
409  *         suggests using NVRAM for storing persistent 
410  *         values.
411  */
412 RPC_STATUS WINAPI UuidCreate(UUID *Uuid)
413 {
414     static int initialised, count;
415
416     ULONGLONG time;
417     static ULONGLONG timelast;
418     static WORD sequence;
419
420     static DWORD status;
421     static BYTE address[MAX_ADAPTER_ADDRESS_LENGTH];
422
423     EnterCriticalSection(&uuid_cs);
424
425     if (!initialised) {
426         RPC_UuidGetSystemTime(&timelast);
427         count = TICKS_PER_CLOCK_TICK;
428
429         sequence = ((rand() & 0xff) << 8) + (rand() & 0xff);
430         sequence &= 0x1fff;
431
432         status = RPC_UuidGetNodeAddress(address);
433         initialised = 1;
434     }
435
436     /* Generate time element of the UUID. Account for going faster
437        than our clock as well as the clock going backwards. */
438     while (1) {
439         RPC_UuidGetSystemTime(&time);
440         if (time > timelast) {
441             count = 0;
442             break;
443         }
444         if (time < timelast) {
445             sequence = (sequence + 1) & 0x1fff;
446             count = 0;
447             break;
448         }
449         if (count < TICKS_PER_CLOCK_TICK) {
450             count++;
451             break;
452         }
453     }
454
455     timelast = time;
456     time += count;
457
458     /* Pack the information into the UUID structure. */
459
460     Uuid->Data1  = (unsigned long)(time & 0xffffffff);
461     Uuid->Data2  = (unsigned short)((time >> 32) & 0xffff);
462     Uuid->Data3  = (unsigned short)((time >> 48) & 0x0fff);
463
464     /* This is a version 1 UUID */
465     Uuid->Data3 |= (1 << 12);
466
467     Uuid->Data4[0]  = sequence & 0xff;
468     Uuid->Data4[1]  = (sequence & 0x3f00) >> 8;
469     Uuid->Data4[1] |= 0x80;
470
471     Uuid->Data4[2] = address[0];
472     Uuid->Data4[3] = address[1];
473     Uuid->Data4[4] = address[2];
474     Uuid->Data4[5] = address[3];
475     Uuid->Data4[6] = address[4];
476     Uuid->Data4[7] = address[5];
477
478     LeaveCriticalSection(&uuid_cs);
479
480     TRACE("%s\n", debugstr_guid(Uuid));
481
482     return status;
483 }
484
485 /*************************************************************************
486  *           UuidCreateSequential   [RPCRT4.@]
487  *
488  * Creates a 128bit UUID.
489  *
490  * RETURNS
491  *
492  *  RPC_S_OK if successful.
493  *  RPC_S_UUID_LOCAL_ONLY if UUID is only locally unique.
494  *
495  */
496 RPC_STATUS WINAPI UuidCreateSequential(UUID *Uuid)
497 {
498    return UuidCreate(Uuid);
499 }
500
501
502 /*************************************************************************
503  *           UuidHash   [RPCRT4.@]
504  *
505  * Generates a hash value for a given UUID
506  *
507  * Code based on FreeDCE implementation
508  *
509  */
510 unsigned short WINAPI UuidHash(UUID *uuid, RPC_STATUS *Status)
511 {
512   BYTE *data = (BYTE*)uuid;
513   short c0 = 0, c1 = 0, x, y;
514   unsigned int i;
515
516   if (!uuid) data = (BYTE*)(uuid = &uuid_nil);
517
518   TRACE("(%s)\n", debugstr_guid(uuid));
519
520   for (i=0; i<sizeof(UUID); i++) {
521     c0 += data[i];
522     c1 += c0;
523   }
524
525   x = -c1 % 255;
526   if (x < 0) x += 255;
527
528   y = (c1 - c0) % 255;
529   if (y < 0) y += 255;
530
531   *Status = RPC_S_OK;
532   return y*256 + x;
533 }
534
535 /*************************************************************************
536  *           UuidToStringA   [RPCRT4.@]
537  *
538  * Converts a UUID to a string.
539  *
540  * UUID format is 8 hex digits, followed by a hyphen then three groups of
541  * 4 hex digits each followed by a hyphen and then 12 hex digits
542  *
543  * RETURNS
544  *
545  *  S_OK if successful.
546  *  S_OUT_OF_MEMORY if unsuccessful.
547  */
548 RPC_STATUS WINAPI UuidToStringA(UUID *Uuid, RPC_CSTR* StringUuid)
549 {
550   *StringUuid = HeapAlloc( GetProcessHeap(), 0, sizeof(char) * 37);
551
552   if(!(*StringUuid))
553     return RPC_S_OUT_OF_MEMORY;
554
555   if (!Uuid) Uuid = &uuid_nil;
556
557   sprintf( (char*)*StringUuid, "%08x-%04x-%04x-%02x%02x-%02x%02x%02x%02x%02x%02x",
558                  Uuid->Data1, Uuid->Data2, Uuid->Data3,
559                  Uuid->Data4[0], Uuid->Data4[1], Uuid->Data4[2],
560                  Uuid->Data4[3], Uuid->Data4[4], Uuid->Data4[5],
561                  Uuid->Data4[6], Uuid->Data4[7] );
562
563   return RPC_S_OK;
564 }
565
566 /*************************************************************************
567  *           UuidToStringW   [RPCRT4.@]
568  *
569  * Converts a UUID to a string.
570  *
571  *  S_OK if successful.
572  *  S_OUT_OF_MEMORY if unsuccessful.
573  */
574 RPC_STATUS WINAPI UuidToStringW(UUID *Uuid, RPC_WSTR* StringUuid)
575 {
576   char buf[37];
577
578   if (!Uuid) Uuid = &uuid_nil;
579
580   sprintf(buf, "%08x-%04x-%04x-%02x%02x-%02x%02x%02x%02x%02x%02x",
581                Uuid->Data1, Uuid->Data2, Uuid->Data3,
582                Uuid->Data4[0], Uuid->Data4[1], Uuid->Data4[2],
583                Uuid->Data4[3], Uuid->Data4[4], Uuid->Data4[5],
584                Uuid->Data4[6], Uuid->Data4[7] );
585
586   *StringUuid = RPCRT4_strdupAtoW(buf);
587
588   if(!(*StringUuid))
589     return RPC_S_OUT_OF_MEMORY;
590
591   return RPC_S_OK;
592 }
593
594 static const BYTE hex2bin[] =
595 {
596     0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,        /* 0x00 */
597     0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,        /* 0x10 */
598     0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,        /* 0x20 */
599     0,1,2,3,4,5,6,7,8,9,0,0,0,0,0,0,        /* 0x30 */
600     0,10,11,12,13,14,15,0,0,0,0,0,0,0,0,0,  /* 0x40 */
601     0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,        /* 0x50 */
602     0,10,11,12,13,14,15                     /* 0x60 */
603 };
604
605 /***********************************************************************
606  *              UuidFromStringA (RPCRT4.@)
607  */
608 RPC_STATUS WINAPI UuidFromStringA(RPC_CSTR s, UUID *uuid)
609 {
610     int i;
611
612     if (!s) return UuidCreateNil( uuid );
613
614     if (strlen((char*)s) != 36) return RPC_S_INVALID_STRING_UUID;
615
616     if ((s[8]!='-') || (s[13]!='-') || (s[18]!='-') || (s[23]!='-'))
617         return RPC_S_INVALID_STRING_UUID;
618
619     for (i=0; i<36; i++)
620     {
621         if ((i == 8)||(i == 13)||(i == 18)||(i == 23)) continue;
622         if (s[i] > 'f' || (!hex2bin[s[i]] && s[i] != '0')) return RPC_S_INVALID_STRING_UUID;
623     }
624
625     /* in form XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX */
626
627     uuid->Data1 = (hex2bin[s[0]] << 28 | hex2bin[s[1]] << 24 | hex2bin[s[2]] << 20 | hex2bin[s[3]] << 16 |
628                    hex2bin[s[4]] << 12 | hex2bin[s[5]]  << 8 | hex2bin[s[6]]  << 4 | hex2bin[s[7]]);
629     uuid->Data2 =  hex2bin[s[9]] << 12 | hex2bin[s[10]] << 8 | hex2bin[s[11]] << 4 | hex2bin[s[12]];
630     uuid->Data3 = hex2bin[s[14]] << 12 | hex2bin[s[15]] << 8 | hex2bin[s[16]] << 4 | hex2bin[s[17]];
631
632     /* these are just sequential bytes */
633     uuid->Data4[0] = hex2bin[s[19]] << 4 | hex2bin[s[20]];
634     uuid->Data4[1] = hex2bin[s[21]] << 4 | hex2bin[s[22]];
635     uuid->Data4[2] = hex2bin[s[24]] << 4 | hex2bin[s[25]];
636     uuid->Data4[3] = hex2bin[s[26]] << 4 | hex2bin[s[27]];
637     uuid->Data4[4] = hex2bin[s[28]] << 4 | hex2bin[s[29]];
638     uuid->Data4[5] = hex2bin[s[30]] << 4 | hex2bin[s[31]];
639     uuid->Data4[6] = hex2bin[s[32]] << 4 | hex2bin[s[33]];
640     uuid->Data4[7] = hex2bin[s[34]] << 4 | hex2bin[s[35]];
641     return RPC_S_OK;
642 }
643
644
645 /***********************************************************************
646  *              UuidFromStringW (RPCRT4.@)
647  */
648 RPC_STATUS WINAPI UuidFromStringW(RPC_WSTR s, UUID *uuid)
649 {
650     int i;
651
652     if (!s) return UuidCreateNil( uuid );
653
654     if (strlenW(s) != 36) return RPC_S_INVALID_STRING_UUID;
655
656     if ((s[8]!='-') || (s[13]!='-') || (s[18]!='-') || (s[23]!='-'))
657         return RPC_S_INVALID_STRING_UUID;
658
659     for (i=0; i<36; i++)
660     {
661         if ((i == 8)||(i == 13)||(i == 18)||(i == 23)) continue;
662         if (s[i] > 'f' || (!hex2bin[s[i]] && s[i] != '0')) return RPC_S_INVALID_STRING_UUID;
663     }
664
665     /* in form XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX */
666
667     uuid->Data1 = (hex2bin[s[0]] << 28 | hex2bin[s[1]] << 24 | hex2bin[s[2]] << 20 | hex2bin[s[3]] << 16 |
668                    hex2bin[s[4]] << 12 | hex2bin[s[5]]  << 8 | hex2bin[s[6]]  << 4 | hex2bin[s[7]]);
669     uuid->Data2 =  hex2bin[s[9]] << 12 | hex2bin[s[10]] << 8 | hex2bin[s[11]] << 4 | hex2bin[s[12]];
670     uuid->Data3 = hex2bin[s[14]] << 12 | hex2bin[s[15]] << 8 | hex2bin[s[16]] << 4 | hex2bin[s[17]];
671
672     /* these are just sequential bytes */
673     uuid->Data4[0] = hex2bin[s[19]] << 4 | hex2bin[s[20]];
674     uuid->Data4[1] = hex2bin[s[21]] << 4 | hex2bin[s[22]];
675     uuid->Data4[2] = hex2bin[s[24]] << 4 | hex2bin[s[25]];
676     uuid->Data4[3] = hex2bin[s[26]] << 4 | hex2bin[s[27]];
677     uuid->Data4[4] = hex2bin[s[28]] << 4 | hex2bin[s[29]];
678     uuid->Data4[5] = hex2bin[s[30]] << 4 | hex2bin[s[31]];
679     uuid->Data4[6] = hex2bin[s[32]] << 4 | hex2bin[s[33]];
680     uuid->Data4[7] = hex2bin[s[34]] << 4 | hex2bin[s[35]];
681     return RPC_S_OK;
682 }
683
684 /***********************************************************************
685  *              DllRegisterServer (RPCRT4.@)
686  */
687
688 HRESULT WINAPI DllRegisterServer( void )
689 {
690     FIXME( "(): stub\n" );
691     return S_OK;
692 }
693
694 static BOOL RPCRT4_StartRPCSS(void)
695 {
696     PROCESS_INFORMATION pi;
697     STARTUPINFOA si;
698     static char cmd[6];
699     BOOL rslt;
700
701     ZeroMemory(&pi, sizeof(PROCESS_INFORMATION));
702     ZeroMemory(&si, sizeof(STARTUPINFOA));
703     si.cb = sizeof(STARTUPINFOA);
704
705     /* apparently it's not OK to use a constant string below */
706     CopyMemory(cmd, "rpcss", 6);
707
708     /* FIXME: will this do the right thing when run as a test? */
709     rslt = CreateProcessA(
710         NULL,           /* executable */
711         cmd,            /* command line */
712         NULL,           /* process security attributes */
713         NULL,           /* primary thread security attributes */
714         FALSE,          /* inherit handles */
715         0,              /* creation flags */
716         NULL,           /* use parent's environment */
717         NULL,           /* use parent's current directory */
718         &si,            /* STARTUPINFO pointer */
719         &pi             /* PROCESS_INFORMATION */
720     );
721
722     if (rslt) {
723       CloseHandle(pi.hProcess);
724       CloseHandle(pi.hThread);
725     }
726
727     return rslt;
728 }
729
730 /***********************************************************************
731  *           RPCRT4_RPCSSOnDemandCall (internal)
732  * 
733  * Attempts to send a message to the RPCSS process
734  * on the local machine, invoking it if necessary.
735  * For remote RPCSS calls, use.... your imagination.
736  * 
737  * PARAMS
738  *     msg             [I] pointer to the RPCSS message
739  *     vardata_payload [I] pointer vardata portion of the RPCSS message
740  *     reply           [O] pointer to reply structure
741  *
742  * RETURNS
743  *     TRUE if successful
744  *     FALSE otherwise
745  */
746 BOOL RPCRT4_RPCSSOnDemandCall(PRPCSS_NP_MESSAGE msg, char *vardata_payload, PRPCSS_NP_REPLY reply)
747 {
748     HANDLE client_handle;
749     BOOL ret;
750     int i, j = 0;
751
752     TRACE("(msg == %p, vardata_payload == %p, reply == %p)\n", msg, vardata_payload, reply);
753
754     client_handle = RPCRT4_RpcssNPConnect();
755
756     while (INVALID_HANDLE_VALUE == client_handle) {
757         /* start the RPCSS process */
758         if (!RPCRT4_StartRPCSS()) {
759             ERR("Unable to start RPCSS process.\n");
760             return FALSE;
761         }
762         /* wait for a connection (w/ periodic polling) */
763         for (i = 0; i < 60; i++) {
764             Sleep(200);
765             client_handle = RPCRT4_RpcssNPConnect();
766             if (INVALID_HANDLE_VALUE != client_handle) break;
767         } 
768         /* we are only willing to try twice */
769         if (j++ >= 1) break;
770     }
771
772     if (INVALID_HANDLE_VALUE == client_handle) {
773         /* no dice! */
774         ERR("Unable to connect to RPCSS process!\n");
775         SetLastError(RPC_E_SERVER_DIED_DNE);
776         return FALSE;
777     }
778
779     /* great, we're connected.  now send the message */
780     ret = TRUE;
781     if (!RPCRT4_SendReceiveNPMsg(client_handle, msg, vardata_payload, reply)) {
782         ERR("Something is amiss: RPC_SendReceive failed.\n");
783         ret = FALSE;
784     }
785     CloseHandle(client_handle);
786
787     return ret;
788 }
789
790 #define MAX_RPC_ERROR_TEXT 256
791
792 /******************************************************************************
793  * DceErrorInqTextW   (rpcrt4.@)
794  *
795  * Notes
796  * 1. On passing a NULL pointer the code does bomb out.
797  * 2. The size of the required buffer is not defined in the documentation.
798  *    It appears to be 256.
799  * 3. The function is defined to return RPC_S_INVALID_ARG but I don't know
800  *    of any value for which it does.
801  * 4. The MSDN documentation currently declares that the second argument is
802  *    unsigned char *, even for the W version.  I don't believe it.
803  */
804 RPC_STATUS RPC_ENTRY DceErrorInqTextW (RPC_STATUS e, RPC_WSTR buffer)
805 {
806     DWORD count;
807     count = FormatMessageW (FORMAT_MESSAGE_FROM_SYSTEM |
808                 FORMAT_MESSAGE_IGNORE_INSERTS,
809                 NULL, e, 0, buffer, MAX_RPC_ERROR_TEXT, NULL);
810     if (!count)
811     {
812         count = FormatMessageW (FORMAT_MESSAGE_FROM_SYSTEM |
813                 FORMAT_MESSAGE_IGNORE_INSERTS,
814                 NULL, RPC_S_NOT_RPC_ERROR, 0, buffer, MAX_RPC_ERROR_TEXT, NULL);
815         if (!count)
816         {
817             ERR ("Failed to translate error\n");
818             return RPC_S_INVALID_ARG;
819         }
820     }
821     return RPC_S_OK;
822 }
823
824 /******************************************************************************
825  * DceErrorInqTextA   (rpcrt4.@)
826  */
827 RPC_STATUS RPC_ENTRY DceErrorInqTextA (RPC_STATUS e, RPC_CSTR buffer)
828 {
829     RPC_STATUS status;
830     WCHAR bufferW [MAX_RPC_ERROR_TEXT];
831     if ((status = DceErrorInqTextW (e, bufferW)) == RPC_S_OK)
832     {
833         if (!WideCharToMultiByte(CP_ACP, 0, bufferW, -1, (LPSTR)buffer, MAX_RPC_ERROR_TEXT,
834                 NULL, NULL))
835         {
836             ERR ("Failed to translate error\n");
837             status = RPC_S_INVALID_ARG;
838         }
839     }
840     return status;
841 }
842
843 /******************************************************************************
844  * I_RpcAllocate   (rpcrt4.@)
845  */
846 void * WINAPI I_RpcAllocate(unsigned int Size)
847 {
848     return HeapAlloc(GetProcessHeap(), 0, Size);
849 }
850
851 /******************************************************************************
852  * I_RpcFree   (rpcrt4.@)
853  */
854 void WINAPI I_RpcFree(void *Object)
855 {
856     HeapFree(GetProcessHeap(), 0, Object);
857 }
858
859 /******************************************************************************
860  * I_RpcMapWin32Status   (rpcrt4.@)
861  */
862 LONG WINAPI I_RpcMapWin32Status(RPC_STATUS status)
863 {
864     FIXME("(%ld): stub\n", status);
865     return 0;
866 }
867
868 /******************************************************************************
869  * RpcErrorStartEnumeration   (rpcrt4.@)
870  */
871 RPC_STATUS RPC_ENTRY RpcErrorStartEnumeration(void** EnumHandle)
872 {
873     FIXME("(%p): stub\n", EnumHandle);
874     return RPC_S_ENTRY_NOT_FOUND;
875 }
876
877 /******************************************************************************
878  * RpcMgmtSetCancelTimeout   (rpcrt4.@)
879  */
880 RPC_STATUS RPC_ENTRY RpcMgmtSetCancelTimeout(LONG Timeout)
881 {
882     FIXME("(%d): stub\n", Timeout);
883     return RPC_S_OK;
884 }
885
886 void RPCRT4_SetThreadCurrentConnection(RpcConnection *Connection)
887 {
888     struct threaddata *tdata = NtCurrentTeb()->ReservedForNtRpc;
889     if (!tdata)
890     {
891         tdata = HeapAlloc(GetProcessHeap(), 0, sizeof(*tdata));
892         if (!tdata) return;
893
894         InitializeCriticalSection(&tdata->cs);
895         tdata->thread_id = GetCurrentThreadId();
896         tdata->connection = Connection;
897
898         EnterCriticalSection(&threaddata_cs);
899         list_add_tail(&threaddata_list, &tdata->entry);
900         LeaveCriticalSection(&threaddata_cs);
901
902         NtCurrentTeb()->ReservedForNtRpc = tdata;
903         return;
904     }
905
906     EnterCriticalSection(&tdata->cs);
907     tdata->connection = Connection;
908     LeaveCriticalSection(&tdata->cs);
909 }
910
911 /******************************************************************************
912  * RpcCancelThread   (rpcrt4.@)
913  */
914 RPC_STATUS RPC_ENTRY RpcCancelThread(void* ThreadHandle)
915 {
916     DWORD target_tid;
917     struct threaddata *tdata;
918
919     TRACE("(%p)\n", ThreadHandle);
920
921     target_tid = GetThreadId(ThreadHandle);
922     if (!target_tid)
923         return RPC_S_INVALID_ARG;
924
925     EnterCriticalSection(&threaddata_cs);
926     LIST_FOR_EACH_ENTRY(tdata, &threaddata_list, struct threaddata, entry)
927         if (tdata->thread_id == target_tid)
928         {
929             EnterCriticalSection(&tdata->cs);
930             if (tdata->connection) rpcrt4_conn_cancel_call(tdata->connection);
931             LeaveCriticalSection(&tdata->cs);
932             break;
933         }
934     LeaveCriticalSection(&threaddata_cs);
935
936     return RPC_S_OK;
937 }