xref: /reactos/dll/win32/rpcrt4/rpcrt4_main.c (revision 4f0b8d3d)
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  * - Statistics: we are supposed to be keeping various counters.  we aren't.
23  *
24  * - Async RPC: Unimplemented.
25  *
26  * - The NT "ports" API, aka LPC.  Greg claims this is on his radar.  Might (or
27  *   might not) enable users to get some kind of meaningful result out of
28  *   NT-based native rpcrt4's.  Commonly-used transport for self-to-self RPC's.
29  */
30 
31 #include <config.h>
32 
33 #include <stdarg.h>
34 #include <stdio.h>
35 //#include <stdlib.h>
36 //#include <string.h>
37 
38 #include "ntstatus.h"
39 #define WIN32_NO_STATUS
40 #define _INC_WINDOWS
41 #include <windef.h>
42 //#include "winerror.h"
43 #include <winbase.h>
44 //#include "winuser.h"
45 //#include "winnt.h"
46 #include <winternl.h>
47 #include <ntsecapi.h>
48 //#include "iptypes.h"
49 #include <iphlpapi.h>
50 #include <wine/unicode.h>
51 #include <rpc.h>
52 
53 //#include "ole2.h"
54 //#include "rpcndr.h"
55 //#include "rpcproxy.h"
56 
57 //#include "rpc_binding.h"
58 #include "rpc_server.h"
59 
60 #include <wine/debug.h>
61 
62 WINE_DEFAULT_DEBUG_CHANNEL(rpc);
63 
64 static UUID uuid_nil;
65 
66 static CRITICAL_SECTION uuid_cs;
67 static CRITICAL_SECTION_DEBUG critsect_debug =
68 {
69     0, 0, &uuid_cs,
70     { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
71       0, 0, { (DWORD_PTR)(__FILE__ ": uuid_cs") }
72 };
73 static CRITICAL_SECTION uuid_cs = { &critsect_debug, -1, 0, 0, 0, 0 };
74 
75 static CRITICAL_SECTION threaddata_cs;
76 static CRITICAL_SECTION_DEBUG threaddata_cs_debug =
77 {
78     0, 0, &threaddata_cs,
79     { &threaddata_cs_debug.ProcessLocksList, &threaddata_cs_debug.ProcessLocksList },
80       0, 0, { (DWORD_PTR)(__FILE__ ": threaddata_cs") }
81 };
82 static CRITICAL_SECTION threaddata_cs = { &threaddata_cs_debug, -1, 0, 0, 0, 0 };
83 
84 static struct list threaddata_list = LIST_INIT(threaddata_list);
85 
86 struct context_handle_list
87 {
88     struct context_handle_list *next;
89     NDR_SCONTEXT context_handle;
90 };
91 
92 struct threaddata
93 {
94     struct list entry;
95     CRITICAL_SECTION cs;
96     DWORD thread_id;
97     RpcConnection *connection;
98     RpcBinding *server_binding;
99     struct context_handle_list *context_handle_list;
100 };
101 
102 /***********************************************************************
103  * DllMain
104  *
105  * PARAMS
106  *     hinstDLL    [I] handle to the DLL's instance
107  *     fdwReason   [I]
108  *     lpvReserved [I] reserved, must be NULL
109  *
110  * RETURNS
111  *     Success: TRUE
112  *     Failure: FALSE
113  */
114 
115 BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved)
116 {
117     struct threaddata *tdata;
118 
119     switch (fdwReason) {
120     case DLL_PROCESS_ATTACH:
121         break;
122 
123     case DLL_THREAD_DETACH:
124         tdata = NtCurrentTeb()->ReservedForNtRpc;
125         if (tdata)
126         {
127             EnterCriticalSection(&threaddata_cs);
128             list_remove(&tdata->entry);
129             LeaveCriticalSection(&threaddata_cs);
130 
131             DeleteCriticalSection(&tdata->cs);
132             if (tdata->connection)
133                 ERR("tdata->connection should be NULL but is still set to %p\n", tdata->connection);
134             if (tdata->server_binding)
135                 ERR("tdata->server_binding should be NULL but is still set to %p\n", tdata->server_binding);
136             HeapFree(GetProcessHeap(), 0, tdata);
137         }
138         break;
139 
140     case DLL_PROCESS_DETACH:
141         RPCRT4_destroy_all_protseqs();
142         RPCRT4_ServerFreeAllRegisteredAuthInfo();
143         break;
144     }
145 
146     return TRUE;
147 }
148 
149 /*************************************************************************
150  *           RpcStringFreeA   [RPCRT4.@]
151  *
152  * Frees a character string allocated by the RPC run-time library.
153  *
154  * RETURNS
155  *
156  *  S_OK if successful.
157  */
158 RPC_STATUS WINAPI RpcStringFreeA(RPC_CSTR* String)
159 {
160   HeapFree( GetProcessHeap(), 0, *String);
161 
162   return RPC_S_OK;
163 }
164 
165 /*************************************************************************
166  *           RpcStringFreeW   [RPCRT4.@]
167  *
168  * Frees a character string allocated by the RPC run-time library.
169  *
170  * RETURNS
171  *
172  *  S_OK if successful.
173  */
174 RPC_STATUS WINAPI RpcStringFreeW(RPC_WSTR* String)
175 {
176   HeapFree( GetProcessHeap(), 0, *String);
177 
178   return RPC_S_OK;
179 }
180 
181 /*************************************************************************
182  *           RpcRaiseException   [RPCRT4.@]
183  *
184  * Raises an exception.
185  */
186 void DECLSPEC_NORETURN WINAPI RpcRaiseException(RPC_STATUS exception)
187 {
188   /* shouldn't return */
189   RaiseException(exception, 0, 0, NULL);
190   ERR("handler continued execution\n");
191   ExitProcess(1);
192 }
193 
194 /*************************************************************************
195  * UuidCompare [RPCRT4.@]
196  *
197  * PARAMS
198  *     UUID *Uuid1        [I] Uuid to compare
199  *     UUID *Uuid2        [I] Uuid to compare
200  *     RPC_STATUS *Status [O] returns RPC_S_OK
201  *
202  * RETURNS
203  *    -1  if Uuid1 is less than Uuid2
204  *     0  if Uuid1 and Uuid2 are equal
205  *     1  if Uuid1 is greater than Uuid2
206  */
207 int WINAPI UuidCompare(UUID *Uuid1, UUID *Uuid2, RPC_STATUS *Status)
208 {
209   int i;
210 
211   TRACE("(%s,%s)\n", debugstr_guid(Uuid1), debugstr_guid(Uuid2));
212 
213   *Status = RPC_S_OK;
214 
215   if (!Uuid1) Uuid1 = &uuid_nil;
216   if (!Uuid2) Uuid2 = &uuid_nil;
217 
218   if (Uuid1 == Uuid2) return 0;
219 
220   if (Uuid1->Data1 != Uuid2->Data1)
221     return Uuid1->Data1 < Uuid2->Data1 ? -1 : 1;
222 
223   if (Uuid1->Data2 != Uuid2->Data2)
224     return Uuid1->Data2 < Uuid2->Data2 ? -1 : 1;
225 
226   if (Uuid1->Data3 != Uuid2->Data3)
227     return Uuid1->Data3 < Uuid2->Data3 ? -1 : 1;
228 
229   for (i = 0; i < 8; i++) {
230     if (Uuid1->Data4[i] < Uuid2->Data4[i])
231       return -1;
232     if (Uuid1->Data4[i] > Uuid2->Data4[i])
233       return 1;
234   }
235 
236   return 0;
237 }
238 
239 /*************************************************************************
240  * UuidEqual [RPCRT4.@]
241  *
242  * PARAMS
243  *     UUID *Uuid1        [I] Uuid to compare
244  *     UUID *Uuid2        [I] Uuid to compare
245  *     RPC_STATUS *Status [O] returns RPC_S_OK
246  *
247  * RETURNS
248  *     TRUE/FALSE
249  */
250 int WINAPI UuidEqual(UUID *Uuid1, UUID *Uuid2, RPC_STATUS *Status)
251 {
252   TRACE("(%s,%s)\n", debugstr_guid(Uuid1), debugstr_guid(Uuid2));
253   return !UuidCompare(Uuid1, Uuid2, Status);
254 }
255 
256 /*************************************************************************
257  * UuidIsNil [RPCRT4.@]
258  *
259  * PARAMS
260  *     UUID *Uuid         [I] Uuid to compare
261  *     RPC_STATUS *Status [O] returns RPC_S_OK
262  *
263  * RETURNS
264  *     TRUE/FALSE
265  */
266 int WINAPI UuidIsNil(UUID *Uuid, RPC_STATUS *Status)
267 {
268   TRACE("(%s)\n", debugstr_guid(Uuid));
269   if (!Uuid) return TRUE;
270   return !UuidCompare(Uuid, &uuid_nil, Status);
271 }
272 
273  /*************************************************************************
274  * UuidCreateNil [RPCRT4.@]
275  *
276  * PARAMS
277  *     UUID *Uuid [O] returns a nil UUID
278  *
279  * RETURNS
280  *     RPC_S_OK
281  */
282 RPC_STATUS WINAPI UuidCreateNil(UUID *Uuid)
283 {
284   *Uuid = uuid_nil;
285   return RPC_S_OK;
286 }
287 
288 /*************************************************************************
289  *           UuidCreate   [RPCRT4.@]
290  *
291  * Creates a 128bit UUID.
292  *
293  * RETURNS
294  *
295  *  RPC_S_OK if successful.
296  *  RPC_S_UUID_LOCAL_ONLY if UUID is only locally unique.
297  *
298  * NOTES
299  *
300  *  Follows RFC 4122, section 4.4 (Algorithms for Creating a UUID from
301  *  Truly Random or Pseudo-Random Numbers)
302  */
303 RPC_STATUS WINAPI UuidCreate(UUID *Uuid)
304 {
305     RtlGenRandom(Uuid, sizeof(*Uuid));
306     /* Clear the version bits and set the version (4) */
307     Uuid->Data3 &= 0x0fff;
308     Uuid->Data3 |= (4 << 12);
309     /* Set the topmost bits of Data4 (clock_seq_hi_and_reserved) as
310      * specified in RFC 4122, section 4.4.
311      */
312     Uuid->Data4[0] &= 0x3f;
313     Uuid->Data4[0] |= 0x80;
314 
315     TRACE("%s\n", debugstr_guid(Uuid));
316 
317     return RPC_S_OK;
318 }
319 
320 /* Number of 100ns ticks per clock tick. To be safe, assume that the clock
321    resolution is at least 1000 * 100 * (1/1000000) = 1/10 of a second */
322 #define TICKS_PER_CLOCK_TICK 1000
323 #define SECSPERDAY  86400
324 #define TICKSPERSEC 10000000
325 /* UUID system time starts at October 15, 1582 */
326 #define SECS_15_OCT_1582_TO_1601  ((17 + 30 + 31 + 365 * 18 + 5) * SECSPERDAY)
327 #define TICKS_15_OCT_1582_TO_1601 ((ULONGLONG)SECS_15_OCT_1582_TO_1601 * TICKSPERSEC)
328 
329 static void RPC_UuidGetSystemTime(ULONGLONG *time)
330 {
331     FILETIME ft;
332 
333     GetSystemTimeAsFileTime(&ft);
334 
335     *time = ((ULONGLONG)ft.dwHighDateTime << 32) | ft.dwLowDateTime;
336     *time += TICKS_15_OCT_1582_TO_1601;
337 }
338 
339 /* Assume that a hardware address is at least 6 bytes long */
340 #define ADDRESS_BYTES_NEEDED 6
341 
342 static RPC_STATUS RPC_UuidGetNodeAddress(BYTE *address)
343 {
344     int i;
345     DWORD status = RPC_S_OK;
346 
347     ULONG buflen = sizeof(IP_ADAPTER_INFO);
348     PIP_ADAPTER_INFO adapter = HeapAlloc(GetProcessHeap(), 0, buflen);
349 
350     if (GetAdaptersInfo(adapter, &buflen) == ERROR_BUFFER_OVERFLOW) {
351         HeapFree(GetProcessHeap(), 0, adapter);
352         adapter = HeapAlloc(GetProcessHeap(), 0, buflen);
353     }
354 
355     if (GetAdaptersInfo(adapter, &buflen) == NO_ERROR) {
356         for (i = 0; i < ADDRESS_BYTES_NEEDED; i++) {
357             address[i] = adapter->Address[i];
358         }
359     }
360     /* We can't get a hardware address, just use random numbers.
361        Set the multicast bit to prevent conflicts with real cards. */
362     else {
363         RtlGenRandom(address, ADDRESS_BYTES_NEEDED);
364         address[0] |= 0x01;
365         status = RPC_S_UUID_LOCAL_ONLY;
366     }
367 
368     HeapFree(GetProcessHeap(), 0, adapter);
369     return status;
370 }
371 
372 /*************************************************************************
373  *           UuidCreateSequential   [RPCRT4.@]
374  *
375  * Creates a 128bit UUID.
376  *
377  * RETURNS
378  *
379  *  RPC_S_OK if successful.
380  *  RPC_S_UUID_LOCAL_ONLY if UUID is only locally unique.
381  *
382  *  FIXME: No compensation for changes across reloading
383  *         this dll or across reboots (e.g. clock going
384  *         backwards and swapped network cards). The RFC
385  *         suggests using NVRAM for storing persistent
386  *         values.
387  */
388 RPC_STATUS WINAPI UuidCreateSequential(UUID *Uuid)
389 {
390     static int initialised, count;
391 
392     ULONGLONG time;
393     static ULONGLONG timelast;
394     static WORD sequence;
395 
396     static DWORD status;
397     static BYTE address[MAX_ADAPTER_ADDRESS_LENGTH];
398 
399     EnterCriticalSection(&uuid_cs);
400 
401     if (!initialised) {
402         RPC_UuidGetSystemTime(&timelast);
403         count = TICKS_PER_CLOCK_TICK;
404 
405         sequence = ((rand() & 0xff) << 8) + (rand() & 0xff);
406         sequence &= 0x1fff;
407 
408         status = RPC_UuidGetNodeAddress(address);
409         initialised = 1;
410     }
411 
412     /* Generate time element of the UUID. Account for going faster
413        than our clock as well as the clock going backwards. */
414     while (1) {
415         RPC_UuidGetSystemTime(&time);
416         if (time > timelast) {
417             count = 0;
418             break;
419         }
420         if (time < timelast) {
421             sequence = (sequence + 1) & 0x1fff;
422             count = 0;
423             break;
424         }
425         if (count < TICKS_PER_CLOCK_TICK) {
426             count++;
427             break;
428         }
429     }
430 
431     timelast = time;
432     time += count;
433 
434     /* Pack the information into the UUID structure. */
435 
436     Uuid->Data1  = (ULONG)(time & 0xffffffff);
437     Uuid->Data2  = (unsigned short)((time >> 32) & 0xffff);
438     Uuid->Data3  = (unsigned short)((time >> 48) & 0x0fff);
439 
440     /* This is a version 1 UUID */
441     Uuid->Data3 |= (1 << 12);
442 
443     Uuid->Data4[0]  = sequence & 0xff;
444     Uuid->Data4[1]  = (sequence & 0x3f00) >> 8;
445     Uuid->Data4[1] |= 0x80;
446     memcpy(&Uuid->Data4[2], address, ADDRESS_BYTES_NEEDED);
447 
448     LeaveCriticalSection(&uuid_cs);
449 
450     TRACE("%s\n", debugstr_guid(Uuid));
451 
452     return status;
453 }
454 
455 
456 /*************************************************************************
457  *           UuidHash   [RPCRT4.@]
458  *
459  * Generates a hash value for a given UUID
460  *
461  * Code based on FreeDCE implementation
462  *
463  */
464 unsigned short WINAPI UuidHash(UUID *uuid, RPC_STATUS *Status)
465 {
466   BYTE *data = (BYTE*)uuid;
467   short c0 = 0, c1 = 0, x, y;
468   unsigned int i;
469 
470   if (!uuid) data = (BYTE*)(uuid = &uuid_nil);
471 
472   TRACE("(%s)\n", debugstr_guid(uuid));
473 
474   for (i=0; i<sizeof(UUID); i++) {
475     c0 += data[i];
476     c1 += c0;
477   }
478 
479   x = -c1 % 255;
480   if (x < 0) x += 255;
481 
482   y = (c1 - c0) % 255;
483   if (y < 0) y += 255;
484 
485   *Status = RPC_S_OK;
486   return y*256 + x;
487 }
488 
489 /*************************************************************************
490  *           UuidToStringA   [RPCRT4.@]
491  *
492  * Converts a UUID to a string.
493  *
494  * UUID format is 8 hex digits, followed by a hyphen then three groups of
495  * 4 hex digits each followed by a hyphen and then 12 hex digits
496  *
497  * RETURNS
498  *
499  *  S_OK if successful.
500  *  S_OUT_OF_MEMORY if unsuccessful.
501  */
502 RPC_STATUS WINAPI UuidToStringA(UUID *Uuid, RPC_CSTR* StringUuid)
503 {
504   *StringUuid = HeapAlloc( GetProcessHeap(), 0, sizeof(char) * 37);
505 
506   if(!(*StringUuid))
507     return RPC_S_OUT_OF_MEMORY;
508 
509   if (!Uuid) Uuid = &uuid_nil;
510 
511   sprintf( (char*)*StringUuid, "%08x-%04x-%04x-%02x%02x-%02x%02x%02x%02x%02x%02x",
512                  Uuid->Data1, Uuid->Data2, Uuid->Data3,
513                  Uuid->Data4[0], Uuid->Data4[1], Uuid->Data4[2],
514                  Uuid->Data4[3], Uuid->Data4[4], Uuid->Data4[5],
515                  Uuid->Data4[6], Uuid->Data4[7] );
516 
517   return RPC_S_OK;
518 }
519 
520 /*************************************************************************
521  *           UuidToStringW   [RPCRT4.@]
522  *
523  * Converts a UUID to a string.
524  *
525  *  S_OK if successful.
526  *  S_OUT_OF_MEMORY if unsuccessful.
527  */
528 RPC_STATUS WINAPI UuidToStringW(UUID *Uuid, RPC_WSTR* StringUuid)
529 {
530   char buf[37];
531 
532   if (!Uuid) Uuid = &uuid_nil;
533 
534   sprintf(buf, "%08x-%04x-%04x-%02x%02x-%02x%02x%02x%02x%02x%02x",
535                Uuid->Data1, Uuid->Data2, Uuid->Data3,
536                Uuid->Data4[0], Uuid->Data4[1], Uuid->Data4[2],
537                Uuid->Data4[3], Uuid->Data4[4], Uuid->Data4[5],
538                Uuid->Data4[6], Uuid->Data4[7] );
539 
540   *StringUuid = RPCRT4_strdupAtoW(buf);
541 
542   if(!(*StringUuid))
543     return RPC_S_OUT_OF_MEMORY;
544 
545   return RPC_S_OK;
546 }
547 
548 static const BYTE hex2bin[] =
549 {
550     0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,        /* 0x00 */
551     0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,        /* 0x10 */
552     0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,        /* 0x20 */
553     0,1,2,3,4,5,6,7,8,9,0,0,0,0,0,0,        /* 0x30 */
554     0,10,11,12,13,14,15,0,0,0,0,0,0,0,0,0,  /* 0x40 */
555     0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,        /* 0x50 */
556     0,10,11,12,13,14,15                     /* 0x60 */
557 };
558 
559 /***********************************************************************
560  *		UuidFromStringA (RPCRT4.@)
561  */
562 RPC_STATUS WINAPI UuidFromStringA(RPC_CSTR s, UUID *uuid)
563 {
564     int i;
565 
566     if (!s) return UuidCreateNil( uuid );
567 
568     if (strlen((char*)s) != 36) return RPC_S_INVALID_STRING_UUID;
569 
570     if ((s[8]!='-') || (s[13]!='-') || (s[18]!='-') || (s[23]!='-'))
571         return RPC_S_INVALID_STRING_UUID;
572 
573     for (i=0; i<36; i++)
574     {
575         if ((i == 8)||(i == 13)||(i == 18)||(i == 23)) continue;
576         if (s[i] > 'f' || (!hex2bin[s[i]] && s[i] != '0')) return RPC_S_INVALID_STRING_UUID;
577     }
578 
579     /* in form XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX */
580 
581     uuid->Data1 = (hex2bin[s[0]] << 28 | hex2bin[s[1]] << 24 | hex2bin[s[2]] << 20 | hex2bin[s[3]] << 16 |
582                    hex2bin[s[4]] << 12 | hex2bin[s[5]]  << 8 | hex2bin[s[6]]  << 4 | hex2bin[s[7]]);
583     uuid->Data2 =  hex2bin[s[9]] << 12 | hex2bin[s[10]] << 8 | hex2bin[s[11]] << 4 | hex2bin[s[12]];
584     uuid->Data3 = hex2bin[s[14]] << 12 | hex2bin[s[15]] << 8 | hex2bin[s[16]] << 4 | hex2bin[s[17]];
585 
586     /* these are just sequential bytes */
587     uuid->Data4[0] = hex2bin[s[19]] << 4 | hex2bin[s[20]];
588     uuid->Data4[1] = hex2bin[s[21]] << 4 | hex2bin[s[22]];
589     uuid->Data4[2] = hex2bin[s[24]] << 4 | hex2bin[s[25]];
590     uuid->Data4[3] = hex2bin[s[26]] << 4 | hex2bin[s[27]];
591     uuid->Data4[4] = hex2bin[s[28]] << 4 | hex2bin[s[29]];
592     uuid->Data4[5] = hex2bin[s[30]] << 4 | hex2bin[s[31]];
593     uuid->Data4[6] = hex2bin[s[32]] << 4 | hex2bin[s[33]];
594     uuid->Data4[7] = hex2bin[s[34]] << 4 | hex2bin[s[35]];
595     return RPC_S_OK;
596 }
597 
598 
599 /***********************************************************************
600  *		UuidFromStringW (RPCRT4.@)
601  */
602 RPC_STATUS WINAPI UuidFromStringW(RPC_WSTR s, UUID *uuid)
603 {
604     int i;
605 
606     if (!s) return UuidCreateNil( uuid );
607 
608     if (strlenW(s) != 36) return RPC_S_INVALID_STRING_UUID;
609 
610     if ((s[8]!='-') || (s[13]!='-') || (s[18]!='-') || (s[23]!='-'))
611         return RPC_S_INVALID_STRING_UUID;
612 
613     for (i=0; i<36; i++)
614     {
615         if ((i == 8)||(i == 13)||(i == 18)||(i == 23)) continue;
616         if (s[i] > 'f' || (!hex2bin[s[i]] && s[i] != '0')) return RPC_S_INVALID_STRING_UUID;
617     }
618 
619     /* in form XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX */
620 
621     uuid->Data1 = (hex2bin[s[0]] << 28 | hex2bin[s[1]] << 24 | hex2bin[s[2]] << 20 | hex2bin[s[3]] << 16 |
622                    hex2bin[s[4]] << 12 | hex2bin[s[5]]  << 8 | hex2bin[s[6]]  << 4 | hex2bin[s[7]]);
623     uuid->Data2 =  hex2bin[s[9]] << 12 | hex2bin[s[10]] << 8 | hex2bin[s[11]] << 4 | hex2bin[s[12]];
624     uuid->Data3 = hex2bin[s[14]] << 12 | hex2bin[s[15]] << 8 | hex2bin[s[16]] << 4 | hex2bin[s[17]];
625 
626     /* these are just sequential bytes */
627     uuid->Data4[0] = hex2bin[s[19]] << 4 | hex2bin[s[20]];
628     uuid->Data4[1] = hex2bin[s[21]] << 4 | hex2bin[s[22]];
629     uuid->Data4[2] = hex2bin[s[24]] << 4 | hex2bin[s[25]];
630     uuid->Data4[3] = hex2bin[s[26]] << 4 | hex2bin[s[27]];
631     uuid->Data4[4] = hex2bin[s[28]] << 4 | hex2bin[s[29]];
632     uuid->Data4[5] = hex2bin[s[30]] << 4 | hex2bin[s[31]];
633     uuid->Data4[6] = hex2bin[s[32]] << 4 | hex2bin[s[33]];
634     uuid->Data4[7] = hex2bin[s[34]] << 4 | hex2bin[s[35]];
635     return RPC_S_OK;
636 }
637 
638 /***********************************************************************
639  *              DllRegisterServer (RPCRT4.@)
640  */
641 
642 HRESULT WINAPI DllRegisterServer( void )
643 {
644     FIXME( "(): stub\n" );
645     return S_OK;
646 }
647 
648 #define MAX_RPC_ERROR_TEXT 256
649 
650 /******************************************************************************
651  * DceErrorInqTextW   (rpcrt4.@)
652  *
653  * Notes
654  * 1. On passing a NULL pointer the code does bomb out.
655  * 2. The size of the required buffer is not defined in the documentation.
656  *    It appears to be 256.
657  * 3. The function is defined to return RPC_S_INVALID_ARG but I don't know
658  *    of any value for which it does.
659  * 4. The MSDN documentation currently declares that the second argument is
660  *    unsigned char *, even for the W version.  I don't believe it.
661  */
662 RPC_STATUS RPC_ENTRY DceErrorInqTextW (RPC_STATUS e, RPC_WSTR buffer)
663 {
664     DWORD count;
665     count = FormatMessageW (FORMAT_MESSAGE_FROM_SYSTEM |
666                 FORMAT_MESSAGE_IGNORE_INSERTS,
667                 NULL, e, 0, buffer, MAX_RPC_ERROR_TEXT, NULL);
668     if (!count)
669     {
670         count = FormatMessageW (FORMAT_MESSAGE_FROM_SYSTEM |
671                 FORMAT_MESSAGE_IGNORE_INSERTS,
672                 NULL, RPC_S_NOT_RPC_ERROR, 0, buffer, MAX_RPC_ERROR_TEXT, NULL);
673         if (!count)
674         {
675             ERR ("Failed to translate error\n");
676             return RPC_S_INVALID_ARG;
677         }
678     }
679     return RPC_S_OK;
680 }
681 
682 /******************************************************************************
683  * DceErrorInqTextA   (rpcrt4.@)
684  */
685 RPC_STATUS RPC_ENTRY DceErrorInqTextA (RPC_STATUS e, RPC_CSTR buffer)
686 {
687     RPC_STATUS status;
688     WCHAR bufferW [MAX_RPC_ERROR_TEXT];
689     if ((status = DceErrorInqTextW (e, bufferW)) == RPC_S_OK)
690     {
691         if (!WideCharToMultiByte(CP_ACP, 0, bufferW, -1, (LPSTR)buffer, MAX_RPC_ERROR_TEXT,
692                 NULL, NULL))
693         {
694             ERR ("Failed to translate error\n");
695             status = RPC_S_INVALID_ARG;
696         }
697     }
698     return status;
699 }
700 
701 /******************************************************************************
702  * I_RpcAllocate   (rpcrt4.@)
703  */
704 void * WINAPI I_RpcAllocate(unsigned int Size)
705 {
706     return HeapAlloc(GetProcessHeap(), 0, Size);
707 }
708 
709 /******************************************************************************
710  * I_RpcFree   (rpcrt4.@)
711  */
712 void WINAPI I_RpcFree(void *Object)
713 {
714     HeapFree(GetProcessHeap(), 0, Object);
715 }
716 
717 /******************************************************************************
718  * I_RpcMapWin32Status   (rpcrt4.@)
719  *
720  * Maps Win32 RPC error codes to NT statuses.
721  *
722  * PARAMS
723  *  status [I] Win32 RPC error code.
724  *
725  * RETURNS
726  *  Appropriate translation into an NT status code.
727  */
728 LONG WINAPI I_RpcMapWin32Status(RPC_STATUS status)
729 {
730     TRACE("(%d)\n", status);
731     switch (status)
732     {
733     case ERROR_ACCESS_DENIED: return STATUS_ACCESS_DENIED;
734     case ERROR_INVALID_HANDLE: return RPC_NT_SS_CONTEXT_MISMATCH;
735     case ERROR_OUTOFMEMORY: return STATUS_NO_MEMORY;
736     case ERROR_INVALID_PARAMETER: return STATUS_INVALID_PARAMETER;
737     case ERROR_INSUFFICIENT_BUFFER: return STATUS_BUFFER_TOO_SMALL;
738     case ERROR_MAX_THRDS_REACHED: return STATUS_NO_MEMORY;
739     case ERROR_NOACCESS: return STATUS_ACCESS_VIOLATION;
740     case ERROR_NOT_ENOUGH_SERVER_MEMORY: return STATUS_INSUFF_SERVER_RESOURCES;
741     case ERROR_WRONG_PASSWORD: return STATUS_WRONG_PASSWORD;
742     case ERROR_INVALID_LOGON_HOURS: return STATUS_INVALID_LOGON_HOURS;
743     case ERROR_PASSWORD_EXPIRED: return STATUS_PASSWORD_EXPIRED;
744     case ERROR_ACCOUNT_DISABLED: return STATUS_ACCOUNT_DISABLED;
745     case ERROR_INVALID_SECURITY_DESCR: return STATUS_INVALID_SECURITY_DESCR;
746     case RPC_S_INVALID_STRING_BINDING: return RPC_NT_INVALID_STRING_BINDING;
747     case RPC_S_WRONG_KIND_OF_BINDING: return RPC_NT_WRONG_KIND_OF_BINDING;
748     case RPC_S_INVALID_BINDING: return RPC_NT_INVALID_BINDING;
749     case RPC_S_PROTSEQ_NOT_SUPPORTED: return RPC_NT_PROTSEQ_NOT_SUPPORTED;
750     case RPC_S_INVALID_RPC_PROTSEQ: return RPC_NT_INVALID_RPC_PROTSEQ;
751     case RPC_S_INVALID_STRING_UUID: return RPC_NT_INVALID_STRING_UUID;
752     case RPC_S_INVALID_ENDPOINT_FORMAT: return RPC_NT_INVALID_ENDPOINT_FORMAT;
753     case RPC_S_INVALID_NET_ADDR: return RPC_NT_INVALID_NET_ADDR;
754     case RPC_S_NO_ENDPOINT_FOUND: return RPC_NT_NO_ENDPOINT_FOUND;
755     case RPC_S_INVALID_TIMEOUT: return RPC_NT_INVALID_TIMEOUT;
756     case RPC_S_OBJECT_NOT_FOUND: return RPC_NT_OBJECT_NOT_FOUND;
757     case RPC_S_ALREADY_REGISTERED: return RPC_NT_ALREADY_REGISTERED;
758     case RPC_S_TYPE_ALREADY_REGISTERED: return RPC_NT_TYPE_ALREADY_REGISTERED;
759     case RPC_S_ALREADY_LISTENING: return RPC_NT_ALREADY_LISTENING;
760     case RPC_S_NO_PROTSEQS_REGISTERED: return RPC_NT_NO_PROTSEQS_REGISTERED;
761     case RPC_S_NOT_LISTENING: return RPC_NT_NOT_LISTENING;
762     case RPC_S_UNKNOWN_MGR_TYPE: return RPC_NT_UNKNOWN_MGR_TYPE;
763     case RPC_S_UNKNOWN_IF: return RPC_NT_UNKNOWN_IF;
764     case RPC_S_NO_BINDINGS: return RPC_NT_NO_BINDINGS;
765     case RPC_S_NO_PROTSEQS: return RPC_NT_NO_PROTSEQS;
766     case RPC_S_CANT_CREATE_ENDPOINT: return RPC_NT_CANT_CREATE_ENDPOINT;
767     case RPC_S_OUT_OF_RESOURCES: return RPC_NT_OUT_OF_RESOURCES;
768     case RPC_S_SERVER_UNAVAILABLE: return RPC_NT_SERVER_UNAVAILABLE;
769     case RPC_S_SERVER_TOO_BUSY: return RPC_NT_SERVER_TOO_BUSY;
770     case RPC_S_INVALID_NETWORK_OPTIONS: return RPC_NT_INVALID_NETWORK_OPTIONS;
771     case RPC_S_NO_CALL_ACTIVE: return RPC_NT_NO_CALL_ACTIVE;
772     case RPC_S_CALL_FAILED: return RPC_NT_CALL_FAILED;
773     case RPC_S_CALL_FAILED_DNE: return RPC_NT_CALL_FAILED_DNE;
774     case RPC_S_PROTOCOL_ERROR: return RPC_NT_PROTOCOL_ERROR;
775     case RPC_S_UNSUPPORTED_TRANS_SYN: return RPC_NT_UNSUPPORTED_TRANS_SYN;
776     case RPC_S_UNSUPPORTED_TYPE: return RPC_NT_UNSUPPORTED_TYPE;
777     case RPC_S_INVALID_TAG: return RPC_NT_INVALID_TAG;
778     case RPC_S_INVALID_BOUND: return RPC_NT_INVALID_BOUND;
779     case RPC_S_NO_ENTRY_NAME: return RPC_NT_NO_ENTRY_NAME;
780     case RPC_S_INVALID_NAME_SYNTAX: return RPC_NT_INVALID_NAME_SYNTAX;
781     case RPC_S_UNSUPPORTED_NAME_SYNTAX: return RPC_NT_UNSUPPORTED_NAME_SYNTAX;
782     case RPC_S_UUID_NO_ADDRESS: return RPC_NT_UUID_NO_ADDRESS;
783     case RPC_S_DUPLICATE_ENDPOINT: return RPC_NT_DUPLICATE_ENDPOINT;
784     case RPC_S_UNKNOWN_AUTHN_TYPE: return RPC_NT_UNKNOWN_AUTHN_TYPE;
785     case RPC_S_MAX_CALLS_TOO_SMALL: return RPC_NT_MAX_CALLS_TOO_SMALL;
786     case RPC_S_STRING_TOO_LONG: return RPC_NT_STRING_TOO_LONG;
787     case RPC_S_PROTSEQ_NOT_FOUND: return RPC_NT_PROTSEQ_NOT_FOUND;
788     case RPC_S_PROCNUM_OUT_OF_RANGE: return RPC_NT_PROCNUM_OUT_OF_RANGE;
789     case RPC_S_BINDING_HAS_NO_AUTH: return RPC_NT_BINDING_HAS_NO_AUTH;
790     case RPC_S_UNKNOWN_AUTHN_SERVICE: return RPC_NT_UNKNOWN_AUTHN_SERVICE;
791     case RPC_S_UNKNOWN_AUTHN_LEVEL: return RPC_NT_UNKNOWN_AUTHN_LEVEL;
792     case RPC_S_INVALID_AUTH_IDENTITY: return RPC_NT_INVALID_AUTH_IDENTITY;
793     case RPC_S_UNKNOWN_AUTHZ_SERVICE: return RPC_NT_UNKNOWN_AUTHZ_SERVICE;
794     case EPT_S_INVALID_ENTRY: return EPT_NT_INVALID_ENTRY;
795     case EPT_S_CANT_PERFORM_OP: return EPT_NT_CANT_PERFORM_OP;
796     case EPT_S_NOT_REGISTERED: return EPT_NT_NOT_REGISTERED;
797     case EPT_S_CANT_CREATE: return EPT_NT_CANT_CREATE;
798     case RPC_S_NOTHING_TO_EXPORT: return RPC_NT_NOTHING_TO_EXPORT;
799     case RPC_S_INCOMPLETE_NAME: return RPC_NT_INCOMPLETE_NAME;
800     case RPC_S_INVALID_VERS_OPTION: return RPC_NT_INVALID_VERS_OPTION;
801     case RPC_S_NO_MORE_MEMBERS: return RPC_NT_NO_MORE_MEMBERS;
802     case RPC_S_NOT_ALL_OBJS_UNEXPORTED: return RPC_NT_NOT_ALL_OBJS_UNEXPORTED;
803     case RPC_S_INTERFACE_NOT_FOUND: return RPC_NT_INTERFACE_NOT_FOUND;
804     case RPC_S_ENTRY_ALREADY_EXISTS: return RPC_NT_ENTRY_ALREADY_EXISTS;
805     case RPC_S_ENTRY_NOT_FOUND: return RPC_NT_ENTRY_NOT_FOUND;
806     case RPC_S_NAME_SERVICE_UNAVAILABLE: return RPC_NT_NAME_SERVICE_UNAVAILABLE;
807     case RPC_S_INVALID_NAF_ID: return RPC_NT_INVALID_NAF_ID;
808     case RPC_S_CANNOT_SUPPORT: return RPC_NT_CANNOT_SUPPORT;
809     case RPC_S_NO_CONTEXT_AVAILABLE: return RPC_NT_NO_CONTEXT_AVAILABLE;
810     case RPC_S_INTERNAL_ERROR: return RPC_NT_INTERNAL_ERROR;
811     case RPC_S_ZERO_DIVIDE: return RPC_NT_ZERO_DIVIDE;
812     case RPC_S_ADDRESS_ERROR: return RPC_NT_ADDRESS_ERROR;
813     case RPC_S_FP_DIV_ZERO: return RPC_NT_FP_DIV_ZERO;
814     case RPC_S_FP_UNDERFLOW: return RPC_NT_FP_UNDERFLOW;
815     case RPC_S_FP_OVERFLOW: return RPC_NT_FP_OVERFLOW;
816     case RPC_S_CALL_IN_PROGRESS: return RPC_NT_CALL_IN_PROGRESS;
817     case RPC_S_NO_MORE_BINDINGS: return RPC_NT_NO_MORE_BINDINGS;
818     case RPC_S_CALL_CANCELLED: return RPC_NT_CALL_CANCELLED;
819     case RPC_S_INVALID_OBJECT: return RPC_NT_INVALID_OBJECT;
820     case RPC_S_INVALID_ASYNC_HANDLE: return RPC_NT_INVALID_ASYNC_HANDLE;
821     case RPC_S_INVALID_ASYNC_CALL: return RPC_NT_INVALID_ASYNC_CALL;
822     case RPC_S_GROUP_MEMBER_NOT_FOUND: return RPC_NT_GROUP_MEMBER_NOT_FOUND;
823     case RPC_X_NO_MORE_ENTRIES: return RPC_NT_NO_MORE_ENTRIES;
824     case RPC_X_SS_CHAR_TRANS_OPEN_FAIL: return RPC_NT_SS_CHAR_TRANS_OPEN_FAIL;
825     case RPC_X_SS_CHAR_TRANS_SHORT_FILE: return RPC_NT_SS_CHAR_TRANS_SHORT_FILE;
826     case RPC_X_SS_IN_NULL_CONTEXT: return RPC_NT_SS_IN_NULL_CONTEXT;
827     case RPC_X_SS_CONTEXT_DAMAGED: return RPC_NT_SS_CONTEXT_DAMAGED;
828     case RPC_X_SS_HANDLES_MISMATCH: return RPC_NT_SS_HANDLES_MISMATCH;
829     case RPC_X_SS_CANNOT_GET_CALL_HANDLE: return RPC_NT_SS_CANNOT_GET_CALL_HANDLE;
830     case RPC_X_NULL_REF_POINTER: return RPC_NT_NULL_REF_POINTER;
831     case RPC_X_ENUM_VALUE_OUT_OF_RANGE: return RPC_NT_ENUM_VALUE_OUT_OF_RANGE;
832     case RPC_X_BYTE_COUNT_TOO_SMALL: return RPC_NT_BYTE_COUNT_TOO_SMALL;
833     case RPC_X_BAD_STUB_DATA: return RPC_NT_BAD_STUB_DATA;
834     case RPC_X_PIPE_CLOSED: return RPC_NT_PIPE_CLOSED;
835     case RPC_X_PIPE_DISCIPLINE_ERROR: return RPC_NT_PIPE_DISCIPLINE_ERROR;
836     case RPC_X_PIPE_EMPTY: return RPC_NT_PIPE_EMPTY;
837     case ERROR_PASSWORD_MUST_CHANGE: return STATUS_PASSWORD_MUST_CHANGE;
838     case ERROR_ACCOUNT_LOCKED_OUT: return STATUS_ACCOUNT_LOCKED_OUT;
839     default: return status;
840     }
841 }
842 
843 /******************************************************************************
844  * I_RpcExceptionFilter   (rpcrt4.@)
845  */
846 int WINAPI I_RpcExceptionFilter(ULONG ExceptionCode)
847 {
848     TRACE("0x%x\n", ExceptionCode);
849     switch (ExceptionCode)
850     {
851     case STATUS_DATATYPE_MISALIGNMENT:
852     case STATUS_BREAKPOINT:
853     case STATUS_ACCESS_VIOLATION:
854     case STATUS_ILLEGAL_INSTRUCTION:
855     case STATUS_PRIVILEGED_INSTRUCTION:
856     case STATUS_INSTRUCTION_MISALIGNMENT:
857     case STATUS_STACK_OVERFLOW:
858     case STATUS_POSSIBLE_DEADLOCK:
859         return EXCEPTION_CONTINUE_SEARCH;
860     default:
861         return EXCEPTION_EXECUTE_HANDLER;
862     }
863 }
864 
865 /******************************************************************************
866  * RpcErrorStartEnumeration   (rpcrt4.@)
867  */
868 RPC_STATUS RPC_ENTRY RpcErrorStartEnumeration(RPC_ERROR_ENUM_HANDLE* EnumHandle)
869 {
870     FIXME("(%p): stub\n", EnumHandle);
871     return RPC_S_ENTRY_NOT_FOUND;
872 }
873 
874 /******************************************************************************
875  * RpcMgmtSetCancelTimeout   (rpcrt4.@)
876  */
877 RPC_STATUS RPC_ENTRY RpcMgmtSetCancelTimeout(LONG Timeout)
878 {
879     FIXME("(%d): stub\n", Timeout);
880     return RPC_S_OK;
881 }
882 
883 static struct threaddata *get_or_create_threaddata(void)
884 {
885     struct threaddata *tdata = NtCurrentTeb()->ReservedForNtRpc;
886     if (!tdata)
887     {
888         tdata = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*tdata));
889         if (!tdata) return NULL;
890 
891         InitializeCriticalSection(&tdata->cs);
892         tdata->thread_id = GetCurrentThreadId();
893 
894         EnterCriticalSection(&threaddata_cs);
895         list_add_tail(&threaddata_list, &tdata->entry);
896         LeaveCriticalSection(&threaddata_cs);
897 
898         NtCurrentTeb()->ReservedForNtRpc = tdata;
899         return tdata;
900     }
901     return tdata;
902 }
903 
904 void RPCRT4_SetThreadCurrentConnection(RpcConnection *Connection)
905 {
906     struct threaddata *tdata = get_or_create_threaddata();
907     if (!tdata) return;
908 
909     EnterCriticalSection(&tdata->cs);
910     tdata->connection = Connection;
911     LeaveCriticalSection(&tdata->cs);
912 }
913 
914 void RPCRT4_SetThreadCurrentCallHandle(RpcBinding *Binding)
915 {
916     struct threaddata *tdata = get_or_create_threaddata();
917     if (!tdata) return;
918 
919     tdata->server_binding = Binding;
920 }
921 
922 RpcBinding *RPCRT4_GetThreadCurrentCallHandle(void)
923 {
924     struct threaddata *tdata = get_or_create_threaddata();
925     if (!tdata) return NULL;
926 
927     return tdata->server_binding;
928 }
929 
930 void RPCRT4_PushThreadContextHandle(NDR_SCONTEXT SContext)
931 {
932     struct threaddata *tdata = get_or_create_threaddata();
933     struct context_handle_list *context_handle_list;
934 
935     if (!tdata) return;
936 
937     context_handle_list = HeapAlloc(GetProcessHeap(), 0, sizeof(*context_handle_list));
938     if (!context_handle_list) return;
939 
940     context_handle_list->context_handle = SContext;
941     context_handle_list->next = tdata->context_handle_list;
942     tdata->context_handle_list = context_handle_list;
943 }
944 
945 void RPCRT4_RemoveThreadContextHandle(NDR_SCONTEXT SContext)
946 {
947     struct threaddata *tdata = get_or_create_threaddata();
948     struct context_handle_list *current, *prev;
949 
950     if (!tdata) return;
951 
952     for (current = tdata->context_handle_list, prev = NULL; current; prev = current, current = current->next)
953     {
954         if (current->context_handle == SContext)
955         {
956             if (prev)
957                 prev->next = current->next;
958             else
959                 tdata->context_handle_list = current->next;
960             HeapFree(GetProcessHeap(), 0, current);
961             return;
962         }
963     }
964 }
965 
966 NDR_SCONTEXT RPCRT4_PopThreadContextHandle(void)
967 {
968     struct threaddata *tdata = get_or_create_threaddata();
969     struct context_handle_list *context_handle_list;
970     NDR_SCONTEXT context_handle;
971 
972     if (!tdata) return NULL;
973 
974     context_handle_list = tdata->context_handle_list;
975     if (!context_handle_list) return NULL;
976     tdata->context_handle_list = context_handle_list->next;
977 
978     context_handle = context_handle_list->context_handle;
979     HeapFree(GetProcessHeap(), 0, context_handle_list);
980     return context_handle;
981 }
982 
983 static RPC_STATUS rpc_cancel_thread(DWORD target_tid)
984 {
985     struct threaddata *tdata;
986 
987     EnterCriticalSection(&threaddata_cs);
988     LIST_FOR_EACH_ENTRY(tdata, &threaddata_list, struct threaddata, entry)
989         if (tdata->thread_id == target_tid)
990         {
991             EnterCriticalSection(&tdata->cs);
992             if (tdata->connection) rpcrt4_conn_cancel_call(tdata->connection);
993             LeaveCriticalSection(&tdata->cs);
994             break;
995         }
996     LeaveCriticalSection(&threaddata_cs);
997 
998     return RPC_S_OK;
999 }
1000 
1001 /******************************************************************************
1002  * RpcCancelThread   (rpcrt4.@)
1003  */
1004 RPC_STATUS RPC_ENTRY RpcCancelThread(void* ThreadHandle)
1005 {
1006     TRACE("(%p)\n", ThreadHandle);
1007     return RpcCancelThreadEx(ThreadHandle, 0);
1008 }
1009 
1010 /******************************************************************************
1011  * RpcCancelThreadEx   (rpcrt4.@)
1012  */
1013 RPC_STATUS RPC_ENTRY RpcCancelThreadEx(void* ThreadHandle, LONG Timeout)
1014 {
1015     DWORD target_tid;
1016 
1017     FIXME("(%p, %d)\n", ThreadHandle, Timeout);
1018 
1019     target_tid = GetThreadId(ThreadHandle);
1020     if (!target_tid)
1021         return RPC_S_INVALID_ARG;
1022 
1023     if (Timeout)
1024     {
1025         FIXME("(%p, %d)\n", ThreadHandle, Timeout);
1026         return RPC_S_OK;
1027     }
1028     else
1029         return rpc_cancel_thread(target_tid);
1030 }
1031