po: Update Lithuanian translation.
[wine/multimedia.git] / dlls / ole32 / rpc.c
blobc33674364cf4ad88f161933e64048f330d6b6991
1 /*
2 * RPC Manager
4 * Copyright 2001 Ove Kåven, TransGaming Technologies
5 * Copyright 2002 Marcus Meissner
6 * Copyright 2005 Mike Hearn, Rob Shearman for CodeWeavers
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.
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.
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
23 #include "config.h"
24 #include "wine/port.h"
26 #include <stdarg.h>
27 #include <string.h>
29 #define COBJMACROS
30 #define NONAMELESSUNION
31 #define NONAMELESSSTRUCT
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"
44 #include "compobj_private.h"
46 #include "wine/debug.h"
48 WINE_DEFAULT_DEBUG_CHANNEL(ole);
50 static void __RPC_STUB dispatch_rpc(RPC_MESSAGE *msg);
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) */
57 static struct list registered_interfaces = LIST_INIT(registered_interfaces); /* (CS csRegIf) */
58 static CRITICAL_SECTION csRegIf;
59 static CRITICAL_SECTION_DEBUG csRegIf_debug =
61 0, 0, &csRegIf,
62 { &csRegIf_debug.ProcessLocksList, &csRegIf_debug.ProcessLocksList },
63 0, 0, { (DWORD_PTR)(__FILE__ ": dcom registered server interfaces") }
65 static CRITICAL_SECTION csRegIf = { &csRegIf_debug, -1, 0, 0, 0, 0 };
67 static struct list channel_hooks = LIST_INIT(channel_hooks); /* (CS csChannelHook) */
68 static CRITICAL_SECTION csChannelHook;
69 static CRITICAL_SECTION_DEBUG csChannelHook_debug =
71 0, 0, &csChannelHook,
72 { &csChannelHook_debug.ProcessLocksList, &csChannelHook_debug.ProcessLocksList },
73 0, 0, { (DWORD_PTR)(__FILE__ ": channel hooks") }
75 static CRITICAL_SECTION csChannelHook = { &csChannelHook_debug, -1, 0, 0, 0, 0 };
77 static WCHAR wszRpcTransport[] = {'n','c','a','l','r','p','c',0};
80 struct registered_if
82 struct list entry;
83 DWORD refs; /* ref count */
84 RPC_SERVER_INTERFACE If; /* interface registered with the RPC runtime */
87 /* get the pipe endpoint specified of the specified apartment */
88 static inline void get_rpc_endpoint(LPWSTR endpoint, const OXID *oxid)
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);
95 typedef struct
97 const IRpcChannelBufferVtbl *lpVtbl;
98 LONG refs;
99 } RpcChannelBuffer;
101 typedef struct
103 RpcChannelBuffer super; /* superclass */
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;
113 struct dispatch_params
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) */
126 struct message_state
128 RPC_BINDING_HANDLE binding_handle;
129 ULONG prefix_data_len;
130 SChannelHookCallInfo channel_hook_info;
131 BOOL bypass_rpcrt;
133 /* client only */
134 HWND target_hwnd;
135 DWORD target_tid;
136 struct dispatch_params params;
139 typedef struct
141 ULONG conformance; /* NDR */
142 GUID id;
143 ULONG size;
144 /* [size_is((size+7)&~7)] */ unsigned char data[1];
145 } WIRE_ORPC_EXTENT;
147 typedef struct
149 ULONG size;
150 ULONG reserved;
151 unsigned char extent[1];
152 } WIRE_ORPC_EXTENT_ARRAY;
154 typedef struct
156 ULONG version;
157 ULONG flags;
158 ULONG reserved1;
159 GUID cid;
160 unsigned char extensions[1];
161 } WIRE_ORPCTHIS;
163 typedef struct
165 ULONG flags;
166 unsigned char extensions[1];
167 } WIRE_ORPCTHAT;
169 struct channel_hook_entry
171 struct list entry;
172 GUID id;
173 IChannelHook *hook;
176 struct channel_hook_buffer_data
178 GUID id;
179 ULONG extension_size;
183 static HRESULT unmarshal_ORPCTHAT(RPC_MESSAGE *msg, ORPCTHAT *orpcthat,
184 ORPC_EXTENT_ARRAY *orpc_ext_array, WIRE_ORPC_EXTENT **first_wire_orpc_extent);
186 /* Channel Hook Functions */
188 static ULONG ChannelHooks_ClientGetSize(SChannelHookCallInfo *info,
189 struct channel_hook_buffer_data **data, unsigned int *hook_count,
190 ULONG *extension_count)
192 struct channel_hook_entry *entry;
193 ULONG total_size = 0;
194 unsigned int hook_index = 0;
196 *hook_count = 0;
197 *extension_count = 0;
199 EnterCriticalSection(&csChannelHook);
201 LIST_FOR_EACH_ENTRY(entry, &channel_hooks, struct channel_hook_entry, entry)
202 (*hook_count)++;
204 if (*hook_count)
205 *data = HeapAlloc(GetProcessHeap(), 0, *hook_count * sizeof(struct channel_hook_buffer_data));
206 else
207 *data = NULL;
209 LIST_FOR_EACH_ENTRY(entry, &channel_hooks, struct channel_hook_entry, entry)
211 ULONG extension_size = 0;
213 IChannelHook_ClientGetSize(entry->hook, &entry->id, &info->iid, &extension_size);
215 TRACE("%s: extension_size = %u\n", debugstr_guid(&entry->id), extension_size);
217 extension_size = (extension_size+7)&~7;
218 (*data)[hook_index].id = entry->id;
219 (*data)[hook_index].extension_size = extension_size;
221 /* an extension is only put onto the wire if it has data to write */
222 if (extension_size)
224 total_size += FIELD_OFFSET(WIRE_ORPC_EXTENT, data[extension_size]);
225 (*extension_count)++;
228 hook_index++;
231 LeaveCriticalSection(&csChannelHook);
233 return total_size;
236 static unsigned char * ChannelHooks_ClientFillBuffer(SChannelHookCallInfo *info,
237 unsigned char *buffer, struct channel_hook_buffer_data *data,
238 unsigned int hook_count)
240 struct channel_hook_entry *entry;
242 EnterCriticalSection(&csChannelHook);
244 LIST_FOR_EACH_ENTRY(entry, &channel_hooks, struct channel_hook_entry, entry)
246 unsigned int i;
247 ULONG extension_size = 0;
248 WIRE_ORPC_EXTENT *wire_orpc_extent = (WIRE_ORPC_EXTENT *)buffer;
250 for (i = 0; i < hook_count; i++)
251 if (IsEqualGUID(&entry->id, &data[i].id))
252 extension_size = data[i].extension_size;
254 /* an extension is only put onto the wire if it has data to write */
255 if (!extension_size)
256 continue;
258 IChannelHook_ClientFillBuffer(entry->hook, &entry->id, &info->iid,
259 &extension_size, buffer + FIELD_OFFSET(WIRE_ORPC_EXTENT, data[0]));
261 TRACE("%s: extension_size = %u\n", debugstr_guid(&entry->id), extension_size);
263 /* FIXME: set unused portion of wire_orpc_extent->data to 0? */
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]);
271 LeaveCriticalSection(&csChannelHook);
273 return buffer;
276 static void ChannelHooks_ServerNotify(SChannelHookCallInfo *info,
277 DWORD lDataRep, WIRE_ORPC_EXTENT *first_wire_orpc_extent,
278 ULONG extension_count)
280 struct channel_hook_entry *entry;
281 ULONG i;
283 EnterCriticalSection(&csChannelHook);
285 LIST_FOR_EACH_ENTRY(entry, &channel_hooks, struct channel_hook_entry, entry)
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])
292 if (IsEqualGUID(&entry->id, &wire_orpc_extent->id))
293 break;
295 if (i == extension_count) wire_orpc_extent = NULL;
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);
303 LeaveCriticalSection(&csChannelHook);
306 static ULONG ChannelHooks_ServerGetSize(SChannelHookCallInfo *info,
307 struct channel_hook_buffer_data **data, unsigned int *hook_count,
308 ULONG *extension_count)
310 struct channel_hook_entry *entry;
311 ULONG total_size = 0;
312 unsigned int hook_index = 0;
314 *hook_count = 0;
315 *extension_count = 0;
317 EnterCriticalSection(&csChannelHook);
319 LIST_FOR_EACH_ENTRY(entry, &channel_hooks, struct channel_hook_entry, entry)
320 (*hook_count)++;
322 if (*hook_count)
323 *data = HeapAlloc(GetProcessHeap(), 0, *hook_count * sizeof(struct channel_hook_buffer_data));
324 else
325 *data = NULL;
327 LIST_FOR_EACH_ENTRY(entry, &channel_hooks, struct channel_hook_entry, entry)
329 ULONG extension_size = 0;
331 IChannelHook_ServerGetSize(entry->hook, &entry->id, &info->iid, S_OK,
332 &extension_size);
334 TRACE("%s: extension_size = %u\n", debugstr_guid(&entry->id), extension_size);
336 extension_size = (extension_size+7)&~7;
337 (*data)[hook_index].id = entry->id;
338 (*data)[hook_index].extension_size = extension_size;
340 /* an extension is only put onto the wire if it has data to write */
341 if (extension_size)
343 total_size += FIELD_OFFSET(WIRE_ORPC_EXTENT, data[extension_size]);
344 (*extension_count)++;
347 hook_index++;
350 LeaveCriticalSection(&csChannelHook);
352 return total_size;
355 static unsigned char * ChannelHooks_ServerFillBuffer(SChannelHookCallInfo *info,
356 unsigned char *buffer, struct channel_hook_buffer_data *data,
357 unsigned int hook_count)
359 struct channel_hook_entry *entry;
361 EnterCriticalSection(&csChannelHook);
363 LIST_FOR_EACH_ENTRY(entry, &channel_hooks, struct channel_hook_entry, entry)
365 unsigned int i;
366 ULONG extension_size = 0;
367 WIRE_ORPC_EXTENT *wire_orpc_extent = (WIRE_ORPC_EXTENT *)buffer;
369 for (i = 0; i < hook_count; i++)
370 if (IsEqualGUID(&entry->id, &data[i].id))
371 extension_size = data[i].extension_size;
373 /* an extension is only put onto the wire if it has data to write */
374 if (!extension_size)
375 continue;
377 IChannelHook_ServerFillBuffer(entry->hook, &entry->id, &info->iid,
378 &extension_size, buffer + FIELD_OFFSET(WIRE_ORPC_EXTENT, data[0]),
379 S_OK);
381 TRACE("%s: extension_size = %u\n", debugstr_guid(&entry->id), extension_size);
383 /* FIXME: set unused portion of wire_orpc_extent->data to 0? */
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]);
391 LeaveCriticalSection(&csChannelHook);
393 return buffer;
396 static void ChannelHooks_ClientNotify(SChannelHookCallInfo *info,
397 DWORD lDataRep, WIRE_ORPC_EXTENT *first_wire_orpc_extent,
398 ULONG extension_count, HRESULT hrFault)
400 struct channel_hook_entry *entry;
401 ULONG i;
403 EnterCriticalSection(&csChannelHook);
405 LIST_FOR_EACH_ENTRY(entry, &channel_hooks, struct channel_hook_entry, entry)
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])
412 if (IsEqualGUID(&entry->id, &wire_orpc_extent->id))
413 break;
415 if (i == extension_count) wire_orpc_extent = NULL;
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);
423 LeaveCriticalSection(&csChannelHook);
426 HRESULT RPC_RegisterChannelHook(REFGUID rguid, IChannelHook *hook)
428 struct channel_hook_entry *entry;
430 TRACE("(%s, %p)\n", debugstr_guid(rguid), hook);
432 entry = HeapAlloc(GetProcessHeap(), 0, sizeof(*entry));
433 if (!entry)
434 return E_OUTOFMEMORY;
436 entry->id = *rguid;
437 entry->hook = hook;
438 IChannelHook_AddRef(hook);
440 EnterCriticalSection(&csChannelHook);
441 list_add_tail(&channel_hooks, &entry->entry);
442 LeaveCriticalSection(&csChannelHook);
444 return S_OK;
447 void RPC_UnregisterAllChannelHooks(void)
449 struct channel_hook_entry *cursor;
450 struct channel_hook_entry *cursor2;
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 DeleteCriticalSection(&csChannelHook);
457 DeleteCriticalSection(&csRegIf);
460 /* RPC Channel Buffer Functions */
462 static HRESULT WINAPI RpcChannelBuffer_QueryInterface(LPRPCCHANNELBUFFER iface, REFIID riid, LPVOID *ppv)
464 *ppv = NULL;
465 if (IsEqualIID(riid,&IID_IRpcChannelBuffer) || IsEqualIID(riid,&IID_IUnknown))
467 *ppv = iface;
468 IUnknown_AddRef(iface);
469 return S_OK;
471 return E_NOINTERFACE;
474 static ULONG WINAPI RpcChannelBuffer_AddRef(LPRPCCHANNELBUFFER iface)
476 RpcChannelBuffer *This = (RpcChannelBuffer *)iface;
477 return InterlockedIncrement(&This->refs);
480 static ULONG WINAPI ServerRpcChannelBuffer_Release(LPRPCCHANNELBUFFER iface)
482 RpcChannelBuffer *This = (RpcChannelBuffer *)iface;
483 ULONG ref;
485 ref = InterlockedDecrement(&This->refs);
486 if (ref)
487 return ref;
489 HeapFree(GetProcessHeap(), 0, This);
490 return 0;
493 static ULONG WINAPI ClientRpcChannelBuffer_Release(LPRPCCHANNELBUFFER iface)
495 ClientRpcChannelBuffer *This = (ClientRpcChannelBuffer *)iface;
496 ULONG ref;
498 ref = InterlockedDecrement(&This->super.refs);
499 if (ref)
500 return ref;
502 if (This->event) CloseHandle(This->event);
503 RpcBindingFree(&This->bind);
504 HeapFree(GetProcessHeap(), 0, This);
505 return 0;
508 static HRESULT WINAPI ServerRpcChannelBuffer_GetBuffer(LPRPCCHANNELBUFFER iface, RPCOLEMESSAGE* olemsg, REFIID riid)
510 RpcChannelBuffer *This = (RpcChannelBuffer *)iface;
511 RPC_MESSAGE *msg = (RPC_MESSAGE *)olemsg;
512 RPC_STATUS status;
513 ORPCTHAT *orpcthat;
514 struct message_state *message_state;
515 ULONG extensions_size;
516 struct channel_hook_buffer_data *channel_hook_data;
517 unsigned int channel_hook_count;
518 ULONG extension_count;
520 TRACE("(%p)->(%p,%s)\n", This, olemsg, debugstr_guid(riid));
522 message_state = msg->Handle;
523 /* restore the binding handle and the real start of data */
524 msg->Handle = message_state->binding_handle;
525 msg->Buffer = (char *)msg->Buffer - message_state->prefix_data_len;
527 extensions_size = ChannelHooks_ServerGetSize(&message_state->channel_hook_info,
528 &channel_hook_data, &channel_hook_count, &extension_count);
530 msg->BufferLength += FIELD_OFFSET(WIRE_ORPCTHAT, extensions) + sizeof(DWORD);
531 if (extensions_size)
533 msg->BufferLength += FIELD_OFFSET(WIRE_ORPC_EXTENT_ARRAY, extent[2*sizeof(DWORD) + extensions_size]);
534 if (extension_count & 1)
535 msg->BufferLength += FIELD_OFFSET(WIRE_ORPC_EXTENT, data[0]);
538 if (message_state->bypass_rpcrt)
540 msg->Buffer = HeapAlloc(GetProcessHeap(), 0, msg->BufferLength);
541 if (msg->Buffer)
542 status = RPC_S_OK;
543 else
545 HeapFree(GetProcessHeap(), 0, channel_hook_data);
546 return E_OUTOFMEMORY;
549 else
550 status = I_RpcGetBuffer(msg);
552 orpcthat = msg->Buffer;
553 msg->Buffer = (char *)msg->Buffer + FIELD_OFFSET(WIRE_ORPCTHAT, extensions);
555 orpcthat->flags = ORPCF_NULL /* FIXME? */;
557 /* NDR representation of orpcthat->extensions */
558 *(DWORD *)msg->Buffer = extensions_size ? 1 : 0;
559 msg->Buffer = (char *)msg->Buffer + sizeof(DWORD);
561 if (extensions_size)
563 WIRE_ORPC_EXTENT_ARRAY *orpc_extent_array = msg->Buffer;
564 orpc_extent_array->size = extension_count;
565 orpc_extent_array->reserved = 0;
566 msg->Buffer = (char *)msg->Buffer + FIELD_OFFSET(WIRE_ORPC_EXTENT_ARRAY, extent);
567 /* NDR representation of orpc_extent_array->extent */
568 *(DWORD *)msg->Buffer = 1;
569 msg->Buffer = (char *)msg->Buffer + sizeof(DWORD);
570 /* NDR representation of [size_is] attribute of orpc_extent_array->extent */
571 *(DWORD *)msg->Buffer = (extension_count + 1) & ~1;
572 msg->Buffer = (char *)msg->Buffer + sizeof(DWORD);
574 msg->Buffer = ChannelHooks_ServerFillBuffer(&message_state->channel_hook_info,
575 msg->Buffer, channel_hook_data, channel_hook_count);
577 /* we must add a dummy extension if there is an odd extension
578 * count to meet the contract specified by the size_is attribute */
579 if (extension_count & 1)
581 WIRE_ORPC_EXTENT *wire_orpc_extent = msg->Buffer;
582 wire_orpc_extent->conformance = 0;
583 wire_orpc_extent->id = GUID_NULL;
584 wire_orpc_extent->size = 0;
585 msg->Buffer = (char *)msg->Buffer + FIELD_OFFSET(WIRE_ORPC_EXTENT, data[0]);
589 HeapFree(GetProcessHeap(), 0, channel_hook_data);
591 /* store the prefixed data length so that we can restore the real buffer
592 * later */
593 message_state->prefix_data_len = (char *)msg->Buffer - (char *)orpcthat;
594 msg->BufferLength -= message_state->prefix_data_len;
595 /* save away the message state again */
596 msg->Handle = message_state;
598 TRACE("-- %d\n", status);
600 return HRESULT_FROM_WIN32(status);
603 static HANDLE ClientRpcChannelBuffer_GetEventHandle(ClientRpcChannelBuffer *This)
605 HANDLE event = InterlockedExchangePointer(&This->event, NULL);
607 /* Note: must be auto-reset event so we can reuse it without a call
608 * to ResetEvent */
609 if (!event) event = CreateEventW(NULL, FALSE, FALSE, NULL);
611 return event;
614 static void ClientRpcChannelBuffer_ReleaseEventHandle(ClientRpcChannelBuffer *This, HANDLE event)
616 if (InterlockedCompareExchangePointer(&This->event, event, NULL))
617 /* already a handle cached in This */
618 CloseHandle(event);
621 static HRESULT WINAPI ClientRpcChannelBuffer_GetBuffer(LPRPCCHANNELBUFFER iface, RPCOLEMESSAGE* olemsg, REFIID riid)
623 ClientRpcChannelBuffer *This = (ClientRpcChannelBuffer *)iface;
624 RPC_MESSAGE *msg = (RPC_MESSAGE *)olemsg;
625 RPC_CLIENT_INTERFACE *cif;
626 RPC_STATUS status;
627 ORPCTHIS *orpcthis;
628 struct message_state *message_state;
629 ULONG extensions_size;
630 struct channel_hook_buffer_data *channel_hook_data;
631 unsigned int channel_hook_count;
632 ULONG extension_count;
633 IPID ipid;
634 HRESULT hr;
635 APARTMENT *apt = NULL;
637 TRACE("(%p)->(%p,%s)\n", This, olemsg, debugstr_guid(riid));
639 cif = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(RPC_CLIENT_INTERFACE));
640 if (!cif)
641 return E_OUTOFMEMORY;
643 message_state = HeapAlloc(GetProcessHeap(), 0, sizeof(*message_state));
644 if (!message_state)
646 HeapFree(GetProcessHeap(), 0, cif);
647 return E_OUTOFMEMORY;
650 cif->Length = sizeof(RPC_CLIENT_INTERFACE);
651 /* RPC interface ID = COM interface ID */
652 cif->InterfaceId.SyntaxGUID = *riid;
653 /* COM objects always have a version of 0.0 */
654 cif->InterfaceId.SyntaxVersion.MajorVersion = 0;
655 cif->InterfaceId.SyntaxVersion.MinorVersion = 0;
656 msg->Handle = This->bind;
657 msg->RpcInterfaceInformation = cif;
659 message_state->prefix_data_len = 0;
660 message_state->binding_handle = This->bind;
662 message_state->channel_hook_info.iid = *riid;
663 message_state->channel_hook_info.cbSize = sizeof(message_state->channel_hook_info);
664 message_state->channel_hook_info.uCausality = COM_CurrentCausalityId();
665 message_state->channel_hook_info.dwServerPid = This->server_pid;
666 message_state->channel_hook_info.iMethod = msg->ProcNum;
667 message_state->channel_hook_info.pObject = NULL; /* only present on server-side */
668 message_state->target_hwnd = NULL;
669 message_state->target_tid = 0;
670 memset(&message_state->params, 0, sizeof(message_state->params));
672 extensions_size = ChannelHooks_ClientGetSize(&message_state->channel_hook_info,
673 &channel_hook_data, &channel_hook_count, &extension_count);
675 msg->BufferLength += FIELD_OFFSET(WIRE_ORPCTHIS, extensions) + sizeof(DWORD);
676 if (extensions_size)
678 msg->BufferLength += FIELD_OFFSET(WIRE_ORPC_EXTENT_ARRAY, extent[2*sizeof(DWORD) + extensions_size]);
679 if (extension_count & 1)
680 msg->BufferLength += FIELD_OFFSET(WIRE_ORPC_EXTENT, data[0]);
683 RpcBindingInqObject(message_state->binding_handle, &ipid);
684 hr = ipid_get_dispatch_params(&ipid, &apt, &message_state->params.stub,
685 &message_state->params.chan,
686 &message_state->params.iid,
687 &message_state->params.iface);
688 if (hr == S_OK)
690 /* stub, chan, iface and iid are unneeded in multi-threaded case as we go
691 * via the RPC runtime */
692 if (apt->multi_threaded)
694 IRpcStubBuffer_Release(message_state->params.stub);
695 message_state->params.stub = NULL;
696 IRpcChannelBuffer_Release(message_state->params.chan);
697 message_state->params.chan = NULL;
698 message_state->params.iface = NULL;
700 else
702 message_state->params.bypass_rpcrt = TRUE;
703 message_state->target_hwnd = apartment_getwindow(apt);
704 message_state->target_tid = apt->tid;
705 /* we assume later on that this being non-NULL is the indicator that
706 * means call directly instead of going through RPC runtime */
707 if (!message_state->target_hwnd)
708 ERR("window for apartment %s is NULL\n", wine_dbgstr_longlong(apt->oxid));
711 if (apt) apartment_release(apt);
712 message_state->params.handle = ClientRpcChannelBuffer_GetEventHandle(This);
713 /* Note: message_state->params.msg is initialised in
714 * ClientRpcChannelBuffer_SendReceive */
716 /* shortcut the RPC runtime */
717 if (message_state->target_hwnd)
719 msg->Buffer = HeapAlloc(GetProcessHeap(), 0, msg->BufferLength);
720 if (msg->Buffer)
721 status = RPC_S_OK;
722 else
723 status = ERROR_OUTOFMEMORY;
725 else
726 status = I_RpcGetBuffer(msg);
728 msg->Handle = message_state;
730 if (status == RPC_S_OK)
732 orpcthis = msg->Buffer;
733 msg->Buffer = (char *)msg->Buffer + FIELD_OFFSET(WIRE_ORPCTHIS, extensions);
735 orpcthis->version.MajorVersion = COM_MAJOR_VERSION;
736 orpcthis->version.MinorVersion = COM_MINOR_VERSION;
737 orpcthis->flags = message_state->channel_hook_info.dwServerPid ? ORPCF_LOCAL : ORPCF_NULL;
738 orpcthis->reserved1 = 0;
739 orpcthis->cid = message_state->channel_hook_info.uCausality;
741 /* NDR representation of orpcthis->extensions */
742 *(DWORD *)msg->Buffer = extensions_size ? 1 : 0;
743 msg->Buffer = (char *)msg->Buffer + sizeof(DWORD);
745 if (extensions_size)
747 ORPC_EXTENT_ARRAY *orpc_extent_array = msg->Buffer;
748 orpc_extent_array->size = extension_count;
749 orpc_extent_array->reserved = 0;
750 msg->Buffer = (char *)msg->Buffer + FIELD_OFFSET(WIRE_ORPC_EXTENT_ARRAY, extent);
751 /* NDR representation of orpc_extent_array->extent */
752 *(DWORD *)msg->Buffer = 1;
753 msg->Buffer = (char *)msg->Buffer + sizeof(DWORD);
754 /* NDR representation of [size_is] attribute of orpc_extent_array->extent */
755 *(DWORD *)msg->Buffer = (extension_count + 1) & ~1;
756 msg->Buffer = (char *)msg->Buffer + sizeof(DWORD);
758 msg->Buffer = ChannelHooks_ClientFillBuffer(&message_state->channel_hook_info,
759 msg->Buffer, channel_hook_data, channel_hook_count);
761 /* we must add a dummy extension if there is an odd extension
762 * count to meet the contract specified by the size_is attribute */
763 if (extension_count & 1)
765 WIRE_ORPC_EXTENT *wire_orpc_extent = msg->Buffer;
766 wire_orpc_extent->conformance = 0;
767 wire_orpc_extent->id = GUID_NULL;
768 wire_orpc_extent->size = 0;
769 msg->Buffer = (char *)msg->Buffer + FIELD_OFFSET(WIRE_ORPC_EXTENT, data[0]);
773 /* store the prefixed data length so that we can restore the real buffer
774 * pointer in ClientRpcChannelBuffer_SendReceive. */
775 message_state->prefix_data_len = (char *)msg->Buffer - (char *)orpcthis;
776 msg->BufferLength -= message_state->prefix_data_len;
779 HeapFree(GetProcessHeap(), 0, channel_hook_data);
781 TRACE("-- %d\n", status);
783 return HRESULT_FROM_WIN32(status);
786 static HRESULT WINAPI ServerRpcChannelBuffer_SendReceive(LPRPCCHANNELBUFFER iface, RPCOLEMESSAGE *olemsg, ULONG *pstatus)
788 FIXME("stub\n");
789 return E_NOTIMPL;
792 /* this thread runs an outgoing RPC */
793 static DWORD WINAPI rpc_sendreceive_thread(LPVOID param)
795 struct dispatch_params *data = param;
797 /* Note: I_RpcSendReceive doesn't raise exceptions like the higher-level
798 * RPC functions do */
799 data->status = I_RpcSendReceive((RPC_MESSAGE *)data->msg);
801 TRACE("completed with status 0x%x\n", data->status);
803 SetEvent(data->handle);
805 return 0;
808 static inline HRESULT ClientRpcChannelBuffer_IsCorrectApartment(ClientRpcChannelBuffer *This, APARTMENT *apt)
810 OXID oxid;
811 if (!apt)
812 return S_FALSE;
813 if (apartment_getoxid(apt, &oxid) != S_OK)
814 return S_FALSE;
815 if (This->oxid != oxid)
816 return S_FALSE;
817 return S_OK;
820 static HRESULT WINAPI ClientRpcChannelBuffer_SendReceive(LPRPCCHANNELBUFFER iface, RPCOLEMESSAGE *olemsg, ULONG *pstatus)
822 ClientRpcChannelBuffer *This = (ClientRpcChannelBuffer *)iface;
823 HRESULT hr;
824 RPC_MESSAGE *msg = (RPC_MESSAGE *)olemsg;
825 RPC_STATUS status;
826 DWORD index;
827 struct message_state *message_state;
828 ORPCTHAT orpcthat;
829 ORPC_EXTENT_ARRAY orpc_ext_array;
830 WIRE_ORPC_EXTENT *first_wire_orpc_extent = NULL;
831 HRESULT hrFault = S_OK;
833 TRACE("(%p) iMethod=%d\n", olemsg, olemsg->iMethod);
835 hr = ClientRpcChannelBuffer_IsCorrectApartment(This, COM_CurrentApt());
836 if (hr != S_OK)
838 ERR("called from wrong apartment, should have been 0x%s\n",
839 wine_dbgstr_longlong(This->oxid));
840 return RPC_E_WRONG_THREAD;
842 /* This situation should be impossible in multi-threaded apartments,
843 * because the calling thread isn't re-enterable.
844 * Note: doing a COM call during the processing of a sent message is
845 * only disallowed if a client call is already being waited for
846 * completion */
847 if (!COM_CurrentApt()->multi_threaded &&
848 COM_CurrentInfo()->pending_call_count_client &&
849 InSendMessage())
851 ERR("can't make an outgoing COM call in response to a sent message\n");
852 return RPC_E_CANTCALLOUT_ININPUTSYNCCALL;
855 message_state = msg->Handle;
856 /* restore the binding handle and the real start of data */
857 msg->Handle = message_state->binding_handle;
858 msg->Buffer = (char *)msg->Buffer - message_state->prefix_data_len;
859 msg->BufferLength += message_state->prefix_data_len;
861 /* Note: this is an optimization in the Microsoft OLE runtime that we need
862 * to copy, as shown by the test_no_couninitialize_client test. without
863 * short-circuiting the RPC runtime in the case below, the test will
864 * deadlock on the loader lock due to the RPC runtime needing to create
865 * a thread to process the RPC when this function is called indirectly
866 * from DllMain */
868 message_state->params.msg = olemsg;
869 if (message_state->params.bypass_rpcrt)
871 TRACE("Calling apartment thread 0x%08x...\n", message_state->target_tid);
873 msg->ProcNum &= ~RPC_FLAGS_VALID_BIT;
875 if (!PostMessageW(message_state->target_hwnd, DM_EXECUTERPC, 0,
876 (LPARAM)&message_state->params))
878 ERR("PostMessage failed with error %u\n", GetLastError());
880 /* Note: message_state->params.iface doesn't have a reference and
881 * so doesn't need to be released */
883 hr = HRESULT_FROM_WIN32(GetLastError());
886 else
888 /* we use a separate thread here because we need to be able to
889 * pump the message loop in the application thread: if we do not,
890 * any windows created by this thread will hang and RPCs that try
891 * and re-enter this STA from an incoming server thread will
892 * deadlock. InstallShield is an example of that.
894 if (!QueueUserWorkItem(rpc_sendreceive_thread, &message_state->params, WT_EXECUTEDEFAULT))
896 ERR("QueueUserWorkItem failed with error %u\n", GetLastError());
897 hr = E_UNEXPECTED;
899 else
900 hr = S_OK;
903 if (hr == S_OK)
905 if (WaitForSingleObject(message_state->params.handle, 0))
907 COM_CurrentInfo()->pending_call_count_client++;
908 hr = CoWaitForMultipleHandles(0, INFINITE, 1, &message_state->params.handle, &index);
909 COM_CurrentInfo()->pending_call_count_client--;
912 ClientRpcChannelBuffer_ReleaseEventHandle(This, message_state->params.handle);
914 /* for WM shortcut, faults are returned in params->hr */
915 if (hr == S_OK)
916 hrFault = message_state->params.hr;
918 status = message_state->params.status;
920 orpcthat.flags = ORPCF_NULL;
921 orpcthat.extensions = NULL;
923 TRACE("RPC call status: 0x%x\n", status);
924 if (status != RPC_S_OK)
925 hr = HRESULT_FROM_WIN32(status);
927 TRACE("hrFault = 0x%08x\n", hrFault);
929 /* FIXME: this condition should be
930 * "hr == S_OK && (!hrFault || msg->BufferLength > FIELD_OFFSET(ORPCTHAT, extensions) + 4)"
931 * but we don't currently reset the message length for PostMessage
932 * dispatched calls */
933 if (hr == S_OK && hrFault == S_OK)
935 HRESULT hr2;
936 char *original_buffer = msg->Buffer;
938 /* handle ORPCTHAT and client extensions */
940 hr2 = unmarshal_ORPCTHAT(msg, &orpcthat, &orpc_ext_array, &first_wire_orpc_extent);
941 if (FAILED(hr2))
942 hr = hr2;
944 message_state->prefix_data_len = (char *)msg->Buffer - original_buffer;
945 msg->BufferLength -= message_state->prefix_data_len;
947 else
948 message_state->prefix_data_len = 0;
950 if (hr == S_OK)
952 ChannelHooks_ClientNotify(&message_state->channel_hook_info,
953 msg->DataRepresentation,
954 first_wire_orpc_extent,
955 orpcthat.extensions && first_wire_orpc_extent ? orpcthat.extensions->size : 0,
956 hrFault);
959 /* save away the message state again */
960 msg->Handle = message_state;
962 if (pstatus) *pstatus = status;
964 if (hr == S_OK)
965 hr = hrFault;
967 TRACE("-- 0x%08x\n", hr);
969 return hr;
972 static HRESULT WINAPI ServerRpcChannelBuffer_FreeBuffer(LPRPCCHANNELBUFFER iface, RPCOLEMESSAGE* olemsg)
974 RPC_MESSAGE *msg = (RPC_MESSAGE *)olemsg;
975 RPC_STATUS status;
976 struct message_state *message_state;
978 TRACE("(%p)\n", msg);
980 message_state = msg->Handle;
981 /* restore the binding handle and the real start of data */
982 msg->Handle = message_state->binding_handle;
983 msg->Buffer = (char *)msg->Buffer - message_state->prefix_data_len;
984 msg->BufferLength += message_state->prefix_data_len;
985 message_state->prefix_data_len = 0;
987 if (message_state->bypass_rpcrt)
989 HeapFree(GetProcessHeap(), 0, msg->Buffer);
990 status = RPC_S_OK;
992 else
993 status = I_RpcFreeBuffer(msg);
995 msg->Handle = message_state;
997 TRACE("-- %d\n", status);
999 return HRESULT_FROM_WIN32(status);
1002 static HRESULT WINAPI ClientRpcChannelBuffer_FreeBuffer(LPRPCCHANNELBUFFER iface, RPCOLEMESSAGE* olemsg)
1004 RPC_MESSAGE *msg = (RPC_MESSAGE *)olemsg;
1005 RPC_STATUS status;
1006 struct message_state *message_state;
1008 TRACE("(%p)\n", msg);
1010 message_state = msg->Handle;
1011 /* restore the binding handle and the real start of data */
1012 msg->Handle = message_state->binding_handle;
1013 msg->Buffer = (char *)msg->Buffer - message_state->prefix_data_len;
1014 msg->BufferLength += message_state->prefix_data_len;
1016 if (message_state->params.bypass_rpcrt)
1018 HeapFree(GetProcessHeap(), 0, msg->Buffer);
1019 status = RPC_S_OK;
1021 else
1022 status = I_RpcFreeBuffer(msg);
1024 HeapFree(GetProcessHeap(), 0, msg->RpcInterfaceInformation);
1025 msg->RpcInterfaceInformation = NULL;
1027 if (message_state->params.stub)
1028 IRpcStubBuffer_Release(message_state->params.stub);
1029 if (message_state->params.chan)
1030 IRpcChannelBuffer_Release(message_state->params.chan);
1031 HeapFree(GetProcessHeap(), 0, message_state);
1033 TRACE("-- %d\n", status);
1035 return HRESULT_FROM_WIN32(status);
1038 static HRESULT WINAPI ClientRpcChannelBuffer_GetDestCtx(LPRPCCHANNELBUFFER iface, DWORD* pdwDestContext, void** ppvDestContext)
1040 ClientRpcChannelBuffer *This = (ClientRpcChannelBuffer *)iface;
1042 TRACE("(%p,%p)\n", pdwDestContext, ppvDestContext);
1044 *pdwDestContext = This->dest_context;
1045 *ppvDestContext = This->dest_context_data;
1047 return S_OK;
1050 static HRESULT WINAPI ServerRpcChannelBuffer_GetDestCtx(LPRPCCHANNELBUFFER iface, DWORD* pdwDestContext, void** ppvDestContext)
1052 WARN("(%p,%p), stub!\n", pdwDestContext, ppvDestContext);
1054 /* FIXME: implement this by storing the dwDestContext and pvDestContext
1055 * values passed into IMarshal_MarshalInterface and returning them here */
1056 *pdwDestContext = MSHCTX_DIFFERENTMACHINE;
1057 *ppvDestContext = NULL;
1058 return S_OK;
1061 static HRESULT WINAPI RpcChannelBuffer_IsConnected(LPRPCCHANNELBUFFER iface)
1063 TRACE("()\n");
1064 /* native does nothing too */
1065 return S_OK;
1068 static const IRpcChannelBufferVtbl ClientRpcChannelBufferVtbl =
1070 RpcChannelBuffer_QueryInterface,
1071 RpcChannelBuffer_AddRef,
1072 ClientRpcChannelBuffer_Release,
1073 ClientRpcChannelBuffer_GetBuffer,
1074 ClientRpcChannelBuffer_SendReceive,
1075 ClientRpcChannelBuffer_FreeBuffer,
1076 ClientRpcChannelBuffer_GetDestCtx,
1077 RpcChannelBuffer_IsConnected
1080 static const IRpcChannelBufferVtbl ServerRpcChannelBufferVtbl =
1082 RpcChannelBuffer_QueryInterface,
1083 RpcChannelBuffer_AddRef,
1084 ServerRpcChannelBuffer_Release,
1085 ServerRpcChannelBuffer_GetBuffer,
1086 ServerRpcChannelBuffer_SendReceive,
1087 ServerRpcChannelBuffer_FreeBuffer,
1088 ServerRpcChannelBuffer_GetDestCtx,
1089 RpcChannelBuffer_IsConnected
1092 /* returns a channel buffer for proxies */
1093 HRESULT RPC_CreateClientChannel(const OXID *oxid, const IPID *ipid,
1094 const OXID_INFO *oxid_info,
1095 DWORD dest_context, void *dest_context_data,
1096 IRpcChannelBuffer **chan)
1098 ClientRpcChannelBuffer *This;
1099 WCHAR endpoint[200];
1100 RPC_BINDING_HANDLE bind;
1101 RPC_STATUS status;
1102 LPWSTR string_binding;
1104 /* FIXME: get the endpoint from oxid_info->psa instead */
1105 get_rpc_endpoint(endpoint, oxid);
1107 TRACE("proxy pipe: connecting to endpoint: %s\n", debugstr_w(endpoint));
1109 status = RpcStringBindingComposeW(
1110 NULL,
1111 wszRpcTransport,
1112 NULL,
1113 endpoint,
1114 NULL,
1115 &string_binding);
1117 if (status == RPC_S_OK)
1119 status = RpcBindingFromStringBindingW(string_binding, &bind);
1121 if (status == RPC_S_OK)
1123 IPID ipid2 = *ipid; /* why can't RpcBindingSetObject take a const? */
1124 status = RpcBindingSetObject(bind, &ipid2);
1125 if (status != RPC_S_OK)
1126 RpcBindingFree(&bind);
1129 RpcStringFreeW(&string_binding);
1132 if (status != RPC_S_OK)
1134 ERR("Couldn't get binding for endpoint %s, status = %d\n", debugstr_w(endpoint), status);
1135 return HRESULT_FROM_WIN32(status);
1138 This = HeapAlloc(GetProcessHeap(), 0, sizeof(*This));
1139 if (!This)
1141 RpcBindingFree(&bind);
1142 return E_OUTOFMEMORY;
1145 This->super.lpVtbl = &ClientRpcChannelBufferVtbl;
1146 This->super.refs = 1;
1147 This->bind = bind;
1148 apartment_getoxid(COM_CurrentApt(), &This->oxid);
1149 This->server_pid = oxid_info->dwPid;
1150 This->dest_context = dest_context;
1151 This->dest_context_data = dest_context_data;
1152 This->event = NULL;
1154 *chan = (IRpcChannelBuffer*)This;
1156 return S_OK;
1159 HRESULT RPC_CreateServerChannel(IRpcChannelBuffer **chan)
1161 RpcChannelBuffer *This = HeapAlloc(GetProcessHeap(), 0, sizeof(*This));
1162 if (!This)
1163 return E_OUTOFMEMORY;
1165 This->lpVtbl = &ServerRpcChannelBufferVtbl;
1166 This->refs = 1;
1168 *chan = (IRpcChannelBuffer*)This;
1170 return S_OK;
1173 /* unmarshals ORPC_EXTENT_ARRAY according to NDR rules, but doesn't allocate
1174 * any memory */
1175 static HRESULT unmarshal_ORPC_EXTENT_ARRAY(RPC_MESSAGE *msg, const char *end,
1176 ORPC_EXTENT_ARRAY *extensions,
1177 WIRE_ORPC_EXTENT **first_wire_orpc_extent)
1179 DWORD pointer_id;
1180 DWORD i;
1182 memcpy(extensions, msg->Buffer, FIELD_OFFSET(WIRE_ORPC_EXTENT_ARRAY, extent));
1183 msg->Buffer = (char *)msg->Buffer + FIELD_OFFSET(WIRE_ORPC_EXTENT_ARRAY, extent);
1185 if ((const char *)msg->Buffer + 2 * sizeof(DWORD) > end)
1186 return RPC_E_INVALID_HEADER;
1188 pointer_id = *(DWORD *)msg->Buffer;
1189 msg->Buffer = (char *)msg->Buffer + sizeof(DWORD);
1190 extensions->extent = NULL;
1192 if (pointer_id)
1194 WIRE_ORPC_EXTENT *wire_orpc_extent;
1196 /* conformance */
1197 if (*(DWORD *)msg->Buffer != ((extensions->size+1)&~1))
1198 return RPC_S_INVALID_BOUND;
1200 msg->Buffer = (char *)msg->Buffer + sizeof(DWORD);
1202 /* arbitrary limit for security (don't know what native does) */
1203 if (extensions->size > 256)
1205 ERR("too many extensions: %d\n", extensions->size);
1206 return RPC_S_INVALID_BOUND;
1209 *first_wire_orpc_extent = wire_orpc_extent = msg->Buffer;
1210 for (i = 0; i < ((extensions->size+1)&~1); i++)
1212 if ((const char *)&wire_orpc_extent->data[0] > end)
1213 return RPC_S_INVALID_BOUND;
1214 if (wire_orpc_extent->conformance != ((wire_orpc_extent->size+7)&~7))
1215 return RPC_S_INVALID_BOUND;
1216 if ((const char *)&wire_orpc_extent->data[wire_orpc_extent->conformance] > end)
1217 return RPC_S_INVALID_BOUND;
1218 TRACE("size %u, guid %s\n", wire_orpc_extent->size, debugstr_guid(&wire_orpc_extent->id));
1219 wire_orpc_extent = (WIRE_ORPC_EXTENT *)&wire_orpc_extent->data[wire_orpc_extent->conformance];
1221 msg->Buffer = wire_orpc_extent;
1224 return S_OK;
1227 /* unmarshals ORPCTHIS according to NDR rules, but doesn't allocate any memory */
1228 static HRESULT unmarshal_ORPCTHIS(RPC_MESSAGE *msg, ORPCTHIS *orpcthis,
1229 ORPC_EXTENT_ARRAY *orpc_ext_array, WIRE_ORPC_EXTENT **first_wire_orpc_extent)
1231 const char *end = (char *)msg->Buffer + msg->BufferLength;
1233 *first_wire_orpc_extent = NULL;
1235 if (msg->BufferLength < FIELD_OFFSET(WIRE_ORPCTHIS, extensions) + sizeof(DWORD))
1237 ERR("invalid buffer length\n");
1238 return RPC_E_INVALID_HEADER;
1241 memcpy(orpcthis, msg->Buffer, FIELD_OFFSET(WIRE_ORPCTHIS, extensions));
1242 msg->Buffer = (char *)msg->Buffer + FIELD_OFFSET(WIRE_ORPCTHIS, extensions);
1244 if ((const char *)msg->Buffer + sizeof(DWORD) > end)
1245 return RPC_E_INVALID_HEADER;
1247 if (*(DWORD *)msg->Buffer)
1248 orpcthis->extensions = orpc_ext_array;
1249 else
1250 orpcthis->extensions = NULL;
1252 msg->Buffer = (char *)msg->Buffer + sizeof(DWORD);
1254 if (orpcthis->extensions)
1256 HRESULT hr = unmarshal_ORPC_EXTENT_ARRAY(msg, end, orpc_ext_array,
1257 first_wire_orpc_extent);
1258 if (FAILED(hr))
1259 return hr;
1262 if ((orpcthis->version.MajorVersion != COM_MAJOR_VERSION) ||
1263 (orpcthis->version.MinorVersion > COM_MINOR_VERSION))
1265 ERR("COM version {%d, %d} not supported\n",
1266 orpcthis->version.MajorVersion, orpcthis->version.MinorVersion);
1267 return RPC_E_VERSION_MISMATCH;
1270 if (orpcthis->flags & ~(ORPCF_LOCAL|ORPCF_RESERVED1|ORPCF_RESERVED2|ORPCF_RESERVED3|ORPCF_RESERVED4))
1272 ERR("invalid flags 0x%x\n", orpcthis->flags & ~(ORPCF_LOCAL|ORPCF_RESERVED1|ORPCF_RESERVED2|ORPCF_RESERVED3|ORPCF_RESERVED4));
1273 return RPC_E_INVALID_HEADER;
1276 return S_OK;
1279 static HRESULT unmarshal_ORPCTHAT(RPC_MESSAGE *msg, ORPCTHAT *orpcthat,
1280 ORPC_EXTENT_ARRAY *orpc_ext_array, WIRE_ORPC_EXTENT **first_wire_orpc_extent)
1282 const char *end = (char *)msg->Buffer + msg->BufferLength;
1284 *first_wire_orpc_extent = NULL;
1286 if (msg->BufferLength < FIELD_OFFSET(WIRE_ORPCTHAT, extensions) + sizeof(DWORD))
1288 ERR("invalid buffer length\n");
1289 return RPC_E_INVALID_HEADER;
1292 memcpy(orpcthat, msg->Buffer, FIELD_OFFSET(WIRE_ORPCTHAT, extensions));
1293 msg->Buffer = (char *)msg->Buffer + FIELD_OFFSET(WIRE_ORPCTHAT, extensions);
1295 if ((const char *)msg->Buffer + sizeof(DWORD) > end)
1296 return RPC_E_INVALID_HEADER;
1298 if (*(DWORD *)msg->Buffer)
1299 orpcthat->extensions = orpc_ext_array;
1300 else
1301 orpcthat->extensions = NULL;
1303 msg->Buffer = (char *)msg->Buffer + sizeof(DWORD);
1305 if (orpcthat->extensions)
1307 HRESULT hr = unmarshal_ORPC_EXTENT_ARRAY(msg, end, orpc_ext_array,
1308 first_wire_orpc_extent);
1309 if (FAILED(hr))
1310 return hr;
1313 if (orpcthat->flags & ~(ORPCF_LOCAL|ORPCF_RESERVED1|ORPCF_RESERVED2|ORPCF_RESERVED3|ORPCF_RESERVED4))
1315 ERR("invalid flags 0x%x\n", orpcthat->flags & ~(ORPCF_LOCAL|ORPCF_RESERVED1|ORPCF_RESERVED2|ORPCF_RESERVED3|ORPCF_RESERVED4));
1316 return RPC_E_INVALID_HEADER;
1319 return S_OK;
1322 void RPC_ExecuteCall(struct dispatch_params *params)
1324 struct message_state *message_state = NULL;
1325 RPC_MESSAGE *msg = (RPC_MESSAGE *)params->msg;
1326 char *original_buffer = msg->Buffer;
1327 ORPCTHIS orpcthis;
1328 ORPC_EXTENT_ARRAY orpc_ext_array;
1329 WIRE_ORPC_EXTENT *first_wire_orpc_extent;
1330 GUID old_causality_id;
1332 /* handle ORPCTHIS and server extensions */
1334 params->hr = unmarshal_ORPCTHIS(msg, &orpcthis, &orpc_ext_array, &first_wire_orpc_extent);
1335 if (params->hr != S_OK)
1337 msg->Buffer = original_buffer;
1338 goto exit;
1341 message_state = HeapAlloc(GetProcessHeap(), 0, sizeof(*message_state));
1342 if (!message_state)
1344 params->hr = E_OUTOFMEMORY;
1345 msg->Buffer = original_buffer;
1346 goto exit;
1349 message_state->prefix_data_len = (char *)msg->Buffer - original_buffer;
1350 message_state->binding_handle = msg->Handle;
1351 message_state->bypass_rpcrt = params->bypass_rpcrt;
1353 message_state->channel_hook_info.iid = params->iid;
1354 message_state->channel_hook_info.cbSize = sizeof(message_state->channel_hook_info);
1355 message_state->channel_hook_info.uCausality = orpcthis.cid;
1356 message_state->channel_hook_info.dwServerPid = GetCurrentProcessId();
1357 message_state->channel_hook_info.iMethod = msg->ProcNum;
1358 message_state->channel_hook_info.pObject = params->iface;
1360 if (orpcthis.extensions && first_wire_orpc_extent &&
1361 orpcthis.extensions->size)
1362 ChannelHooks_ServerNotify(&message_state->channel_hook_info, msg->DataRepresentation, first_wire_orpc_extent, orpcthis.extensions->size);
1364 msg->Handle = message_state;
1365 msg->BufferLength -= message_state->prefix_data_len;
1367 /* call message filter */
1369 if (COM_CurrentApt()->filter)
1371 DWORD handlecall;
1372 INTERFACEINFO interface_info;
1373 CALLTYPE calltype;
1375 interface_info.pUnk = params->iface;
1376 interface_info.iid = params->iid;
1377 interface_info.wMethod = msg->ProcNum;
1379 if (IsEqualGUID(&orpcthis.cid, &COM_CurrentInfo()->causality_id))
1380 calltype = CALLTYPE_NESTED;
1381 else if (COM_CurrentInfo()->pending_call_count_server == 0)
1382 calltype = CALLTYPE_TOPLEVEL;
1383 else
1384 calltype = CALLTYPE_TOPLEVEL_CALLPENDING;
1386 handlecall = IMessageFilter_HandleInComingCall(COM_CurrentApt()->filter,
1387 calltype,
1388 UlongToHandle(GetCurrentProcessId()),
1389 0 /* FIXME */,
1390 &interface_info);
1391 TRACE("IMessageFilter_HandleInComingCall returned %d\n", handlecall);
1392 switch (handlecall)
1394 case SERVERCALL_REJECTED:
1395 params->hr = RPC_E_CALL_REJECTED;
1396 goto exit_reset_state;
1397 case SERVERCALL_RETRYLATER:
1398 #if 0 /* FIXME: handle retries on the client side before enabling this code */
1399 params->hr = RPC_E_RETRY;
1400 goto exit_reset_state;
1401 #else
1402 FIXME("retry call later not implemented\n");
1403 break;
1404 #endif
1405 case SERVERCALL_ISHANDLED:
1406 default:
1407 break;
1411 /* invoke the method */
1413 /* save the old causality ID - note: any calls executed while processing
1414 * messages received during the SendReceive will appear to originate from
1415 * this call - this should be checked with what Windows does */
1416 old_causality_id = COM_CurrentInfo()->causality_id;
1417 COM_CurrentInfo()->causality_id = orpcthis.cid;
1418 COM_CurrentInfo()->pending_call_count_server++;
1419 params->hr = IRpcStubBuffer_Invoke(params->stub, params->msg, params->chan);
1420 COM_CurrentInfo()->pending_call_count_server--;
1421 COM_CurrentInfo()->causality_id = old_causality_id;
1423 /* the invoke allocated a new buffer, so free the old one */
1424 if (message_state->bypass_rpcrt && original_buffer != msg->Buffer)
1425 HeapFree(GetProcessHeap(), 0, original_buffer);
1427 exit_reset_state:
1428 message_state = msg->Handle;
1429 msg->Handle = message_state->binding_handle;
1430 msg->Buffer = (char *)msg->Buffer - message_state->prefix_data_len;
1431 msg->BufferLength += message_state->prefix_data_len;
1433 exit:
1434 HeapFree(GetProcessHeap(), 0, message_state);
1435 if (params->handle) SetEvent(params->handle);
1438 static void __RPC_STUB dispatch_rpc(RPC_MESSAGE *msg)
1440 struct dispatch_params *params;
1441 APARTMENT *apt;
1442 IPID ipid;
1443 HRESULT hr;
1445 RpcBindingInqObject(msg->Handle, &ipid);
1447 TRACE("ipid = %s, iMethod = %d\n", debugstr_guid(&ipid), msg->ProcNum);
1449 params = HeapAlloc(GetProcessHeap(), 0, sizeof(*params));
1450 if (!params)
1452 RpcRaiseException(E_OUTOFMEMORY);
1453 return;
1456 hr = ipid_get_dispatch_params(&ipid, &apt, &params->stub, &params->chan,
1457 &params->iid, &params->iface);
1458 if (hr != S_OK)
1460 ERR("no apartment found for ipid %s\n", debugstr_guid(&ipid));
1461 HeapFree(GetProcessHeap(), 0, params);
1462 RpcRaiseException(hr);
1463 return;
1466 params->msg = (RPCOLEMESSAGE *)msg;
1467 params->status = RPC_S_OK;
1468 params->hr = S_OK;
1469 params->handle = NULL;
1470 params->bypass_rpcrt = FALSE;
1472 /* Note: this is the important difference between STAs and MTAs - we
1473 * always execute RPCs to STAs in the thread that originally created the
1474 * apartment (i.e. the one that pumps messages to the window) */
1475 if (!apt->multi_threaded)
1477 params->handle = CreateEventW(NULL, FALSE, FALSE, NULL);
1479 TRACE("Calling apartment thread 0x%08x...\n", apt->tid);
1481 if (PostMessageW(apartment_getwindow(apt), DM_EXECUTERPC, 0, (LPARAM)params))
1482 WaitForSingleObject(params->handle, INFINITE);
1483 else
1485 ERR("PostMessage failed with error %u\n", GetLastError());
1486 IRpcChannelBuffer_Release(params->chan);
1487 IRpcStubBuffer_Release(params->stub);
1489 CloseHandle(params->handle);
1491 else
1493 BOOL joined = FALSE;
1494 if (!COM_CurrentInfo()->apt)
1496 apartment_joinmta();
1497 joined = TRUE;
1499 RPC_ExecuteCall(params);
1500 if (joined)
1502 apartment_release(COM_CurrentInfo()->apt);
1503 COM_CurrentInfo()->apt = NULL;
1507 hr = params->hr;
1508 if (params->chan)
1509 IRpcChannelBuffer_Release(params->chan);
1510 if (params->stub)
1511 IRpcStubBuffer_Release(params->stub);
1512 HeapFree(GetProcessHeap(), 0, params);
1514 apartment_release(apt);
1516 /* if IRpcStubBuffer_Invoke fails, we should raise an exception to tell
1517 * the RPC runtime that the call failed */
1518 if (hr) RpcRaiseException(hr);
1521 /* stub registration */
1522 HRESULT RPC_RegisterInterface(REFIID riid)
1524 struct registered_if *rif;
1525 BOOL found = FALSE;
1526 HRESULT hr = S_OK;
1528 TRACE("(%s)\n", debugstr_guid(riid));
1530 EnterCriticalSection(&csRegIf);
1531 LIST_FOR_EACH_ENTRY(rif, &registered_interfaces, struct registered_if, entry)
1533 if (IsEqualGUID(&rif->If.InterfaceId.SyntaxGUID, riid))
1535 rif->refs++;
1536 found = TRUE;
1537 break;
1540 if (!found)
1542 TRACE("Creating new interface\n");
1544 rif = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*rif));
1545 if (rif)
1547 RPC_STATUS status;
1549 rif->refs = 1;
1550 rif->If.Length = sizeof(RPC_SERVER_INTERFACE);
1551 /* RPC interface ID = COM interface ID */
1552 rif->If.InterfaceId.SyntaxGUID = *riid;
1553 rif->If.DispatchTable = &rpc_dispatch;
1554 /* all other fields are 0, including the version asCOM objects
1555 * always have a version of 0.0 */
1556 status = RpcServerRegisterIfEx(
1557 (RPC_IF_HANDLE)&rif->If,
1558 NULL, NULL,
1559 RPC_IF_OLE | RPC_IF_AUTOLISTEN,
1560 RPC_C_LISTEN_MAX_CALLS_DEFAULT,
1561 NULL);
1562 if (status == RPC_S_OK)
1563 list_add_tail(&registered_interfaces, &rif->entry);
1564 else
1566 ERR("RpcServerRegisterIfEx failed with error %d\n", status);
1567 HeapFree(GetProcessHeap(), 0, rif);
1568 hr = HRESULT_FROM_WIN32(status);
1571 else
1572 hr = E_OUTOFMEMORY;
1574 LeaveCriticalSection(&csRegIf);
1575 return hr;
1578 /* stub unregistration */
1579 void RPC_UnregisterInterface(REFIID riid)
1581 struct registered_if *rif;
1582 EnterCriticalSection(&csRegIf);
1583 LIST_FOR_EACH_ENTRY(rif, &registered_interfaces, struct registered_if, entry)
1585 if (IsEqualGUID(&rif->If.InterfaceId.SyntaxGUID, riid))
1587 if (!--rif->refs)
1589 RpcServerUnregisterIf((RPC_IF_HANDLE)&rif->If, NULL, TRUE);
1590 list_remove(&rif->entry);
1591 HeapFree(GetProcessHeap(), 0, rif);
1593 break;
1596 LeaveCriticalSection(&csRegIf);
1599 /* get the info for an OXID, including the IPID for the rem unknown interface
1600 * and the string binding */
1601 HRESULT RPC_ResolveOxid(OXID oxid, OXID_INFO *oxid_info)
1603 TRACE("%s\n", wine_dbgstr_longlong(oxid));
1605 oxid_info->dwTid = 0;
1606 oxid_info->dwPid = 0;
1607 oxid_info->dwAuthnHint = RPC_C_AUTHN_LEVEL_NONE;
1608 /* FIXME: this is a hack around not having an OXID resolver yet -
1609 * this function should contact the machine's OXID resolver and then it
1610 * should give us the IPID of the IRemUnknown interface */
1611 oxid_info->ipidRemUnknown.Data1 = 0xffffffff;
1612 oxid_info->ipidRemUnknown.Data2 = 0xffff;
1613 oxid_info->ipidRemUnknown.Data3 = 0xffff;
1614 memcpy(oxid_info->ipidRemUnknown.Data4, &oxid, sizeof(OXID));
1615 oxid_info->psa = NULL /* FIXME */;
1617 return S_OK;
1620 /* make the apartment reachable by other threads and processes and create the
1621 * IRemUnknown object */
1622 void RPC_StartRemoting(struct apartment *apt)
1624 if (!InterlockedExchange(&apt->remoting_started, TRUE))
1626 WCHAR endpoint[200];
1627 RPC_STATUS status;
1629 get_rpc_endpoint(endpoint, &apt->oxid);
1631 status = RpcServerUseProtseqEpW(
1632 wszRpcTransport,
1633 RPC_C_PROTSEQ_MAX_REQS_DEFAULT,
1634 endpoint,
1635 NULL);
1636 if (status != RPC_S_OK)
1637 ERR("Couldn't register endpoint %s\n", debugstr_w(endpoint));
1639 /* FIXME: move remote unknown exporting into this function */
1641 start_apartment_remote_unknown();
1645 static HRESULT create_server(REFCLSID rclsid, HANDLE *process)
1647 static const WCHAR wszLocalServer32[] = { 'L','o','c','a','l','S','e','r','v','e','r','3','2',0 };
1648 static const WCHAR embedding[] = { ' ', '-','E','m','b','e','d','d','i','n','g',0 };
1649 HKEY key;
1650 HRESULT hres;
1651 WCHAR command[MAX_PATH+sizeof(embedding)/sizeof(WCHAR)];
1652 DWORD size = (MAX_PATH+1) * sizeof(WCHAR);
1653 STARTUPINFOW sinfo;
1654 PROCESS_INFORMATION pinfo;
1656 hres = COM_OpenKeyForCLSID(rclsid, wszLocalServer32, KEY_READ, &key);
1657 if (FAILED(hres)) {
1658 ERR("class %s not registered\n", debugstr_guid(rclsid));
1659 return hres;
1662 hres = RegQueryValueExW(key, NULL, NULL, NULL, (LPBYTE)command, &size);
1663 RegCloseKey(key);
1664 if (hres) {
1665 WARN("No default value for LocalServer32 key\n");
1666 return REGDB_E_CLASSNOTREG; /* FIXME: check retval */
1669 memset(&sinfo,0,sizeof(sinfo));
1670 sinfo.cb = sizeof(sinfo);
1672 /* EXE servers are started with the -Embedding switch. */
1674 strcatW(command, embedding);
1676 TRACE("activating local server %s for %s\n", debugstr_w(command), debugstr_guid(rclsid));
1678 /* FIXME: Win2003 supports a ServerExecutable value that is passed into
1679 * CreateProcess */
1680 if (!CreateProcessW(NULL, command, NULL, NULL, FALSE, 0, NULL, NULL, &sinfo, &pinfo)) {
1681 WARN("failed to run local server %s\n", debugstr_w(command));
1682 return HRESULT_FROM_WIN32(GetLastError());
1684 *process = pinfo.hProcess;
1685 CloseHandle(pinfo.hThread);
1687 return S_OK;
1691 * start_local_service() - start a service given its name and parameters
1693 static DWORD start_local_service(LPCWSTR name, DWORD num, LPCWSTR *params)
1695 SC_HANDLE handle, hsvc;
1696 DWORD r = ERROR_FUNCTION_FAILED;
1698 TRACE("Starting service %s %d params\n", debugstr_w(name), num);
1700 handle = OpenSCManagerW(NULL, NULL, SC_MANAGER_CONNECT);
1701 if (!handle)
1702 return r;
1703 hsvc = OpenServiceW(handle, name, SERVICE_START);
1704 if (hsvc)
1706 if(StartServiceW(hsvc, num, params))
1707 r = ERROR_SUCCESS;
1708 else
1709 r = GetLastError();
1710 if (r == ERROR_SERVICE_ALREADY_RUNNING)
1711 r = ERROR_SUCCESS;
1712 CloseServiceHandle(hsvc);
1714 else
1715 r = GetLastError();
1716 CloseServiceHandle(handle);
1718 TRACE("StartService returned error %u (%s)\n", r, (r == ERROR_SUCCESS) ? "ok":"failed");
1720 return r;
1724 * create_local_service() - start a COM server in a service
1726 * To start a Local Service, we read the AppID value under
1727 * the class's CLSID key, then open the HKCR\\AppId key specified
1728 * there and check for a LocalService value.
1730 * Note: Local Services are not supported under Windows 9x
1732 static HRESULT create_local_service(REFCLSID rclsid)
1734 HRESULT hres;
1735 WCHAR buf[CHARS_IN_GUID];
1736 static const WCHAR szLocalService[] = { 'L','o','c','a','l','S','e','r','v','i','c','e',0 };
1737 static const WCHAR szServiceParams[] = {'S','e','r','v','i','c','e','P','a','r','a','m','s',0};
1738 HKEY hkey;
1739 LONG r;
1740 DWORD type, sz;
1742 TRACE("Attempting to start Local service for %s\n", debugstr_guid(rclsid));
1744 hres = COM_OpenKeyForAppIdFromCLSID(rclsid, KEY_READ, &hkey);
1745 if (FAILED(hres))
1746 return hres;
1748 /* read the LocalService and ServiceParameters values from the AppID key */
1749 sz = sizeof buf;
1750 r = RegQueryValueExW(hkey, szLocalService, NULL, &type, (LPBYTE)buf, &sz);
1751 if (r==ERROR_SUCCESS && type==REG_SZ)
1753 DWORD num_args = 0;
1754 LPWSTR args[1] = { NULL };
1757 * FIXME: I'm not really sure how to deal with the service parameters.
1758 * I suspect that the string returned from RegQueryValueExW
1759 * should be split into a number of arguments by spaces.
1760 * It would make more sense if ServiceParams contained a
1761 * REG_MULTI_SZ here, but it's a REG_SZ for the services
1762 * that I'm interested in for the moment.
1764 r = RegQueryValueExW(hkey, szServiceParams, NULL, &type, NULL, &sz);
1765 if (r == ERROR_SUCCESS && type == REG_SZ && sz)
1767 args[0] = HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY,sz);
1768 num_args++;
1769 RegQueryValueExW(hkey, szServiceParams, NULL, &type, (LPBYTE)args[0], &sz);
1771 r = start_local_service(buf, num_args, (LPCWSTR *)args);
1772 if (r != ERROR_SUCCESS)
1773 hres = REGDB_E_CLASSNOTREG; /* FIXME: check retval */
1774 HeapFree(GetProcessHeap(),0,args[0]);
1776 else
1778 WARN("No LocalService value\n");
1779 hres = REGDB_E_CLASSNOTREG; /* FIXME: check retval */
1781 RegCloseKey(hkey);
1783 return hres;
1787 static void get_localserver_pipe_name(WCHAR *pipefn, REFCLSID rclsid)
1789 static const WCHAR wszPipeRef[] = {'\\','\\','.','\\','p','i','p','e','\\',0};
1790 strcpyW(pipefn, wszPipeRef);
1791 StringFromGUID2(rclsid, pipefn + sizeof(wszPipeRef)/sizeof(wszPipeRef[0]) - 1, CHARS_IN_GUID);
1794 /* FIXME: should call to rpcss instead */
1795 HRESULT RPC_GetLocalClassObject(REFCLSID rclsid, REFIID iid, LPVOID *ppv)
1797 HRESULT hres;
1798 HANDLE hPipe;
1799 WCHAR pipefn[100];
1800 DWORD res, bufferlen;
1801 char marshalbuffer[200];
1802 IStream *pStm;
1803 LARGE_INTEGER seekto;
1804 ULARGE_INTEGER newpos;
1805 int tries = 0;
1807 static const int MAXTRIES = 30; /* 30 seconds */
1809 TRACE("rclsid=%s, iid=%s\n", debugstr_guid(rclsid), debugstr_guid(iid));
1811 get_localserver_pipe_name(pipefn, rclsid);
1813 while (tries++ < MAXTRIES) {
1814 TRACE("waiting for %s\n", debugstr_w(pipefn));
1816 WaitNamedPipeW( pipefn, NMPWAIT_WAIT_FOREVER );
1817 hPipe = CreateFileW(pipefn, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, 0);
1818 if (hPipe == INVALID_HANDLE_VALUE) {
1819 DWORD index;
1820 DWORD start_ticks;
1821 HANDLE process = 0;
1822 if (tries == 1) {
1823 if ( (hres = create_local_service(rclsid)) &&
1824 (hres = create_server(rclsid, &process)) )
1825 return hres;
1826 } else {
1827 WARN("Connecting to %s, no response yet, retrying: le is %u\n", debugstr_w(pipefn), GetLastError());
1829 /* wait for one second, even if messages arrive */
1830 start_ticks = GetTickCount();
1831 do {
1832 if (SUCCEEDED(CoWaitForMultipleHandles(0, 1000, (process != 0),
1833 &process, &index)) && process && !index)
1835 WARN( "server for %s failed to start\n", debugstr_guid(rclsid) );
1836 CloseHandle( hPipe );
1837 CloseHandle( process );
1838 return E_NOINTERFACE;
1840 } while (GetTickCount() - start_ticks < 1000);
1841 if (process) CloseHandle( process );
1842 continue;
1844 bufferlen = 0;
1845 if (!ReadFile(hPipe,marshalbuffer,sizeof(marshalbuffer),&bufferlen,NULL)) {
1846 FIXME("Failed to read marshal id from classfactory of %s.\n",debugstr_guid(rclsid));
1847 Sleep(1000);
1848 continue;
1850 TRACE("read marshal id from pipe\n");
1851 CloseHandle(hPipe);
1852 break;
1855 if (tries >= MAXTRIES)
1856 return E_NOINTERFACE;
1858 hres = CreateStreamOnHGlobal(0,TRUE,&pStm);
1859 if (hres) return hres;
1860 hres = IStream_Write(pStm,marshalbuffer,bufferlen,&res);
1861 if (hres) goto out;
1862 seekto.u.LowPart = 0;seekto.u.HighPart = 0;
1863 hres = IStream_Seek(pStm,seekto,STREAM_SEEK_SET,&newpos);
1865 TRACE("unmarshalling classfactory\n");
1866 hres = CoUnmarshalInterface(pStm,&IID_IClassFactory,ppv);
1867 out:
1868 IStream_Release(pStm);
1869 return hres;
1873 struct local_server_params
1875 CLSID clsid;
1876 IStream *stream;
1877 HANDLE ready_event;
1878 HANDLE stop_event;
1879 HANDLE thread;
1880 BOOL multi_use;
1883 /* FIXME: should call to rpcss instead */
1884 static DWORD WINAPI local_server_thread(LPVOID param)
1886 struct local_server_params * lsp = param;
1887 WCHAR pipefn[100];
1888 HRESULT hres;
1889 IStream *pStm = lsp->stream;
1890 STATSTG ststg;
1891 unsigned char *buffer;
1892 int buflen;
1893 LARGE_INTEGER seekto;
1894 ULARGE_INTEGER newpos;
1895 ULONG res;
1896 BOOL multi_use = lsp->multi_use;
1897 OVERLAPPED ovl;
1898 HANDLE pipe_event, hPipe, new_pipe;
1899 DWORD bytes;
1901 TRACE("Starting threader for %s.\n",debugstr_guid(&lsp->clsid));
1903 memset(&ovl, 0, sizeof(ovl));
1904 get_localserver_pipe_name(pipefn, &lsp->clsid);
1905 ovl.hEvent = pipe_event = CreateEventW(NULL, FALSE, FALSE, NULL);
1907 hPipe = CreateNamedPipeW( pipefn, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
1908 PIPE_TYPE_BYTE|PIPE_WAIT, PIPE_UNLIMITED_INSTANCES,
1909 4096, 4096, 500 /* 0.5 second timeout */, NULL );
1910 if (hPipe == INVALID_HANDLE_VALUE)
1912 FIXME("pipe creation failed for %s, le is %u\n", debugstr_w(pipefn), GetLastError());
1913 CloseHandle(pipe_event);
1914 return 1;
1917 SetEvent(lsp->ready_event);
1919 while (1) {
1920 if (!ConnectNamedPipe(hPipe, &ovl))
1922 DWORD error = GetLastError();
1923 if (error == ERROR_IO_PENDING)
1925 HANDLE handles[2] = { pipe_event, lsp->stop_event };
1926 DWORD ret;
1927 ret = WaitForMultipleObjects(2, handles, FALSE, INFINITE);
1928 if (ret != WAIT_OBJECT_0)
1930 CloseHandle(hPipe);
1931 break;
1934 /* client already connected isn't an error */
1935 else if (error != ERROR_PIPE_CONNECTED)
1937 ERR("ConnectNamedPipe failed with error %d\n", GetLastError());
1938 CloseHandle(hPipe);
1939 break;
1943 TRACE("marshalling IClassFactory to client\n");
1945 hres = IStream_Stat(pStm,&ststg,STATFLAG_NONAME);
1946 if (hres)
1948 CloseHandle(hPipe);
1949 CloseHandle(pipe_event);
1950 return hres;
1953 seekto.u.LowPart = 0;
1954 seekto.u.HighPart = 0;
1955 hres = IStream_Seek(pStm,seekto,STREAM_SEEK_SET,&newpos);
1956 if (hres) {
1957 FIXME("IStream_Seek failed, %x\n",hres);
1958 CloseHandle(hPipe);
1959 CloseHandle(pipe_event);
1960 return hres;
1963 buflen = ststg.cbSize.u.LowPart;
1964 buffer = HeapAlloc(GetProcessHeap(),0,buflen);
1966 hres = IStream_Read(pStm,buffer,buflen,&res);
1967 if (hres) {
1968 FIXME("Stream Read failed, %x\n",hres);
1969 CloseHandle(hPipe);
1970 CloseHandle(pipe_event);
1971 HeapFree(GetProcessHeap(),0,buffer);
1972 return hres;
1975 WriteFile(hPipe,buffer,buflen,&res,&ovl);
1976 GetOverlappedResult(hPipe, &ovl, &bytes, TRUE);
1977 HeapFree(GetProcessHeap(),0,buffer);
1979 FlushFileBuffers(hPipe);
1980 DisconnectNamedPipe(hPipe);
1981 TRACE("done marshalling IClassFactory\n");
1983 if (!multi_use)
1985 TRACE("single use object, shutting down pipe %s\n", debugstr_w(pipefn));
1986 CloseHandle(hPipe);
1987 break;
1989 new_pipe = CreateNamedPipeW( pipefn, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
1990 PIPE_TYPE_BYTE|PIPE_WAIT, PIPE_UNLIMITED_INSTANCES,
1991 4096, 4096, 500 /* 0.5 second timeout */, NULL );
1992 CloseHandle(hPipe);
1993 if (new_pipe == INVALID_HANDLE_VALUE)
1995 FIXME("pipe creation failed for %s, le is %u\n", debugstr_w(pipefn), GetLastError());
1996 CloseHandle(pipe_event);
1997 return 1;
1999 hPipe = new_pipe;
2001 CloseHandle(pipe_event);
2002 return 0;
2005 /* starts listening for a local server */
2006 HRESULT RPC_StartLocalServer(REFCLSID clsid, IStream *stream, BOOL multi_use, void **registration)
2008 DWORD tid;
2009 struct local_server_params *lsp;
2011 lsp = HeapAlloc(GetProcessHeap(), 0, sizeof(*lsp));
2012 if (!lsp)
2013 return E_OUTOFMEMORY;
2015 lsp->clsid = *clsid;
2016 lsp->stream = stream;
2017 IStream_AddRef(stream);
2018 lsp->ready_event = CreateEventW(NULL, FALSE, FALSE, NULL);
2019 if (!lsp->ready_event)
2021 HeapFree(GetProcessHeap(), 0, lsp);
2022 return HRESULT_FROM_WIN32(GetLastError());
2024 lsp->stop_event = CreateEventW(NULL, FALSE, FALSE, NULL);
2025 if (!lsp->stop_event)
2027 CloseHandle(lsp->ready_event);
2028 HeapFree(GetProcessHeap(), 0, lsp);
2029 return HRESULT_FROM_WIN32(GetLastError());
2031 lsp->multi_use = multi_use;
2033 lsp->thread = CreateThread(NULL, 0, local_server_thread, lsp, 0, &tid);
2034 if (!lsp->thread)
2036 CloseHandle(lsp->ready_event);
2037 CloseHandle(lsp->stop_event);
2038 HeapFree(GetProcessHeap(), 0, lsp);
2039 return HRESULT_FROM_WIN32(GetLastError());
2042 WaitForSingleObject(lsp->ready_event, INFINITE);
2043 CloseHandle(lsp->ready_event);
2044 lsp->ready_event = NULL;
2046 *registration = lsp;
2047 return S_OK;
2050 /* stops listening for a local server */
2051 void RPC_StopLocalServer(void *registration)
2053 struct local_server_params *lsp = registration;
2055 /* signal local_server_thread to stop */
2056 SetEvent(lsp->stop_event);
2057 /* wait for it to exit */
2058 WaitForSingleObject(lsp->thread, INFINITE);
2060 IStream_Release(lsp->stream);
2061 CloseHandle(lsp->stop_event);
2062 CloseHandle(lsp->thread);
2063 HeapFree(GetProcessHeap(), 0, lsp);