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