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