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
24 #include "wine/port.h"
30 #define NONAMELESSUNION
31 #define NONAMELESSSTRUCT
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 =
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 =
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};
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);
97 const IRpcChannelBufferVtbl *lpVtbl;
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) */
128 RPC_BINDING_HANDLE binding_handle;
129 ULONG prefix_data_len;
130 SChannelHookCallInfo channel_hook_info;
136 struct dispatch_params params;
141 ULONG conformance; /* NDR */
144 /* [size_is((size+7)&~7)] */ unsigned char data[1];
151 unsigned char extent[1];
152 } WIRE_ORPC_EXTENT_ARRAY;
160 unsigned char extensions[1];
166 unsigned char extensions[1];
169 struct channel_hook_entry
176 struct channel_hook_buffer_data
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;
197 *extension_count = 0;
199 EnterCriticalSection(&csChannelHook);
201 LIST_FOR_EACH_ENTRY(entry, &channel_hooks, struct channel_hook_entry, entry)
205 *data = HeapAlloc(GetProcessHeap(), 0, *hook_count * sizeof(struct channel_hook_buffer_data));
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 */
224 total_size += FIELD_OFFSET(WIRE_ORPC_EXTENT, data[extension_size]);
225 (*extension_count)++;
231 LeaveCriticalSection(&csChannelHook);
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)
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 */
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);
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;
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;
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))
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,
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;
315 *extension_count = 0;
317 EnterCriticalSection(&csChannelHook);
319 LIST_FOR_EACH_ENTRY(entry, &channel_hooks, struct channel_hook_entry, entry)
323 *data = HeapAlloc(GetProcessHeap(), 0, *hook_count * sizeof(struct channel_hook_buffer_data));
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,
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 */
343 total_size += FIELD_OFFSET(WIRE_ORPC_EXTENT, data[extension_size]);
344 (*extension_count)++;
350 LeaveCriticalSection(&csChannelHook);
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)
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 */
377 IChannelHook_ServerFillBuffer(entry->hook, &entry->id, &info->iid,
378 &extension_size, buffer + FIELD_OFFSET(WIRE_ORPC_EXTENT, data[0]),
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);
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;
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;
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))
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,
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));
434 return E_OUTOFMEMORY;
438 IChannelHook_AddRef(hook);
440 EnterCriticalSection(&csChannelHook);
441 list_add_tail(&channel_hooks, &entry->entry);
442 LeaveCriticalSection(&csChannelHook);
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);
458 /* RPC Channel Buffer Functions */
460 static HRESULT WINAPI RpcChannelBuffer_QueryInterface(LPRPCCHANNELBUFFER iface, REFIID riid, LPVOID *ppv)
463 if (IsEqualIID(riid,&IID_IRpcChannelBuffer) || IsEqualIID(riid,&IID_IUnknown))
466 IUnknown_AddRef(iface);
469 return E_NOINTERFACE;
472 static ULONG WINAPI RpcChannelBuffer_AddRef(LPRPCCHANNELBUFFER iface)
474 RpcChannelBuffer *This = (RpcChannelBuffer *)iface;
475 return InterlockedIncrement(&This->refs);
478 static ULONG WINAPI ServerRpcChannelBuffer_Release(LPRPCCHANNELBUFFER iface)
480 RpcChannelBuffer *This = (RpcChannelBuffer *)iface;
483 ref = InterlockedDecrement(&This->refs);
487 HeapFree(GetProcessHeap(), 0, This);
491 static ULONG WINAPI ClientRpcChannelBuffer_Release(LPRPCCHANNELBUFFER iface)
493 ClientRpcChannelBuffer *This = (ClientRpcChannelBuffer *)iface;
496 ref = InterlockedDecrement(&This->super.refs);
500 if (This->event) CloseHandle(This->event);
501 RpcBindingFree(&This->bind);
502 HeapFree(GetProcessHeap(), 0, This);
506 static HRESULT WINAPI ServerRpcChannelBuffer_GetBuffer(LPRPCCHANNELBUFFER iface, RPCOLEMESSAGE* olemsg, REFIID riid)
508 RpcChannelBuffer *This = (RpcChannelBuffer *)iface;
509 RPC_MESSAGE *msg = (RPC_MESSAGE *)olemsg;
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;
518 TRACE("(%p)->(%p,%s)\n", This, olemsg, debugstr_guid(riid));
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;
525 extensions_size = ChannelHooks_ServerGetSize(&message_state->channel_hook_info,
526 &channel_hook_data, &channel_hook_count, &extension_count);
528 msg->BufferLength += FIELD_OFFSET(WIRE_ORPCTHAT, extensions) + sizeof(DWORD);
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]);
536 if (message_state->bypass_rpcrt)
538 msg->Buffer = HeapAlloc(GetProcessHeap(), 0, msg->BufferLength);
543 HeapFree(GetProcessHeap(), 0, channel_hook_data);
544 return E_OUTOFMEMORY;
548 status = I_RpcGetBuffer(msg);
550 orpcthat = msg->Buffer;
551 msg->Buffer = (char *)msg->Buffer + FIELD_OFFSET(WIRE_ORPCTHAT, extensions);
553 orpcthat->flags = ORPCF_NULL /* FIXME? */;
555 /* NDR representation of orpcthat->extensions */
556 *(DWORD *)msg->Buffer = extensions_size ? 1 : 0;
557 msg->Buffer = (char *)msg->Buffer + sizeof(DWORD);
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);
572 msg->Buffer = ChannelHooks_ServerFillBuffer(&message_state->channel_hook_info,
573 msg->Buffer, channel_hook_data, channel_hook_count);
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)
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]);
587 HeapFree(GetProcessHeap(), 0, channel_hook_data);
589 /* store the prefixed data length so that we can restore the real buffer
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;
596 TRACE("-- %d\n", status);
598 return HRESULT_FROM_WIN32(status);
601 static HANDLE ClientRpcChannelBuffer_GetEventHandle(ClientRpcChannelBuffer *This)
603 HANDLE event = InterlockedExchangePointer(&This->event, NULL);
605 /* Note: must be auto-reset event so we can reuse it without a call
607 if (!event) event = CreateEventW(NULL, FALSE, FALSE, NULL);
612 static void ClientRpcChannelBuffer_ReleaseEventHandle(ClientRpcChannelBuffer *This, HANDLE event)
614 if (InterlockedCompareExchangePointer(&This->event, event, NULL))
615 /* already a handle cached in This */
619 static HRESULT WINAPI ClientRpcChannelBuffer_GetBuffer(LPRPCCHANNELBUFFER iface, RPCOLEMESSAGE* olemsg, REFIID riid)
621 ClientRpcChannelBuffer *This = (ClientRpcChannelBuffer *)iface;
622 RPC_MESSAGE *msg = (RPC_MESSAGE *)olemsg;
623 RPC_CLIENT_INTERFACE *cif;
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;
633 APARTMENT *apt = NULL;
635 TRACE("(%p)->(%p,%s)\n", This, olemsg, debugstr_guid(riid));
637 cif = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(RPC_CLIENT_INTERFACE));
639 return E_OUTOFMEMORY;
641 message_state = HeapAlloc(GetProcessHeap(), 0, sizeof(*message_state));
644 HeapFree(GetProcessHeap(), 0, cif);
645 return E_OUTOFMEMORY;
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;
657 message_state->prefix_data_len = 0;
658 message_state->binding_handle = This->bind;
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));
670 extensions_size = ChannelHooks_ClientGetSize(&message_state->channel_hook_info,
671 &channel_hook_data, &channel_hook_count, &extension_count);
673 msg->BufferLength += FIELD_OFFSET(WIRE_ORPCTHIS, extensions) + sizeof(DWORD);
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]);
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);
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)
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;
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));
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 */
714 /* shortcut the RPC runtime */
715 if (message_state->target_hwnd)
717 msg->Buffer = HeapAlloc(GetProcessHeap(), 0, msg->BufferLength);
721 status = ERROR_OUTOFMEMORY;
724 status = I_RpcGetBuffer(msg);
726 msg->Handle = message_state;
728 if (status == RPC_S_OK)
730 orpcthis = msg->Buffer;
731 msg->Buffer = (char *)msg->Buffer + FIELD_OFFSET(WIRE_ORPCTHIS, extensions);
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;
739 /* NDR representation of orpcthis->extensions */
740 *(DWORD *)msg->Buffer = extensions_size ? 1 : 0;
741 msg->Buffer = (char *)msg->Buffer + sizeof(DWORD);
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);
756 msg->Buffer = ChannelHooks_ClientFillBuffer(&message_state->channel_hook_info,
757 msg->Buffer, channel_hook_data, channel_hook_count);
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)
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]);
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;
777 HeapFree(GetProcessHeap(), 0, channel_hook_data);
779 TRACE("-- %d\n", status);
781 return HRESULT_FROM_WIN32(status);
784 static HRESULT WINAPI ServerRpcChannelBuffer_SendReceive(LPRPCCHANNELBUFFER iface, RPCOLEMESSAGE *olemsg, ULONG *pstatus)
790 /* this thread runs an outgoing RPC */
791 static DWORD WINAPI rpc_sendreceive_thread(LPVOID param)
793 struct dispatch_params *data = param;
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);
799 TRACE("completed with status 0x%x\n", data->status);
801 SetEvent(data->handle);
806 static inline HRESULT ClientRpcChannelBuffer_IsCorrectApartment(ClientRpcChannelBuffer *This, APARTMENT *apt)
811 if (apartment_getoxid(apt, &oxid) != S_OK)
813 if (This->oxid != oxid)
818 static HRESULT WINAPI ClientRpcChannelBuffer_SendReceive(LPRPCCHANNELBUFFER iface, RPCOLEMESSAGE *olemsg, ULONG *pstatus)
820 ClientRpcChannelBuffer *This = (ClientRpcChannelBuffer *)iface;
822 RPC_MESSAGE *msg = (RPC_MESSAGE *)olemsg;
825 struct message_state *message_state;
827 ORPC_EXTENT_ARRAY orpc_ext_array;
828 WIRE_ORPC_EXTENT *first_wire_orpc_extent = NULL;
829 HRESULT hrFault = S_OK;
831 TRACE("(%p) iMethod=%d\n", olemsg, olemsg->iMethod);
833 hr = ClientRpcChannelBuffer_IsCorrectApartment(This, COM_CurrentApt());
836 ERR("called from wrong apartment, should have been 0x%s\n",
837 wine_dbgstr_longlong(This->oxid));
838 return RPC_E_WRONG_THREAD;
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
845 if (!COM_CurrentApt()->multi_threaded &&
846 COM_CurrentInfo()->pending_call_count_client &&
849 ERR("can't make an outgoing COM call in response to a sent message\n");
850 return RPC_E_CANTCALLOUT_ININPUTSYNCCALL;
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;
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
866 message_state->params.msg = olemsg;
867 if (message_state->params.bypass_rpcrt)
869 TRACE("Calling apartment thread 0x%08x...\n", message_state->target_tid);
871 msg->ProcNum &= ~RPC_FLAGS_VALID_BIT;
873 if (!PostMessageW(message_state->target_hwnd, DM_EXECUTERPC, 0,
874 (LPARAM)&message_state->params))
876 ERR("PostMessage failed with error %u\n", GetLastError());
878 /* Note: message_state->params.iface doesn't have a reference and
879 * so doesn't need to be released */
881 hr = HRESULT_FROM_WIN32(GetLastError());
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.
892 if (!QueueUserWorkItem(rpc_sendreceive_thread, &message_state->params, WT_EXECUTEDEFAULT))
894 ERR("QueueUserWorkItem failed with error %u\n", GetLastError());
903 if (WaitForSingleObject(message_state->params.handle, 0))
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--;
910 ClientRpcChannelBuffer_ReleaseEventHandle(This, message_state->params.handle);
912 /* for WM shortcut, faults are returned in params->hr */
914 hrFault = message_state->params.hr;
916 status = message_state->params.status;
918 orpcthat.flags = ORPCF_NULL;
919 orpcthat.extensions = NULL;
921 TRACE("RPC call status: 0x%x\n", status);
922 if (status != RPC_S_OK)
923 hr = HRESULT_FROM_WIN32(status);
925 TRACE("hrFault = 0x%08x\n", hrFault);
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)
934 char *original_buffer = msg->Buffer;
936 /* handle ORPCTHAT and client extensions */
938 hr2 = unmarshal_ORPCTHAT(msg, &orpcthat, &orpc_ext_array, &first_wire_orpc_extent);
942 message_state->prefix_data_len = (char *)msg->Buffer - original_buffer;
943 msg->BufferLength -= message_state->prefix_data_len;
946 message_state->prefix_data_len = 0;
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,
957 /* save away the message state again */
958 msg->Handle = message_state;
960 if (pstatus) *pstatus = status;
965 TRACE("-- 0x%08x\n", hr);
970 static HRESULT WINAPI ServerRpcChannelBuffer_FreeBuffer(LPRPCCHANNELBUFFER iface, RPCOLEMESSAGE* olemsg)
972 RPC_MESSAGE *msg = (RPC_MESSAGE *)olemsg;
974 struct message_state *message_state;
976 TRACE("(%p)\n", msg);
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;
985 if (message_state->bypass_rpcrt)
987 HeapFree(GetProcessHeap(), 0, msg->Buffer);
991 status = I_RpcFreeBuffer(msg);
993 msg->Handle = message_state;
995 TRACE("-- %d\n", status);
997 return HRESULT_FROM_WIN32(status);
1000 static HRESULT WINAPI ClientRpcChannelBuffer_FreeBuffer(LPRPCCHANNELBUFFER iface, RPCOLEMESSAGE* olemsg)
1002 RPC_MESSAGE *msg = (RPC_MESSAGE *)olemsg;
1004 struct message_state *message_state;
1006 TRACE("(%p)\n", msg);
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;
1014 if (message_state->params.bypass_rpcrt)
1016 HeapFree(GetProcessHeap(), 0, msg->Buffer);
1020 status = I_RpcFreeBuffer(msg);
1022 HeapFree(GetProcessHeap(), 0, msg->RpcInterfaceInformation);
1023 msg->RpcInterfaceInformation = NULL;
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);
1031 TRACE("-- %d\n", status);
1033 return HRESULT_FROM_WIN32(status);
1036 static HRESULT WINAPI ClientRpcChannelBuffer_GetDestCtx(LPRPCCHANNELBUFFER iface, DWORD* pdwDestContext, void** ppvDestContext)
1038 ClientRpcChannelBuffer *This = (ClientRpcChannelBuffer *)iface;
1040 TRACE("(%p,%p)\n", pdwDestContext, ppvDestContext);
1042 *pdwDestContext = This->dest_context;
1043 *ppvDestContext = This->dest_context_data;
1048 static HRESULT WINAPI ServerRpcChannelBuffer_GetDestCtx(LPRPCCHANNELBUFFER iface, DWORD* pdwDestContext, void** ppvDestContext)
1050 WARN("(%p,%p), stub!\n", pdwDestContext, ppvDestContext);
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;
1059 static HRESULT WINAPI RpcChannelBuffer_IsConnected(LPRPCCHANNELBUFFER iface)
1062 /* native does nothing too */
1066 static const IRpcChannelBufferVtbl ClientRpcChannelBufferVtbl =
1068 RpcChannelBuffer_QueryInterface,
1069 RpcChannelBuffer_AddRef,
1070 ClientRpcChannelBuffer_Release,
1071 ClientRpcChannelBuffer_GetBuffer,
1072 ClientRpcChannelBuffer_SendReceive,
1073 ClientRpcChannelBuffer_FreeBuffer,
1074 ClientRpcChannelBuffer_GetDestCtx,
1075 RpcChannelBuffer_IsConnected
1078 static const IRpcChannelBufferVtbl ServerRpcChannelBufferVtbl =
1080 RpcChannelBuffer_QueryInterface,
1081 RpcChannelBuffer_AddRef,
1082 ServerRpcChannelBuffer_Release,
1083 ServerRpcChannelBuffer_GetBuffer,
1084 ServerRpcChannelBuffer_SendReceive,
1085 ServerRpcChannelBuffer_FreeBuffer,
1086 ServerRpcChannelBuffer_GetDestCtx,
1087 RpcChannelBuffer_IsConnected
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)
1096 ClientRpcChannelBuffer *This;
1097 WCHAR endpoint[200];
1098 RPC_BINDING_HANDLE bind;
1100 LPWSTR string_binding;
1102 /* FIXME: get the endpoint from oxid_info->psa instead */
1103 get_rpc_endpoint(endpoint, oxid);
1105 TRACE("proxy pipe: connecting to endpoint: %s\n", debugstr_w(endpoint));
1107 status = RpcStringBindingComposeW(
1115 if (status == RPC_S_OK)
1117 status = RpcBindingFromStringBindingW(string_binding, &bind);
1119 if (status == RPC_S_OK)
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);
1127 RpcStringFreeW(&string_binding);
1130 if (status != RPC_S_OK)
1132 ERR("Couldn't get binding for endpoint %s, status = %d\n", debugstr_w(endpoint), status);
1133 return HRESULT_FROM_WIN32(status);
1136 This = HeapAlloc(GetProcessHeap(), 0, sizeof(*This));
1139 RpcBindingFree(&bind);
1140 return E_OUTOFMEMORY;
1143 This->super.lpVtbl = &ClientRpcChannelBufferVtbl;
1144 This->super.refs = 1;
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;
1152 *chan = (IRpcChannelBuffer*)This;
1157 HRESULT RPC_CreateServerChannel(IRpcChannelBuffer **chan)
1159 RpcChannelBuffer *This = HeapAlloc(GetProcessHeap(), 0, sizeof(*This));
1161 return E_OUTOFMEMORY;
1163 This->lpVtbl = &ServerRpcChannelBufferVtbl;
1166 *chan = (IRpcChannelBuffer*)This;
1171 /* unmarshals ORPC_EXTENT_ARRAY according to NDR rules, but doesn't allocate
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)
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);
1183 if ((const char *)msg->Buffer + 2 * sizeof(DWORD) > end)
1184 return RPC_E_INVALID_HEADER;
1186 pointer_id = *(DWORD *)msg->Buffer;
1187 msg->Buffer = (char *)msg->Buffer + sizeof(DWORD);
1188 extensions->extent = NULL;
1192 WIRE_ORPC_EXTENT *wire_orpc_extent;
1195 if (*(DWORD *)msg->Buffer != ((extensions->size+1)&~1))
1196 return RPC_S_INVALID_BOUND;
1198 msg->Buffer = (char *)msg->Buffer + sizeof(DWORD);
1200 /* arbitrary limit for security (don't know what native does) */
1201 if (extensions->size > 256)
1203 ERR("too many extensions: %d\n", extensions->size);
1204 return RPC_S_INVALID_BOUND;
1207 *first_wire_orpc_extent = wire_orpc_extent = msg->Buffer;
1208 for (i = 0; i < ((extensions->size+1)&~1); i++)
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];
1219 msg->Buffer = wire_orpc_extent;
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)
1229 const char *end = (char *)msg->Buffer + msg->BufferLength;
1231 *first_wire_orpc_extent = NULL;
1233 if (msg->BufferLength < FIELD_OFFSET(WIRE_ORPCTHIS, extensions) + sizeof(DWORD))
1235 ERR("invalid buffer length\n");
1236 return RPC_E_INVALID_HEADER;
1239 memcpy(orpcthis, msg->Buffer, FIELD_OFFSET(WIRE_ORPCTHIS, extensions));
1240 msg->Buffer = (char *)msg->Buffer + FIELD_OFFSET(WIRE_ORPCTHIS, extensions);
1242 if ((const char *)msg->Buffer + sizeof(DWORD) > end)
1243 return RPC_E_INVALID_HEADER;
1245 if (*(DWORD *)msg->Buffer)
1246 orpcthis->extensions = orpc_ext_array;
1248 orpcthis->extensions = NULL;
1250 msg->Buffer = (char *)msg->Buffer + sizeof(DWORD);
1252 if (orpcthis->extensions)
1254 HRESULT hr = unmarshal_ORPC_EXTENT_ARRAY(msg, end, orpc_ext_array,
1255 first_wire_orpc_extent);
1260 if ((orpcthis->version.MajorVersion != COM_MAJOR_VERSION) ||
1261 (orpcthis->version.MinorVersion > COM_MINOR_VERSION))
1263 ERR("COM version {%d, %d} not supported\n",
1264 orpcthis->version.MajorVersion, orpcthis->version.MinorVersion);
1265 return RPC_E_VERSION_MISMATCH;
1268 if (orpcthis->flags & ~(ORPCF_LOCAL|ORPCF_RESERVED1|ORPCF_RESERVED2|ORPCF_RESERVED3|ORPCF_RESERVED4))
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;
1277 static HRESULT unmarshal_ORPCTHAT(RPC_MESSAGE *msg, ORPCTHAT *orpcthat,
1278 ORPC_EXTENT_ARRAY *orpc_ext_array, WIRE_ORPC_EXTENT **first_wire_orpc_extent)
1280 const char *end = (char *)msg->Buffer + msg->BufferLength;
1282 *first_wire_orpc_extent = NULL;
1284 if (msg->BufferLength < FIELD_OFFSET(WIRE_ORPCTHAT, extensions) + sizeof(DWORD))
1286 ERR("invalid buffer length\n");
1287 return RPC_E_INVALID_HEADER;
1290 memcpy(orpcthat, msg->Buffer, FIELD_OFFSET(WIRE_ORPCTHAT, extensions));
1291 msg->Buffer = (char *)msg->Buffer + FIELD_OFFSET(WIRE_ORPCTHAT, extensions);
1293 if ((const char *)msg->Buffer + sizeof(DWORD) > end)
1294 return RPC_E_INVALID_HEADER;
1296 if (*(DWORD *)msg->Buffer)
1297 orpcthat->extensions = orpc_ext_array;
1299 orpcthat->extensions = NULL;
1301 msg->Buffer = (char *)msg->Buffer + sizeof(DWORD);
1303 if (orpcthat->extensions)
1305 HRESULT hr = unmarshal_ORPC_EXTENT_ARRAY(msg, end, orpc_ext_array,
1306 first_wire_orpc_extent);
1311 if (orpcthat->flags & ~(ORPCF_LOCAL|ORPCF_RESERVED1|ORPCF_RESERVED2|ORPCF_RESERVED3|ORPCF_RESERVED4))
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;
1320 void RPC_ExecuteCall(struct dispatch_params *params)
1322 struct message_state *message_state = NULL;
1323 RPC_MESSAGE *msg = (RPC_MESSAGE *)params->msg;
1324 char *original_buffer = msg->Buffer;
1326 ORPC_EXTENT_ARRAY orpc_ext_array;
1327 WIRE_ORPC_EXTENT *first_wire_orpc_extent;
1328 GUID old_causality_id;
1330 /* handle ORPCTHIS and server extensions */
1332 params->hr = unmarshal_ORPCTHIS(msg, &orpcthis, &orpc_ext_array, &first_wire_orpc_extent);
1333 if (params->hr != S_OK)
1335 msg->Buffer = original_buffer;
1339 message_state = HeapAlloc(GetProcessHeap(), 0, sizeof(*message_state));
1342 params->hr = E_OUTOFMEMORY;
1343 msg->Buffer = original_buffer;
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;
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;
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);
1362 msg->Handle = message_state;
1363 msg->BufferLength -= message_state->prefix_data_len;
1365 /* call message filter */
1367 if (COM_CurrentApt()->filter)
1370 INTERFACEINFO interface_info;
1373 interface_info.pUnk = params->iface;
1374 interface_info.iid = params->iid;
1375 interface_info.wMethod = msg->ProcNum;
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;
1382 calltype = CALLTYPE_TOPLEVEL_CALLPENDING;
1384 handlecall = IMessageFilter_HandleInComingCall(COM_CurrentApt()->filter,
1386 UlongToHandle(GetCurrentProcessId()),
1389 TRACE("IMessageFilter_HandleInComingCall returned %d\n", handlecall);
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;
1400 FIXME("retry call later not implemented\n");
1403 case SERVERCALL_ISHANDLED:
1409 /* invoke the method */
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;
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);
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;
1432 HeapFree(GetProcessHeap(), 0, message_state);
1433 if (params->handle) SetEvent(params->handle);
1436 static void __RPC_STUB dispatch_rpc(RPC_MESSAGE *msg)
1438 struct dispatch_params *params;
1443 RpcBindingInqObject(msg->Handle, &ipid);
1445 TRACE("ipid = %s, iMethod = %d\n", debugstr_guid(&ipid), msg->ProcNum);
1447 params = HeapAlloc(GetProcessHeap(), 0, sizeof(*params));
1450 RpcRaiseException(E_OUTOFMEMORY);
1454 hr = ipid_get_dispatch_params(&ipid, &apt, ¶ms->stub, ¶ms->chan,
1455 ¶ms->iid, ¶ms->iface);
1458 ERR("no apartment found for ipid %s\n", debugstr_guid(&ipid));
1459 HeapFree(GetProcessHeap(), 0, params);
1460 RpcRaiseException(hr);
1464 params->msg = (RPCOLEMESSAGE *)msg;
1465 params->status = RPC_S_OK;
1467 params->handle = NULL;
1468 params->bypass_rpcrt = FALSE;
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)
1475 params->handle = CreateEventW(NULL, FALSE, FALSE, NULL);
1477 TRACE("Calling apartment thread 0x%08x...\n", apt->tid);
1479 if (PostMessageW(apartment_getwindow(apt), DM_EXECUTERPC, 0, (LPARAM)params))
1480 WaitForSingleObject(params->handle, INFINITE);
1483 ERR("PostMessage failed with error %u\n", GetLastError());
1484 IRpcChannelBuffer_Release(params->chan);
1485 IRpcStubBuffer_Release(params->stub);
1487 CloseHandle(params->handle);
1491 BOOL joined = FALSE;
1492 if (!COM_CurrentInfo()->apt)
1494 apartment_joinmta();
1497 RPC_ExecuteCall(params);
1500 apartment_release(COM_CurrentInfo()->apt);
1501 COM_CurrentInfo()->apt = NULL;
1507 IRpcChannelBuffer_Release(params->chan);
1509 IRpcStubBuffer_Release(params->stub);
1510 HeapFree(GetProcessHeap(), 0, params);
1512 apartment_release(apt);
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);
1519 /* stub registration */
1520 HRESULT RPC_RegisterInterface(REFIID riid)
1522 struct registered_if *rif;
1526 TRACE("(%s)\n", debugstr_guid(riid));
1528 EnterCriticalSection(&csRegIf);
1529 LIST_FOR_EACH_ENTRY(rif, ®istered_interfaces, struct registered_if, entry)
1531 if (IsEqualGUID(&rif->If.InterfaceId.SyntaxGUID, riid))
1540 TRACE("Creating new interface\n");
1542 rif = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*rif));
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,
1557 RPC_IF_OLE | RPC_IF_AUTOLISTEN,
1558 RPC_C_LISTEN_MAX_CALLS_DEFAULT,
1560 if (status == RPC_S_OK)
1561 list_add_tail(®istered_interfaces, &rif->entry);
1564 ERR("RpcServerRegisterIfEx failed with error %d\n", status);
1565 HeapFree(GetProcessHeap(), 0, rif);
1566 hr = HRESULT_FROM_WIN32(status);
1572 LeaveCriticalSection(&csRegIf);
1576 /* stub unregistration */
1577 void RPC_UnregisterInterface(REFIID riid)
1579 struct registered_if *rif;
1580 EnterCriticalSection(&csRegIf);
1581 LIST_FOR_EACH_ENTRY(rif, ®istered_interfaces, struct registered_if, entry)
1583 if (IsEqualGUID(&rif->If.InterfaceId.SyntaxGUID, riid))
1587 RpcServerUnregisterIf((RPC_IF_HANDLE)&rif->If, NULL, TRUE);
1588 list_remove(&rif->entry);
1589 HeapFree(GetProcessHeap(), 0, rif);
1594 LeaveCriticalSection(&csRegIf);
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)
1601 TRACE("%s\n", wine_dbgstr_longlong(oxid));
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 */;
1618 /* make the apartment reachable by other threads and processes and create the
1619 * IRemUnknown object */
1620 void RPC_StartRemoting(struct apartment *apt)
1622 if (!InterlockedExchange(&apt->remoting_started, TRUE))
1624 WCHAR endpoint[200];
1627 get_rpc_endpoint(endpoint, &apt->oxid);
1629 status = RpcServerUseProtseqEpW(
1631 RPC_C_PROTSEQ_MAX_REQS_DEFAULT,
1634 if (status != RPC_S_OK)
1635 ERR("Couldn't register endpoint %s\n", debugstr_w(endpoint));
1637 /* FIXME: move remote unknown exporting into this function */
1639 start_apartment_remote_unknown();
1643 static HRESULT create_server(REFCLSID rclsid, HANDLE *process)
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 };
1649 WCHAR command[MAX_PATH+sizeof(embedding)/sizeof(WCHAR)];
1650 DWORD size = (MAX_PATH+1) * sizeof(WCHAR);
1652 PROCESS_INFORMATION pinfo;
1654 hres = COM_OpenKeyForCLSID(rclsid, wszLocalServer32, KEY_READ, &key);
1656 ERR("class %s not registered\n", debugstr_guid(rclsid));
1660 hres = RegQueryValueExW(key, NULL, NULL, NULL, (LPBYTE)command, &size);
1663 WARN("No default value for LocalServer32 key\n");
1664 return REGDB_E_CLASSNOTREG; /* FIXME: check retval */
1667 memset(&sinfo,0,sizeof(sinfo));
1668 sinfo.cb = sizeof(sinfo);
1670 /* EXE servers are started with the -Embedding switch. */
1672 strcatW(command, embedding);
1674 TRACE("activating local server %s for %s\n", debugstr_w(command), debugstr_guid(rclsid));
1676 /* FIXME: Win2003 supports a ServerExecutable value that is passed into
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());
1682 *process = pinfo.hProcess;
1683 CloseHandle(pinfo.hThread);
1689 * start_local_service() - start a service given its name and parameters
1691 static DWORD start_local_service(LPCWSTR name, DWORD num, LPCWSTR *params)
1693 SC_HANDLE handle, hsvc;
1694 DWORD r = ERROR_FUNCTION_FAILED;
1696 TRACE("Starting service %s %d params\n", debugstr_w(name), num);
1698 handle = OpenSCManagerW(NULL, NULL, SC_MANAGER_CONNECT);
1701 hsvc = OpenServiceW(handle, name, SERVICE_START);
1704 if(StartServiceW(hsvc, num, params))
1708 if (r == ERROR_SERVICE_ALREADY_RUNNING)
1710 CloseServiceHandle(hsvc);
1714 CloseServiceHandle(handle);
1716 TRACE("StartService returned error %u (%s)\n", r, (r == ERROR_SUCCESS) ? "ok":"failed");
1722 * create_local_service() - start a COM server in a service
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.
1728 * Note: Local Services are not supported under Windows 9x
1730 static HRESULT create_local_service(REFCLSID rclsid)
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};
1740 TRACE("Attempting to start Local service for %s\n", debugstr_guid(rclsid));
1742 hres = COM_OpenKeyForAppIdFromCLSID(rclsid, KEY_READ, &hkey);
1746 /* read the LocalService and ServiceParameters values from the AppID key */
1748 r = RegQueryValueExW(hkey, szLocalService, NULL, &type, (LPBYTE)buf, &sz);
1749 if (r==ERROR_SUCCESS && type==REG_SZ)
1752 LPWSTR args[1] = { NULL };
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.
1762 r = RegQueryValueExW(hkey, szServiceParams, NULL, &type, NULL, &sz);
1763 if (r == ERROR_SUCCESS && type == REG_SZ && sz)
1765 args[0] = HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY,sz);
1767 RegQueryValueExW(hkey, szServiceParams, NULL, &type, (LPBYTE)args[0], &sz);
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]);
1776 WARN("No LocalService value\n");
1777 hres = REGDB_E_CLASSNOTREG; /* FIXME: check retval */
1785 static void get_localserver_pipe_name(WCHAR *pipefn, REFCLSID rclsid)
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);
1792 /* FIXME: should call to rpcss instead */
1793 HRESULT RPC_GetLocalClassObject(REFCLSID rclsid, REFIID iid, LPVOID *ppv)
1798 DWORD res, bufferlen;
1799 char marshalbuffer[200];
1801 LARGE_INTEGER seekto;
1802 ULARGE_INTEGER newpos;
1805 static const int MAXTRIES = 30; /* 30 seconds */
1807 TRACE("rclsid=%s, iid=%s\n", debugstr_guid(rclsid), debugstr_guid(iid));
1809 get_localserver_pipe_name(pipefn, rclsid);
1811 while (tries++ < MAXTRIES) {
1812 TRACE("waiting for %s\n", debugstr_w(pipefn));
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) {
1821 if ( (hres = create_local_service(rclsid)) &&
1822 (hres = create_server(rclsid, &process)) )
1825 WARN("Connecting to %s, no response yet, retrying: le is %u\n", debugstr_w(pipefn), GetLastError());
1827 /* wait for one second, even if messages arrive */
1828 start_ticks = GetTickCount();
1830 if (SUCCEEDED(CoWaitForMultipleHandles(0, 1000, (process != 0),
1831 &process, &index)) && process && !index)
1833 WARN( "server for %s failed to start\n", debugstr_guid(rclsid) );
1834 CloseHandle( hPipe );
1835 CloseHandle( process );
1836 return E_NOINTERFACE;
1838 } while (GetTickCount() - start_ticks < 1000);
1839 if (process) CloseHandle( process );
1843 if (!ReadFile(hPipe,marshalbuffer,sizeof(marshalbuffer),&bufferlen,NULL)) {
1844 FIXME("Failed to read marshal id from classfactory of %s.\n",debugstr_guid(rclsid));
1848 TRACE("read marshal id from pipe\n");
1853 if (tries >= MAXTRIES)
1854 return E_NOINTERFACE;
1856 hres = CreateStreamOnHGlobal(0,TRUE,&pStm);
1857 if (hres) return hres;
1858 hres = IStream_Write(pStm,marshalbuffer,bufferlen,&res);
1860 seekto.u.LowPart = 0;seekto.u.HighPart = 0;
1861 hres = IStream_Seek(pStm,seekto,STREAM_SEEK_SET,&newpos);
1863 TRACE("unmarshalling classfactory\n");
1864 hres = CoUnmarshalInterface(pStm,&IID_IClassFactory,ppv);
1866 IStream_Release(pStm);
1871 struct local_server_params
1881 /* FIXME: should call to rpcss instead */
1882 static DWORD WINAPI local_server_thread(LPVOID param)
1884 struct local_server_params * lsp = param;
1887 IStream *pStm = lsp->stream;
1889 unsigned char *buffer;
1891 LARGE_INTEGER seekto;
1892 ULARGE_INTEGER newpos;
1894 BOOL multi_use = lsp->multi_use;
1896 HANDLE pipe_event, hPipe, new_pipe;
1899 TRACE("Starting threader for %s.\n",debugstr_guid(&lsp->clsid));
1901 memset(&ovl, 0, sizeof(ovl));
1902 get_localserver_pipe_name(pipefn, &lsp->clsid);
1903 ovl.hEvent = pipe_event = CreateEventW(NULL, FALSE, FALSE, NULL);
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)
1910 FIXME("pipe creation failed for %s, le is %u\n", debugstr_w(pipefn), GetLastError());
1911 CloseHandle(pipe_event);
1915 SetEvent(lsp->ready_event);
1918 if (!ConnectNamedPipe(hPipe, &ovl))
1920 DWORD error = GetLastError();
1921 if (error == ERROR_IO_PENDING)
1923 HANDLE handles[2] = { pipe_event, lsp->stop_event };
1925 ret = WaitForMultipleObjects(2, handles, FALSE, INFINITE);
1926 if (ret != WAIT_OBJECT_0)
1932 /* client already connected isn't an error */
1933 else if (error != ERROR_PIPE_CONNECTED)
1935 ERR("ConnectNamedPipe failed with error %d\n", GetLastError());
1941 TRACE("marshalling IClassFactory to client\n");
1943 hres = IStream_Stat(pStm,&ststg,STATFLAG_NONAME);
1947 CloseHandle(pipe_event);
1951 seekto.u.LowPart = 0;
1952 seekto.u.HighPart = 0;
1953 hres = IStream_Seek(pStm,seekto,STREAM_SEEK_SET,&newpos);
1955 FIXME("IStream_Seek failed, %x\n",hres);
1957 CloseHandle(pipe_event);
1961 buflen = ststg.cbSize.u.LowPart;
1962 buffer = HeapAlloc(GetProcessHeap(),0,buflen);
1964 hres = IStream_Read(pStm,buffer,buflen,&res);
1966 FIXME("Stream Read failed, %x\n",hres);
1968 CloseHandle(pipe_event);
1969 HeapFree(GetProcessHeap(),0,buffer);
1973 WriteFile(hPipe,buffer,buflen,&res,&ovl);
1974 GetOverlappedResult(hPipe, &ovl, &bytes, TRUE);
1975 HeapFree(GetProcessHeap(),0,buffer);
1977 FlushFileBuffers(hPipe);
1978 DisconnectNamedPipe(hPipe);
1979 TRACE("done marshalling IClassFactory\n");
1983 TRACE("single use object, shutting down pipe %s\n", debugstr_w(pipefn));
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 );
1991 if (new_pipe == INVALID_HANDLE_VALUE)
1993 FIXME("pipe creation failed for %s, le is %u\n", debugstr_w(pipefn), GetLastError());
1994 CloseHandle(pipe_event);
1999 CloseHandle(pipe_event);
2003 /* starts listening for a local server */
2004 HRESULT RPC_StartLocalServer(REFCLSID clsid, IStream *stream, BOOL multi_use, void **registration)
2007 struct local_server_params *lsp;
2009 lsp = HeapAlloc(GetProcessHeap(), 0, sizeof(*lsp));
2011 return E_OUTOFMEMORY;
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)
2019 HeapFree(GetProcessHeap(), 0, lsp);
2020 return HRESULT_FROM_WIN32(GetLastError());
2022 lsp->stop_event = CreateEventW(NULL, FALSE, FALSE, NULL);
2023 if (!lsp->stop_event)
2025 CloseHandle(lsp->ready_event);
2026 HeapFree(GetProcessHeap(), 0, lsp);
2027 return HRESULT_FROM_WIN32(GetLastError());
2029 lsp->multi_use = multi_use;
2031 lsp->thread = CreateThread(NULL, 0, local_server_thread, lsp, 0, &tid);
2034 CloseHandle(lsp->ready_event);
2035 CloseHandle(lsp->stop_event);
2036 HeapFree(GetProcessHeap(), 0, lsp);
2037 return HRESULT_FROM_WIN32(GetLastError());
2040 WaitForSingleObject(lsp->ready_event, INFINITE);
2041 CloseHandle(lsp->ready_event);
2042 lsp->ready_event = NULL;
2044 *registration = lsp;
2048 /* stops listening for a local server */
2049 void RPC_StopLocalServer(void *registration)
2051 struct local_server_params *lsp = registration;
2053 /* signal local_server_thread to stop */
2054 SetEvent(lsp->stop_event);
2055 /* wait for it to exit */
2056 WaitForSingleObject(lsp->thread, INFINITE);
2058 IStream_Release(lsp->stream);
2059 CloseHandle(lsp->stop_event);
2060 CloseHandle(lsp->thread);
2061 HeapFree(GetProcessHeap(), 0, lsp);