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