advapi32: Remove a useless macro.
[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 <stdlib.h>
27 #include <stdarg.h>
28 #include <stdio.h>
29 #include <string.h>
30 #include <assert.h>
31
32 #define COBJMACROS
33 #define NONAMELESSUNION
34 #define NONAMELESSSTRUCT
35
36 #include "windef.h"
37 #include "winbase.h"
38 #include "winuser.h"
39 #include "winsvc.h"
40 #include "objbase.h"
41 #include "ole2.h"
42 #include "rpc.h"
43 #include "winerror.h"
44 #include "winreg.h"
45 #include "wtypes.h"
46 #include "wine/unicode.h"
47
48 #include "compobj_private.h"
49
50 #include "wine/debug.h"
51
52 WINE_DEFAULT_DEBUG_CHANNEL(ole);
53
54 static void __RPC_STUB dispatch_rpc(RPC_MESSAGE *msg);
55
56 /* we only use one function to dispatch calls for all methods - we use the
57  * RPC_IF_OLE flag to tell the RPC runtime that this is the case */
58 static RPC_DISPATCH_FUNCTION rpc_dispatch_table[1] = { dispatch_rpc }; /* (RO) */
59 static RPC_DISPATCH_TABLE rpc_dispatch = { 1, rpc_dispatch_table }; /* (RO) */
60
61 static struct list registered_interfaces = LIST_INIT(registered_interfaces); /* (CS csRegIf) */
62 static CRITICAL_SECTION csRegIf;
63 static CRITICAL_SECTION_DEBUG csRegIf_debug =
64 {
65     0, 0, &csRegIf,
66     { &csRegIf_debug.ProcessLocksList, &csRegIf_debug.ProcessLocksList },
67       0, 0, { (DWORD_PTR)(__FILE__ ": dcom registered server interfaces") }
68 };
69 static CRITICAL_SECTION csRegIf = { &csRegIf_debug, -1, 0, 0, 0, 0 };
70
71 static struct list channel_hooks = LIST_INIT(channel_hooks); /* (CS csChannelHook) */
72 static CRITICAL_SECTION csChannelHook;
73 static CRITICAL_SECTION_DEBUG csChannelHook_debug =
74 {
75     0, 0, &csChannelHook,
76     { &csChannelHook_debug.ProcessLocksList, &csChannelHook_debug.ProcessLocksList },
77       0, 0, { (DWORD_PTR)(__FILE__ ": channel hooks") }
78 };
79 static CRITICAL_SECTION csChannelHook = { &csChannelHook_debug, -1, 0, 0, 0, 0 };
80
81 static WCHAR wszRpcTransport[] = {'n','c','a','l','r','p','c',0};
82
83
84 struct registered_if
85 {
86     struct list entry;
87     DWORD refs; /* ref count */
88     RPC_SERVER_INTERFACE If; /* interface registered with the RPC runtime */
89 };
90
91 /* get the pipe endpoint specified of the specified apartment */
92 static inline void get_rpc_endpoint(LPWSTR endpoint, const OXID *oxid)
93 {
94     /* FIXME: should get endpoint from rpcss */
95     static const WCHAR wszEndpointFormat[] = {'\\','p','i','p','e','\\','O','L','E','_','%','0','8','l','x','%','0','8','l','x',0};
96     wsprintfW(endpoint, wszEndpointFormat, (DWORD)(*oxid >> 32),(DWORD)*oxid);
97 }
98
99 typedef struct
100 {
101     const IRpcChannelBufferVtbl *lpVtbl;
102     LONG                  refs;
103 } RpcChannelBuffer;
104
105 typedef struct
106 {
107     RpcChannelBuffer       super; /* superclass */
108
109     RPC_BINDING_HANDLE     bind; /* handle to the remote server */
110     OXID                   oxid; /* apartment in which the channel is valid */
111     DWORD                  dest_context; /* returned from GetDestCtx */
112     LPVOID                 dest_context_data; /* returned from GetDestCtx */
113     HANDLE                 event; /* cached event handle */
114 } ClientRpcChannelBuffer;
115
116 struct dispatch_params
117 {
118     RPCOLEMESSAGE     *msg; /* message */
119     IRpcStubBuffer    *stub; /* stub buffer, if applicable */
120     IRpcChannelBuffer *chan; /* server channel buffer, if applicable */
121     IID                iid; /* ID of interface being called */
122     IUnknown          *iface; /* interface being called */
123     HANDLE             handle; /* handle that will become signaled when call finishes */
124     RPC_STATUS         status; /* status (out) */
125     HRESULT            hr; /* hresult (out) */
126 };
127
128 struct message_state
129 {
130     RPC_BINDING_HANDLE binding_handle;
131     ULONG prefix_data_len;
132     SChannelHookCallInfo channel_hook_info;
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 = 0; /* FIXME */
604     message_state->channel_hook_info.iMethod = msg->ProcNum;
605     message_state->channel_hook_info.pObject = NULL; /* only present on server-side */
606
607     extensions_size = ChannelHooks_ClientGetSize(&message_state->channel_hook_info,
608         &channel_hook_data, &channel_hook_count, &extension_count);
609
610     msg->BufferLength += FIELD_OFFSET(ORPCTHIS, extensions) + 4;
611     if (extensions_size)
612     {
613         msg->BufferLength += FIELD_OFFSET(ORPC_EXTENT_ARRAY, extent) + 2*sizeof(DWORD) + extensions_size;
614         if (extension_count & 1)
615             msg->BufferLength += FIELD_OFFSET(WIRE_ORPC_EXTENT, data[0]);
616     }
617
618     status = I_RpcGetBuffer(msg);
619
620     message_state->prefix_data_len = 0;
621     message_state->binding_handle = This->bind;
622     msg->Handle = message_state;
623
624     if (status == RPC_S_OK)
625     {
626         orpcthis = (ORPCTHIS *)msg->Buffer;
627         msg->Buffer = (char *)msg->Buffer + FIELD_OFFSET(ORPCTHIS, extensions);
628
629         orpcthis->version.MajorVersion = COM_MAJOR_VERSION;
630         orpcthis->version.MinorVersion = COM_MINOR_VERSION;
631         orpcthis->flags = message_state->channel_hook_info.dwServerPid ? ORPCF_LOCAL : ORPCF_NULL;
632         orpcthis->reserved1 = 0;
633         orpcthis->cid = message_state->channel_hook_info.uCausality;
634
635         /* NDR representation of orpcthis->extensions */
636         *(DWORD *)msg->Buffer = extensions_size ? 1 : 0;
637         msg->Buffer = (char *)msg->Buffer + sizeof(DWORD);
638
639         if (extensions_size)
640         {
641             ORPC_EXTENT_ARRAY *orpc_extent_array = msg->Buffer;
642             orpc_extent_array->size = extension_count;
643             orpc_extent_array->reserved = 0;
644             msg->Buffer = (char *)msg->Buffer + FIELD_OFFSET(ORPC_EXTENT_ARRAY, extent);
645             /* NDR representation of orpc_extent_array->extent */
646             *(DWORD *)msg->Buffer = 1;
647             msg->Buffer = (char *)msg->Buffer + sizeof(DWORD);
648             /* NDR representation of [size_is] attribute of orpc_extent_array->extent */
649             *(DWORD *)msg->Buffer = (extension_count + 1) & ~1;
650             msg->Buffer = (char *)msg->Buffer + sizeof(DWORD);
651
652             msg->Buffer = ChannelHooks_ClientFillBuffer(&message_state->channel_hook_info,
653                 msg->Buffer, channel_hook_data, channel_hook_count);
654
655             /* we must add a dummy extension if there is an odd extension
656              * count to meet the contract specified by the size_is attribute */
657             if (extension_count & 1)
658             {
659                 WIRE_ORPC_EXTENT *wire_orpc_extent = msg->Buffer;
660                 wire_orpc_extent->conformance = 0;
661                 memcpy(&wire_orpc_extent->id, &GUID_NULL, sizeof(wire_orpc_extent->id));
662                 wire_orpc_extent->size = 0;
663                 msg->Buffer = (char *)msg->Buffer + FIELD_OFFSET(WIRE_ORPC_EXTENT, data[0]);
664             }
665         }
666
667         /* store the prefixed data length so that we can restore the real buffer
668          * pointer in ClientRpcChannelBuffer_SendReceive. */
669         message_state->prefix_data_len = (char *)msg->Buffer - (char *)orpcthis;
670         msg->BufferLength -= message_state->prefix_data_len;
671     }
672
673     TRACE("-- %ld\n", status);
674
675     return HRESULT_FROM_WIN32(status);
676 }
677
678 static HRESULT WINAPI ServerRpcChannelBuffer_SendReceive(LPRPCCHANNELBUFFER iface, RPCOLEMESSAGE *olemsg, ULONG *pstatus)
679 {
680     FIXME("stub\n");
681     return E_NOTIMPL;
682 }
683
684 static HANDLE ClientRpcChannelBuffer_GetEventHandle(ClientRpcChannelBuffer *This)
685 {
686     HANDLE event = InterlockedExchangePointer(&This->event, NULL);
687
688     /* Note: must be auto-reset event so we can reuse it without a call
689      * to ResetEvent */
690     if (!event) event = CreateEventW(NULL, FALSE, FALSE, NULL);
691
692     return event;
693 }
694
695 static void ClientRpcChannelBuffer_ReleaseEventHandle(ClientRpcChannelBuffer *This, HANDLE event)
696 {
697     if (InterlockedCompareExchangePointer(&This->event, event, NULL))
698         /* already a handle cached in This */
699         CloseHandle(event);
700 }
701
702 /* this thread runs an outgoing RPC */
703 static DWORD WINAPI rpc_sendreceive_thread(LPVOID param)
704 {
705     struct dispatch_params *data = (struct dispatch_params *) param;
706
707     /* FIXME: trap and rethrow RPC exceptions in app thread */
708     data->status = I_RpcSendReceive((RPC_MESSAGE *)data->msg);
709
710     TRACE("completed with status 0x%lx\n", data->status);
711
712     SetEvent(data->handle);
713
714     return 0;
715 }
716
717 static inline HRESULT ClientRpcChannelBuffer_IsCorrectApartment(ClientRpcChannelBuffer *This, APARTMENT *apt)
718 {
719     OXID oxid;
720     if (!apt)
721         return S_FALSE;
722     if (apartment_getoxid(apt, &oxid) != S_OK)
723         return S_FALSE;
724     if (This->oxid != oxid)
725         return S_FALSE;
726     return S_OK;
727 }
728
729 static HRESULT WINAPI ClientRpcChannelBuffer_SendReceive(LPRPCCHANNELBUFFER iface, RPCOLEMESSAGE *olemsg, ULONG *pstatus)
730 {
731     ClientRpcChannelBuffer *This = (ClientRpcChannelBuffer *)iface;
732     HRESULT hr;
733     RPC_MESSAGE *msg = (RPC_MESSAGE *)olemsg;
734     RPC_STATUS status;
735     DWORD index;
736     struct dispatch_params *params;
737     APARTMENT *apt = NULL;
738     IPID ipid;
739     struct message_state *message_state;
740     ORPCTHAT orpcthat;
741     ORPC_EXTENT_ARRAY orpc_ext_array;
742     WIRE_ORPC_EXTENT *first_wire_orpc_extent = NULL;
743     HRESULT hrFault = S_OK;
744
745     TRACE("(%p) iMethod=%d\n", olemsg, olemsg->iMethod);
746
747     hr = ClientRpcChannelBuffer_IsCorrectApartment(This, COM_CurrentApt());
748     if (hr != S_OK)
749     {
750         ERR("called from wrong apartment, should have been 0x%s\n",
751             wine_dbgstr_longlong(This->oxid));
752         return RPC_E_WRONG_THREAD;
753     }
754     /* this situation should be impossible in multi-threaded apartments,
755      * because the calling thread isn't re-entrable.
756      * Note: doing a COM call during the processing of a sent message is
757      * only disallowed if a client call is already being waited for
758      * completion */
759     if (!COM_CurrentApt()->multi_threaded &&
760         COM_CurrentInfo()->pending_call_count_client &&
761         InSendMessage())
762     {
763         ERR("can't make an outgoing COM call in response to a sent message\n");
764         return RPC_E_CANTCALLOUT_ININPUTSYNCCALL;
765     }
766
767     params = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*params));
768     if (!params) return E_OUTOFMEMORY;
769
770     message_state = (struct message_state *)msg->Handle;
771     /* restore the binding handle and the real start of data */
772     msg->Handle = message_state->binding_handle;
773     msg->Buffer = (char *)msg->Buffer - message_state->prefix_data_len;
774     msg->BufferLength += message_state->prefix_data_len;
775
776     params->msg = olemsg;
777     params->status = RPC_S_OK;
778     params->hr = S_OK;
779
780     /* Note: this is an optimization in the Microsoft OLE runtime that we need
781      * to copy, as shown by the test_no_couninitialize_client test. without
782      * short-circuiting the RPC runtime in the case below, the test will
783      * deadlock on the loader lock due to the RPC runtime needing to create
784      * a thread to process the RPC when this function is called indirectly
785      * from DllMain */
786
787     RpcBindingInqObject(message_state->binding_handle, &ipid);
788     hr = ipid_get_dispatch_params(&ipid, &apt, &params->stub, &params->chan,
789                                   &params->iid, &params->iface);
790     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, (LPARAM)params))
796         {
797             ERR("PostMessage failed with error %d\n", GetLastError());
798             hr = HRESULT_FROM_WIN32(GetLastError());
799         }
800     }
801     else
802     {
803         if (hr == S_OK)
804         {
805             /* otherwise, we go via RPC runtime so the stub and channel aren't
806              * needed here */
807             IRpcStubBuffer_Release(params->stub);
808             params->stub = NULL;
809             IRpcChannelBuffer_Release(params->chan);
810             params->chan = NULL;
811         }
812
813         /* we use a separate thread here because we need to be able to
814          * pump the message loop in the application thread: if we do not,
815          * any windows created by this thread will hang and RPCs that try
816          * and re-enter this STA from an incoming server thread will
817          * deadlock. InstallShield is an example of that.
818          */
819         if (!QueueUserWorkItem(rpc_sendreceive_thread, params, WT_EXECUTEDEFAULT))
820         {
821             ERR("QueueUserWorkItem failed with error %x\n", GetLastError());
822             hr = E_UNEXPECTED;
823         }
824         else
825             hr = S_OK;
826     }
827     if (apt) apartment_release(apt);
828
829     if (hr == S_OK)
830     {
831         if (WaitForSingleObject(params->handle, 0))
832         {
833             COM_CurrentInfo()->pending_call_count_client++;
834             hr = CoWaitForMultipleHandles(0, INFINITE, 1, &params->handle, &index);
835             COM_CurrentInfo()->pending_call_count_client--;
836         }
837     }
838     ClientRpcChannelBuffer_ReleaseEventHandle(This, params->handle);
839
840     /* for WM shortcut, faults are returned in params->hr */
841     if (hr == S_OK)
842         hrFault = params->hr;
843
844     status = params->status;
845     HeapFree(GetProcessHeap(), 0, params);
846     params = NULL;
847
848     orpcthat.flags = ORPCF_NULL;
849     orpcthat.extensions = NULL;
850
851     /* for normal RPC calls, faults are returned in first 4 bytes of the
852      * buffer */
853     TRACE("RPC call status: 0x%lx\n", status);
854     if (status == RPC_S_CALL_FAILED)
855         hrFault = *(HRESULT *)olemsg->Buffer;
856     else if (status != RPC_S_OK)
857         hr = HRESULT_FROM_WIN32(status);
858
859     TRACE("hrFault = 0x%08x\n", hrFault);
860
861     /* FIXME: this condition should be
862      * "hr == S_OK && (!hrFault || msg->BufferLength > FIELD_OFFSET(ORPCTHAT, extentions) + 4)"
863      * but we don't currently reset the message length for PostMessage
864      * dispatched calls */
865     if (hr == S_OK && hrFault == S_OK)
866     {
867         HRESULT hr2;
868         char *original_buffer = msg->Buffer;
869
870         /* handle ORPCTHAT and client extensions */
871
872         hr2 = unmarshal_ORPCTHAT(msg, &orpcthat, &orpc_ext_array, &first_wire_orpc_extent);
873         if (FAILED(hr2))
874             hr = hr2;
875
876         message_state->prefix_data_len = (char *)msg->Buffer - original_buffer;
877         msg->BufferLength -= message_state->prefix_data_len;
878     }
879     else
880         message_state->prefix_data_len = 0;
881
882     if (hr == S_OK)
883     {
884         ChannelHooks_ClientNotify(&message_state->channel_hook_info,
885                                   msg->DataRepresentation,
886                                   first_wire_orpc_extent,
887                                   orpcthat.extensions && first_wire_orpc_extent ? orpcthat.extensions->size : 0,
888                                   hrFault);
889     }
890
891     /* save away the message state again */
892     msg->Handle = message_state;
893
894     if (pstatus) *pstatus = status;
895
896     if (hr == S_OK)
897         hr = hrFault;
898
899     TRACE("-- 0x%08x\n", hr);
900
901     return hr;
902 }
903
904 static HRESULT WINAPI ServerRpcChannelBuffer_FreeBuffer(LPRPCCHANNELBUFFER iface, RPCOLEMESSAGE* olemsg)
905 {
906     RPC_MESSAGE *msg = (RPC_MESSAGE *)olemsg;
907     RPC_STATUS status;
908     struct message_state *message_state;
909
910     TRACE("(%p)\n", msg);
911
912     message_state = (struct message_state *)msg->Handle;
913     /* restore the binding handle and the real start of data */
914     msg->Handle = message_state->binding_handle;
915     msg->Buffer = (char *)msg->Buffer - message_state->prefix_data_len;
916     msg->BufferLength += message_state->prefix_data_len;
917     message_state->prefix_data_len = 0;
918
919     status = I_RpcFreeBuffer(msg);
920
921     msg->Handle = message_state;
922
923     TRACE("-- %ld\n", status);
924
925     return HRESULT_FROM_WIN32(status);
926 }
927
928 static HRESULT WINAPI ClientRpcChannelBuffer_FreeBuffer(LPRPCCHANNELBUFFER iface, RPCOLEMESSAGE* olemsg)
929 {
930     RPC_MESSAGE *msg = (RPC_MESSAGE *)olemsg;
931     RPC_STATUS status;
932     struct message_state *message_state;
933
934     TRACE("(%p)\n", msg);
935
936     message_state = (struct message_state *)msg->Handle;
937     /* restore the binding handle and the real start of data */
938     msg->Handle = message_state->binding_handle;
939     msg->Buffer = (char *)msg->Buffer - message_state->prefix_data_len;
940     msg->BufferLength += message_state->prefix_data_len;
941
942     status = I_RpcFreeBuffer(msg);
943
944     HeapFree(GetProcessHeap(), 0, msg->RpcInterfaceInformation);
945     msg->RpcInterfaceInformation = NULL;
946     HeapFree(GetProcessHeap(), 0, message_state);
947
948     TRACE("-- %ld\n", status);
949
950     return HRESULT_FROM_WIN32(status);
951 }
952
953 static HRESULT WINAPI ClientRpcChannelBuffer_GetDestCtx(LPRPCCHANNELBUFFER iface, DWORD* pdwDestContext, void** ppvDestContext)
954 {
955     ClientRpcChannelBuffer *This = (ClientRpcChannelBuffer *)iface;
956
957     TRACE("(%p,%p)\n", pdwDestContext, ppvDestContext);
958
959     *pdwDestContext = This->dest_context;
960     *ppvDestContext = This->dest_context_data;
961
962     return S_OK;
963 }
964
965 static HRESULT WINAPI ServerRpcChannelBuffer_GetDestCtx(LPRPCCHANNELBUFFER iface, DWORD* pdwDestContext, void** ppvDestContext)
966 {
967     FIXME("(%p,%p), stub!\n", pdwDestContext, ppvDestContext);
968     return E_FAIL;
969 }
970
971 static HRESULT WINAPI RpcChannelBuffer_IsConnected(LPRPCCHANNELBUFFER iface)
972 {
973     TRACE("()\n");
974     /* native does nothing too */
975     return S_OK;
976 }
977
978 static const IRpcChannelBufferVtbl ClientRpcChannelBufferVtbl =
979 {
980     RpcChannelBuffer_QueryInterface,
981     RpcChannelBuffer_AddRef,
982     ClientRpcChannelBuffer_Release,
983     ClientRpcChannelBuffer_GetBuffer,
984     ClientRpcChannelBuffer_SendReceive,
985     ClientRpcChannelBuffer_FreeBuffer,
986     ClientRpcChannelBuffer_GetDestCtx,
987     RpcChannelBuffer_IsConnected
988 };
989
990 static const IRpcChannelBufferVtbl ServerRpcChannelBufferVtbl =
991 {
992     RpcChannelBuffer_QueryInterface,
993     RpcChannelBuffer_AddRef,
994     ServerRpcChannelBuffer_Release,
995     ServerRpcChannelBuffer_GetBuffer,
996     ServerRpcChannelBuffer_SendReceive,
997     ServerRpcChannelBuffer_FreeBuffer,
998     ServerRpcChannelBuffer_GetDestCtx,
999     RpcChannelBuffer_IsConnected
1000 };
1001
1002 /* returns a channel buffer for proxies */
1003 HRESULT RPC_CreateClientChannel(const OXID *oxid, const IPID *ipid,
1004                                 DWORD dest_context, void *dest_context_data,
1005                                 IRpcChannelBuffer **chan)
1006 {
1007     ClientRpcChannelBuffer *This;
1008     WCHAR                   endpoint[200];
1009     RPC_BINDING_HANDLE      bind;
1010     RPC_STATUS              status;
1011     LPWSTR                  string_binding;
1012
1013     /* connect to the apartment listener thread */
1014     get_rpc_endpoint(endpoint, oxid);
1015
1016     TRACE("proxy pipe: connecting to endpoint: %s\n", debugstr_w(endpoint));
1017
1018     status = RpcStringBindingComposeW(
1019         NULL,
1020         wszRpcTransport,
1021         NULL,
1022         endpoint,
1023         NULL,
1024         &string_binding);
1025         
1026     if (status == RPC_S_OK)
1027     {
1028         status = RpcBindingFromStringBindingW(string_binding, &bind);
1029
1030         if (status == RPC_S_OK)
1031         {
1032             IPID ipid2 = *ipid; /* why can't RpcBindingSetObject take a const? */
1033             status = RpcBindingSetObject(bind, &ipid2);
1034             if (status != RPC_S_OK)
1035                 RpcBindingFree(&bind);
1036         }
1037
1038         RpcStringFreeW(&string_binding);
1039     }
1040
1041     if (status != RPC_S_OK)
1042     {
1043         ERR("Couldn't get binding for endpoint %s, status = %ld\n", debugstr_w(endpoint), status);
1044         return HRESULT_FROM_WIN32(status);
1045     }
1046
1047     This = HeapAlloc(GetProcessHeap(), 0, sizeof(*This));
1048     if (!This)
1049     {
1050         RpcBindingFree(&bind);
1051         return E_OUTOFMEMORY;
1052     }
1053
1054     This->super.lpVtbl = &ClientRpcChannelBufferVtbl;
1055     This->super.refs = 1;
1056     This->bind = bind;
1057     apartment_getoxid(COM_CurrentApt(), &This->oxid);
1058     This->dest_context = dest_context;
1059     This->dest_context_data = dest_context_data;
1060     This->event = NULL;
1061
1062     *chan = (IRpcChannelBuffer*)This;
1063
1064     return S_OK;
1065 }
1066
1067 HRESULT RPC_CreateServerChannel(IRpcChannelBuffer **chan)
1068 {
1069     RpcChannelBuffer *This = HeapAlloc(GetProcessHeap(), 0, sizeof(*This));
1070     if (!This)
1071         return E_OUTOFMEMORY;
1072
1073     This->lpVtbl = &ServerRpcChannelBufferVtbl;
1074     This->refs = 1;
1075     
1076     *chan = (IRpcChannelBuffer*)This;
1077
1078     return S_OK;
1079 }
1080
1081 /* unmarshals ORPC_EXTENT_ARRAY according to NDR rules, but doesn't allocate
1082  * any memory */
1083 static HRESULT unmarshal_ORPC_EXTENT_ARRAY(RPC_MESSAGE *msg, const char *end,
1084                                            ORPC_EXTENT_ARRAY *extensions,
1085                                            WIRE_ORPC_EXTENT **first_wire_orpc_extent)
1086 {
1087     DWORD pointer_id;
1088     DWORD i;
1089
1090     memcpy(extensions, msg->Buffer, FIELD_OFFSET(ORPC_EXTENT_ARRAY, extent));
1091     msg->Buffer = (char *)msg->Buffer + FIELD_OFFSET(ORPC_EXTENT_ARRAY, extent);
1092
1093     if ((const char *)msg->Buffer + 2 * sizeof(DWORD) > end)
1094         return RPC_E_INVALID_HEADER;
1095
1096     pointer_id = *(DWORD *)msg->Buffer;
1097     msg->Buffer = (char *)msg->Buffer + sizeof(DWORD);
1098     extensions->extent = NULL;
1099
1100     if (pointer_id)
1101     {
1102         WIRE_ORPC_EXTENT *wire_orpc_extent;
1103
1104         /* conformance */
1105         if (*(DWORD *)msg->Buffer != ((extensions->size+1)&~1))
1106             return RPC_S_INVALID_BOUND;
1107
1108         msg->Buffer = (char *)msg->Buffer + sizeof(DWORD);
1109
1110         /* arbritary limit for security (don't know what native does) */
1111         if (extensions->size > 256)
1112         {
1113             ERR("too many extensions: %ld\n", extensions->size);
1114             return RPC_S_INVALID_BOUND;
1115         }
1116
1117         *first_wire_orpc_extent = wire_orpc_extent = (WIRE_ORPC_EXTENT *)msg->Buffer;
1118         for (i = 0; i < ((extensions->size+1)&~1); i++)
1119         {
1120             if ((const char *)&wire_orpc_extent->data[0] > end)
1121                 return RPC_S_INVALID_BOUND;
1122             if (wire_orpc_extent->conformance != ((wire_orpc_extent->size+7)&~7))
1123                 return RPC_S_INVALID_BOUND;
1124             if ((const char *)&wire_orpc_extent->data[wire_orpc_extent->conformance] > end)
1125                 return RPC_S_INVALID_BOUND;
1126             TRACE("size %u, guid %s\n", wire_orpc_extent->size, debugstr_guid(&wire_orpc_extent->id));
1127             wire_orpc_extent = (WIRE_ORPC_EXTENT *)&wire_orpc_extent->data[wire_orpc_extent->conformance];
1128         }
1129         msg->Buffer = wire_orpc_extent;
1130     }
1131
1132     return S_OK;
1133 }
1134
1135 /* unmarshals ORPCTHIS according to NDR rules, but doesn't allocate any memory */
1136 static HRESULT unmarshal_ORPCTHIS(RPC_MESSAGE *msg, ORPCTHIS *orpcthis,
1137     ORPC_EXTENT_ARRAY *orpc_ext_array, WIRE_ORPC_EXTENT **first_wire_orpc_extent)
1138 {
1139     const char *end = (char *)msg->Buffer + msg->BufferLength;
1140
1141     *first_wire_orpc_extent = NULL;
1142
1143     if (msg->BufferLength < FIELD_OFFSET(ORPCTHIS, extensions) + 4)
1144     {
1145         ERR("invalid buffer length\n");
1146         return RPC_E_INVALID_HEADER;
1147     }
1148
1149     memcpy(orpcthis, msg->Buffer, FIELD_OFFSET(ORPCTHIS, extensions));
1150     msg->Buffer = (char *)msg->Buffer + FIELD_OFFSET(ORPCTHIS, extensions);
1151
1152     if ((const char *)msg->Buffer + sizeof(DWORD) > end)
1153         return RPC_E_INVALID_HEADER;
1154
1155     if (*(DWORD *)msg->Buffer)
1156         orpcthis->extensions = orpc_ext_array;
1157     else
1158         orpcthis->extensions = NULL;
1159
1160     msg->Buffer = (char *)msg->Buffer + sizeof(DWORD);
1161
1162     if (orpcthis->extensions)
1163     {
1164         HRESULT hr = unmarshal_ORPC_EXTENT_ARRAY(msg, end, orpc_ext_array,
1165                                                  first_wire_orpc_extent);
1166         if (FAILED(hr))
1167             return hr;
1168     }
1169
1170     if ((orpcthis->version.MajorVersion != COM_MAJOR_VERSION) ||
1171         (orpcthis->version.MinorVersion > COM_MINOR_VERSION))
1172     {
1173         ERR("COM version {%d, %d} not supported\n",
1174             orpcthis->version.MajorVersion, orpcthis->version.MinorVersion);
1175         return RPC_E_VERSION_MISMATCH;
1176     }
1177
1178     if (orpcthis->flags & ~(ORPCF_LOCAL|ORPCF_RESERVED1|ORPCF_RESERVED2|ORPCF_RESERVED3|ORPCF_RESERVED4))
1179     {
1180         ERR("invalid flags 0x%lx\n", orpcthis->flags & ~(ORPCF_LOCAL|ORPCF_RESERVED1|ORPCF_RESERVED2|ORPCF_RESERVED3|ORPCF_RESERVED4));
1181         return RPC_E_INVALID_HEADER;
1182     }
1183
1184     return S_OK;
1185 }
1186
1187 static HRESULT unmarshal_ORPCTHAT(RPC_MESSAGE *msg, ORPCTHAT *orpcthat,
1188                                   ORPC_EXTENT_ARRAY *orpc_ext_array, WIRE_ORPC_EXTENT **first_wire_orpc_extent)
1189 {
1190     const char *end = (char *)msg->Buffer + msg->BufferLength;
1191
1192     *first_wire_orpc_extent = NULL;
1193
1194     if (msg->BufferLength < FIELD_OFFSET(ORPCTHAT, extensions) + 4)
1195     {
1196         ERR("invalid buffer length\n");
1197         return RPC_E_INVALID_HEADER;
1198     }
1199
1200     memcpy(orpcthat, msg->Buffer, FIELD_OFFSET(ORPCTHAT, extensions));
1201     msg->Buffer = (char *)msg->Buffer + FIELD_OFFSET(ORPCTHAT, extensions);
1202
1203     if ((const char *)msg->Buffer + sizeof(DWORD) > end)
1204         return RPC_E_INVALID_HEADER;
1205
1206     if (*(DWORD *)msg->Buffer)
1207         orpcthat->extensions = orpc_ext_array;
1208     else
1209         orpcthat->extensions = NULL;
1210
1211     msg->Buffer = (char *)msg->Buffer + sizeof(DWORD);
1212
1213     if (orpcthat->extensions)
1214     {
1215         HRESULT hr = unmarshal_ORPC_EXTENT_ARRAY(msg, end, orpc_ext_array,
1216                                                  first_wire_orpc_extent);
1217         if (FAILED(hr))
1218             return hr;
1219     }
1220
1221     if (orpcthat->flags & ~(ORPCF_LOCAL|ORPCF_RESERVED1|ORPCF_RESERVED2|ORPCF_RESERVED3|ORPCF_RESERVED4))
1222     {
1223         ERR("invalid flags 0x%lx\n", orpcthat->flags & ~(ORPCF_LOCAL|ORPCF_RESERVED1|ORPCF_RESERVED2|ORPCF_RESERVED3|ORPCF_RESERVED4));
1224         return RPC_E_INVALID_HEADER;
1225     }
1226
1227     return S_OK;
1228 }
1229
1230 void RPC_ExecuteCall(struct dispatch_params *params)
1231 {
1232     struct message_state *message_state = NULL;
1233     RPC_MESSAGE *msg = (RPC_MESSAGE *)params->msg;
1234     char *original_buffer = msg->Buffer;
1235     ORPCTHIS orpcthis;
1236     ORPC_EXTENT_ARRAY orpc_ext_array;
1237     WIRE_ORPC_EXTENT *first_wire_orpc_extent;
1238     GUID old_causality_id;
1239
1240     /* handle ORPCTHIS and server extensions */
1241
1242     params->hr = unmarshal_ORPCTHIS(msg, &orpcthis, &orpc_ext_array, &first_wire_orpc_extent);
1243     if (params->hr != S_OK)
1244     {
1245         msg->Buffer = original_buffer;
1246         goto exit;
1247     }
1248
1249     message_state = HeapAlloc(GetProcessHeap(), 0, sizeof(*message_state));
1250     if (!message_state)
1251     {
1252         params->hr = E_OUTOFMEMORY;
1253         msg->Buffer = original_buffer;
1254         goto exit;
1255     }
1256
1257     message_state->prefix_data_len = (char *)msg->Buffer - original_buffer;
1258     message_state->binding_handle = msg->Handle;
1259
1260     message_state->channel_hook_info.iid = params->iid;
1261     message_state->channel_hook_info.cbSize = sizeof(message_state->channel_hook_info);
1262     message_state->channel_hook_info.uCausality = orpcthis.cid;
1263     message_state->channel_hook_info.dwServerPid = GetCurrentProcessId();
1264     message_state->channel_hook_info.iMethod = msg->ProcNum;
1265     message_state->channel_hook_info.pObject = params->iface;
1266
1267     if (orpcthis.extensions && first_wire_orpc_extent &&
1268         orpcthis.extensions->size)
1269         ChannelHooks_ServerNotify(&message_state->channel_hook_info, msg->DataRepresentation, first_wire_orpc_extent, orpcthis.extensions->size);
1270
1271     msg->Handle = message_state;
1272     msg->BufferLength -= message_state->prefix_data_len;
1273
1274     /* call message filter */
1275
1276     if (COM_CurrentApt()->filter)
1277     {
1278         DWORD handlecall;
1279         INTERFACEINFO interface_info;
1280         CALLTYPE calltype;
1281
1282         interface_info.pUnk = params->iface;
1283         interface_info.iid = params->iid;
1284         interface_info.wMethod = msg->ProcNum;
1285
1286         if (IsEqualGUID(&orpcthis.cid, &COM_CurrentInfo()->causality_id))
1287             calltype = CALLTYPE_NESTED;
1288         else if (COM_CurrentInfo()->pending_call_count_server == 0)
1289             calltype = CALLTYPE_TOPLEVEL;
1290         else
1291             calltype = CALLTYPE_TOPLEVEL_CALLPENDING;
1292
1293         handlecall = IMessageFilter_HandleInComingCall(COM_CurrentApt()->filter,
1294                                                        calltype,
1295                                                        (HTASK)GetCurrentProcessId(),
1296                                                        0 /* FIXME */,
1297                                                        &interface_info);
1298         TRACE("IMessageFilter_HandleInComingCall returned %d\n", handlecall);
1299         switch (handlecall)
1300         {
1301         case SERVERCALL_REJECTED:
1302             params->hr = RPC_E_CALL_REJECTED;
1303             goto exit_reset_state;
1304         case SERVERCALL_RETRYLATER:
1305 #if 0 /* FIXME: handle retries on the client side before enabling this code */
1306             params->hr = RPC_E_RETRY;
1307             goto exit_reset_state;
1308 #else
1309             FIXME("retry call later not implemented\n");
1310             break;
1311 #endif
1312         case SERVERCALL_ISHANDLED:
1313         default:
1314             break;
1315         }
1316     }
1317
1318     /* invoke the method */
1319
1320     /* save the old causality ID - note: any calls executed while processing
1321      * messages received during the SendReceive will appear to originate from
1322      * this call - this should be checked with what Windows does */
1323     old_causality_id = COM_CurrentInfo()->causality_id;
1324     COM_CurrentInfo()->causality_id = orpcthis.cid;
1325     COM_CurrentInfo()->pending_call_count_server++;
1326     params->hr = IRpcStubBuffer_Invoke(params->stub, params->msg, params->chan);
1327     COM_CurrentInfo()->pending_call_count_server--;
1328     COM_CurrentInfo()->causality_id = old_causality_id;
1329
1330 exit_reset_state:
1331     message_state = (struct message_state *)msg->Handle;
1332     msg->Handle = message_state->binding_handle;
1333     msg->Buffer = (char *)msg->Buffer - message_state->prefix_data_len;
1334     msg->BufferLength += message_state->prefix_data_len;
1335
1336 exit:
1337     HeapFree(GetProcessHeap(), 0, message_state);
1338     IRpcStubBuffer_Release(params->stub);
1339     IRpcChannelBuffer_Release(params->chan);
1340     if (params->handle) SetEvent(params->handle);
1341 }
1342
1343 static void __RPC_STUB dispatch_rpc(RPC_MESSAGE *msg)
1344 {
1345     struct dispatch_params *params;
1346     APARTMENT *apt;
1347     IPID ipid;
1348     HRESULT hr;
1349
1350     RpcBindingInqObject(msg->Handle, &ipid);
1351
1352     TRACE("ipid = %s, iMethod = %d\n", debugstr_guid(&ipid), msg->ProcNum);
1353
1354     params = HeapAlloc(GetProcessHeap(), 0, sizeof(*params));
1355     if (!params) return RpcRaiseException(E_OUTOFMEMORY);
1356
1357     hr = ipid_get_dispatch_params(&ipid, &apt, &params->stub, &params->chan,
1358                                   &params->iid, &params->iface);
1359     if (hr != S_OK)
1360     {
1361         ERR("no apartment found for ipid %s\n", debugstr_guid(&ipid));
1362         HeapFree(GetProcessHeap(), 0, params);
1363         return RpcRaiseException(hr);
1364     }
1365
1366     params->msg = (RPCOLEMESSAGE *)msg;
1367     params->status = RPC_S_OK;
1368     params->hr = S_OK;
1369     params->handle = NULL;
1370
1371     /* Note: this is the important difference between STAs and MTAs - we
1372      * always execute RPCs to STAs in the thread that originally created the
1373      * apartment (i.e. the one that pumps messages to the window) */
1374     if (!apt->multi_threaded)
1375     {
1376         params->handle = CreateEventW(NULL, FALSE, FALSE, NULL);
1377
1378         TRACE("Calling apartment thread 0x%08x...\n", apt->tid);
1379
1380         if (PostMessageW(apartment_getwindow(apt), DM_EXECUTERPC, 0, (LPARAM)params))
1381             WaitForSingleObject(params->handle, INFINITE);
1382         else
1383         {
1384             ERR("PostMessage failed with error %d\n", GetLastError());
1385             IRpcChannelBuffer_Release(params->chan);
1386             IRpcStubBuffer_Release(params->stub);
1387         }
1388         CloseHandle(params->handle);
1389     }
1390     else
1391     {
1392         BOOL joined = FALSE;
1393         if (!COM_CurrentInfo()->apt)
1394         {
1395             apartment_joinmta();
1396             joined = TRUE;
1397         }
1398         RPC_ExecuteCall(params);
1399         if (joined)
1400         {
1401             apartment_release(COM_CurrentInfo()->apt);
1402             COM_CurrentInfo()->apt = NULL;
1403         }
1404     }
1405
1406     hr = params->hr;
1407     HeapFree(GetProcessHeap(), 0, params);
1408
1409     apartment_release(apt);
1410
1411     /* if IRpcStubBuffer_Invoke fails, we should raise an exception to tell
1412      * the RPC runtime that the call failed */
1413     if (hr) RpcRaiseException(hr);
1414 }
1415
1416 /* stub registration */
1417 HRESULT RPC_RegisterInterface(REFIID riid)
1418 {
1419     struct registered_if *rif;
1420     BOOL found = FALSE;
1421     HRESULT hr = S_OK;
1422     
1423     TRACE("(%s)\n", debugstr_guid(riid));
1424
1425     EnterCriticalSection(&csRegIf);
1426     LIST_FOR_EACH_ENTRY(rif, &registered_interfaces, struct registered_if, entry)
1427     {
1428         if (IsEqualGUID(&rif->If.InterfaceId.SyntaxGUID, riid))
1429         {
1430             rif->refs++;
1431             found = TRUE;
1432             break;
1433         }
1434     }
1435     if (!found)
1436     {
1437         TRACE("Creating new interface\n");
1438
1439         rif = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*rif));
1440         if (rif)
1441         {
1442             RPC_STATUS status;
1443
1444             rif->refs = 1;
1445             rif->If.Length = sizeof(RPC_SERVER_INTERFACE);
1446             /* RPC interface ID = COM interface ID */
1447             rif->If.InterfaceId.SyntaxGUID = *riid;
1448             rif->If.DispatchTable = &rpc_dispatch;
1449             /* all other fields are 0, including the version asCOM objects
1450              * always have a version of 0.0 */
1451             status = RpcServerRegisterIfEx(
1452                 (RPC_IF_HANDLE)&rif->If,
1453                 NULL, NULL,
1454                 RPC_IF_OLE | RPC_IF_AUTOLISTEN,
1455                 RPC_C_LISTEN_MAX_CALLS_DEFAULT,
1456                 NULL);
1457             if (status == RPC_S_OK)
1458                 list_add_tail(&registered_interfaces, &rif->entry);
1459             else
1460             {
1461                 ERR("RpcServerRegisterIfEx failed with error %ld\n", status);
1462                 HeapFree(GetProcessHeap(), 0, rif);
1463                 hr = HRESULT_FROM_WIN32(status);
1464             }
1465         }
1466         else
1467             hr = E_OUTOFMEMORY;
1468     }
1469     LeaveCriticalSection(&csRegIf);
1470     return hr;
1471 }
1472
1473 /* stub unregistration */
1474 void RPC_UnregisterInterface(REFIID riid)
1475 {
1476     struct registered_if *rif;
1477     EnterCriticalSection(&csRegIf);
1478     LIST_FOR_EACH_ENTRY(rif, &registered_interfaces, struct registered_if, entry)
1479     {
1480         if (IsEqualGUID(&rif->If.InterfaceId.SyntaxGUID, riid))
1481         {
1482             if (!--rif->refs)
1483             {
1484                 RpcServerUnregisterIf((RPC_IF_HANDLE)&rif->If, NULL, TRUE);
1485                 list_remove(&rif->entry);
1486                 HeapFree(GetProcessHeap(), 0, rif);
1487             }
1488             break;
1489         }
1490     }
1491     LeaveCriticalSection(&csRegIf);
1492 }
1493
1494 /* make the apartment reachable by other threads and processes and create the
1495  * IRemUnknown object */
1496 void RPC_StartRemoting(struct apartment *apt)
1497 {
1498     if (!InterlockedExchange(&apt->remoting_started, TRUE))
1499     {
1500         WCHAR endpoint[200];
1501         RPC_STATUS status;
1502
1503         get_rpc_endpoint(endpoint, &apt->oxid);
1504     
1505         status = RpcServerUseProtseqEpW(
1506             wszRpcTransport,
1507             RPC_C_PROTSEQ_MAX_REQS_DEFAULT,
1508             endpoint,
1509             NULL);
1510         if (status != RPC_S_OK)
1511             ERR("Couldn't register endpoint %s\n", debugstr_w(endpoint));
1512
1513         /* FIXME: move remote unknown exporting into this function */
1514     }
1515     start_apartment_remote_unknown();
1516 }
1517
1518
1519 static HRESULT create_server(REFCLSID rclsid)
1520 {
1521     static const WCHAR  wszLocalServer32[] = { 'L','o','c','a','l','S','e','r','v','e','r','3','2',0 };
1522     static const WCHAR  embedding[] = { ' ', '-','E','m','b','e','d','d','i','n','g',0 };
1523     HKEY                key;
1524     HRESULT             hres;
1525     WCHAR               command[MAX_PATH+sizeof(embedding)/sizeof(WCHAR)];
1526     DWORD               size = (MAX_PATH+1) * sizeof(WCHAR);
1527     STARTUPINFOW        sinfo;
1528     PROCESS_INFORMATION pinfo;
1529
1530     hres = COM_OpenKeyForCLSID(rclsid, wszLocalServer32, KEY_READ, &key);
1531     if (FAILED(hres)) {
1532         ERR("class %s not registered\n", debugstr_guid(rclsid));
1533         return hres;
1534     }
1535
1536     hres = RegQueryValueExW(key, NULL, NULL, NULL, (LPBYTE)command, &size);
1537     RegCloseKey(key);
1538     if (hres) {
1539         WARN("No default value for LocalServer32 key\n");
1540         return REGDB_E_CLASSNOTREG; /* FIXME: check retval */
1541     }
1542
1543     memset(&sinfo,0,sizeof(sinfo));
1544     sinfo.cb = sizeof(sinfo);
1545
1546     /* EXE servers are started with the -Embedding switch. */
1547
1548     strcatW(command, embedding);
1549
1550     TRACE("activating local server %s for %s\n", debugstr_w(command), debugstr_guid(rclsid));
1551
1552     /* FIXME: Win2003 supports a ServerExecutable value that is passed into
1553      * CreateProcess */
1554     if (!CreateProcessW(NULL, command, NULL, NULL, FALSE, 0, NULL, NULL, &sinfo, &pinfo)) {
1555         WARN("failed to run local server %s\n", debugstr_w(command));
1556         return HRESULT_FROM_WIN32(GetLastError());
1557     }
1558     CloseHandle(pinfo.hProcess);
1559     CloseHandle(pinfo.hThread);
1560
1561     return S_OK;
1562 }
1563
1564 /*
1565  * start_local_service()  - start a service given its name and parameters
1566  */
1567 static DWORD start_local_service(LPCWSTR name, DWORD num, LPCWSTR *params)
1568 {
1569     SC_HANDLE handle, hsvc;
1570     DWORD     r = ERROR_FUNCTION_FAILED;
1571
1572     TRACE("Starting service %s %d params\n", debugstr_w(name), num);
1573
1574     handle = OpenSCManagerW(NULL, NULL, SC_MANAGER_CONNECT);
1575     if (!handle)
1576         return r;
1577     hsvc = OpenServiceW(handle, name, SERVICE_START);
1578     if (hsvc)
1579     {
1580         if(StartServiceW(hsvc, num, params))
1581             r = ERROR_SUCCESS;
1582         else
1583             r = GetLastError();
1584         if (r == ERROR_SERVICE_ALREADY_RUNNING)
1585             r = ERROR_SUCCESS;
1586         CloseServiceHandle(hsvc);
1587     }
1588     else
1589         r = GetLastError();
1590     CloseServiceHandle(handle);
1591
1592     TRACE("StartService returned error %d (%s)\n", r, (r == ERROR_SUCCESS) ? "ok":"failed");
1593
1594     return r;
1595 }
1596
1597 /*
1598  * create_local_service()  - start a COM server in a service
1599  *
1600  *   To start a Local Service, we read the AppID value under
1601  * the class's CLSID key, then open the HKCR\\AppId key specified
1602  * there and check for a LocalService value.
1603  *
1604  * Note:  Local Services are not supported under Windows 9x
1605  */
1606 static HRESULT create_local_service(REFCLSID rclsid)
1607 {
1608     HRESULT hres;
1609     WCHAR buf[CHARS_IN_GUID];
1610     static const WCHAR szLocalService[] = { 'L','o','c','a','l','S','e','r','v','i','c','e',0 };
1611     static const WCHAR szServiceParams[] = {'S','e','r','v','i','c','e','P','a','r','a','m','s',0};
1612     HKEY hkey;
1613     LONG r;
1614     DWORD type, sz;
1615
1616     TRACE("Attempting to start Local service for %s\n", debugstr_guid(rclsid));
1617
1618     hres = COM_OpenKeyForAppIdFromCLSID(rclsid, KEY_READ, &hkey);
1619     if (FAILED(hres))
1620         return hres;
1621
1622     /* read the LocalService and ServiceParameters values from the AppID key */
1623     sz = sizeof buf;
1624     r = RegQueryValueExW(hkey, szLocalService, NULL, &type, (LPBYTE)buf, &sz);
1625     if (r==ERROR_SUCCESS && type==REG_SZ)
1626     {
1627         DWORD num_args = 0;
1628         LPWSTR args[1] = { NULL };
1629
1630         /*
1631          * FIXME: I'm not really sure how to deal with the service parameters.
1632          *        I suspect that the string returned from RegQueryValueExW
1633          *        should be split into a number of arguments by spaces.
1634          *        It would make more sense if ServiceParams contained a
1635          *        REG_MULTI_SZ here, but it's a REG_SZ for the services
1636          *        that I'm interested in for the moment.
1637          */
1638         r = RegQueryValueExW(hkey, szServiceParams, NULL, &type, NULL, &sz);
1639         if (r == ERROR_SUCCESS && type == REG_SZ && sz)
1640         {
1641             args[0] = HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY,sz);
1642             num_args++;
1643             RegQueryValueExW(hkey, szServiceParams, NULL, &type, (LPBYTE)args[0], &sz);
1644         }
1645         r = start_local_service(buf, num_args, (LPCWSTR *)args);
1646         if (r != ERROR_SUCCESS)
1647             hres = REGDB_E_CLASSNOTREG; /* FIXME: check retval */
1648         HeapFree(GetProcessHeap(),0,args[0]);
1649     }
1650     else
1651     {
1652         WARN("No LocalService value\n");
1653         hres = REGDB_E_CLASSNOTREG; /* FIXME: check retval */
1654     }
1655     RegCloseKey(hkey);
1656
1657     return hres;
1658 }
1659
1660
1661 static void get_localserver_pipe_name(WCHAR *pipefn, REFCLSID rclsid)
1662 {
1663     static const WCHAR wszPipeRef[] = {'\\','\\','.','\\','p','i','p','e','\\',0};
1664     strcpyW(pipefn, wszPipeRef);
1665     StringFromGUID2(rclsid, pipefn + sizeof(wszPipeRef)/sizeof(wszPipeRef[0]) - 1, CHARS_IN_GUID);
1666 }
1667
1668 /* FIXME: should call to rpcss instead */
1669 HRESULT RPC_GetLocalClassObject(REFCLSID rclsid, REFIID iid, LPVOID *ppv)
1670 {
1671     HRESULT        hres;
1672     HANDLE         hPipe;
1673     WCHAR          pipefn[100];
1674     DWORD          res, bufferlen;
1675     char           marshalbuffer[200];
1676     IStream       *pStm;
1677     LARGE_INTEGER  seekto;
1678     ULARGE_INTEGER newpos;
1679     int            tries = 0;
1680
1681     static const int MAXTRIES = 30; /* 30 seconds */
1682
1683     TRACE("rclsid=%s, iid=%s\n", debugstr_guid(rclsid), debugstr_guid(iid));
1684
1685     get_localserver_pipe_name(pipefn, rclsid);
1686
1687     while (tries++ < MAXTRIES) {
1688         TRACE("waiting for %s\n", debugstr_w(pipefn));
1689       
1690         WaitNamedPipeW( pipefn, NMPWAIT_WAIT_FOREVER );
1691         hPipe = CreateFileW(pipefn, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, 0);
1692         if (hPipe == INVALID_HANDLE_VALUE) {
1693             if (tries == 1) {
1694                 if ( (hres = create_local_service(rclsid)) &&
1695                      (hres = create_server(rclsid)) )
1696                     return hres;
1697                 Sleep(1000);
1698             } else {
1699                 WARN("Connecting to %s, no response yet, retrying: le is %x\n", debugstr_w(pipefn), GetLastError());
1700                 Sleep(1000);
1701             }
1702             continue;
1703         }
1704         bufferlen = 0;
1705         if (!ReadFile(hPipe,marshalbuffer,sizeof(marshalbuffer),&bufferlen,NULL)) {
1706             FIXME("Failed to read marshal id from classfactory of %s.\n",debugstr_guid(rclsid));
1707             Sleep(1000);
1708             continue;
1709         }
1710         TRACE("read marshal id from pipe\n");
1711         CloseHandle(hPipe);
1712         break;
1713     }
1714     
1715     if (tries >= MAXTRIES)
1716         return E_NOINTERFACE;
1717     
1718     hres = CreateStreamOnHGlobal(0,TRUE,&pStm);
1719     if (hres) return hres;
1720     hres = IStream_Write(pStm,marshalbuffer,bufferlen,&res);
1721     if (hres) goto out;
1722     seekto.u.LowPart = 0;seekto.u.HighPart = 0;
1723     hres = IStream_Seek(pStm,seekto,SEEK_SET,&newpos);
1724     
1725     TRACE("unmarshalling classfactory\n");
1726     hres = CoUnmarshalInterface(pStm,&IID_IClassFactory,ppv);
1727 out:
1728     IStream_Release(pStm);
1729     return hres;
1730 }
1731
1732
1733 struct local_server_params
1734 {
1735     CLSID clsid;
1736     IStream *stream;
1737     HANDLE ready_event;
1738 };
1739
1740 /* FIXME: should call to rpcss instead */
1741 static DWORD WINAPI local_server_thread(LPVOID param)
1742 {
1743     struct local_server_params * lsp = (struct local_server_params *)param;
1744     HANDLE              hPipe;
1745     WCHAR               pipefn[100];
1746     HRESULT             hres;
1747     IStream             *pStm = lsp->stream;
1748     STATSTG             ststg;
1749     unsigned char       *buffer;
1750     int                 buflen;
1751     LARGE_INTEGER       seekto;
1752     ULARGE_INTEGER      newpos;
1753     ULONG               res;
1754
1755     TRACE("Starting threader for %s.\n",debugstr_guid(&lsp->clsid));
1756
1757     get_localserver_pipe_name(pipefn, &lsp->clsid);
1758
1759     hPipe = CreateNamedPipeW( pipefn, PIPE_ACCESS_DUPLEX,
1760                               PIPE_TYPE_BYTE|PIPE_WAIT, PIPE_UNLIMITED_INSTANCES,
1761                               4096, 4096, 500 /* 0.5 second timeout */, NULL );
1762
1763     SetEvent(lsp->ready_event);
1764
1765     HeapFree(GetProcessHeap(), 0, lsp);
1766
1767     if (hPipe == INVALID_HANDLE_VALUE)
1768     {
1769         FIXME("pipe creation failed for %s, le is %d\n", debugstr_w(pipefn), GetLastError());
1770         return 1;
1771     }
1772     
1773     while (1) {
1774         if (!ConnectNamedPipe(hPipe,NULL) && GetLastError() != ERROR_PIPE_CONNECTED) {
1775             ERR("Failure during ConnectNamedPipe %d, ABORT!\n",GetLastError());
1776             break;
1777         }
1778
1779         TRACE("marshalling IClassFactory to client\n");
1780         
1781         hres = IStream_Stat(pStm,&ststg,0);
1782         if (hres) return hres;
1783
1784         seekto.u.LowPart = 0;
1785         seekto.u.HighPart = 0;
1786         hres = IStream_Seek(pStm,seekto,SEEK_SET,&newpos);
1787         if (hres) {
1788             FIXME("IStream_Seek failed, %x\n",hres);
1789             return hres;
1790         }
1791
1792         buflen = ststg.cbSize.u.LowPart;
1793         buffer = HeapAlloc(GetProcessHeap(),0,buflen);
1794         
1795         hres = IStream_Read(pStm,buffer,buflen,&res);
1796         if (hres) {
1797             FIXME("Stream Read failed, %x\n",hres);
1798             HeapFree(GetProcessHeap(),0,buffer);
1799             return hres;
1800         }
1801         
1802         WriteFile(hPipe,buffer,buflen,&res,NULL);
1803         HeapFree(GetProcessHeap(),0,buffer);
1804
1805         FlushFileBuffers(hPipe);
1806         DisconnectNamedPipe(hPipe);
1807
1808         TRACE("done marshalling IClassFactory\n");
1809     }
1810     CloseHandle(hPipe);
1811     IStream_Release(pStm);
1812     return 0;
1813 }
1814
1815 void RPC_StartLocalServer(REFCLSID clsid, IStream *stream)
1816 {
1817     DWORD tid;
1818     HANDLE thread, ready_event;
1819     struct local_server_params *lsp = HeapAlloc(GetProcessHeap(), 0, sizeof(*lsp));
1820
1821     lsp->clsid = *clsid;
1822     lsp->stream = stream;
1823     IStream_AddRef(stream);
1824     lsp->ready_event = ready_event = CreateEventW(NULL, FALSE, FALSE, NULL);
1825
1826     thread = CreateThread(NULL, 0, local_server_thread, lsp, 0, &tid);
1827     CloseHandle(thread);
1828     /* FIXME: failure handling */
1829
1830     WaitForSingleObject(ready_event, INFINITE);
1831     CloseHandle(ready_event);
1832 }