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