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