ws2_32/tests: Add SO_ERROR [set|get]sockopt tests.
[wine] / dlls / ole32 / rpc.c
1 /*
2  *      RPC Manager
3  *
4  * Copyright 2001  Ove Kåven, TransGaming Technologies
5  * Copyright 2002  Marcus Meissner
6  * Copyright 2005  Mike Hearn, Rob Shearman for CodeWeavers
7  *
8  * This library is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU Lesser General Public
10  * License as published by the Free Software Foundation; either
11  * version 2.1 of the License, or (at your option) any later version.
12  *
13  * This library is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16  * Lesser General Public License for more details.
17  *
18  * You should have received a copy of the GNU Lesser General Public
19  * License along with this library; if not, write to the Free Software
20  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
21  */
22
23 #include "config.h"
24 #include "wine/port.h"
25
26 #include <stdarg.h>
27 #include <string.h>
28
29 #define COBJMACROS
30 #define NONAMELESSUNION
31 #define NONAMELESSSTRUCT
32
33 #include "windef.h"
34 #include "winbase.h"
35 #include "winuser.h"
36 #include "winsvc.h"
37 #include "objbase.h"
38 #include "ole2.h"
39 #include "rpc.h"
40 #include "winerror.h"
41 #include "winreg.h"
42 #include "wine/unicode.h"
43
44 #include "compobj_private.h"
45
46 #include "wine/debug.h"
47
48 WINE_DEFAULT_DEBUG_CHANNEL(ole);
49
50 static void __RPC_STUB dispatch_rpc(RPC_MESSAGE *msg);
51
52 /* we only use one function to dispatch calls for all methods - we use the
53  * RPC_IF_OLE flag to tell the RPC runtime that this is the case */
54 static RPC_DISPATCH_FUNCTION rpc_dispatch_table[1] = { dispatch_rpc }; /* (RO) */
55 static RPC_DISPATCH_TABLE rpc_dispatch = { 1, rpc_dispatch_table }; /* (RO) */
56
57 static struct list registered_interfaces = LIST_INIT(registered_interfaces); /* (CS csRegIf) */
58 static CRITICAL_SECTION csRegIf;
59 static CRITICAL_SECTION_DEBUG csRegIf_debug =
60 {
61     0, 0, &csRegIf,
62     { &csRegIf_debug.ProcessLocksList, &csRegIf_debug.ProcessLocksList },
63       0, 0, { (DWORD_PTR)(__FILE__ ": dcom registered server interfaces") }
64 };
65 static CRITICAL_SECTION csRegIf = { &csRegIf_debug, -1, 0, 0, 0, 0 };
66
67 static struct list channel_hooks = LIST_INIT(channel_hooks); /* (CS csChannelHook) */
68 static CRITICAL_SECTION csChannelHook;
69 static CRITICAL_SECTION_DEBUG csChannelHook_debug =
70 {
71     0, 0, &csChannelHook,
72     { &csChannelHook_debug.ProcessLocksList, &csChannelHook_debug.ProcessLocksList },
73       0, 0, { (DWORD_PTR)(__FILE__ ": channel hooks") }
74 };
75 static CRITICAL_SECTION csChannelHook = { &csChannelHook_debug, -1, 0, 0, 0, 0 };
76
77 static WCHAR wszRpcTransport[] = {'n','c','a','l','r','p','c',0};
78
79
80 struct registered_if
81 {
82     struct list entry;
83     DWORD refs; /* ref count */
84     RPC_SERVER_INTERFACE If; /* interface registered with the RPC runtime */
85 };
86
87 /* get the pipe endpoint specified of the specified apartment */
88 static inline void get_rpc_endpoint(LPWSTR endpoint, const OXID *oxid)
89 {
90     /* FIXME: should get endpoint from rpcss */
91     static const WCHAR wszEndpointFormat[] = {'\\','p','i','p','e','\\','O','L','E','_','%','0','8','l','x','%','0','8','l','x',0};
92     wsprintfW(endpoint, wszEndpointFormat, (DWORD)(*oxid >> 32),(DWORD)*oxid);
93 }
94
95 typedef struct
96 {
97     IRpcChannelBuffer IRpcChannelBuffer_iface;
98     LONG refs;
99
100     DWORD dest_context; /* returned from GetDestCtx */
101     void *dest_context_data; /* returned from GetDestCtx */
102 } RpcChannelBuffer;
103
104 typedef struct
105 {
106     RpcChannelBuffer       super; /* superclass */
107
108     RPC_BINDING_HANDLE     bind; /* handle to the remote server */
109     OXID                   oxid; /* apartment in which the channel is valid */
110     DWORD                  server_pid; /* id of server process */
111     HANDLE                 event; /* cached event handle */
112 } ClientRpcChannelBuffer;
113
114 struct dispatch_params
115 {
116     RPCOLEMESSAGE     *msg; /* message */
117     IRpcStubBuffer    *stub; /* stub buffer, if applicable */
118     IRpcChannelBuffer *chan; /* server channel buffer, if applicable */
119     IID                iid; /* ID of interface being called */
120     IUnknown          *iface; /* interface being called */
121     HANDLE             handle; /* handle that will become signaled when call finishes */
122     BOOL               bypass_rpcrt; /* bypass RPC runtime? */
123     RPC_STATUS         status; /* status (out) */
124     HRESULT            hr; /* hresult (out) */
125 };
126
127 struct message_state
128 {
129     RPC_BINDING_HANDLE binding_handle;
130     ULONG prefix_data_len;
131     SChannelHookCallInfo channel_hook_info;
132     BOOL bypass_rpcrt;
133
134     /* client only */
135     HWND target_hwnd;
136     DWORD target_tid;
137     struct dispatch_params params;
138 };
139
140 typedef struct
141 {
142     ULONG conformance; /* NDR */
143     GUID id;
144     ULONG size;
145     /* [size_is((size+7)&~7)] */ unsigned char data[1];
146 } WIRE_ORPC_EXTENT;
147
148 typedef struct
149 {
150     ULONG size;
151     ULONG reserved;
152     unsigned char extent[1];
153 } WIRE_ORPC_EXTENT_ARRAY;
154
155 typedef struct
156 {
157     ULONG version;
158     ULONG flags;
159     ULONG reserved1;
160     GUID  cid;
161     unsigned char extensions[1];
162 } WIRE_ORPCTHIS;
163
164 typedef struct
165 {
166     ULONG flags;
167     unsigned char extensions[1];
168 } WIRE_ORPCTHAT;
169
170 struct channel_hook_entry
171 {
172     struct list entry;
173     GUID id;
174     IChannelHook *hook;
175 };
176
177 struct channel_hook_buffer_data
178 {
179     GUID id;
180     ULONG extension_size;
181 };
182
183
184 static HRESULT unmarshal_ORPCTHAT(RPC_MESSAGE *msg, ORPCTHAT *orpcthat,
185                                   ORPC_EXTENT_ARRAY *orpc_ext_array, WIRE_ORPC_EXTENT **first_wire_orpc_extent);
186
187 /* Channel Hook Functions */
188
189 static ULONG ChannelHooks_ClientGetSize(SChannelHookCallInfo *info,
190     struct channel_hook_buffer_data **data, unsigned int *hook_count,
191     ULONG *extension_count)
192 {
193     struct channel_hook_entry *entry;
194     ULONG total_size = 0;
195     unsigned int hook_index = 0;
196
197     *hook_count = 0;
198     *extension_count = 0;
199
200     EnterCriticalSection(&csChannelHook);
201
202     LIST_FOR_EACH_ENTRY(entry, &channel_hooks, struct channel_hook_entry, entry)
203         (*hook_count)++;
204
205     if (*hook_count)
206         *data = HeapAlloc(GetProcessHeap(), 0, *hook_count * sizeof(struct channel_hook_buffer_data));
207     else
208         *data = NULL;
209
210     LIST_FOR_EACH_ENTRY(entry, &channel_hooks, struct channel_hook_entry, entry)
211     {
212         ULONG extension_size = 0;
213
214         IChannelHook_ClientGetSize(entry->hook, &entry->id, &info->iid, &extension_size);
215
216         TRACE("%s: extension_size = %u\n", debugstr_guid(&entry->id), extension_size);
217
218         extension_size = (extension_size+7)&~7;
219         (*data)[hook_index].id = entry->id;
220         (*data)[hook_index].extension_size = extension_size;
221
222         /* an extension is only put onto the wire if it has data to write */
223         if (extension_size)
224         {
225             total_size += FIELD_OFFSET(WIRE_ORPC_EXTENT, data[extension_size]);
226             (*extension_count)++;
227         }
228
229         hook_index++;
230     }
231
232     LeaveCriticalSection(&csChannelHook);
233
234     return total_size;
235 }
236
237 static unsigned char * ChannelHooks_ClientFillBuffer(SChannelHookCallInfo *info,
238     unsigned char *buffer, struct channel_hook_buffer_data *data,
239     unsigned int hook_count)
240 {
241     struct channel_hook_entry *entry;
242
243     EnterCriticalSection(&csChannelHook);
244
245     LIST_FOR_EACH_ENTRY(entry, &channel_hooks, struct channel_hook_entry, entry)
246     {
247         unsigned int i;
248         ULONG extension_size = 0;
249         WIRE_ORPC_EXTENT *wire_orpc_extent = (WIRE_ORPC_EXTENT *)buffer;
250
251         for (i = 0; i < hook_count; i++)
252             if (IsEqualGUID(&entry->id, &data[i].id))
253                 extension_size = data[i].extension_size;
254
255         /* an extension is only put onto the wire if it has data to write */
256         if (!extension_size)
257             continue;
258
259         IChannelHook_ClientFillBuffer(entry->hook, &entry->id, &info->iid,
260             &extension_size, buffer + FIELD_OFFSET(WIRE_ORPC_EXTENT, data[0]));
261
262         TRACE("%s: extension_size = %u\n", debugstr_guid(&entry->id), extension_size);
263
264         /* FIXME: set unused portion of wire_orpc_extent->data to 0? */
265
266         wire_orpc_extent->conformance = (extension_size+7)&~7;
267         wire_orpc_extent->size = extension_size;
268         wire_orpc_extent->id = entry->id;
269         buffer += FIELD_OFFSET(WIRE_ORPC_EXTENT, data[wire_orpc_extent->conformance]);
270     }
271
272     LeaveCriticalSection(&csChannelHook);
273
274     return buffer;
275 }
276
277 static void ChannelHooks_ServerNotify(SChannelHookCallInfo *info,
278     DWORD lDataRep, WIRE_ORPC_EXTENT *first_wire_orpc_extent,
279     ULONG extension_count)
280 {
281     struct channel_hook_entry *entry;
282     ULONG i;
283
284     EnterCriticalSection(&csChannelHook);
285
286     LIST_FOR_EACH_ENTRY(entry, &channel_hooks, struct channel_hook_entry, entry)
287     {
288         WIRE_ORPC_EXTENT *wire_orpc_extent;
289         for (i = 0, wire_orpc_extent = first_wire_orpc_extent;
290              i < extension_count;
291              i++, wire_orpc_extent = (WIRE_ORPC_EXTENT *)&wire_orpc_extent->data[wire_orpc_extent->conformance])
292         {
293             if (IsEqualGUID(&entry->id, &wire_orpc_extent->id))
294                 break;
295         }
296         if (i == extension_count) wire_orpc_extent = NULL;
297
298         IChannelHook_ServerNotify(entry->hook, &entry->id, &info->iid,
299             wire_orpc_extent ? wire_orpc_extent->size : 0,
300             wire_orpc_extent ? wire_orpc_extent->data : NULL,
301             lDataRep);
302     }
303
304     LeaveCriticalSection(&csChannelHook);
305 }
306
307 static ULONG ChannelHooks_ServerGetSize(SChannelHookCallInfo *info,
308                                         struct channel_hook_buffer_data **data, unsigned int *hook_count,
309                                         ULONG *extension_count)
310 {
311     struct channel_hook_entry *entry;
312     ULONG total_size = 0;
313     unsigned int hook_index = 0;
314
315     *hook_count = 0;
316     *extension_count = 0;
317
318     EnterCriticalSection(&csChannelHook);
319
320     LIST_FOR_EACH_ENTRY(entry, &channel_hooks, struct channel_hook_entry, entry)
321         (*hook_count)++;
322
323     if (*hook_count)
324         *data = HeapAlloc(GetProcessHeap(), 0, *hook_count * sizeof(struct channel_hook_buffer_data));
325     else
326         *data = NULL;
327
328     LIST_FOR_EACH_ENTRY(entry, &channel_hooks, struct channel_hook_entry, entry)
329     {
330         ULONG extension_size = 0;
331
332         IChannelHook_ServerGetSize(entry->hook, &entry->id, &info->iid, S_OK,
333                                    &extension_size);
334
335         TRACE("%s: extension_size = %u\n", debugstr_guid(&entry->id), extension_size);
336
337         extension_size = (extension_size+7)&~7;
338         (*data)[hook_index].id = entry->id;
339         (*data)[hook_index].extension_size = extension_size;
340
341         /* an extension is only put onto the wire if it has data to write */
342         if (extension_size)
343         {
344             total_size += FIELD_OFFSET(WIRE_ORPC_EXTENT, data[extension_size]);
345             (*extension_count)++;
346         }
347
348         hook_index++;
349     }
350
351     LeaveCriticalSection(&csChannelHook);
352
353     return total_size;
354 }
355
356 static unsigned char * ChannelHooks_ServerFillBuffer(SChannelHookCallInfo *info,
357                                                      unsigned char *buffer, struct channel_hook_buffer_data *data,
358                                                      unsigned int hook_count)
359 {
360     struct channel_hook_entry *entry;
361
362     EnterCriticalSection(&csChannelHook);
363
364     LIST_FOR_EACH_ENTRY(entry, &channel_hooks, struct channel_hook_entry, entry)
365     {
366         unsigned int i;
367         ULONG extension_size = 0;
368         WIRE_ORPC_EXTENT *wire_orpc_extent = (WIRE_ORPC_EXTENT *)buffer;
369
370         for (i = 0; i < hook_count; i++)
371             if (IsEqualGUID(&entry->id, &data[i].id))
372                 extension_size = data[i].extension_size;
373
374         /* an extension is only put onto the wire if it has data to write */
375         if (!extension_size)
376             continue;
377
378         IChannelHook_ServerFillBuffer(entry->hook, &entry->id, &info->iid,
379                                       &extension_size, buffer + FIELD_OFFSET(WIRE_ORPC_EXTENT, data[0]),
380                                       S_OK);
381
382         TRACE("%s: extension_size = %u\n", debugstr_guid(&entry->id), extension_size);
383
384         /* FIXME: set unused portion of wire_orpc_extent->data to 0? */
385
386         wire_orpc_extent->conformance = (extension_size+7)&~7;
387         wire_orpc_extent->size = extension_size;
388         wire_orpc_extent->id = entry->id;
389         buffer += FIELD_OFFSET(WIRE_ORPC_EXTENT, data[wire_orpc_extent->conformance]);
390     }
391
392     LeaveCriticalSection(&csChannelHook);
393
394     return buffer;
395 }
396
397 static void ChannelHooks_ClientNotify(SChannelHookCallInfo *info,
398                                       DWORD lDataRep, WIRE_ORPC_EXTENT *first_wire_orpc_extent,
399                                       ULONG extension_count, HRESULT hrFault)
400 {
401     struct channel_hook_entry *entry;
402     ULONG i;
403
404     EnterCriticalSection(&csChannelHook);
405
406     LIST_FOR_EACH_ENTRY(entry, &channel_hooks, struct channel_hook_entry, entry)
407     {
408         WIRE_ORPC_EXTENT *wire_orpc_extent;
409         for (i = 0, wire_orpc_extent = first_wire_orpc_extent;
410              i < extension_count;
411              i++, wire_orpc_extent = (WIRE_ORPC_EXTENT *)&wire_orpc_extent->data[wire_orpc_extent->conformance])
412         {
413             if (IsEqualGUID(&entry->id, &wire_orpc_extent->id))
414                 break;
415         }
416         if (i == extension_count) wire_orpc_extent = NULL;
417
418         IChannelHook_ClientNotify(entry->hook, &entry->id, &info->iid,
419                                   wire_orpc_extent ? wire_orpc_extent->size : 0,
420                                   wire_orpc_extent ? wire_orpc_extent->data : NULL,
421                                   lDataRep, hrFault);
422     }
423
424     LeaveCriticalSection(&csChannelHook);
425 }
426
427 HRESULT RPC_RegisterChannelHook(REFGUID rguid, IChannelHook *hook)
428 {
429     struct channel_hook_entry *entry;
430
431     TRACE("(%s, %p)\n", debugstr_guid(rguid), hook);
432
433     entry = HeapAlloc(GetProcessHeap(), 0, sizeof(*entry));
434     if (!entry)
435         return E_OUTOFMEMORY;
436
437     entry->id = *rguid;
438     entry->hook = hook;
439     IChannelHook_AddRef(hook);
440
441     EnterCriticalSection(&csChannelHook);
442     list_add_tail(&channel_hooks, &entry->entry);
443     LeaveCriticalSection(&csChannelHook);
444
445     return S_OK;
446 }
447
448 void RPC_UnregisterAllChannelHooks(void)
449 {
450     struct channel_hook_entry *cursor;
451     struct channel_hook_entry *cursor2;
452
453     EnterCriticalSection(&csChannelHook);
454     LIST_FOR_EACH_ENTRY_SAFE(cursor, cursor2, &channel_hooks, struct channel_hook_entry, entry)
455         HeapFree(GetProcessHeap(), 0, cursor);
456     LeaveCriticalSection(&csChannelHook);
457     DeleteCriticalSection(&csChannelHook);
458     DeleteCriticalSection(&csRegIf);
459 }
460
461 /* RPC Channel Buffer Functions */
462
463 static HRESULT WINAPI RpcChannelBuffer_QueryInterface(IRpcChannelBuffer *iface, REFIID riid, LPVOID *ppv)
464 {
465     *ppv = NULL;
466     if (IsEqualIID(riid,&IID_IRpcChannelBuffer) || IsEqualIID(riid,&IID_IUnknown))
467     {
468         *ppv = iface;
469         IRpcChannelBuffer_AddRef(iface);
470         return S_OK;
471     }
472     return E_NOINTERFACE;
473 }
474
475 static ULONG WINAPI RpcChannelBuffer_AddRef(LPRPCCHANNELBUFFER iface)
476 {
477     RpcChannelBuffer *This = (RpcChannelBuffer *)iface;
478     return InterlockedIncrement(&This->refs);
479 }
480
481 static ULONG WINAPI ServerRpcChannelBuffer_Release(LPRPCCHANNELBUFFER iface)
482 {
483     RpcChannelBuffer *This = (RpcChannelBuffer *)iface;
484     ULONG ref;
485
486     ref = InterlockedDecrement(&This->refs);
487     if (ref)
488         return ref;
489
490     HeapFree(GetProcessHeap(), 0, This);
491     return 0;
492 }
493
494 static ULONG WINAPI ClientRpcChannelBuffer_Release(LPRPCCHANNELBUFFER iface)
495 {
496     ClientRpcChannelBuffer *This = (ClientRpcChannelBuffer *)iface;
497     ULONG ref;
498
499     ref = InterlockedDecrement(&This->super.refs);
500     if (ref)
501         return ref;
502
503     if (This->event) CloseHandle(This->event);
504     RpcBindingFree(&This->bind);
505     HeapFree(GetProcessHeap(), 0, This);
506     return 0;
507 }
508
509 static HRESULT WINAPI ServerRpcChannelBuffer_GetBuffer(LPRPCCHANNELBUFFER iface, RPCOLEMESSAGE* olemsg, REFIID riid)
510 {
511     RpcChannelBuffer *This = (RpcChannelBuffer *)iface;
512     RPC_MESSAGE *msg = (RPC_MESSAGE *)olemsg;
513     RPC_STATUS status;
514     ORPCTHAT *orpcthat;
515     struct message_state *message_state;
516     ULONG extensions_size;
517     struct channel_hook_buffer_data *channel_hook_data;
518     unsigned int channel_hook_count;
519     ULONG extension_count;
520
521     TRACE("(%p)->(%p,%s)\n", This, olemsg, debugstr_guid(riid));
522
523     message_state = msg->Handle;
524     /* restore the binding handle and the real start of data */
525     msg->Handle = message_state->binding_handle;
526     msg->Buffer = (char *)msg->Buffer - message_state->prefix_data_len;
527
528     extensions_size = ChannelHooks_ServerGetSize(&message_state->channel_hook_info,
529                                                  &channel_hook_data, &channel_hook_count, &extension_count);
530
531     msg->BufferLength += FIELD_OFFSET(WIRE_ORPCTHAT, extensions) + sizeof(DWORD);
532     if (extensions_size)
533     {
534         msg->BufferLength += FIELD_OFFSET(WIRE_ORPC_EXTENT_ARRAY, extent[2*sizeof(DWORD) + extensions_size]);
535         if (extension_count & 1)
536             msg->BufferLength += FIELD_OFFSET(WIRE_ORPC_EXTENT, data[0]);
537     }
538
539     if (message_state->bypass_rpcrt)
540     {
541         msg->Buffer = HeapAlloc(GetProcessHeap(), 0, msg->BufferLength);
542         if (msg->Buffer)
543             status = RPC_S_OK;
544         else
545         {
546             HeapFree(GetProcessHeap(), 0, channel_hook_data);
547             return E_OUTOFMEMORY;
548         }
549     }
550     else
551         status = I_RpcGetBuffer(msg);
552
553     orpcthat = msg->Buffer;
554     msg->Buffer = (char *)msg->Buffer + FIELD_OFFSET(WIRE_ORPCTHAT, extensions);
555
556     orpcthat->flags = ORPCF_NULL /* FIXME? */;
557
558     /* NDR representation of orpcthat->extensions */
559     *(DWORD *)msg->Buffer = extensions_size ? 1 : 0;
560     msg->Buffer = (char *)msg->Buffer + sizeof(DWORD);
561
562     if (extensions_size)
563     {
564         WIRE_ORPC_EXTENT_ARRAY *orpc_extent_array = msg->Buffer;
565         orpc_extent_array->size = extension_count;
566         orpc_extent_array->reserved = 0;
567         msg->Buffer = (char *)msg->Buffer + FIELD_OFFSET(WIRE_ORPC_EXTENT_ARRAY, extent);
568         /* NDR representation of orpc_extent_array->extent */
569         *(DWORD *)msg->Buffer = 1;
570         msg->Buffer = (char *)msg->Buffer + sizeof(DWORD);
571         /* NDR representation of [size_is] attribute of orpc_extent_array->extent */
572         *(DWORD *)msg->Buffer = (extension_count + 1) & ~1;
573         msg->Buffer = (char *)msg->Buffer + sizeof(DWORD);
574
575         msg->Buffer = ChannelHooks_ServerFillBuffer(&message_state->channel_hook_info,
576                                                     msg->Buffer, channel_hook_data, channel_hook_count);
577
578         /* we must add a dummy extension if there is an odd extension
579          * count to meet the contract specified by the size_is attribute */
580         if (extension_count & 1)
581         {
582             WIRE_ORPC_EXTENT *wire_orpc_extent = msg->Buffer;
583             wire_orpc_extent->conformance = 0;
584             wire_orpc_extent->id = GUID_NULL;
585             wire_orpc_extent->size = 0;
586             msg->Buffer = (char *)msg->Buffer + FIELD_OFFSET(WIRE_ORPC_EXTENT, data[0]);
587         }
588     }
589
590     HeapFree(GetProcessHeap(), 0, channel_hook_data);
591
592     /* store the prefixed data length so that we can restore the real buffer
593      * later */
594     message_state->prefix_data_len = (char *)msg->Buffer - (char *)orpcthat;
595     msg->BufferLength -= message_state->prefix_data_len;
596     /* save away the message state again */
597     msg->Handle = message_state;
598
599     TRACE("-- %d\n", status);
600
601     return HRESULT_FROM_WIN32(status);
602 }
603
604 static HANDLE ClientRpcChannelBuffer_GetEventHandle(ClientRpcChannelBuffer *This)
605 {
606     HANDLE event = InterlockedExchangePointer(&This->event, NULL);
607
608     /* Note: must be auto-reset event so we can reuse it without a call
609     * to ResetEvent */
610     if (!event) event = CreateEventW(NULL, FALSE, FALSE, NULL);
611
612     return event;
613 }
614
615 static void ClientRpcChannelBuffer_ReleaseEventHandle(ClientRpcChannelBuffer *This, HANDLE event)
616 {
617     if (InterlockedCompareExchangePointer(&This->event, event, NULL))
618         /* already a handle cached in This */
619         CloseHandle(event);
620 }
621
622 static HRESULT WINAPI ClientRpcChannelBuffer_GetBuffer(LPRPCCHANNELBUFFER iface, RPCOLEMESSAGE* olemsg, REFIID riid)
623 {
624     ClientRpcChannelBuffer *This = (ClientRpcChannelBuffer *)iface;
625     RPC_MESSAGE *msg = (RPC_MESSAGE *)olemsg;
626     RPC_CLIENT_INTERFACE *cif;
627     RPC_STATUS status;
628     ORPCTHIS *orpcthis;
629     struct message_state *message_state;
630     ULONG extensions_size;
631     struct channel_hook_buffer_data *channel_hook_data;
632     unsigned int channel_hook_count;
633     ULONG extension_count;
634     IPID ipid;
635     HRESULT hr;
636     APARTMENT *apt = NULL;
637
638     TRACE("(%p)->(%p,%s)\n", This, olemsg, debugstr_guid(riid));
639
640     cif = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(RPC_CLIENT_INTERFACE));
641     if (!cif)
642         return E_OUTOFMEMORY;
643
644     message_state = HeapAlloc(GetProcessHeap(), 0, sizeof(*message_state));
645     if (!message_state)
646     {
647         HeapFree(GetProcessHeap(), 0, cif);
648         return E_OUTOFMEMORY;
649     }
650
651     cif->Length = sizeof(RPC_CLIENT_INTERFACE);
652     /* RPC interface ID = COM interface ID */
653     cif->InterfaceId.SyntaxGUID = *riid;
654     /* COM objects always have a version of 0.0 */
655     cif->InterfaceId.SyntaxVersion.MajorVersion = 0;
656     cif->InterfaceId.SyntaxVersion.MinorVersion = 0;
657     msg->Handle = This->bind;
658     msg->RpcInterfaceInformation = cif;
659
660     message_state->prefix_data_len = 0;
661     message_state->binding_handle = This->bind;
662
663     message_state->channel_hook_info.iid = *riid;
664     message_state->channel_hook_info.cbSize = sizeof(message_state->channel_hook_info);
665     message_state->channel_hook_info.uCausality = COM_CurrentCausalityId();
666     message_state->channel_hook_info.dwServerPid = This->server_pid;
667     message_state->channel_hook_info.iMethod = msg->ProcNum;
668     message_state->channel_hook_info.pObject = NULL; /* only present on server-side */
669     message_state->target_hwnd = NULL;
670     message_state->target_tid = 0;
671     memset(&message_state->params, 0, sizeof(message_state->params));
672
673     extensions_size = ChannelHooks_ClientGetSize(&message_state->channel_hook_info,
674         &channel_hook_data, &channel_hook_count, &extension_count);
675
676     msg->BufferLength += FIELD_OFFSET(WIRE_ORPCTHIS, extensions) + sizeof(DWORD);
677     if (extensions_size)
678     {
679         msg->BufferLength += FIELD_OFFSET(WIRE_ORPC_EXTENT_ARRAY, extent[2*sizeof(DWORD) + extensions_size]);
680         if (extension_count & 1)
681             msg->BufferLength += FIELD_OFFSET(WIRE_ORPC_EXTENT, data[0]);
682     }
683
684     RpcBindingInqObject(message_state->binding_handle, &ipid);
685     hr = ipid_get_dispatch_params(&ipid, &apt, &message_state->params.stub,
686                                   &message_state->params.chan,
687                                   &message_state->params.iid,
688                                   &message_state->params.iface);
689     if (hr == S_OK)
690     {
691         /* stub, chan, iface and iid are unneeded in multi-threaded case as we go
692          * via the RPC runtime */
693         if (apt->multi_threaded)
694         {
695             IRpcStubBuffer_Release(message_state->params.stub);
696             message_state->params.stub = NULL;
697             IRpcChannelBuffer_Release(message_state->params.chan);
698             message_state->params.chan = NULL;
699             message_state->params.iface = NULL;
700         }
701         else
702         {
703             message_state->params.bypass_rpcrt = TRUE;
704             message_state->target_hwnd = apartment_getwindow(apt);
705             message_state->target_tid = apt->tid;
706             /* we assume later on that this being non-NULL is the indicator that
707              * means call directly instead of going through RPC runtime */
708             if (!message_state->target_hwnd)
709                 ERR("window for apartment %s is NULL\n", wine_dbgstr_longlong(apt->oxid));
710         }
711     }
712     if (apt) apartment_release(apt);
713     message_state->params.handle = ClientRpcChannelBuffer_GetEventHandle(This);
714     /* Note: message_state->params.msg is initialised in
715      * ClientRpcChannelBuffer_SendReceive */
716
717     /* shortcut the RPC runtime */
718     if (message_state->target_hwnd)
719     {
720         msg->Buffer = HeapAlloc(GetProcessHeap(), 0, msg->BufferLength);
721         if (msg->Buffer)
722             status = RPC_S_OK;
723         else
724             status = ERROR_OUTOFMEMORY;
725     }
726     else
727         status = I_RpcGetBuffer(msg);
728
729     msg->Handle = message_state;
730
731     if (status == RPC_S_OK)
732     {
733         orpcthis = msg->Buffer;
734         msg->Buffer = (char *)msg->Buffer + FIELD_OFFSET(WIRE_ORPCTHIS, extensions);
735
736         orpcthis->version.MajorVersion = COM_MAJOR_VERSION;
737         orpcthis->version.MinorVersion = COM_MINOR_VERSION;
738         orpcthis->flags = message_state->channel_hook_info.dwServerPid ? ORPCF_LOCAL : ORPCF_NULL;
739         orpcthis->reserved1 = 0;
740         orpcthis->cid = message_state->channel_hook_info.uCausality;
741
742         /* NDR representation of orpcthis->extensions */
743         *(DWORD *)msg->Buffer = extensions_size ? 1 : 0;
744         msg->Buffer = (char *)msg->Buffer + sizeof(DWORD);
745
746         if (extensions_size)
747         {
748             ORPC_EXTENT_ARRAY *orpc_extent_array = msg->Buffer;
749             orpc_extent_array->size = extension_count;
750             orpc_extent_array->reserved = 0;
751             msg->Buffer = (char *)msg->Buffer + FIELD_OFFSET(WIRE_ORPC_EXTENT_ARRAY, extent);
752             /* NDR representation of orpc_extent_array->extent */
753             *(DWORD *)msg->Buffer = 1;
754             msg->Buffer = (char *)msg->Buffer + sizeof(DWORD);
755             /* NDR representation of [size_is] attribute of orpc_extent_array->extent */
756             *(DWORD *)msg->Buffer = (extension_count + 1) & ~1;
757             msg->Buffer = (char *)msg->Buffer + sizeof(DWORD);
758
759             msg->Buffer = ChannelHooks_ClientFillBuffer(&message_state->channel_hook_info,
760                 msg->Buffer, channel_hook_data, channel_hook_count);
761
762             /* we must add a dummy extension if there is an odd extension
763              * count to meet the contract specified by the size_is attribute */
764             if (extension_count & 1)
765             {
766                 WIRE_ORPC_EXTENT *wire_orpc_extent = msg->Buffer;
767                 wire_orpc_extent->conformance = 0;
768                 wire_orpc_extent->id = GUID_NULL;
769                 wire_orpc_extent->size = 0;
770                 msg->Buffer = (char *)msg->Buffer + FIELD_OFFSET(WIRE_ORPC_EXTENT, data[0]);
771             }
772         }
773
774         /* store the prefixed data length so that we can restore the real buffer
775          * pointer in ClientRpcChannelBuffer_SendReceive. */
776         message_state->prefix_data_len = (char *)msg->Buffer - (char *)orpcthis;
777         msg->BufferLength -= message_state->prefix_data_len;
778     }
779
780     HeapFree(GetProcessHeap(), 0, channel_hook_data);
781
782     TRACE("-- %d\n", status);
783
784     return HRESULT_FROM_WIN32(status);
785 }
786
787 static HRESULT WINAPI ServerRpcChannelBuffer_SendReceive(LPRPCCHANNELBUFFER iface, RPCOLEMESSAGE *olemsg, ULONG *pstatus)
788 {
789     FIXME("stub\n");
790     return E_NOTIMPL;
791 }
792
793 /* this thread runs an outgoing RPC */
794 static DWORD WINAPI rpc_sendreceive_thread(LPVOID param)
795 {
796     struct dispatch_params *data = param;
797
798     /* Note: I_RpcSendReceive doesn't raise exceptions like the higher-level
799      * RPC functions do */
800     data->status = I_RpcSendReceive((RPC_MESSAGE *)data->msg);
801
802     TRACE("completed with status 0x%x\n", data->status);
803
804     SetEvent(data->handle);
805
806     return 0;
807 }
808
809 static inline HRESULT ClientRpcChannelBuffer_IsCorrectApartment(ClientRpcChannelBuffer *This, APARTMENT *apt)
810 {
811     OXID oxid;
812     if (!apt)
813         return S_FALSE;
814     if (apartment_getoxid(apt, &oxid) != S_OK)
815         return S_FALSE;
816     if (This->oxid != oxid)
817         return S_FALSE;
818     return S_OK;
819 }
820
821 static HRESULT WINAPI ClientRpcChannelBuffer_SendReceive(LPRPCCHANNELBUFFER iface, RPCOLEMESSAGE *olemsg, ULONG *pstatus)
822 {
823     ClientRpcChannelBuffer *This = (ClientRpcChannelBuffer *)iface;
824     HRESULT hr;
825     RPC_MESSAGE *msg = (RPC_MESSAGE *)olemsg;
826     RPC_STATUS status;
827     DWORD index;
828     struct message_state *message_state;
829     ORPCTHAT orpcthat;
830     ORPC_EXTENT_ARRAY orpc_ext_array;
831     WIRE_ORPC_EXTENT *first_wire_orpc_extent = NULL;
832     HRESULT hrFault = S_OK;
833
834     TRACE("(%p) iMethod=%d\n", olemsg, olemsg->iMethod);
835
836     hr = ClientRpcChannelBuffer_IsCorrectApartment(This, COM_CurrentApt());
837     if (hr != S_OK)
838     {
839         ERR("called from wrong apartment, should have been 0x%s\n",
840             wine_dbgstr_longlong(This->oxid));
841         return RPC_E_WRONG_THREAD;
842     }
843     /* This situation should be impossible in multi-threaded apartments,
844      * because the calling thread isn't re-enterable.
845      * Note: doing a COM call during the processing of a sent message is
846      * only disallowed if a client call is already being waited for
847      * completion */
848     if (!COM_CurrentApt()->multi_threaded &&
849         COM_CurrentInfo()->pending_call_count_client &&
850         InSendMessage())
851     {
852         ERR("can't make an outgoing COM call in response to a sent message\n");
853         return RPC_E_CANTCALLOUT_ININPUTSYNCCALL;
854     }
855
856     message_state = msg->Handle;
857     /* restore the binding handle and the real start of data */
858     msg->Handle = message_state->binding_handle;
859     msg->Buffer = (char *)msg->Buffer - message_state->prefix_data_len;
860     msg->BufferLength += message_state->prefix_data_len;
861
862     /* Note: this is an optimization in the Microsoft OLE runtime that we need
863      * to copy, as shown by the test_no_couninitialize_client test. without
864      * short-circuiting the RPC runtime in the case below, the test will
865      * deadlock on the loader lock due to the RPC runtime needing to create
866      * a thread to process the RPC when this function is called indirectly
867      * from DllMain */
868
869     message_state->params.msg = olemsg;
870     if (message_state->params.bypass_rpcrt)
871     {
872         TRACE("Calling apartment thread 0x%08x...\n", message_state->target_tid);
873
874         msg->ProcNum &= ~RPC_FLAGS_VALID_BIT;
875
876         if (!PostMessageW(message_state->target_hwnd, DM_EXECUTERPC, 0,
877                           (LPARAM)&message_state->params))
878         {
879             ERR("PostMessage failed with error %u\n", GetLastError());
880
881             /* Note: message_state->params.iface doesn't have a reference and
882              * so doesn't need to be released */
883
884             hr = HRESULT_FROM_WIN32(GetLastError());
885         }
886     }
887     else
888     {
889         /* we use a separate thread here because we need to be able to
890          * pump the message loop in the application thread: if we do not,
891          * any windows created by this thread will hang and RPCs that try
892          * and re-enter this STA from an incoming server thread will
893          * deadlock. InstallShield is an example of that.
894          */
895         if (!QueueUserWorkItem(rpc_sendreceive_thread, &message_state->params, WT_EXECUTEDEFAULT))
896         {
897             ERR("QueueUserWorkItem failed with error %u\n", GetLastError());
898             hr = E_UNEXPECTED;
899         }
900         else
901             hr = S_OK;
902     }
903
904     if (hr == S_OK)
905     {
906         if (WaitForSingleObject(message_state->params.handle, 0))
907         {
908             COM_CurrentInfo()->pending_call_count_client++;
909             hr = CoWaitForMultipleHandles(0, INFINITE, 1, &message_state->params.handle, &index);
910             COM_CurrentInfo()->pending_call_count_client--;
911         }
912     }
913     ClientRpcChannelBuffer_ReleaseEventHandle(This, message_state->params.handle);
914
915     /* for WM shortcut, faults are returned in params->hr */
916     if (hr == S_OK)
917         hrFault = message_state->params.hr;
918
919     status = message_state->params.status;
920
921     orpcthat.flags = ORPCF_NULL;
922     orpcthat.extensions = NULL;
923
924     TRACE("RPC call status: 0x%x\n", status);
925     if (status != RPC_S_OK)
926         hr = HRESULT_FROM_WIN32(status);
927
928     TRACE("hrFault = 0x%08x\n", hrFault);
929
930     /* FIXME: this condition should be
931      * "hr == S_OK && (!hrFault || msg->BufferLength > FIELD_OFFSET(ORPCTHAT, extensions) + 4)"
932      * but we don't currently reset the message length for PostMessage
933      * dispatched calls */
934     if (hr == S_OK && hrFault == S_OK)
935     {
936         HRESULT hr2;
937         char *original_buffer = msg->Buffer;
938
939         /* handle ORPCTHAT and client extensions */
940
941         hr2 = unmarshal_ORPCTHAT(msg, &orpcthat, &orpc_ext_array, &first_wire_orpc_extent);
942         if (FAILED(hr2))
943             hr = hr2;
944
945         message_state->prefix_data_len = (char *)msg->Buffer - original_buffer;
946         msg->BufferLength -= message_state->prefix_data_len;
947     }
948     else
949         message_state->prefix_data_len = 0;
950
951     if (hr == S_OK)
952     {
953         ChannelHooks_ClientNotify(&message_state->channel_hook_info,
954                                   msg->DataRepresentation,
955                                   first_wire_orpc_extent,
956                                   orpcthat.extensions && first_wire_orpc_extent ? orpcthat.extensions->size : 0,
957                                   hrFault);
958     }
959
960     /* save away the message state again */
961     msg->Handle = message_state;
962
963     if (pstatus) *pstatus = status;
964
965     if (hr == S_OK)
966         hr = hrFault;
967
968     TRACE("-- 0x%08x\n", hr);
969
970     return hr;
971 }
972
973 static HRESULT WINAPI ServerRpcChannelBuffer_FreeBuffer(LPRPCCHANNELBUFFER iface, RPCOLEMESSAGE* olemsg)
974 {
975     RPC_MESSAGE *msg = (RPC_MESSAGE *)olemsg;
976     RPC_STATUS status;
977     struct message_state *message_state;
978
979     TRACE("(%p)\n", msg);
980
981     message_state = msg->Handle;
982     /* restore the binding handle and the real start of data */
983     msg->Handle = message_state->binding_handle;
984     msg->Buffer = (char *)msg->Buffer - message_state->prefix_data_len;
985     msg->BufferLength += message_state->prefix_data_len;
986     message_state->prefix_data_len = 0;
987
988     if (message_state->bypass_rpcrt)
989     {
990         HeapFree(GetProcessHeap(), 0, msg->Buffer);
991         status = RPC_S_OK;
992     }
993     else
994         status = I_RpcFreeBuffer(msg);
995
996     msg->Handle = message_state;
997
998     TRACE("-- %d\n", status);
999
1000     return HRESULT_FROM_WIN32(status);
1001 }
1002
1003 static HRESULT WINAPI ClientRpcChannelBuffer_FreeBuffer(LPRPCCHANNELBUFFER iface, RPCOLEMESSAGE* olemsg)
1004 {
1005     RPC_MESSAGE *msg = (RPC_MESSAGE *)olemsg;
1006     RPC_STATUS status;
1007     struct message_state *message_state;
1008
1009     TRACE("(%p)\n", msg);
1010
1011     message_state = msg->Handle;
1012     /* restore the binding handle and the real start of data */
1013     msg->Handle = message_state->binding_handle;
1014     msg->Buffer = (char *)msg->Buffer - message_state->prefix_data_len;
1015     msg->BufferLength += message_state->prefix_data_len;
1016
1017     if (message_state->params.bypass_rpcrt)
1018     {
1019         HeapFree(GetProcessHeap(), 0, msg->Buffer);
1020         status = RPC_S_OK;
1021     }
1022     else
1023         status = I_RpcFreeBuffer(msg);
1024
1025     HeapFree(GetProcessHeap(), 0, msg->RpcInterfaceInformation);
1026     msg->RpcInterfaceInformation = NULL;
1027
1028     if (message_state->params.stub)
1029         IRpcStubBuffer_Release(message_state->params.stub);
1030     if (message_state->params.chan)
1031         IRpcChannelBuffer_Release(message_state->params.chan);
1032     HeapFree(GetProcessHeap(), 0, message_state);
1033
1034     TRACE("-- %d\n", status);
1035
1036     return HRESULT_FROM_WIN32(status);
1037 }
1038
1039 static HRESULT WINAPI ClientRpcChannelBuffer_GetDestCtx(LPRPCCHANNELBUFFER iface, DWORD* pdwDestContext, void** ppvDestContext)
1040 {
1041     ClientRpcChannelBuffer *This = (ClientRpcChannelBuffer *)iface;
1042
1043     TRACE("(%p,%p)\n", pdwDestContext, ppvDestContext);
1044
1045     *pdwDestContext = This->super.dest_context;
1046     *ppvDestContext = This->super.dest_context_data;
1047
1048     return S_OK;
1049 }
1050
1051 static HRESULT WINAPI ServerRpcChannelBuffer_GetDestCtx(LPRPCCHANNELBUFFER iface, DWORD* dest_context, void** dest_context_data)
1052 {
1053     RpcChannelBuffer *This = (RpcChannelBuffer *)iface;
1054
1055     TRACE("(%p,%p)\n", dest_context, dest_context_data);
1056
1057     *dest_context = This->dest_context;
1058     *dest_context_data = This->dest_context_data;
1059     return S_OK;
1060 }
1061
1062 static HRESULT WINAPI RpcChannelBuffer_IsConnected(LPRPCCHANNELBUFFER iface)
1063 {
1064     TRACE("()\n");
1065     /* native does nothing too */
1066     return S_OK;
1067 }
1068
1069 static const IRpcChannelBufferVtbl ClientRpcChannelBufferVtbl =
1070 {
1071     RpcChannelBuffer_QueryInterface,
1072     RpcChannelBuffer_AddRef,
1073     ClientRpcChannelBuffer_Release,
1074     ClientRpcChannelBuffer_GetBuffer,
1075     ClientRpcChannelBuffer_SendReceive,
1076     ClientRpcChannelBuffer_FreeBuffer,
1077     ClientRpcChannelBuffer_GetDestCtx,
1078     RpcChannelBuffer_IsConnected
1079 };
1080
1081 static const IRpcChannelBufferVtbl ServerRpcChannelBufferVtbl =
1082 {
1083     RpcChannelBuffer_QueryInterface,
1084     RpcChannelBuffer_AddRef,
1085     ServerRpcChannelBuffer_Release,
1086     ServerRpcChannelBuffer_GetBuffer,
1087     ServerRpcChannelBuffer_SendReceive,
1088     ServerRpcChannelBuffer_FreeBuffer,
1089     ServerRpcChannelBuffer_GetDestCtx,
1090     RpcChannelBuffer_IsConnected
1091 };
1092
1093 /* returns a channel buffer for proxies */
1094 HRESULT RPC_CreateClientChannel(const OXID *oxid, const IPID *ipid,
1095                                 const OXID_INFO *oxid_info,
1096                                 DWORD dest_context, void *dest_context_data,
1097                                 IRpcChannelBuffer **chan)
1098 {
1099     ClientRpcChannelBuffer *This;
1100     WCHAR                   endpoint[200];
1101     RPC_BINDING_HANDLE      bind;
1102     RPC_STATUS              status;
1103     LPWSTR                  string_binding;
1104
1105     /* FIXME: get the endpoint from oxid_info->psa instead */
1106     get_rpc_endpoint(endpoint, oxid);
1107
1108     TRACE("proxy pipe: connecting to endpoint: %s\n", debugstr_w(endpoint));
1109
1110     status = RpcStringBindingComposeW(
1111         NULL,
1112         wszRpcTransport,
1113         NULL,
1114         endpoint,
1115         NULL,
1116         &string_binding);
1117         
1118     if (status == RPC_S_OK)
1119     {
1120         status = RpcBindingFromStringBindingW(string_binding, &bind);
1121
1122         if (status == RPC_S_OK)
1123         {
1124             IPID ipid2 = *ipid; /* why can't RpcBindingSetObject take a const? */
1125             status = RpcBindingSetObject(bind, &ipid2);
1126             if (status != RPC_S_OK)
1127                 RpcBindingFree(&bind);
1128         }
1129
1130         RpcStringFreeW(&string_binding);
1131     }
1132
1133     if (status != RPC_S_OK)
1134     {
1135         ERR("Couldn't get binding for endpoint %s, status = %d\n", debugstr_w(endpoint), status);
1136         return HRESULT_FROM_WIN32(status);
1137     }
1138
1139     This = HeapAlloc(GetProcessHeap(), 0, sizeof(*This));
1140     if (!This)
1141     {
1142         RpcBindingFree(&bind);
1143         return E_OUTOFMEMORY;
1144     }
1145
1146     This->super.IRpcChannelBuffer_iface.lpVtbl = &ClientRpcChannelBufferVtbl;
1147     This->super.refs = 1;
1148     This->super.dest_context = dest_context;
1149     This->super.dest_context_data = dest_context_data;
1150     This->bind = bind;
1151     apartment_getoxid(COM_CurrentApt(), &This->oxid);
1152     This->server_pid = oxid_info->dwPid;
1153     This->event = NULL;
1154
1155     *chan = &This->super.IRpcChannelBuffer_iface;
1156
1157     return S_OK;
1158 }
1159
1160 HRESULT RPC_CreateServerChannel(DWORD dest_context, void *dest_context_data, IRpcChannelBuffer **chan)
1161 {
1162     RpcChannelBuffer *This = HeapAlloc(GetProcessHeap(), 0, sizeof(*This));
1163     if (!This)
1164         return E_OUTOFMEMORY;
1165
1166     This->IRpcChannelBuffer_iface.lpVtbl = &ServerRpcChannelBufferVtbl;
1167     This->refs = 1;
1168     This->dest_context = dest_context;
1169     This->dest_context_data = dest_context_data;
1170     
1171     *chan = &This->IRpcChannelBuffer_iface;
1172
1173     return S_OK;
1174 }
1175
1176 /* unmarshals ORPC_EXTENT_ARRAY according to NDR rules, but doesn't allocate
1177  * any memory */
1178 static HRESULT unmarshal_ORPC_EXTENT_ARRAY(RPC_MESSAGE *msg, const char *end,
1179                                            ORPC_EXTENT_ARRAY *extensions,
1180                                            WIRE_ORPC_EXTENT **first_wire_orpc_extent)
1181 {
1182     DWORD pointer_id;
1183     DWORD i;
1184
1185     memcpy(extensions, msg->Buffer, FIELD_OFFSET(WIRE_ORPC_EXTENT_ARRAY, extent));
1186     msg->Buffer = (char *)msg->Buffer + FIELD_OFFSET(WIRE_ORPC_EXTENT_ARRAY, extent);
1187
1188     if ((const char *)msg->Buffer + 2 * sizeof(DWORD) > end)
1189         return RPC_E_INVALID_HEADER;
1190
1191     pointer_id = *(DWORD *)msg->Buffer;
1192     msg->Buffer = (char *)msg->Buffer + sizeof(DWORD);
1193     extensions->extent = NULL;
1194
1195     if (pointer_id)
1196     {
1197         WIRE_ORPC_EXTENT *wire_orpc_extent;
1198
1199         /* conformance */
1200         if (*(DWORD *)msg->Buffer != ((extensions->size+1)&~1))
1201             return RPC_S_INVALID_BOUND;
1202
1203         msg->Buffer = (char *)msg->Buffer + sizeof(DWORD);
1204
1205         /* arbitrary limit for security (don't know what native does) */
1206         if (extensions->size > 256)
1207         {
1208             ERR("too many extensions: %d\n", extensions->size);
1209             return RPC_S_INVALID_BOUND;
1210         }
1211
1212         *first_wire_orpc_extent = wire_orpc_extent = msg->Buffer;
1213         for (i = 0; i < ((extensions->size+1)&~1); i++)
1214         {
1215             if ((const char *)&wire_orpc_extent->data[0] > end)
1216                 return RPC_S_INVALID_BOUND;
1217             if (wire_orpc_extent->conformance != ((wire_orpc_extent->size+7)&~7))
1218                 return RPC_S_INVALID_BOUND;
1219             if ((const char *)&wire_orpc_extent->data[wire_orpc_extent->conformance] > end)
1220                 return RPC_S_INVALID_BOUND;
1221             TRACE("size %u, guid %s\n", wire_orpc_extent->size, debugstr_guid(&wire_orpc_extent->id));
1222             wire_orpc_extent = (WIRE_ORPC_EXTENT *)&wire_orpc_extent->data[wire_orpc_extent->conformance];
1223         }
1224         msg->Buffer = wire_orpc_extent;
1225     }
1226
1227     return S_OK;
1228 }
1229
1230 /* unmarshals ORPCTHIS according to NDR rules, but doesn't allocate any memory */
1231 static HRESULT unmarshal_ORPCTHIS(RPC_MESSAGE *msg, ORPCTHIS *orpcthis,
1232     ORPC_EXTENT_ARRAY *orpc_ext_array, WIRE_ORPC_EXTENT **first_wire_orpc_extent)
1233 {
1234     const char *end = (char *)msg->Buffer + msg->BufferLength;
1235
1236     *first_wire_orpc_extent = NULL;
1237
1238     if (msg->BufferLength < FIELD_OFFSET(WIRE_ORPCTHIS, extensions) + sizeof(DWORD))
1239     {
1240         ERR("invalid buffer length\n");
1241         return RPC_E_INVALID_HEADER;
1242     }
1243
1244     memcpy(orpcthis, msg->Buffer, FIELD_OFFSET(WIRE_ORPCTHIS, extensions));
1245     msg->Buffer = (char *)msg->Buffer + FIELD_OFFSET(WIRE_ORPCTHIS, extensions);
1246
1247     if ((const char *)msg->Buffer + sizeof(DWORD) > end)
1248         return RPC_E_INVALID_HEADER;
1249
1250     if (*(DWORD *)msg->Buffer)
1251         orpcthis->extensions = orpc_ext_array;
1252     else
1253         orpcthis->extensions = NULL;
1254
1255     msg->Buffer = (char *)msg->Buffer + sizeof(DWORD);
1256
1257     if (orpcthis->extensions)
1258     {
1259         HRESULT hr = unmarshal_ORPC_EXTENT_ARRAY(msg, end, orpc_ext_array,
1260                                                  first_wire_orpc_extent);
1261         if (FAILED(hr))
1262             return hr;
1263     }
1264
1265     if ((orpcthis->version.MajorVersion != COM_MAJOR_VERSION) ||
1266         (orpcthis->version.MinorVersion > COM_MINOR_VERSION))
1267     {
1268         ERR("COM version {%d, %d} not supported\n",
1269             orpcthis->version.MajorVersion, orpcthis->version.MinorVersion);
1270         return RPC_E_VERSION_MISMATCH;
1271     }
1272
1273     if (orpcthis->flags & ~(ORPCF_LOCAL|ORPCF_RESERVED1|ORPCF_RESERVED2|ORPCF_RESERVED3|ORPCF_RESERVED4))
1274     {
1275         ERR("invalid flags 0x%x\n", orpcthis->flags & ~(ORPCF_LOCAL|ORPCF_RESERVED1|ORPCF_RESERVED2|ORPCF_RESERVED3|ORPCF_RESERVED4));
1276         return RPC_E_INVALID_HEADER;
1277     }
1278
1279     return S_OK;
1280 }
1281
1282 static HRESULT unmarshal_ORPCTHAT(RPC_MESSAGE *msg, ORPCTHAT *orpcthat,
1283                                   ORPC_EXTENT_ARRAY *orpc_ext_array, WIRE_ORPC_EXTENT **first_wire_orpc_extent)
1284 {
1285     const char *end = (char *)msg->Buffer + msg->BufferLength;
1286
1287     *first_wire_orpc_extent = NULL;
1288
1289     if (msg->BufferLength < FIELD_OFFSET(WIRE_ORPCTHAT, extensions) + sizeof(DWORD))
1290     {
1291         ERR("invalid buffer length\n");
1292         return RPC_E_INVALID_HEADER;
1293     }
1294
1295     memcpy(orpcthat, msg->Buffer, FIELD_OFFSET(WIRE_ORPCTHAT, extensions));
1296     msg->Buffer = (char *)msg->Buffer + FIELD_OFFSET(WIRE_ORPCTHAT, extensions);
1297
1298     if ((const char *)msg->Buffer + sizeof(DWORD) > end)
1299         return RPC_E_INVALID_HEADER;
1300
1301     if (*(DWORD *)msg->Buffer)
1302         orpcthat->extensions = orpc_ext_array;
1303     else
1304         orpcthat->extensions = NULL;
1305
1306     msg->Buffer = (char *)msg->Buffer + sizeof(DWORD);
1307
1308     if (orpcthat->extensions)
1309     {
1310         HRESULT hr = unmarshal_ORPC_EXTENT_ARRAY(msg, end, orpc_ext_array,
1311                                                  first_wire_orpc_extent);
1312         if (FAILED(hr))
1313             return hr;
1314     }
1315
1316     if (orpcthat->flags & ~(ORPCF_LOCAL|ORPCF_RESERVED1|ORPCF_RESERVED2|ORPCF_RESERVED3|ORPCF_RESERVED4))
1317     {
1318         ERR("invalid flags 0x%x\n", orpcthat->flags & ~(ORPCF_LOCAL|ORPCF_RESERVED1|ORPCF_RESERVED2|ORPCF_RESERVED3|ORPCF_RESERVED4));
1319         return RPC_E_INVALID_HEADER;
1320     }
1321
1322     return S_OK;
1323 }
1324
1325 void RPC_ExecuteCall(struct dispatch_params *params)
1326 {
1327     struct message_state *message_state = NULL;
1328     RPC_MESSAGE *msg = (RPC_MESSAGE *)params->msg;
1329     char *original_buffer = msg->Buffer;
1330     ORPCTHIS orpcthis;
1331     ORPC_EXTENT_ARRAY orpc_ext_array;
1332     WIRE_ORPC_EXTENT *first_wire_orpc_extent;
1333     GUID old_causality_id;
1334
1335     /* handle ORPCTHIS and server extensions */
1336
1337     params->hr = unmarshal_ORPCTHIS(msg, &orpcthis, &orpc_ext_array, &first_wire_orpc_extent);
1338     if (params->hr != S_OK)
1339     {
1340         msg->Buffer = original_buffer;
1341         goto exit;
1342     }
1343
1344     message_state = HeapAlloc(GetProcessHeap(), 0, sizeof(*message_state));
1345     if (!message_state)
1346     {
1347         params->hr = E_OUTOFMEMORY;
1348         msg->Buffer = original_buffer;
1349         goto exit;
1350     }
1351
1352     message_state->prefix_data_len = (char *)msg->Buffer - original_buffer;
1353     message_state->binding_handle = msg->Handle;
1354     message_state->bypass_rpcrt = params->bypass_rpcrt;
1355
1356     message_state->channel_hook_info.iid = params->iid;
1357     message_state->channel_hook_info.cbSize = sizeof(message_state->channel_hook_info);
1358     message_state->channel_hook_info.uCausality = orpcthis.cid;
1359     message_state->channel_hook_info.dwServerPid = GetCurrentProcessId();
1360     message_state->channel_hook_info.iMethod = msg->ProcNum;
1361     message_state->channel_hook_info.pObject = params->iface;
1362
1363     if (orpcthis.extensions && first_wire_orpc_extent &&
1364         orpcthis.extensions->size)
1365         ChannelHooks_ServerNotify(&message_state->channel_hook_info, msg->DataRepresentation, first_wire_orpc_extent, orpcthis.extensions->size);
1366
1367     msg->Handle = message_state;
1368     msg->BufferLength -= message_state->prefix_data_len;
1369
1370     /* call message filter */
1371
1372     if (COM_CurrentApt()->filter)
1373     {
1374         DWORD handlecall;
1375         INTERFACEINFO interface_info;
1376         CALLTYPE calltype;
1377
1378         interface_info.pUnk = params->iface;
1379         interface_info.iid = params->iid;
1380         interface_info.wMethod = msg->ProcNum;
1381
1382         if (IsEqualGUID(&orpcthis.cid, &COM_CurrentInfo()->causality_id))
1383             calltype = CALLTYPE_NESTED;
1384         else if (COM_CurrentInfo()->pending_call_count_server == 0)
1385             calltype = CALLTYPE_TOPLEVEL;
1386         else
1387             calltype = CALLTYPE_TOPLEVEL_CALLPENDING;
1388
1389         handlecall = IMessageFilter_HandleInComingCall(COM_CurrentApt()->filter,
1390                                                        calltype,
1391                                                        UlongToHandle(GetCurrentProcessId()),
1392                                                        0 /* FIXME */,
1393                                                        &interface_info);
1394         TRACE("IMessageFilter_HandleInComingCall returned %d\n", handlecall);
1395         switch (handlecall)
1396         {
1397         case SERVERCALL_REJECTED:
1398             params->hr = RPC_E_CALL_REJECTED;
1399             goto exit_reset_state;
1400         case SERVERCALL_RETRYLATER:
1401 #if 0 /* FIXME: handle retries on the client side before enabling this code */
1402             params->hr = RPC_E_RETRY;
1403             goto exit_reset_state;
1404 #else
1405             FIXME("retry call later not implemented\n");
1406             break;
1407 #endif
1408         case SERVERCALL_ISHANDLED:
1409         default:
1410             break;
1411         }
1412     }
1413
1414     /* invoke the method */
1415
1416     /* save the old causality ID - note: any calls executed while processing
1417      * messages received during the SendReceive will appear to originate from
1418      * this call - this should be checked with what Windows does */
1419     old_causality_id = COM_CurrentInfo()->causality_id;
1420     COM_CurrentInfo()->causality_id = orpcthis.cid;
1421     COM_CurrentInfo()->pending_call_count_server++;
1422     params->hr = IRpcStubBuffer_Invoke(params->stub, params->msg, params->chan);
1423     COM_CurrentInfo()->pending_call_count_server--;
1424     COM_CurrentInfo()->causality_id = old_causality_id;
1425
1426     /* the invoke allocated a new buffer, so free the old one */
1427     if (message_state->bypass_rpcrt && original_buffer != msg->Buffer)
1428         HeapFree(GetProcessHeap(), 0, original_buffer);
1429
1430 exit_reset_state:
1431     message_state = msg->Handle;
1432     msg->Handle = message_state->binding_handle;
1433     msg->Buffer = (char *)msg->Buffer - message_state->prefix_data_len;
1434     msg->BufferLength += message_state->prefix_data_len;
1435
1436 exit:
1437     HeapFree(GetProcessHeap(), 0, message_state);
1438     if (params->handle) SetEvent(params->handle);
1439 }
1440
1441 static void __RPC_STUB dispatch_rpc(RPC_MESSAGE *msg)
1442 {
1443     struct dispatch_params *params;
1444     APARTMENT *apt;
1445     IPID ipid;
1446     HRESULT hr;
1447
1448     RpcBindingInqObject(msg->Handle, &ipid);
1449
1450     TRACE("ipid = %s, iMethod = %d\n", debugstr_guid(&ipid), msg->ProcNum);
1451
1452     params = HeapAlloc(GetProcessHeap(), 0, sizeof(*params));
1453     if (!params)
1454     {
1455         RpcRaiseException(E_OUTOFMEMORY);
1456         return;
1457     }
1458
1459     hr = ipid_get_dispatch_params(&ipid, &apt, &params->stub, &params->chan,
1460                                   &params->iid, &params->iface);
1461     if (hr != S_OK)
1462     {
1463         ERR("no apartment found for ipid %s\n", debugstr_guid(&ipid));
1464         HeapFree(GetProcessHeap(), 0, params);
1465         RpcRaiseException(hr);
1466         return;
1467     }
1468
1469     params->msg = (RPCOLEMESSAGE *)msg;
1470     params->status = RPC_S_OK;
1471     params->hr = S_OK;
1472     params->handle = NULL;
1473     params->bypass_rpcrt = FALSE;
1474
1475     /* Note: this is the important difference between STAs and MTAs - we
1476      * always execute RPCs to STAs in the thread that originally created the
1477      * apartment (i.e. the one that pumps messages to the window) */
1478     if (!apt->multi_threaded)
1479     {
1480         params->handle = CreateEventW(NULL, FALSE, FALSE, NULL);
1481
1482         TRACE("Calling apartment thread 0x%08x...\n", apt->tid);
1483
1484         if (PostMessageW(apartment_getwindow(apt), DM_EXECUTERPC, 0, (LPARAM)params))
1485             WaitForSingleObject(params->handle, INFINITE);
1486         else
1487         {
1488             ERR("PostMessage failed with error %u\n", GetLastError());
1489             IRpcChannelBuffer_Release(params->chan);
1490             IRpcStubBuffer_Release(params->stub);
1491         }
1492         CloseHandle(params->handle);
1493     }
1494     else
1495     {
1496         BOOL joined = FALSE;
1497         if (!COM_CurrentInfo()->apt)
1498         {
1499             apartment_joinmta();
1500             joined = TRUE;
1501         }
1502         RPC_ExecuteCall(params);
1503         if (joined)
1504         {
1505             apartment_release(COM_CurrentInfo()->apt);
1506             COM_CurrentInfo()->apt = NULL;
1507         }
1508     }
1509
1510     hr = params->hr;
1511     if (params->chan)
1512         IRpcChannelBuffer_Release(params->chan);
1513     if (params->stub)
1514         IRpcStubBuffer_Release(params->stub);
1515     HeapFree(GetProcessHeap(), 0, params);
1516
1517     apartment_release(apt);
1518
1519     /* if IRpcStubBuffer_Invoke fails, we should raise an exception to tell
1520      * the RPC runtime that the call failed */
1521     if (hr) RpcRaiseException(hr);
1522 }
1523
1524 /* stub registration */
1525 HRESULT RPC_RegisterInterface(REFIID riid)
1526 {
1527     struct registered_if *rif;
1528     BOOL found = FALSE;
1529     HRESULT hr = S_OK;
1530     
1531     TRACE("(%s)\n", debugstr_guid(riid));
1532
1533     EnterCriticalSection(&csRegIf);
1534     LIST_FOR_EACH_ENTRY(rif, &registered_interfaces, struct registered_if, entry)
1535     {
1536         if (IsEqualGUID(&rif->If.InterfaceId.SyntaxGUID, riid))
1537         {
1538             rif->refs++;
1539             found = TRUE;
1540             break;
1541         }
1542     }
1543     if (!found)
1544     {
1545         TRACE("Creating new interface\n");
1546
1547         rif = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*rif));
1548         if (rif)
1549         {
1550             RPC_STATUS status;
1551
1552             rif->refs = 1;
1553             rif->If.Length = sizeof(RPC_SERVER_INTERFACE);
1554             /* RPC interface ID = COM interface ID */
1555             rif->If.InterfaceId.SyntaxGUID = *riid;
1556             rif->If.DispatchTable = &rpc_dispatch;
1557             /* all other fields are 0, including the version asCOM objects
1558              * always have a version of 0.0 */
1559             status = RpcServerRegisterIfEx(
1560                 (RPC_IF_HANDLE)&rif->If,
1561                 NULL, NULL,
1562                 RPC_IF_OLE | RPC_IF_AUTOLISTEN,
1563                 RPC_C_LISTEN_MAX_CALLS_DEFAULT,
1564                 NULL);
1565             if (status == RPC_S_OK)
1566                 list_add_tail(&registered_interfaces, &rif->entry);
1567             else
1568             {
1569                 ERR("RpcServerRegisterIfEx failed with error %d\n", status);
1570                 HeapFree(GetProcessHeap(), 0, rif);
1571                 hr = HRESULT_FROM_WIN32(status);
1572             }
1573         }
1574         else
1575             hr = E_OUTOFMEMORY;
1576     }
1577     LeaveCriticalSection(&csRegIf);
1578     return hr;
1579 }
1580
1581 /* stub unregistration */
1582 void RPC_UnregisterInterface(REFIID riid)
1583 {
1584     struct registered_if *rif;
1585     EnterCriticalSection(&csRegIf);
1586     LIST_FOR_EACH_ENTRY(rif, &registered_interfaces, struct registered_if, entry)
1587     {
1588         if (IsEqualGUID(&rif->If.InterfaceId.SyntaxGUID, riid))
1589         {
1590             if (!--rif->refs)
1591             {
1592                 RpcServerUnregisterIf((RPC_IF_HANDLE)&rif->If, NULL, TRUE);
1593                 list_remove(&rif->entry);
1594                 HeapFree(GetProcessHeap(), 0, rif);
1595             }
1596             break;
1597         }
1598     }
1599     LeaveCriticalSection(&csRegIf);
1600 }
1601
1602 /* get the info for an OXID, including the IPID for the rem unknown interface
1603  * and the string binding */
1604 HRESULT RPC_ResolveOxid(OXID oxid, OXID_INFO *oxid_info)
1605 {
1606     TRACE("%s\n", wine_dbgstr_longlong(oxid));
1607
1608     oxid_info->dwTid = 0;
1609     oxid_info->dwPid = 0;
1610     oxid_info->dwAuthnHint = RPC_C_AUTHN_LEVEL_NONE;
1611     /* FIXME: this is a hack around not having an OXID resolver yet -
1612      * this function should contact the machine's OXID resolver and then it
1613      * should give us the IPID of the IRemUnknown interface */
1614     oxid_info->ipidRemUnknown.Data1 = 0xffffffff;
1615     oxid_info->ipidRemUnknown.Data2 = 0xffff;
1616     oxid_info->ipidRemUnknown.Data3 = 0xffff;
1617     memcpy(oxid_info->ipidRemUnknown.Data4, &oxid, sizeof(OXID));
1618     oxid_info->psa = NULL /* FIXME */;
1619
1620     return S_OK;
1621 }
1622
1623 /* make the apartment reachable by other threads and processes and create the
1624  * IRemUnknown object */
1625 void RPC_StartRemoting(struct apartment *apt)
1626 {
1627     if (!InterlockedExchange(&apt->remoting_started, TRUE))
1628     {
1629         WCHAR endpoint[200];
1630         RPC_STATUS status;
1631
1632         get_rpc_endpoint(endpoint, &apt->oxid);
1633     
1634         status = RpcServerUseProtseqEpW(
1635             wszRpcTransport,
1636             RPC_C_PROTSEQ_MAX_REQS_DEFAULT,
1637             endpoint,
1638             NULL);
1639         if (status != RPC_S_OK)
1640             ERR("Couldn't register endpoint %s\n", debugstr_w(endpoint));
1641
1642         /* FIXME: move remote unknown exporting into this function */
1643     }
1644     start_apartment_remote_unknown();
1645 }
1646
1647
1648 static HRESULT create_server(REFCLSID rclsid, HANDLE *process)
1649 {
1650     static const WCHAR  wszLocalServer32[] = { 'L','o','c','a','l','S','e','r','v','e','r','3','2',0 };
1651     static const WCHAR  embedding[] = { ' ', '-','E','m','b','e','d','d','i','n','g',0 };
1652     HKEY                key;
1653     HRESULT             hres;
1654     WCHAR               command[MAX_PATH+sizeof(embedding)/sizeof(WCHAR)];
1655     DWORD               size = (MAX_PATH+1) * sizeof(WCHAR);
1656     STARTUPINFOW        sinfo;
1657     PROCESS_INFORMATION pinfo;
1658
1659     hres = COM_OpenKeyForCLSID(rclsid, wszLocalServer32, KEY_READ, &key);
1660     if (FAILED(hres)) {
1661         ERR("class %s not registered\n", debugstr_guid(rclsid));
1662         return hres;
1663     }
1664
1665     hres = RegQueryValueExW(key, NULL, NULL, NULL, (LPBYTE)command, &size);
1666     RegCloseKey(key);
1667     if (hres) {
1668         WARN("No default value for LocalServer32 key\n");
1669         return REGDB_E_CLASSNOTREG; /* FIXME: check retval */
1670     }
1671
1672     memset(&sinfo,0,sizeof(sinfo));
1673     sinfo.cb = sizeof(sinfo);
1674
1675     /* EXE servers are started with the -Embedding switch. */
1676
1677     strcatW(command, embedding);
1678
1679     TRACE("activating local server %s for %s\n", debugstr_w(command), debugstr_guid(rclsid));
1680
1681     /* FIXME: Win2003 supports a ServerExecutable value that is passed into
1682      * CreateProcess */
1683     if (!CreateProcessW(NULL, command, NULL, NULL, FALSE, DETACHED_PROCESS, NULL, NULL, &sinfo, &pinfo)) {
1684         WARN("failed to run local server %s\n", debugstr_w(command));
1685         return HRESULT_FROM_WIN32(GetLastError());
1686     }
1687     *process = pinfo.hProcess;
1688     CloseHandle(pinfo.hThread);
1689
1690     return S_OK;
1691 }
1692
1693 /*
1694  * start_local_service()  - start a service given its name and parameters
1695  */
1696 static DWORD start_local_service(LPCWSTR name, DWORD num, LPCWSTR *params)
1697 {
1698     SC_HANDLE handle, hsvc;
1699     DWORD     r = ERROR_FUNCTION_FAILED;
1700
1701     TRACE("Starting service %s %d params\n", debugstr_w(name), num);
1702
1703     handle = OpenSCManagerW(NULL, NULL, SC_MANAGER_CONNECT);
1704     if (!handle)
1705         return r;
1706     hsvc = OpenServiceW(handle, name, SERVICE_START);
1707     if (hsvc)
1708     {
1709         if(StartServiceW(hsvc, num, params))
1710             r = ERROR_SUCCESS;
1711         else
1712             r = GetLastError();
1713         if (r == ERROR_SERVICE_ALREADY_RUNNING)
1714             r = ERROR_SUCCESS;
1715         CloseServiceHandle(hsvc);
1716     }
1717     else
1718         r = GetLastError();
1719     CloseServiceHandle(handle);
1720
1721     TRACE("StartService returned error %u (%s)\n", r, (r == ERROR_SUCCESS) ? "ok":"failed");
1722
1723     return r;
1724 }
1725
1726 /*
1727  * create_local_service()  - start a COM server in a service
1728  *
1729  *   To start a Local Service, we read the AppID value under
1730  * the class's CLSID key, then open the HKCR\\AppId key specified
1731  * there and check for a LocalService value.
1732  *
1733  * Note:  Local Services are not supported under Windows 9x
1734  */
1735 static HRESULT create_local_service(REFCLSID rclsid)
1736 {
1737     HRESULT hres;
1738     WCHAR buf[CHARS_IN_GUID];
1739     static const WCHAR szLocalService[] = { 'L','o','c','a','l','S','e','r','v','i','c','e',0 };
1740     static const WCHAR szServiceParams[] = {'S','e','r','v','i','c','e','P','a','r','a','m','s',0};
1741     HKEY hkey;
1742     LONG r;
1743     DWORD type, sz;
1744
1745     TRACE("Attempting to start Local service for %s\n", debugstr_guid(rclsid));
1746
1747     hres = COM_OpenKeyForAppIdFromCLSID(rclsid, KEY_READ, &hkey);
1748     if (FAILED(hres))
1749         return hres;
1750
1751     /* read the LocalService and ServiceParameters values from the AppID key */
1752     sz = sizeof buf;
1753     r = RegQueryValueExW(hkey, szLocalService, NULL, &type, (LPBYTE)buf, &sz);
1754     if (r==ERROR_SUCCESS && type==REG_SZ)
1755     {
1756         DWORD num_args = 0;
1757         LPWSTR args[1] = { NULL };
1758
1759         /*
1760          * FIXME: I'm not really sure how to deal with the service parameters.
1761          *        I suspect that the string returned from RegQueryValueExW
1762          *        should be split into a number of arguments by spaces.
1763          *        It would make more sense if ServiceParams contained a
1764          *        REG_MULTI_SZ here, but it's a REG_SZ for the services
1765          *        that I'm interested in for the moment.
1766          */
1767         r = RegQueryValueExW(hkey, szServiceParams, NULL, &type, NULL, &sz);
1768         if (r == ERROR_SUCCESS && type == REG_SZ && sz)
1769         {
1770             args[0] = HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY,sz);
1771             num_args++;
1772             RegQueryValueExW(hkey, szServiceParams, NULL, &type, (LPBYTE)args[0], &sz);
1773         }
1774         r = start_local_service(buf, num_args, (LPCWSTR *)args);
1775         if (r != ERROR_SUCCESS)
1776             hres = REGDB_E_CLASSNOTREG; /* FIXME: check retval */
1777         HeapFree(GetProcessHeap(),0,args[0]);
1778     }
1779     else
1780     {
1781         WARN("No LocalService value\n");
1782         hres = REGDB_E_CLASSNOTREG; /* FIXME: check retval */
1783     }
1784     RegCloseKey(hkey);
1785
1786     return hres;
1787 }
1788
1789
1790 static void get_localserver_pipe_name(WCHAR *pipefn, REFCLSID rclsid)
1791 {
1792     static const WCHAR wszPipeRef[] = {'\\','\\','.','\\','p','i','p','e','\\',0};
1793     strcpyW(pipefn, wszPipeRef);
1794     StringFromGUID2(rclsid, pipefn + sizeof(wszPipeRef)/sizeof(wszPipeRef[0]) - 1, CHARS_IN_GUID);
1795 }
1796
1797 /* FIXME: should call to rpcss instead */
1798 HRESULT RPC_GetLocalClassObject(REFCLSID rclsid, REFIID iid, LPVOID *ppv)
1799 {
1800     HRESULT        hres;
1801     HANDLE         hPipe;
1802     WCHAR          pipefn[100];
1803     DWORD          res, bufferlen;
1804     char           marshalbuffer[200];
1805     IStream       *pStm;
1806     LARGE_INTEGER  seekto;
1807     ULARGE_INTEGER newpos;
1808     int            tries = 0;
1809
1810     static const int MAXTRIES = 30; /* 30 seconds */
1811
1812     TRACE("rclsid=%s, iid=%s\n", debugstr_guid(rclsid), debugstr_guid(iid));
1813
1814     get_localserver_pipe_name(pipefn, rclsid);
1815
1816     while (tries++ < MAXTRIES) {
1817         TRACE("waiting for %s\n", debugstr_w(pipefn));
1818
1819         WaitNamedPipeW( pipefn, NMPWAIT_WAIT_FOREVER );
1820         hPipe = CreateFileW(pipefn, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, 0);
1821         if (hPipe == INVALID_HANDLE_VALUE) {
1822             DWORD index;
1823             DWORD start_ticks;
1824             HANDLE process = 0;
1825             if (tries == 1) {
1826                 if ( (hres = create_local_service(rclsid)) &&
1827                      (hres = create_server(rclsid, &process)) )
1828                     return hres;
1829             } else {
1830                 WARN("Connecting to %s, no response yet, retrying: le is %u\n", debugstr_w(pipefn), GetLastError());
1831             }
1832             /* wait for one second, even if messages arrive */
1833             start_ticks = GetTickCount();
1834             do {
1835                 if (SUCCEEDED(CoWaitForMultipleHandles(0, 1000, (process != 0),
1836                                                        &process, &index)) && process && !index)
1837                 {
1838                     WARN( "server for %s failed to start\n", debugstr_guid(rclsid) );
1839                     CloseHandle( hPipe );
1840                     CloseHandle( process );
1841                     return E_NOINTERFACE;
1842                 }
1843             } while (GetTickCount() - start_ticks < 1000);
1844             if (process) CloseHandle( process );
1845             continue;
1846         }
1847         bufferlen = 0;
1848         if (!ReadFile(hPipe,marshalbuffer,sizeof(marshalbuffer),&bufferlen,NULL)) {
1849             FIXME("Failed to read marshal id from classfactory of %s.\n",debugstr_guid(rclsid));
1850             Sleep(1000);
1851             continue;
1852         }
1853         TRACE("read marshal id from pipe\n");
1854         CloseHandle(hPipe);
1855         break;
1856     }
1857     
1858     if (tries >= MAXTRIES)
1859         return E_NOINTERFACE;
1860     
1861     hres = CreateStreamOnHGlobal(0,TRUE,&pStm);
1862     if (hres) return hres;
1863     hres = IStream_Write(pStm,marshalbuffer,bufferlen,&res);
1864     if (hres) goto out;
1865     seekto.u.LowPart = 0;seekto.u.HighPart = 0;
1866     hres = IStream_Seek(pStm,seekto,STREAM_SEEK_SET,&newpos);
1867     
1868     TRACE("unmarshalling classfactory\n");
1869     hres = CoUnmarshalInterface(pStm,&IID_IClassFactory,ppv);
1870 out:
1871     IStream_Release(pStm);
1872     return hres;
1873 }
1874
1875
1876 struct local_server_params
1877 {
1878     CLSID clsid;
1879     IStream *stream;
1880     HANDLE ready_event;
1881     HANDLE stop_event;
1882     HANDLE thread;
1883     BOOL multi_use;
1884 };
1885
1886 /* FIXME: should call to rpcss instead */
1887 static DWORD WINAPI local_server_thread(LPVOID param)
1888 {
1889     struct local_server_params * lsp = param;
1890     WCHAR               pipefn[100];
1891     HRESULT             hres;
1892     IStream             *pStm = lsp->stream;
1893     STATSTG             ststg;
1894     unsigned char       *buffer;
1895     int                 buflen;
1896     LARGE_INTEGER       seekto;
1897     ULARGE_INTEGER      newpos;
1898     ULONG               res;
1899     BOOL multi_use = lsp->multi_use;
1900     OVERLAPPED ovl;
1901     HANDLE pipe_event, hPipe, new_pipe;
1902     DWORD  bytes;
1903
1904     TRACE("Starting threader for %s.\n",debugstr_guid(&lsp->clsid));
1905
1906     memset(&ovl, 0, sizeof(ovl));
1907     get_localserver_pipe_name(pipefn, &lsp->clsid);
1908     ovl.hEvent = pipe_event = CreateEventW(NULL, FALSE, FALSE, NULL);
1909
1910     hPipe = CreateNamedPipeW( pipefn, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
1911                               PIPE_TYPE_BYTE|PIPE_WAIT, PIPE_UNLIMITED_INSTANCES,
1912                               4096, 4096, 500 /* 0.5 second timeout */, NULL );
1913     if (hPipe == INVALID_HANDLE_VALUE)
1914     {
1915         FIXME("pipe creation failed for %s, le is %u\n", debugstr_w(pipefn), GetLastError());
1916         CloseHandle(pipe_event);
1917         return 1;
1918     }
1919
1920     SetEvent(lsp->ready_event);
1921
1922     while (1) {
1923         if (!ConnectNamedPipe(hPipe, &ovl))
1924         {
1925             DWORD error = GetLastError();
1926             if (error == ERROR_IO_PENDING)
1927             {
1928                 HANDLE handles[2] = { pipe_event, lsp->stop_event };
1929                 DWORD ret;
1930                 ret = WaitForMultipleObjects(2, handles, FALSE, INFINITE);
1931                 if (ret != WAIT_OBJECT_0)
1932                 {
1933                     CloseHandle(hPipe);
1934                     break;
1935                 }
1936             }
1937             /* client already connected isn't an error */
1938             else if (error != ERROR_PIPE_CONNECTED)
1939             {
1940                 ERR("ConnectNamedPipe failed with error %d\n", GetLastError());
1941                 CloseHandle(hPipe);
1942                 break;
1943             }
1944         }
1945
1946         TRACE("marshalling IClassFactory to client\n");
1947         
1948         hres = IStream_Stat(pStm,&ststg,STATFLAG_NONAME);
1949         if (hres)
1950         {
1951             CloseHandle(hPipe);
1952             CloseHandle(pipe_event);
1953             return hres;
1954         }
1955
1956         seekto.u.LowPart = 0;
1957         seekto.u.HighPart = 0;
1958         hres = IStream_Seek(pStm,seekto,STREAM_SEEK_SET,&newpos);
1959         if (hres) {
1960             FIXME("IStream_Seek failed, %x\n",hres);
1961             CloseHandle(hPipe);
1962             CloseHandle(pipe_event);
1963             return hres;
1964         }
1965
1966         buflen = ststg.cbSize.u.LowPart;
1967         buffer = HeapAlloc(GetProcessHeap(),0,buflen);
1968         
1969         hres = IStream_Read(pStm,buffer,buflen,&res);
1970         if (hres) {
1971             FIXME("Stream Read failed, %x\n",hres);
1972             CloseHandle(hPipe);
1973             CloseHandle(pipe_event);
1974             HeapFree(GetProcessHeap(),0,buffer);
1975             return hres;
1976         }
1977         
1978         WriteFile(hPipe,buffer,buflen,&res,&ovl);
1979         GetOverlappedResult(hPipe, &ovl, &bytes, TRUE);
1980         HeapFree(GetProcessHeap(),0,buffer);
1981
1982         FlushFileBuffers(hPipe);
1983         DisconnectNamedPipe(hPipe);
1984         TRACE("done marshalling IClassFactory\n");
1985
1986         if (!multi_use)
1987         {
1988             TRACE("single use object, shutting down pipe %s\n", debugstr_w(pipefn));
1989             CloseHandle(hPipe);
1990             break;
1991         }
1992         new_pipe = CreateNamedPipeW( pipefn, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
1993                                      PIPE_TYPE_BYTE|PIPE_WAIT, PIPE_UNLIMITED_INSTANCES,
1994                                      4096, 4096, 500 /* 0.5 second timeout */, NULL );
1995         CloseHandle(hPipe);
1996         if (new_pipe == INVALID_HANDLE_VALUE)
1997         {
1998             FIXME("pipe creation failed for %s, le is %u\n", debugstr_w(pipefn), GetLastError());
1999             CloseHandle(pipe_event);
2000             return 1;
2001         }
2002         hPipe = new_pipe;
2003     }
2004     CloseHandle(pipe_event);
2005     return 0;
2006 }
2007
2008 /* starts listening for a local server */
2009 HRESULT RPC_StartLocalServer(REFCLSID clsid, IStream *stream, BOOL multi_use, void **registration)
2010 {
2011     DWORD tid;
2012     struct local_server_params *lsp;
2013
2014     lsp = HeapAlloc(GetProcessHeap(), 0, sizeof(*lsp));
2015     if (!lsp)
2016         return E_OUTOFMEMORY;
2017
2018     lsp->clsid = *clsid;
2019     lsp->stream = stream;
2020     IStream_AddRef(stream);
2021     lsp->ready_event = CreateEventW(NULL, FALSE, FALSE, NULL);
2022     if (!lsp->ready_event)
2023     {
2024         HeapFree(GetProcessHeap(), 0, lsp);
2025         return HRESULT_FROM_WIN32(GetLastError());
2026     }
2027     lsp->stop_event = CreateEventW(NULL, FALSE, FALSE, NULL);
2028     if (!lsp->stop_event)
2029     {
2030         CloseHandle(lsp->ready_event);
2031         HeapFree(GetProcessHeap(), 0, lsp);
2032         return HRESULT_FROM_WIN32(GetLastError());
2033     }
2034     lsp->multi_use = multi_use;
2035
2036     lsp->thread = CreateThread(NULL, 0, local_server_thread, lsp, 0, &tid);
2037     if (!lsp->thread)
2038     {
2039         CloseHandle(lsp->ready_event);
2040         CloseHandle(lsp->stop_event);
2041         HeapFree(GetProcessHeap(), 0, lsp);
2042         return HRESULT_FROM_WIN32(GetLastError());
2043     }
2044
2045     WaitForSingleObject(lsp->ready_event, INFINITE);
2046     CloseHandle(lsp->ready_event);
2047     lsp->ready_event = NULL;
2048
2049     *registration = lsp;
2050     return S_OK;
2051 }
2052
2053 /* stops listening for a local server */
2054 void RPC_StopLocalServer(void *registration)
2055 {
2056     struct local_server_params *lsp = registration;
2057
2058     /* signal local_server_thread to stop */
2059     SetEvent(lsp->stop_event);
2060     /* wait for it to exit */
2061     WaitForSingleObject(lsp->thread, INFINITE);
2062
2063     IStream_Release(lsp->stream);
2064     CloseHandle(lsp->stop_event);
2065     CloseHandle(lsp->thread);
2066     HeapFree(GetProcessHeap(), 0, lsp);
2067 }