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