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