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"
33 #define NONAMELESSUNION
34 #define NONAMELESSSTRUCT
46 #include "wine/unicode.h"
48 #include "compobj_private.h"
50 #include "wine/debug.h"
52 WINE_DEFAULT_DEBUG_CHANNEL(ole);
54 static void __RPC_STUB dispatch_rpc(RPC_MESSAGE *msg);
56 /* we only use one function to dispatch calls for all methods - we use the
57 * RPC_IF_OLE flag to tell the RPC runtime that this is the case */
58 static RPC_DISPATCH_FUNCTION rpc_dispatch_table[1] = { dispatch_rpc }; /* (RO) */
59 static RPC_DISPATCH_TABLE rpc_dispatch = { 1, rpc_dispatch_table }; /* (RO) */
61 static struct list registered_interfaces = LIST_INIT(registered_interfaces); /* (CS csRegIf) */
62 static CRITICAL_SECTION csRegIf;
63 static CRITICAL_SECTION_DEBUG csRegIf_debug =
66 { &csRegIf_debug.ProcessLocksList, &csRegIf_debug.ProcessLocksList },
67 0, 0, { (DWORD_PTR)(__FILE__ ": dcom registered server interfaces") }
69 static CRITICAL_SECTION csRegIf = { &csRegIf_debug, -1, 0, 0, 0, 0 };
71 static struct list channel_hooks = LIST_INIT(channel_hooks); /* (CS csChannelHook) */
72 static CRITICAL_SECTION csChannelHook;
73 static CRITICAL_SECTION_DEBUG csChannelHook_debug =
76 { &csChannelHook_debug.ProcessLocksList, &csChannelHook_debug.ProcessLocksList },
77 0, 0, { (DWORD_PTR)(__FILE__ ": channel hooks") }
79 static CRITICAL_SECTION csChannelHook = { &csChannelHook_debug, -1, 0, 0, 0, 0 };
81 static WCHAR wszRpcTransport[] = {'n','c','a','l','r','p','c',0};
87 DWORD refs; /* ref count */
88 RPC_SERVER_INTERFACE If; /* interface registered with the RPC runtime */
91 /* get the pipe endpoint specified of the specified apartment */
92 static inline void get_rpc_endpoint(LPWSTR endpoint, const OXID *oxid)
94 /* FIXME: should get endpoint from rpcss */
95 static const WCHAR wszEndpointFormat[] = {'\\','p','i','p','e','\\','O','L','E','_','%','0','8','l','x','%','0','8','l','x',0};
96 wsprintfW(endpoint, wszEndpointFormat, (DWORD)(*oxid >> 32),(DWORD)*oxid);
101 const IRpcChannelBufferVtbl *lpVtbl;
107 RpcChannelBuffer super; /* superclass */
109 RPC_BINDING_HANDLE bind; /* handle to the remote server */
110 OXID oxid; /* apartment in which the channel is valid */
111 DWORD dest_context; /* returned from GetDestCtx */
112 LPVOID dest_context_data; /* returned from GetDestCtx */
113 HANDLE event; /* cached event handle */
114 } ClientRpcChannelBuffer;
116 struct dispatch_params
118 RPCOLEMESSAGE *msg; /* message */
119 IRpcStubBuffer *stub; /* stub buffer, if applicable */
120 IRpcChannelBuffer *chan; /* server channel buffer, if applicable */
121 IID iid; /* ID of interface being called */
122 IUnknown *iface; /* interface being called */
123 HANDLE handle; /* handle that will become signaled when call finishes */
124 RPC_STATUS status; /* status (out) */
125 HRESULT hr; /* hresult (out) */
130 RPC_BINDING_HANDLE binding_handle;
131 ULONG prefix_data_len;
132 SChannelHookCallInfo channel_hook_info;
137 ULONG conformance; /* NDR */
140 /* [size_is((size+7)&~7)] */ unsigned char data[1];
143 struct channel_hook_entry
150 struct channel_hook_buffer_data
153 ULONG extension_size;
157 static HRESULT unmarshal_ORPCTHAT(RPC_MESSAGE *msg, ORPCTHAT *orpcthat,
158 ORPC_EXTENT_ARRAY *orpc_ext_array, WIRE_ORPC_EXTENT **first_wire_orpc_extent);
160 /* Channel Hook Functions */
162 static ULONG ChannelHooks_ClientGetSize(SChannelHookCallInfo *info,
163 struct channel_hook_buffer_data **data, unsigned int *hook_count,
164 ULONG *extension_count)
166 struct channel_hook_entry *entry;
167 ULONG total_size = 0;
168 unsigned int hook_index = 0;
171 *extension_count = 0;
173 EnterCriticalSection(&csChannelHook);
175 LIST_FOR_EACH_ENTRY(entry, &channel_hooks, struct channel_hook_entry, entry)
179 *data = HeapAlloc(GetProcessHeap(), 0, *hook_count * sizeof(struct channel_hook_buffer_data));
183 LIST_FOR_EACH_ENTRY(entry, &channel_hooks, struct channel_hook_entry, entry)
185 ULONG extension_size = 0;
187 IChannelHook_ClientGetSize(entry->hook, &entry->id, &info->iid, &extension_size);
189 TRACE("%s: extension_size = %u\n", debugstr_guid(&entry->id), extension_size);
191 extension_size = (extension_size+7)&~7;
192 (*data)[hook_index].id = entry->id;
193 (*data)[hook_index].extension_size = extension_size;
195 /* an extension is only put onto the wire if it has data to write */
198 total_size += FIELD_OFFSET(WIRE_ORPC_EXTENT, data[extension_size]);
199 (*extension_count)++;
205 LeaveCriticalSection(&csChannelHook);
210 static unsigned char * ChannelHooks_ClientFillBuffer(SChannelHookCallInfo *info,
211 unsigned char *buffer, struct channel_hook_buffer_data *data,
212 unsigned int hook_count)
214 struct channel_hook_entry *entry;
216 EnterCriticalSection(&csChannelHook);
218 LIST_FOR_EACH_ENTRY(entry, &channel_hooks, struct channel_hook_entry, entry)
221 ULONG extension_size = 0;
222 WIRE_ORPC_EXTENT *wire_orpc_extent = (WIRE_ORPC_EXTENT *)buffer;
224 for (i = 0; i < hook_count; i++)
225 if (IsEqualGUID(&entry->id, &data[i].id))
226 extension_size = data[i].extension_size;
228 /* an extension is only put onto the wire if it has data to write */
232 IChannelHook_ClientFillBuffer(entry->hook, &entry->id, &info->iid,
233 &extension_size, buffer + FIELD_OFFSET(WIRE_ORPC_EXTENT, data[0]));
235 TRACE("%s: extension_size = %u\n", debugstr_guid(&entry->id), extension_size);
237 /* FIXME: set unused portion of wire_orpc_extent->data to 0? */
239 wire_orpc_extent->conformance = (extension_size+7)&~7;
240 wire_orpc_extent->size = extension_size;
241 memcpy(&wire_orpc_extent->id, &entry->id, sizeof(wire_orpc_extent->id));
242 buffer += FIELD_OFFSET(WIRE_ORPC_EXTENT, data[wire_orpc_extent->conformance]);
245 LeaveCriticalSection(&csChannelHook);
247 HeapFree(GetProcessHeap(), 0, data);
252 static void ChannelHooks_ServerNotify(SChannelHookCallInfo *info,
253 DWORD lDataRep, WIRE_ORPC_EXTENT *first_wire_orpc_extent,
254 ULONG extension_count)
256 struct channel_hook_entry *entry;
259 EnterCriticalSection(&csChannelHook);
261 LIST_FOR_EACH_ENTRY(entry, &channel_hooks, struct channel_hook_entry, entry)
263 WIRE_ORPC_EXTENT *wire_orpc_extent;
264 for (i = 0, wire_orpc_extent = first_wire_orpc_extent;
266 i++, wire_orpc_extent = (WIRE_ORPC_EXTENT *)&wire_orpc_extent->data[wire_orpc_extent->conformance])
268 if (IsEqualGUID(&entry->id, &wire_orpc_extent->id))
271 if (i == extension_count) wire_orpc_extent = NULL;
273 IChannelHook_ServerNotify(entry->hook, &entry->id, &info->iid,
274 wire_orpc_extent ? wire_orpc_extent->size : 0,
275 wire_orpc_extent ? wire_orpc_extent->data : NULL,
279 LeaveCriticalSection(&csChannelHook);
282 static ULONG ChannelHooks_ServerGetSize(SChannelHookCallInfo *info,
283 struct channel_hook_buffer_data **data, unsigned int *hook_count,
284 ULONG *extension_count)
286 struct channel_hook_entry *entry;
287 ULONG total_size = 0;
288 unsigned int hook_index = 0;
291 *extension_count = 0;
293 EnterCriticalSection(&csChannelHook);
295 LIST_FOR_EACH_ENTRY(entry, &channel_hooks, struct channel_hook_entry, entry)
299 *data = HeapAlloc(GetProcessHeap(), 0, *hook_count * sizeof(struct channel_hook_buffer_data));
303 LIST_FOR_EACH_ENTRY(entry, &channel_hooks, struct channel_hook_entry, entry)
305 ULONG extension_size = 0;
307 IChannelHook_ServerGetSize(entry->hook, &entry->id, &info->iid, S_OK,
310 TRACE("%s: extension_size = %u\n", debugstr_guid(&entry->id), extension_size);
312 extension_size = (extension_size+7)&~7;
313 (*data)[hook_index].id = entry->id;
314 (*data)[hook_index].extension_size = extension_size;
316 /* an extension is only put onto the wire if it has data to write */
319 total_size += FIELD_OFFSET(WIRE_ORPC_EXTENT, data[extension_size]);
320 (*extension_count)++;
326 LeaveCriticalSection(&csChannelHook);
331 static unsigned char * ChannelHooks_ServerFillBuffer(SChannelHookCallInfo *info,
332 unsigned char *buffer, struct channel_hook_buffer_data *data,
333 unsigned int hook_count)
335 struct channel_hook_entry *entry;
337 EnterCriticalSection(&csChannelHook);
339 LIST_FOR_EACH_ENTRY(entry, &channel_hooks, struct channel_hook_entry, entry)
342 ULONG extension_size = 0;
343 WIRE_ORPC_EXTENT *wire_orpc_extent = (WIRE_ORPC_EXTENT *)buffer;
345 for (i = 0; i < hook_count; i++)
346 if (IsEqualGUID(&entry->id, &data[i].id))
347 extension_size = data[i].extension_size;
349 /* an extension is only put onto the wire if it has data to write */
353 IChannelHook_ServerFillBuffer(entry->hook, &entry->id, &info->iid,
354 &extension_size, buffer + FIELD_OFFSET(WIRE_ORPC_EXTENT, data[0]),
357 TRACE("%s: extension_size = %u\n", debugstr_guid(&entry->id), extension_size);
359 /* FIXME: set unused portion of wire_orpc_extent->data to 0? */
361 wire_orpc_extent->conformance = (extension_size+7)&~7;
362 wire_orpc_extent->size = extension_size;
363 memcpy(&wire_orpc_extent->id, &entry->id, sizeof(wire_orpc_extent->id));
364 buffer += FIELD_OFFSET(WIRE_ORPC_EXTENT, data[wire_orpc_extent->conformance]);
367 LeaveCriticalSection(&csChannelHook);
369 HeapFree(GetProcessHeap(), 0, data);
374 static void ChannelHooks_ClientNotify(SChannelHookCallInfo *info,
375 DWORD lDataRep, WIRE_ORPC_EXTENT *first_wire_orpc_extent,
376 ULONG extension_count, HRESULT hrFault)
378 struct channel_hook_entry *entry;
381 EnterCriticalSection(&csChannelHook);
383 LIST_FOR_EACH_ENTRY(entry, &channel_hooks, struct channel_hook_entry, entry)
385 WIRE_ORPC_EXTENT *wire_orpc_extent;
386 for (i = 0, wire_orpc_extent = first_wire_orpc_extent;
388 i++, wire_orpc_extent = (WIRE_ORPC_EXTENT *)&wire_orpc_extent->data[wire_orpc_extent->conformance])
390 if (IsEqualGUID(&entry->id, &wire_orpc_extent->id))
393 if (i == extension_count) wire_orpc_extent = NULL;
395 IChannelHook_ClientNotify(entry->hook, &entry->id, &info->iid,
396 wire_orpc_extent ? wire_orpc_extent->size : 0,
397 wire_orpc_extent ? wire_orpc_extent->data : NULL,
401 LeaveCriticalSection(&csChannelHook);
404 HRESULT RPC_RegisterChannelHook(REFGUID rguid, IChannelHook *hook)
406 struct channel_hook_entry *entry;
408 TRACE("(%s, %p)\n", debugstr_guid(rguid), hook);
410 entry = HeapAlloc(GetProcessHeap(), 0, sizeof(*entry));
412 return E_OUTOFMEMORY;
414 memcpy(&entry->id, rguid, sizeof(entry->id));
416 IChannelHook_AddRef(hook);
418 EnterCriticalSection(&csChannelHook);
419 list_add_tail(&channel_hooks, &entry->entry);
420 LeaveCriticalSection(&csChannelHook);
425 void RPC_UnregisterAllChannelHooks(void)
427 struct channel_hook_entry *cursor;
428 struct channel_hook_entry *cursor2;
430 EnterCriticalSection(&csChannelHook);
431 LIST_FOR_EACH_ENTRY_SAFE(cursor, cursor2, &channel_hooks, struct channel_hook_entry, entry)
432 HeapFree(GetProcessHeap(), 0, cursor);
433 LeaveCriticalSection(&csChannelHook);
436 /* RPC Channel Buffer Functions */
438 static HRESULT WINAPI RpcChannelBuffer_QueryInterface(LPRPCCHANNELBUFFER iface, REFIID riid, LPVOID *ppv)
441 if (IsEqualIID(riid,&IID_IRpcChannelBuffer) || IsEqualIID(riid,&IID_IUnknown))
443 *ppv = (LPVOID)iface;
444 IUnknown_AddRef(iface);
447 return E_NOINTERFACE;
450 static ULONG WINAPI RpcChannelBuffer_AddRef(LPRPCCHANNELBUFFER iface)
452 RpcChannelBuffer *This = (RpcChannelBuffer *)iface;
453 return InterlockedIncrement(&This->refs);
456 static ULONG WINAPI ServerRpcChannelBuffer_Release(LPRPCCHANNELBUFFER iface)
458 RpcChannelBuffer *This = (RpcChannelBuffer *)iface;
461 ref = InterlockedDecrement(&This->refs);
465 HeapFree(GetProcessHeap(), 0, This);
469 static ULONG WINAPI ClientRpcChannelBuffer_Release(LPRPCCHANNELBUFFER iface)
471 ClientRpcChannelBuffer *This = (ClientRpcChannelBuffer *)iface;
474 ref = InterlockedDecrement(&This->super.refs);
478 if (This->event) CloseHandle(This->event);
479 RpcBindingFree(&This->bind);
480 HeapFree(GetProcessHeap(), 0, This);
484 static HRESULT WINAPI ServerRpcChannelBuffer_GetBuffer(LPRPCCHANNELBUFFER iface, RPCOLEMESSAGE* olemsg, REFIID riid)
486 RpcChannelBuffer *This = (RpcChannelBuffer *)iface;
487 RPC_MESSAGE *msg = (RPC_MESSAGE *)olemsg;
490 struct message_state *message_state;
491 ULONG extensions_size;
492 struct channel_hook_buffer_data *channel_hook_data;
493 unsigned int channel_hook_count;
494 ULONG extension_count;
496 TRACE("(%p)->(%p,%s)\n", This, olemsg, debugstr_guid(riid));
498 message_state = (struct message_state *)msg->Handle;
499 /* restore the binding handle and the real start of data */
500 msg->Handle = message_state->binding_handle;
501 msg->Buffer = (char *)msg->Buffer - message_state->prefix_data_len;
503 extensions_size = ChannelHooks_ServerGetSize(&message_state->channel_hook_info,
504 &channel_hook_data, &channel_hook_count, &extension_count);
506 msg->BufferLength += FIELD_OFFSET(ORPCTHAT, extensions) + 4;
509 msg->BufferLength += FIELD_OFFSET(ORPC_EXTENT_ARRAY, extent) + 2*sizeof(DWORD) + extensions_size;
510 if (extension_count & 1)
511 msg->BufferLength += FIELD_OFFSET(WIRE_ORPC_EXTENT, data[0]);
514 status = I_RpcGetBuffer(msg);
516 orpcthat = (ORPCTHAT *)msg->Buffer;
517 msg->Buffer = (char *)msg->Buffer + FIELD_OFFSET(ORPCTHAT, extensions);
519 orpcthat->flags = ORPCF_NULL /* FIXME? */;
521 /* NDR representation of orpcthat->extensions */
522 *(DWORD *)msg->Buffer = extensions_size ? 1 : 0;
523 msg->Buffer = (char *)msg->Buffer + sizeof(DWORD);
527 ORPC_EXTENT_ARRAY *orpc_extent_array = msg->Buffer;
528 orpc_extent_array->size = extension_count;
529 orpc_extent_array->reserved = 0;
530 msg->Buffer = (char *)msg->Buffer + FIELD_OFFSET(ORPC_EXTENT_ARRAY, extent);
531 /* NDR representation of orpc_extent_array->extent */
532 *(DWORD *)msg->Buffer = 1;
533 msg->Buffer = (char *)msg->Buffer + sizeof(DWORD);
534 /* NDR representation of [size_is] attribute of orpc_extent_array->extent */
535 *(DWORD *)msg->Buffer = (extension_count + 1) & ~1;
536 msg->Buffer = (char *)msg->Buffer + sizeof(DWORD);
538 msg->Buffer = ChannelHooks_ServerFillBuffer(&message_state->channel_hook_info,
539 msg->Buffer, channel_hook_data, channel_hook_count);
541 /* we must add a dummy extension if there is an odd extension
542 * count to meet the contract specified by the size_is attribute */
543 if (extension_count & 1)
545 WIRE_ORPC_EXTENT *wire_orpc_extent = msg->Buffer;
546 wire_orpc_extent->conformance = 0;
547 memcpy(&wire_orpc_extent->id, &GUID_NULL, sizeof(wire_orpc_extent->id));
548 wire_orpc_extent->size = 0;
549 msg->Buffer = (char *)msg->Buffer + FIELD_OFFSET(WIRE_ORPC_EXTENT, data[0]);
553 /* store the prefixed data length so that we can restore the real buffer
555 message_state->prefix_data_len = (char *)msg->Buffer - (char *)orpcthat;
556 msg->BufferLength -= message_state->prefix_data_len;
557 /* save away the message state again */
558 msg->Handle = message_state;
560 TRACE("-- %ld\n", status);
562 return HRESULT_FROM_WIN32(status);
565 static HRESULT WINAPI ClientRpcChannelBuffer_GetBuffer(LPRPCCHANNELBUFFER iface, RPCOLEMESSAGE* olemsg, REFIID riid)
567 ClientRpcChannelBuffer *This = (ClientRpcChannelBuffer *)iface;
568 RPC_MESSAGE *msg = (RPC_MESSAGE *)olemsg;
569 RPC_CLIENT_INTERFACE *cif;
572 struct message_state *message_state;
573 ULONG extensions_size;
574 struct channel_hook_buffer_data *channel_hook_data;
575 unsigned int channel_hook_count;
576 ULONG extension_count;
578 TRACE("(%p)->(%p,%s)\n", This, olemsg, debugstr_guid(riid));
580 cif = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(RPC_CLIENT_INTERFACE));
582 return E_OUTOFMEMORY;
584 message_state = HeapAlloc(GetProcessHeap(), 0, sizeof(*message_state));
587 HeapFree(GetProcessHeap(), 0, cif);
588 return E_OUTOFMEMORY;
591 cif->Length = sizeof(RPC_CLIENT_INTERFACE);
592 /* RPC interface ID = COM interface ID */
593 cif->InterfaceId.SyntaxGUID = *riid;
594 /* COM objects always have a version of 0.0 */
595 cif->InterfaceId.SyntaxVersion.MajorVersion = 0;
596 cif->InterfaceId.SyntaxVersion.MinorVersion = 0;
597 msg->Handle = This->bind;
598 msg->RpcInterfaceInformation = cif;
600 message_state->channel_hook_info.iid = *riid;
601 message_state->channel_hook_info.cbSize = sizeof(message_state->channel_hook_info);
602 message_state->channel_hook_info.uCausality = COM_CurrentCausalityId();
603 message_state->channel_hook_info.dwServerPid = 0; /* FIXME */
604 message_state->channel_hook_info.iMethod = msg->ProcNum;
605 message_state->channel_hook_info.pObject = NULL; /* only present on server-side */
607 extensions_size = ChannelHooks_ClientGetSize(&message_state->channel_hook_info,
608 &channel_hook_data, &channel_hook_count, &extension_count);
610 msg->BufferLength += FIELD_OFFSET(ORPCTHIS, extensions) + 4;
613 msg->BufferLength += FIELD_OFFSET(ORPC_EXTENT_ARRAY, extent) + 2*sizeof(DWORD) + extensions_size;
614 if (extension_count & 1)
615 msg->BufferLength += FIELD_OFFSET(WIRE_ORPC_EXTENT, data[0]);
618 status = I_RpcGetBuffer(msg);
620 message_state->prefix_data_len = 0;
621 message_state->binding_handle = This->bind;
622 msg->Handle = message_state;
624 if (status == RPC_S_OK)
626 orpcthis = (ORPCTHIS *)msg->Buffer;
627 msg->Buffer = (char *)msg->Buffer + FIELD_OFFSET(ORPCTHIS, extensions);
629 orpcthis->version.MajorVersion = COM_MAJOR_VERSION;
630 orpcthis->version.MinorVersion = COM_MINOR_VERSION;
631 orpcthis->flags = message_state->channel_hook_info.dwServerPid ? ORPCF_LOCAL : ORPCF_NULL;
632 orpcthis->reserved1 = 0;
633 orpcthis->cid = message_state->channel_hook_info.uCausality;
635 /* NDR representation of orpcthis->extensions */
636 *(DWORD *)msg->Buffer = extensions_size ? 1 : 0;
637 msg->Buffer = (char *)msg->Buffer + sizeof(DWORD);
641 ORPC_EXTENT_ARRAY *orpc_extent_array = msg->Buffer;
642 orpc_extent_array->size = extension_count;
643 orpc_extent_array->reserved = 0;
644 msg->Buffer = (char *)msg->Buffer + FIELD_OFFSET(ORPC_EXTENT_ARRAY, extent);
645 /* NDR representation of orpc_extent_array->extent */
646 *(DWORD *)msg->Buffer = 1;
647 msg->Buffer = (char *)msg->Buffer + sizeof(DWORD);
648 /* NDR representation of [size_is] attribute of orpc_extent_array->extent */
649 *(DWORD *)msg->Buffer = (extension_count + 1) & ~1;
650 msg->Buffer = (char *)msg->Buffer + sizeof(DWORD);
652 msg->Buffer = ChannelHooks_ClientFillBuffer(&message_state->channel_hook_info,
653 msg->Buffer, channel_hook_data, channel_hook_count);
655 /* we must add a dummy extension if there is an odd extension
656 * count to meet the contract specified by the size_is attribute */
657 if (extension_count & 1)
659 WIRE_ORPC_EXTENT *wire_orpc_extent = msg->Buffer;
660 wire_orpc_extent->conformance = 0;
661 memcpy(&wire_orpc_extent->id, &GUID_NULL, sizeof(wire_orpc_extent->id));
662 wire_orpc_extent->size = 0;
663 msg->Buffer = (char *)msg->Buffer + FIELD_OFFSET(WIRE_ORPC_EXTENT, data[0]);
667 /* store the prefixed data length so that we can restore the real buffer
668 * pointer in ClientRpcChannelBuffer_SendReceive. */
669 message_state->prefix_data_len = (char *)msg->Buffer - (char *)orpcthis;
670 msg->BufferLength -= message_state->prefix_data_len;
673 TRACE("-- %ld\n", status);
675 return HRESULT_FROM_WIN32(status);
678 static HRESULT WINAPI ServerRpcChannelBuffer_SendReceive(LPRPCCHANNELBUFFER iface, RPCOLEMESSAGE *olemsg, ULONG *pstatus)
684 static HANDLE ClientRpcChannelBuffer_GetEventHandle(ClientRpcChannelBuffer *This)
686 HANDLE event = InterlockedExchangePointer(&This->event, NULL);
688 /* Note: must be auto-reset event so we can reuse it without a call
690 if (!event) event = CreateEventW(NULL, FALSE, FALSE, NULL);
695 static void ClientRpcChannelBuffer_ReleaseEventHandle(ClientRpcChannelBuffer *This, HANDLE event)
697 if (InterlockedCompareExchangePointer(&This->event, event, NULL))
698 /* already a handle cached in This */
702 /* this thread runs an outgoing RPC */
703 static DWORD WINAPI rpc_sendreceive_thread(LPVOID param)
705 struct dispatch_params *data = (struct dispatch_params *) param;
707 /* FIXME: trap and rethrow RPC exceptions in app thread */
708 data->status = I_RpcSendReceive((RPC_MESSAGE *)data->msg);
710 TRACE("completed with status 0x%lx\n", data->status);
712 SetEvent(data->handle);
717 static inline HRESULT ClientRpcChannelBuffer_IsCorrectApartment(ClientRpcChannelBuffer *This, APARTMENT *apt)
722 if (apartment_getoxid(apt, &oxid) != S_OK)
724 if (This->oxid != oxid)
729 static HRESULT WINAPI ClientRpcChannelBuffer_SendReceive(LPRPCCHANNELBUFFER iface, RPCOLEMESSAGE *olemsg, ULONG *pstatus)
731 ClientRpcChannelBuffer *This = (ClientRpcChannelBuffer *)iface;
733 RPC_MESSAGE *msg = (RPC_MESSAGE *)olemsg;
736 struct dispatch_params *params;
737 APARTMENT *apt = NULL;
739 struct message_state *message_state;
741 ORPC_EXTENT_ARRAY orpc_ext_array;
742 WIRE_ORPC_EXTENT *first_wire_orpc_extent = NULL;
743 HRESULT hrFault = S_OK;
745 TRACE("(%p) iMethod=%d\n", olemsg, olemsg->iMethod);
747 hr = ClientRpcChannelBuffer_IsCorrectApartment(This, COM_CurrentApt());
750 ERR("called from wrong apartment, should have been 0x%s\n",
751 wine_dbgstr_longlong(This->oxid));
752 return RPC_E_WRONG_THREAD;
754 /* this situation should be impossible in multi-threaded apartments,
755 * because the calling thread isn't re-entrable.
756 * Note: doing a COM call during the processing of a sent message is
757 * only disallowed if a client call is already being waited for
759 if (!COM_CurrentApt()->multi_threaded &&
760 COM_CurrentInfo()->pending_call_count_client &&
763 ERR("can't make an outgoing COM call in response to a sent message\n");
764 return RPC_E_CANTCALLOUT_ININPUTSYNCCALL;
767 params = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*params));
768 if (!params) return E_OUTOFMEMORY;
770 message_state = (struct message_state *)msg->Handle;
771 /* restore the binding handle and the real start of data */
772 msg->Handle = message_state->binding_handle;
773 msg->Buffer = (char *)msg->Buffer - message_state->prefix_data_len;
774 msg->BufferLength += message_state->prefix_data_len;
776 params->msg = olemsg;
777 params->status = RPC_S_OK;
780 /* Note: this is an optimization in the Microsoft OLE runtime that we need
781 * to copy, as shown by the test_no_couninitialize_client test. without
782 * short-circuiting the RPC runtime in the case below, the test will
783 * deadlock on the loader lock due to the RPC runtime needing to create
784 * a thread to process the RPC when this function is called indirectly
787 RpcBindingInqObject(message_state->binding_handle, &ipid);
788 hr = ipid_get_dispatch_params(&ipid, &apt, ¶ms->stub, ¶ms->chan,
789 ¶ms->iid, ¶ms->iface);
790 params->handle = ClientRpcChannelBuffer_GetEventHandle(This);
791 if ((hr == S_OK) && !apt->multi_threaded)
793 TRACE("Calling apartment thread 0x%08x...\n", apt->tid);
795 if (!PostMessageW(apartment_getwindow(apt), DM_EXECUTERPC, 0, (LPARAM)params))
797 ERR("PostMessage failed with error %d\n", GetLastError());
798 hr = HRESULT_FROM_WIN32(GetLastError());
805 /* otherwise, we go via RPC runtime so the stub and channel aren't
807 IRpcStubBuffer_Release(params->stub);
809 IRpcChannelBuffer_Release(params->chan);
813 /* we use a separate thread here because we need to be able to
814 * pump the message loop in the application thread: if we do not,
815 * any windows created by this thread will hang and RPCs that try
816 * and re-enter this STA from an incoming server thread will
817 * deadlock. InstallShield is an example of that.
819 if (!QueueUserWorkItem(rpc_sendreceive_thread, params, WT_EXECUTEDEFAULT))
821 ERR("QueueUserWorkItem failed with error %x\n", GetLastError());
827 if (apt) apartment_release(apt);
831 if (WaitForSingleObject(params->handle, 0))
833 COM_CurrentInfo()->pending_call_count_client++;
834 hr = CoWaitForMultipleHandles(0, INFINITE, 1, ¶ms->handle, &index);
835 COM_CurrentInfo()->pending_call_count_client--;
838 ClientRpcChannelBuffer_ReleaseEventHandle(This, params->handle);
840 /* for WM shortcut, faults are returned in params->hr */
842 hrFault = params->hr;
844 status = params->status;
845 HeapFree(GetProcessHeap(), 0, params);
848 orpcthat.flags = ORPCF_NULL;
849 orpcthat.extensions = NULL;
851 /* for normal RPC calls, faults are returned in first 4 bytes of the
853 TRACE("RPC call status: 0x%lx\n", status);
854 if (status == RPC_S_CALL_FAILED)
855 hrFault = *(HRESULT *)olemsg->Buffer;
856 else if (status != RPC_S_OK)
857 hr = HRESULT_FROM_WIN32(status);
859 TRACE("hrFault = 0x%08x\n", hrFault);
861 /* FIXME: this condition should be
862 * "hr == S_OK && (!hrFault || msg->BufferLength > FIELD_OFFSET(ORPCTHAT, extentions) + 4)"
863 * but we don't currently reset the message length for PostMessage
864 * dispatched calls */
865 if (hr == S_OK && hrFault == S_OK)
868 char *original_buffer = msg->Buffer;
870 /* handle ORPCTHAT and client extensions */
872 hr2 = unmarshal_ORPCTHAT(msg, &orpcthat, &orpc_ext_array, &first_wire_orpc_extent);
876 message_state->prefix_data_len = (char *)msg->Buffer - original_buffer;
877 msg->BufferLength -= message_state->prefix_data_len;
880 message_state->prefix_data_len = 0;
884 ChannelHooks_ClientNotify(&message_state->channel_hook_info,
885 msg->DataRepresentation,
886 first_wire_orpc_extent,
887 orpcthat.extensions && first_wire_orpc_extent ? orpcthat.extensions->size : 0,
891 /* save away the message state again */
892 msg->Handle = message_state;
894 if (pstatus) *pstatus = status;
899 TRACE("-- 0x%08x\n", hr);
904 static HRESULT WINAPI ServerRpcChannelBuffer_FreeBuffer(LPRPCCHANNELBUFFER iface, RPCOLEMESSAGE* olemsg)
906 RPC_MESSAGE *msg = (RPC_MESSAGE *)olemsg;
908 struct message_state *message_state;
910 TRACE("(%p)\n", msg);
912 message_state = (struct message_state *)msg->Handle;
913 /* restore the binding handle and the real start of data */
914 msg->Handle = message_state->binding_handle;
915 msg->Buffer = (char *)msg->Buffer - message_state->prefix_data_len;
916 msg->BufferLength += message_state->prefix_data_len;
917 message_state->prefix_data_len = 0;
919 status = I_RpcFreeBuffer(msg);
921 msg->Handle = message_state;
923 TRACE("-- %ld\n", status);
925 return HRESULT_FROM_WIN32(status);
928 static HRESULT WINAPI ClientRpcChannelBuffer_FreeBuffer(LPRPCCHANNELBUFFER iface, RPCOLEMESSAGE* olemsg)
930 RPC_MESSAGE *msg = (RPC_MESSAGE *)olemsg;
932 struct message_state *message_state;
934 TRACE("(%p)\n", msg);
936 message_state = (struct message_state *)msg->Handle;
937 /* restore the binding handle and the real start of data */
938 msg->Handle = message_state->binding_handle;
939 msg->Buffer = (char *)msg->Buffer - message_state->prefix_data_len;
940 msg->BufferLength += message_state->prefix_data_len;
942 status = I_RpcFreeBuffer(msg);
944 HeapFree(GetProcessHeap(), 0, msg->RpcInterfaceInformation);
945 msg->RpcInterfaceInformation = NULL;
946 HeapFree(GetProcessHeap(), 0, message_state);
948 TRACE("-- %ld\n", status);
950 return HRESULT_FROM_WIN32(status);
953 static HRESULT WINAPI ClientRpcChannelBuffer_GetDestCtx(LPRPCCHANNELBUFFER iface, DWORD* pdwDestContext, void** ppvDestContext)
955 ClientRpcChannelBuffer *This = (ClientRpcChannelBuffer *)iface;
957 TRACE("(%p,%p)\n", pdwDestContext, ppvDestContext);
959 *pdwDestContext = This->dest_context;
960 *ppvDestContext = This->dest_context_data;
965 static HRESULT WINAPI ServerRpcChannelBuffer_GetDestCtx(LPRPCCHANNELBUFFER iface, DWORD* pdwDestContext, void** ppvDestContext)
967 FIXME("(%p,%p), stub!\n", pdwDestContext, ppvDestContext);
971 static HRESULT WINAPI RpcChannelBuffer_IsConnected(LPRPCCHANNELBUFFER iface)
974 /* native does nothing too */
978 static const IRpcChannelBufferVtbl ClientRpcChannelBufferVtbl =
980 RpcChannelBuffer_QueryInterface,
981 RpcChannelBuffer_AddRef,
982 ClientRpcChannelBuffer_Release,
983 ClientRpcChannelBuffer_GetBuffer,
984 ClientRpcChannelBuffer_SendReceive,
985 ClientRpcChannelBuffer_FreeBuffer,
986 ClientRpcChannelBuffer_GetDestCtx,
987 RpcChannelBuffer_IsConnected
990 static const IRpcChannelBufferVtbl ServerRpcChannelBufferVtbl =
992 RpcChannelBuffer_QueryInterface,
993 RpcChannelBuffer_AddRef,
994 ServerRpcChannelBuffer_Release,
995 ServerRpcChannelBuffer_GetBuffer,
996 ServerRpcChannelBuffer_SendReceive,
997 ServerRpcChannelBuffer_FreeBuffer,
998 ServerRpcChannelBuffer_GetDestCtx,
999 RpcChannelBuffer_IsConnected
1002 /* returns a channel buffer for proxies */
1003 HRESULT RPC_CreateClientChannel(const OXID *oxid, const IPID *ipid,
1004 DWORD dest_context, void *dest_context_data,
1005 IRpcChannelBuffer **chan)
1007 ClientRpcChannelBuffer *This;
1008 WCHAR endpoint[200];
1009 RPC_BINDING_HANDLE bind;
1011 LPWSTR string_binding;
1013 /* connect to the apartment listener thread */
1014 get_rpc_endpoint(endpoint, oxid);
1016 TRACE("proxy pipe: connecting to endpoint: %s\n", debugstr_w(endpoint));
1018 status = RpcStringBindingComposeW(
1026 if (status == RPC_S_OK)
1028 status = RpcBindingFromStringBindingW(string_binding, &bind);
1030 if (status == RPC_S_OK)
1032 IPID ipid2 = *ipid; /* why can't RpcBindingSetObject take a const? */
1033 status = RpcBindingSetObject(bind, &ipid2);
1034 if (status != RPC_S_OK)
1035 RpcBindingFree(&bind);
1038 RpcStringFreeW(&string_binding);
1041 if (status != RPC_S_OK)
1043 ERR("Couldn't get binding for endpoint %s, status = %ld\n", debugstr_w(endpoint), status);
1044 return HRESULT_FROM_WIN32(status);
1047 This = HeapAlloc(GetProcessHeap(), 0, sizeof(*This));
1050 RpcBindingFree(&bind);
1051 return E_OUTOFMEMORY;
1054 This->super.lpVtbl = &ClientRpcChannelBufferVtbl;
1055 This->super.refs = 1;
1057 apartment_getoxid(COM_CurrentApt(), &This->oxid);
1058 This->dest_context = dest_context;
1059 This->dest_context_data = dest_context_data;
1062 *chan = (IRpcChannelBuffer*)This;
1067 HRESULT RPC_CreateServerChannel(IRpcChannelBuffer **chan)
1069 RpcChannelBuffer *This = HeapAlloc(GetProcessHeap(), 0, sizeof(*This));
1071 return E_OUTOFMEMORY;
1073 This->lpVtbl = &ServerRpcChannelBufferVtbl;
1076 *chan = (IRpcChannelBuffer*)This;
1081 /* unmarshals ORPC_EXTENT_ARRAY according to NDR rules, but doesn't allocate
1083 static HRESULT unmarshal_ORPC_EXTENT_ARRAY(RPC_MESSAGE *msg, const char *end,
1084 ORPC_EXTENT_ARRAY *extensions,
1085 WIRE_ORPC_EXTENT **first_wire_orpc_extent)
1090 memcpy(extensions, msg->Buffer, FIELD_OFFSET(ORPC_EXTENT_ARRAY, extent));
1091 msg->Buffer = (char *)msg->Buffer + FIELD_OFFSET(ORPC_EXTENT_ARRAY, extent);
1093 if ((const char *)msg->Buffer + 2 * sizeof(DWORD) > end)
1094 return RPC_E_INVALID_HEADER;
1096 pointer_id = *(DWORD *)msg->Buffer;
1097 msg->Buffer = (char *)msg->Buffer + sizeof(DWORD);
1098 extensions->extent = NULL;
1102 WIRE_ORPC_EXTENT *wire_orpc_extent;
1105 if (*(DWORD *)msg->Buffer != ((extensions->size+1)&~1))
1106 return RPC_S_INVALID_BOUND;
1108 msg->Buffer = (char *)msg->Buffer + sizeof(DWORD);
1110 /* arbritary limit for security (don't know what native does) */
1111 if (extensions->size > 256)
1113 ERR("too many extensions: %ld\n", extensions->size);
1114 return RPC_S_INVALID_BOUND;
1117 *first_wire_orpc_extent = wire_orpc_extent = (WIRE_ORPC_EXTENT *)msg->Buffer;
1118 for (i = 0; i < ((extensions->size+1)&~1); i++)
1120 if ((const char *)&wire_orpc_extent->data[0] > end)
1121 return RPC_S_INVALID_BOUND;
1122 if (wire_orpc_extent->conformance != ((wire_orpc_extent->size+7)&~7))
1123 return RPC_S_INVALID_BOUND;
1124 if ((const char *)&wire_orpc_extent->data[wire_orpc_extent->conformance] > end)
1125 return RPC_S_INVALID_BOUND;
1126 TRACE("size %u, guid %s\n", wire_orpc_extent->size, debugstr_guid(&wire_orpc_extent->id));
1127 wire_orpc_extent = (WIRE_ORPC_EXTENT *)&wire_orpc_extent->data[wire_orpc_extent->conformance];
1129 msg->Buffer = wire_orpc_extent;
1135 /* unmarshals ORPCTHIS according to NDR rules, but doesn't allocate any memory */
1136 static HRESULT unmarshal_ORPCTHIS(RPC_MESSAGE *msg, ORPCTHIS *orpcthis,
1137 ORPC_EXTENT_ARRAY *orpc_ext_array, WIRE_ORPC_EXTENT **first_wire_orpc_extent)
1139 const char *end = (char *)msg->Buffer + msg->BufferLength;
1141 *first_wire_orpc_extent = NULL;
1143 if (msg->BufferLength < FIELD_OFFSET(ORPCTHIS, extensions) + 4)
1145 ERR("invalid buffer length\n");
1146 return RPC_E_INVALID_HEADER;
1149 memcpy(orpcthis, msg->Buffer, FIELD_OFFSET(ORPCTHIS, extensions));
1150 msg->Buffer = (char *)msg->Buffer + FIELD_OFFSET(ORPCTHIS, extensions);
1152 if ((const char *)msg->Buffer + sizeof(DWORD) > end)
1153 return RPC_E_INVALID_HEADER;
1155 if (*(DWORD *)msg->Buffer)
1156 orpcthis->extensions = orpc_ext_array;
1158 orpcthis->extensions = NULL;
1160 msg->Buffer = (char *)msg->Buffer + sizeof(DWORD);
1162 if (orpcthis->extensions)
1164 HRESULT hr = unmarshal_ORPC_EXTENT_ARRAY(msg, end, orpc_ext_array,
1165 first_wire_orpc_extent);
1170 if ((orpcthis->version.MajorVersion != COM_MAJOR_VERSION) ||
1171 (orpcthis->version.MinorVersion > COM_MINOR_VERSION))
1173 ERR("COM version {%d, %d} not supported\n",
1174 orpcthis->version.MajorVersion, orpcthis->version.MinorVersion);
1175 return RPC_E_VERSION_MISMATCH;
1178 if (orpcthis->flags & ~(ORPCF_LOCAL|ORPCF_RESERVED1|ORPCF_RESERVED2|ORPCF_RESERVED3|ORPCF_RESERVED4))
1180 ERR("invalid flags 0x%lx\n", orpcthis->flags & ~(ORPCF_LOCAL|ORPCF_RESERVED1|ORPCF_RESERVED2|ORPCF_RESERVED3|ORPCF_RESERVED4));
1181 return RPC_E_INVALID_HEADER;
1187 static HRESULT unmarshal_ORPCTHAT(RPC_MESSAGE *msg, ORPCTHAT *orpcthat,
1188 ORPC_EXTENT_ARRAY *orpc_ext_array, WIRE_ORPC_EXTENT **first_wire_orpc_extent)
1190 const char *end = (char *)msg->Buffer + msg->BufferLength;
1192 *first_wire_orpc_extent = NULL;
1194 if (msg->BufferLength < FIELD_OFFSET(ORPCTHAT, extensions) + 4)
1196 ERR("invalid buffer length\n");
1197 return RPC_E_INVALID_HEADER;
1200 memcpy(orpcthat, msg->Buffer, FIELD_OFFSET(ORPCTHAT, extensions));
1201 msg->Buffer = (char *)msg->Buffer + FIELD_OFFSET(ORPCTHAT, extensions);
1203 if ((const char *)msg->Buffer + sizeof(DWORD) > end)
1204 return RPC_E_INVALID_HEADER;
1206 if (*(DWORD *)msg->Buffer)
1207 orpcthat->extensions = orpc_ext_array;
1209 orpcthat->extensions = NULL;
1211 msg->Buffer = (char *)msg->Buffer + sizeof(DWORD);
1213 if (orpcthat->extensions)
1215 HRESULT hr = unmarshal_ORPC_EXTENT_ARRAY(msg, end, orpc_ext_array,
1216 first_wire_orpc_extent);
1221 if (orpcthat->flags & ~(ORPCF_LOCAL|ORPCF_RESERVED1|ORPCF_RESERVED2|ORPCF_RESERVED3|ORPCF_RESERVED4))
1223 ERR("invalid flags 0x%lx\n", orpcthat->flags & ~(ORPCF_LOCAL|ORPCF_RESERVED1|ORPCF_RESERVED2|ORPCF_RESERVED3|ORPCF_RESERVED4));
1224 return RPC_E_INVALID_HEADER;
1230 void RPC_ExecuteCall(struct dispatch_params *params)
1232 struct message_state *message_state = NULL;
1233 RPC_MESSAGE *msg = (RPC_MESSAGE *)params->msg;
1234 char *original_buffer = msg->Buffer;
1236 ORPC_EXTENT_ARRAY orpc_ext_array;
1237 WIRE_ORPC_EXTENT *first_wire_orpc_extent;
1238 GUID old_causality_id;
1240 /* handle ORPCTHIS and server extensions */
1242 params->hr = unmarshal_ORPCTHIS(msg, &orpcthis, &orpc_ext_array, &first_wire_orpc_extent);
1243 if (params->hr != S_OK)
1245 msg->Buffer = original_buffer;
1249 message_state = HeapAlloc(GetProcessHeap(), 0, sizeof(*message_state));
1252 params->hr = E_OUTOFMEMORY;
1253 msg->Buffer = original_buffer;
1257 message_state->prefix_data_len = (char *)msg->Buffer - original_buffer;
1258 message_state->binding_handle = msg->Handle;
1260 message_state->channel_hook_info.iid = params->iid;
1261 message_state->channel_hook_info.cbSize = sizeof(message_state->channel_hook_info);
1262 message_state->channel_hook_info.uCausality = orpcthis.cid;
1263 message_state->channel_hook_info.dwServerPid = GetCurrentProcessId();
1264 message_state->channel_hook_info.iMethod = msg->ProcNum;
1265 message_state->channel_hook_info.pObject = params->iface;
1267 if (orpcthis.extensions && first_wire_orpc_extent &&
1268 orpcthis.extensions->size)
1269 ChannelHooks_ServerNotify(&message_state->channel_hook_info, msg->DataRepresentation, first_wire_orpc_extent, orpcthis.extensions->size);
1271 msg->Handle = message_state;
1272 msg->BufferLength -= message_state->prefix_data_len;
1274 /* call message filter */
1276 if (COM_CurrentApt()->filter)
1279 INTERFACEINFO interface_info;
1282 interface_info.pUnk = params->iface;
1283 interface_info.iid = params->iid;
1284 interface_info.wMethod = msg->ProcNum;
1286 if (IsEqualGUID(&orpcthis.cid, &COM_CurrentInfo()->causality_id))
1287 calltype = CALLTYPE_NESTED;
1288 else if (COM_CurrentInfo()->pending_call_count_server == 0)
1289 calltype = CALLTYPE_TOPLEVEL;
1291 calltype = CALLTYPE_TOPLEVEL_CALLPENDING;
1293 handlecall = IMessageFilter_HandleInComingCall(COM_CurrentApt()->filter,
1295 (HTASK)GetCurrentProcessId(),
1298 TRACE("IMessageFilter_HandleInComingCall returned %d\n", handlecall);
1301 case SERVERCALL_REJECTED:
1302 params->hr = RPC_E_CALL_REJECTED;
1303 goto exit_reset_state;
1304 case SERVERCALL_RETRYLATER:
1305 #if 0 /* FIXME: handle retries on the client side before enabling this code */
1306 params->hr = RPC_E_RETRY;
1307 goto exit_reset_state;
1309 FIXME("retry call later not implemented\n");
1312 case SERVERCALL_ISHANDLED:
1318 /* invoke the method */
1320 /* save the old causality ID - note: any calls executed while processing
1321 * messages received during the SendReceive will appear to originate from
1322 * this call - this should be checked with what Windows does */
1323 old_causality_id = COM_CurrentInfo()->causality_id;
1324 COM_CurrentInfo()->causality_id = orpcthis.cid;
1325 COM_CurrentInfo()->pending_call_count_server++;
1326 params->hr = IRpcStubBuffer_Invoke(params->stub, params->msg, params->chan);
1327 COM_CurrentInfo()->pending_call_count_server--;
1328 COM_CurrentInfo()->causality_id = old_causality_id;
1331 message_state = (struct message_state *)msg->Handle;
1332 msg->Handle = message_state->binding_handle;
1333 msg->Buffer = (char *)msg->Buffer - message_state->prefix_data_len;
1334 msg->BufferLength += message_state->prefix_data_len;
1337 HeapFree(GetProcessHeap(), 0, message_state);
1338 IRpcStubBuffer_Release(params->stub);
1339 IRpcChannelBuffer_Release(params->chan);
1340 if (params->handle) SetEvent(params->handle);
1343 static void __RPC_STUB dispatch_rpc(RPC_MESSAGE *msg)
1345 struct dispatch_params *params;
1350 RpcBindingInqObject(msg->Handle, &ipid);
1352 TRACE("ipid = %s, iMethod = %d\n", debugstr_guid(&ipid), msg->ProcNum);
1354 params = HeapAlloc(GetProcessHeap(), 0, sizeof(*params));
1355 if (!params) return RpcRaiseException(E_OUTOFMEMORY);
1357 hr = ipid_get_dispatch_params(&ipid, &apt, ¶ms->stub, ¶ms->chan,
1358 ¶ms->iid, ¶ms->iface);
1361 ERR("no apartment found for ipid %s\n", debugstr_guid(&ipid));
1362 HeapFree(GetProcessHeap(), 0, params);
1363 return RpcRaiseException(hr);
1366 params->msg = (RPCOLEMESSAGE *)msg;
1367 params->status = RPC_S_OK;
1369 params->handle = NULL;
1371 /* Note: this is the important difference between STAs and MTAs - we
1372 * always execute RPCs to STAs in the thread that originally created the
1373 * apartment (i.e. the one that pumps messages to the window) */
1374 if (!apt->multi_threaded)
1376 params->handle = CreateEventW(NULL, FALSE, FALSE, NULL);
1378 TRACE("Calling apartment thread 0x%08x...\n", apt->tid);
1380 if (PostMessageW(apartment_getwindow(apt), DM_EXECUTERPC, 0, (LPARAM)params))
1381 WaitForSingleObject(params->handle, INFINITE);
1384 ERR("PostMessage failed with error %d\n", GetLastError());
1385 IRpcChannelBuffer_Release(params->chan);
1386 IRpcStubBuffer_Release(params->stub);
1388 CloseHandle(params->handle);
1392 BOOL joined = FALSE;
1393 if (!COM_CurrentInfo()->apt)
1395 apartment_joinmta();
1398 RPC_ExecuteCall(params);
1401 apartment_release(COM_CurrentInfo()->apt);
1402 COM_CurrentInfo()->apt = NULL;
1407 HeapFree(GetProcessHeap(), 0, params);
1409 apartment_release(apt);
1411 /* if IRpcStubBuffer_Invoke fails, we should raise an exception to tell
1412 * the RPC runtime that the call failed */
1413 if (hr) RpcRaiseException(hr);
1416 /* stub registration */
1417 HRESULT RPC_RegisterInterface(REFIID riid)
1419 struct registered_if *rif;
1423 TRACE("(%s)\n", debugstr_guid(riid));
1425 EnterCriticalSection(&csRegIf);
1426 LIST_FOR_EACH_ENTRY(rif, ®istered_interfaces, struct registered_if, entry)
1428 if (IsEqualGUID(&rif->If.InterfaceId.SyntaxGUID, riid))
1437 TRACE("Creating new interface\n");
1439 rif = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*rif));
1445 rif->If.Length = sizeof(RPC_SERVER_INTERFACE);
1446 /* RPC interface ID = COM interface ID */
1447 rif->If.InterfaceId.SyntaxGUID = *riid;
1448 rif->If.DispatchTable = &rpc_dispatch;
1449 /* all other fields are 0, including the version asCOM objects
1450 * always have a version of 0.0 */
1451 status = RpcServerRegisterIfEx(
1452 (RPC_IF_HANDLE)&rif->If,
1454 RPC_IF_OLE | RPC_IF_AUTOLISTEN,
1455 RPC_C_LISTEN_MAX_CALLS_DEFAULT,
1457 if (status == RPC_S_OK)
1458 list_add_tail(®istered_interfaces, &rif->entry);
1461 ERR("RpcServerRegisterIfEx failed with error %ld\n", status);
1462 HeapFree(GetProcessHeap(), 0, rif);
1463 hr = HRESULT_FROM_WIN32(status);
1469 LeaveCriticalSection(&csRegIf);
1473 /* stub unregistration */
1474 void RPC_UnregisterInterface(REFIID riid)
1476 struct registered_if *rif;
1477 EnterCriticalSection(&csRegIf);
1478 LIST_FOR_EACH_ENTRY(rif, ®istered_interfaces, struct registered_if, entry)
1480 if (IsEqualGUID(&rif->If.InterfaceId.SyntaxGUID, riid))
1484 RpcServerUnregisterIf((RPC_IF_HANDLE)&rif->If, NULL, TRUE);
1485 list_remove(&rif->entry);
1486 HeapFree(GetProcessHeap(), 0, rif);
1491 LeaveCriticalSection(&csRegIf);
1494 /* make the apartment reachable by other threads and processes and create the
1495 * IRemUnknown object */
1496 void RPC_StartRemoting(struct apartment *apt)
1498 if (!InterlockedExchange(&apt->remoting_started, TRUE))
1500 WCHAR endpoint[200];
1503 get_rpc_endpoint(endpoint, &apt->oxid);
1505 status = RpcServerUseProtseqEpW(
1507 RPC_C_PROTSEQ_MAX_REQS_DEFAULT,
1510 if (status != RPC_S_OK)
1511 ERR("Couldn't register endpoint %s\n", debugstr_w(endpoint));
1513 /* FIXME: move remote unknown exporting into this function */
1515 start_apartment_remote_unknown();
1519 static HRESULT create_server(REFCLSID rclsid)
1521 static const WCHAR wszLocalServer32[] = { 'L','o','c','a','l','S','e','r','v','e','r','3','2',0 };
1522 static const WCHAR embedding[] = { ' ', '-','E','m','b','e','d','d','i','n','g',0 };
1525 WCHAR command[MAX_PATH+sizeof(embedding)/sizeof(WCHAR)];
1526 DWORD size = (MAX_PATH+1) * sizeof(WCHAR);
1528 PROCESS_INFORMATION pinfo;
1530 hres = COM_OpenKeyForCLSID(rclsid, wszLocalServer32, KEY_READ, &key);
1532 ERR("class %s not registered\n", debugstr_guid(rclsid));
1536 hres = RegQueryValueExW(key, NULL, NULL, NULL, (LPBYTE)command, &size);
1539 WARN("No default value for LocalServer32 key\n");
1540 return REGDB_E_CLASSNOTREG; /* FIXME: check retval */
1543 memset(&sinfo,0,sizeof(sinfo));
1544 sinfo.cb = sizeof(sinfo);
1546 /* EXE servers are started with the -Embedding switch. */
1548 strcatW(command, embedding);
1550 TRACE("activating local server %s for %s\n", debugstr_w(command), debugstr_guid(rclsid));
1552 /* FIXME: Win2003 supports a ServerExecutable value that is passed into
1554 if (!CreateProcessW(NULL, command, NULL, NULL, FALSE, 0, NULL, NULL, &sinfo, &pinfo)) {
1555 WARN("failed to run local server %s\n", debugstr_w(command));
1556 return HRESULT_FROM_WIN32(GetLastError());
1558 CloseHandle(pinfo.hProcess);
1559 CloseHandle(pinfo.hThread);
1565 * start_local_service() - start a service given its name and parameters
1567 static DWORD start_local_service(LPCWSTR name, DWORD num, LPCWSTR *params)
1569 SC_HANDLE handle, hsvc;
1570 DWORD r = ERROR_FUNCTION_FAILED;
1572 TRACE("Starting service %s %d params\n", debugstr_w(name), num);
1574 handle = OpenSCManagerW(NULL, NULL, SC_MANAGER_CONNECT);
1577 hsvc = OpenServiceW(handle, name, SERVICE_START);
1580 if(StartServiceW(hsvc, num, params))
1584 if (r == ERROR_SERVICE_ALREADY_RUNNING)
1586 CloseServiceHandle(hsvc);
1590 CloseServiceHandle(handle);
1592 TRACE("StartService returned error %d (%s)\n", r, (r == ERROR_SUCCESS) ? "ok":"failed");
1598 * create_local_service() - start a COM server in a service
1600 * To start a Local Service, we read the AppID value under
1601 * the class's CLSID key, then open the HKCR\\AppId key specified
1602 * there and check for a LocalService value.
1604 * Note: Local Services are not supported under Windows 9x
1606 static HRESULT create_local_service(REFCLSID rclsid)
1609 WCHAR buf[CHARS_IN_GUID];
1610 static const WCHAR szLocalService[] = { 'L','o','c','a','l','S','e','r','v','i','c','e',0 };
1611 static const WCHAR szServiceParams[] = {'S','e','r','v','i','c','e','P','a','r','a','m','s',0};
1616 TRACE("Attempting to start Local service for %s\n", debugstr_guid(rclsid));
1618 hres = COM_OpenKeyForAppIdFromCLSID(rclsid, KEY_READ, &hkey);
1622 /* read the LocalService and ServiceParameters values from the AppID key */
1624 r = RegQueryValueExW(hkey, szLocalService, NULL, &type, (LPBYTE)buf, &sz);
1625 if (r==ERROR_SUCCESS && type==REG_SZ)
1628 LPWSTR args[1] = { NULL };
1631 * FIXME: I'm not really sure how to deal with the service parameters.
1632 * I suspect that the string returned from RegQueryValueExW
1633 * should be split into a number of arguments by spaces.
1634 * It would make more sense if ServiceParams contained a
1635 * REG_MULTI_SZ here, but it's a REG_SZ for the services
1636 * that I'm interested in for the moment.
1638 r = RegQueryValueExW(hkey, szServiceParams, NULL, &type, NULL, &sz);
1639 if (r == ERROR_SUCCESS && type == REG_SZ && sz)
1641 args[0] = HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY,sz);
1643 RegQueryValueExW(hkey, szServiceParams, NULL, &type, (LPBYTE)args[0], &sz);
1645 r = start_local_service(buf, num_args, (LPCWSTR *)args);
1646 if (r != ERROR_SUCCESS)
1647 hres = REGDB_E_CLASSNOTREG; /* FIXME: check retval */
1648 HeapFree(GetProcessHeap(),0,args[0]);
1652 WARN("No LocalService value\n");
1653 hres = REGDB_E_CLASSNOTREG; /* FIXME: check retval */
1661 static void get_localserver_pipe_name(WCHAR *pipefn, REFCLSID rclsid)
1663 static const WCHAR wszPipeRef[] = {'\\','\\','.','\\','p','i','p','e','\\',0};
1664 strcpyW(pipefn, wszPipeRef);
1665 StringFromGUID2(rclsid, pipefn + sizeof(wszPipeRef)/sizeof(wszPipeRef[0]) - 1, CHARS_IN_GUID);
1668 /* FIXME: should call to rpcss instead */
1669 HRESULT RPC_GetLocalClassObject(REFCLSID rclsid, REFIID iid, LPVOID *ppv)
1674 DWORD res, bufferlen;
1675 char marshalbuffer[200];
1677 LARGE_INTEGER seekto;
1678 ULARGE_INTEGER newpos;
1681 static const int MAXTRIES = 30; /* 30 seconds */
1683 TRACE("rclsid=%s, iid=%s\n", debugstr_guid(rclsid), debugstr_guid(iid));
1685 get_localserver_pipe_name(pipefn, rclsid);
1687 while (tries++ < MAXTRIES) {
1688 TRACE("waiting for %s\n", debugstr_w(pipefn));
1690 WaitNamedPipeW( pipefn, NMPWAIT_WAIT_FOREVER );
1691 hPipe = CreateFileW(pipefn, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, 0);
1692 if (hPipe == INVALID_HANDLE_VALUE) {
1694 if ( (hres = create_local_service(rclsid)) &&
1695 (hres = create_server(rclsid)) )
1699 WARN("Connecting to %s, no response yet, retrying: le is %x\n", debugstr_w(pipefn), GetLastError());
1705 if (!ReadFile(hPipe,marshalbuffer,sizeof(marshalbuffer),&bufferlen,NULL)) {
1706 FIXME("Failed to read marshal id from classfactory of %s.\n",debugstr_guid(rclsid));
1710 TRACE("read marshal id from pipe\n");
1715 if (tries >= MAXTRIES)
1716 return E_NOINTERFACE;
1718 hres = CreateStreamOnHGlobal(0,TRUE,&pStm);
1719 if (hres) return hres;
1720 hres = IStream_Write(pStm,marshalbuffer,bufferlen,&res);
1722 seekto.u.LowPart = 0;seekto.u.HighPart = 0;
1723 hres = IStream_Seek(pStm,seekto,SEEK_SET,&newpos);
1725 TRACE("unmarshalling classfactory\n");
1726 hres = CoUnmarshalInterface(pStm,&IID_IClassFactory,ppv);
1728 IStream_Release(pStm);
1733 struct local_server_params
1740 /* FIXME: should call to rpcss instead */
1741 static DWORD WINAPI local_server_thread(LPVOID param)
1743 struct local_server_params * lsp = (struct local_server_params *)param;
1747 IStream *pStm = lsp->stream;
1749 unsigned char *buffer;
1751 LARGE_INTEGER seekto;
1752 ULARGE_INTEGER newpos;
1755 TRACE("Starting threader for %s.\n",debugstr_guid(&lsp->clsid));
1757 get_localserver_pipe_name(pipefn, &lsp->clsid);
1759 hPipe = CreateNamedPipeW( pipefn, PIPE_ACCESS_DUPLEX,
1760 PIPE_TYPE_BYTE|PIPE_WAIT, PIPE_UNLIMITED_INSTANCES,
1761 4096, 4096, 500 /* 0.5 second timeout */, NULL );
1763 SetEvent(lsp->ready_event);
1765 HeapFree(GetProcessHeap(), 0, lsp);
1767 if (hPipe == INVALID_HANDLE_VALUE)
1769 FIXME("pipe creation failed for %s, le is %d\n", debugstr_w(pipefn), GetLastError());
1774 if (!ConnectNamedPipe(hPipe,NULL) && GetLastError() != ERROR_PIPE_CONNECTED) {
1775 ERR("Failure during ConnectNamedPipe %d, ABORT!\n",GetLastError());
1779 TRACE("marshalling IClassFactory to client\n");
1781 hres = IStream_Stat(pStm,&ststg,0);
1782 if (hres) return hres;
1784 seekto.u.LowPart = 0;
1785 seekto.u.HighPart = 0;
1786 hres = IStream_Seek(pStm,seekto,SEEK_SET,&newpos);
1788 FIXME("IStream_Seek failed, %x\n",hres);
1792 buflen = ststg.cbSize.u.LowPart;
1793 buffer = HeapAlloc(GetProcessHeap(),0,buflen);
1795 hres = IStream_Read(pStm,buffer,buflen,&res);
1797 FIXME("Stream Read failed, %x\n",hres);
1798 HeapFree(GetProcessHeap(),0,buffer);
1802 WriteFile(hPipe,buffer,buflen,&res,NULL);
1803 HeapFree(GetProcessHeap(),0,buffer);
1805 FlushFileBuffers(hPipe);
1806 DisconnectNamedPipe(hPipe);
1808 TRACE("done marshalling IClassFactory\n");
1811 IStream_Release(pStm);
1815 void RPC_StartLocalServer(REFCLSID clsid, IStream *stream)
1818 HANDLE thread, ready_event;
1819 struct local_server_params *lsp = HeapAlloc(GetProcessHeap(), 0, sizeof(*lsp));
1821 lsp->clsid = *clsid;
1822 lsp->stream = stream;
1823 IStream_AddRef(stream);
1824 lsp->ready_event = ready_event = CreateEventW(NULL, FALSE, FALSE, NULL);
1826 thread = CreateThread(NULL, 0, local_server_thread, lsp, 0, &tid);
1827 CloseHandle(thread);
1828 /* FIXME: failure handling */
1830 WaitForSingleObject(ready_event, INFINITE);
1831 CloseHandle(ready_event);