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 RPC_STATUS status; /* status (out) */
122 HRESULT hr; /* hresult (out) */
127 RPC_BINDING_HANDLE binding_handle;
128 ULONG prefix_data_len;
129 SChannelHookCallInfo channel_hook_info;
132 struct dispatch_params params;
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 = This->server_pid;
604 message_state->channel_hook_info.iMethod = msg->ProcNum;
605 message_state->channel_hook_info.pObject = NULL; /* only present on server-side */
606 memset(&message_state->params, 0, sizeof(message_state->params));
608 extensions_size = ChannelHooks_ClientGetSize(&message_state->channel_hook_info,
609 &channel_hook_data, &channel_hook_count, &extension_count);
611 msg->BufferLength += FIELD_OFFSET(ORPCTHIS, extensions) + 4;
614 msg->BufferLength += FIELD_OFFSET(ORPC_EXTENT_ARRAY, extent) + 2*sizeof(DWORD) + extensions_size;
615 if (extension_count & 1)
616 msg->BufferLength += FIELD_OFFSET(WIRE_ORPC_EXTENT, data[0]);
619 status = I_RpcGetBuffer(msg);
621 message_state->prefix_data_len = 0;
622 message_state->binding_handle = This->bind;
623 msg->Handle = message_state;
625 if (status == RPC_S_OK)
627 orpcthis = (ORPCTHIS *)msg->Buffer;
628 msg->Buffer = (char *)msg->Buffer + FIELD_OFFSET(ORPCTHIS, extensions);
630 orpcthis->version.MajorVersion = COM_MAJOR_VERSION;
631 orpcthis->version.MinorVersion = COM_MINOR_VERSION;
632 orpcthis->flags = message_state->channel_hook_info.dwServerPid ? ORPCF_LOCAL : ORPCF_NULL;
633 orpcthis->reserved1 = 0;
634 orpcthis->cid = message_state->channel_hook_info.uCausality;
636 /* NDR representation of orpcthis->extensions */
637 *(DWORD *)msg->Buffer = extensions_size ? 1 : 0;
638 msg->Buffer = (char *)msg->Buffer + sizeof(DWORD);
642 ORPC_EXTENT_ARRAY *orpc_extent_array = msg->Buffer;
643 orpc_extent_array->size = extension_count;
644 orpc_extent_array->reserved = 0;
645 msg->Buffer = (char *)msg->Buffer + FIELD_OFFSET(ORPC_EXTENT_ARRAY, extent);
646 /* NDR representation of orpc_extent_array->extent */
647 *(DWORD *)msg->Buffer = 1;
648 msg->Buffer = (char *)msg->Buffer + sizeof(DWORD);
649 /* NDR representation of [size_is] attribute of orpc_extent_array->extent */
650 *(DWORD *)msg->Buffer = (extension_count + 1) & ~1;
651 msg->Buffer = (char *)msg->Buffer + sizeof(DWORD);
653 msg->Buffer = ChannelHooks_ClientFillBuffer(&message_state->channel_hook_info,
654 msg->Buffer, channel_hook_data, channel_hook_count);
656 /* we must add a dummy extension if there is an odd extension
657 * count to meet the contract specified by the size_is attribute */
658 if (extension_count & 1)
660 WIRE_ORPC_EXTENT *wire_orpc_extent = msg->Buffer;
661 wire_orpc_extent->conformance = 0;
662 memcpy(&wire_orpc_extent->id, &GUID_NULL, sizeof(wire_orpc_extent->id));
663 wire_orpc_extent->size = 0;
664 msg->Buffer = (char *)msg->Buffer + FIELD_OFFSET(WIRE_ORPC_EXTENT, data[0]);
668 /* store the prefixed data length so that we can restore the real buffer
669 * pointer in ClientRpcChannelBuffer_SendReceive. */
670 message_state->prefix_data_len = (char *)msg->Buffer - (char *)orpcthis;
671 msg->BufferLength -= message_state->prefix_data_len;
674 TRACE("-- %ld\n", status);
676 return HRESULT_FROM_WIN32(status);
679 static HRESULT WINAPI ServerRpcChannelBuffer_SendReceive(LPRPCCHANNELBUFFER iface, RPCOLEMESSAGE *olemsg, ULONG *pstatus)
685 static HANDLE ClientRpcChannelBuffer_GetEventHandle(ClientRpcChannelBuffer *This)
687 HANDLE event = InterlockedExchangePointer(&This->event, NULL);
689 /* Note: must be auto-reset event so we can reuse it without a call
691 if (!event) event = CreateEventW(NULL, FALSE, FALSE, NULL);
696 static void ClientRpcChannelBuffer_ReleaseEventHandle(ClientRpcChannelBuffer *This, HANDLE event)
698 if (InterlockedCompareExchangePointer(&This->event, event, NULL))
699 /* already a handle cached in This */
703 /* this thread runs an outgoing RPC */
704 static DWORD WINAPI rpc_sendreceive_thread(LPVOID param)
706 struct dispatch_params *data = (struct dispatch_params *) param;
708 /* Note: I_RpcSendReceive doesn't raise exceptions like the higher-level
709 * RPC functions do */
710 data->status = I_RpcSendReceive((RPC_MESSAGE *)data->msg);
712 TRACE("completed with status 0x%lx\n", data->status);
714 SetEvent(data->handle);
719 static inline HRESULT ClientRpcChannelBuffer_IsCorrectApartment(ClientRpcChannelBuffer *This, APARTMENT *apt)
724 if (apartment_getoxid(apt, &oxid) != S_OK)
726 if (This->oxid != oxid)
731 static HRESULT WINAPI ClientRpcChannelBuffer_SendReceive(LPRPCCHANNELBUFFER iface, RPCOLEMESSAGE *olemsg, ULONG *pstatus)
733 ClientRpcChannelBuffer *This = (ClientRpcChannelBuffer *)iface;
735 RPC_MESSAGE *msg = (RPC_MESSAGE *)olemsg;
738 APARTMENT *apt = NULL;
740 struct message_state *message_state;
742 ORPC_EXTENT_ARRAY orpc_ext_array;
743 WIRE_ORPC_EXTENT *first_wire_orpc_extent = NULL;
744 HRESULT hrFault = S_OK;
746 TRACE("(%p) iMethod=%d\n", olemsg, olemsg->iMethod);
748 hr = ClientRpcChannelBuffer_IsCorrectApartment(This, COM_CurrentApt());
751 ERR("called from wrong apartment, should have been 0x%s\n",
752 wine_dbgstr_longlong(This->oxid));
753 return RPC_E_WRONG_THREAD;
755 /* this situation should be impossible in multi-threaded apartments,
756 * because the calling thread isn't re-entrable.
757 * Note: doing a COM call during the processing of a sent message is
758 * only disallowed if a client call is already being waited for
760 if (!COM_CurrentApt()->multi_threaded &&
761 COM_CurrentInfo()->pending_call_count_client &&
764 ERR("can't make an outgoing COM call in response to a sent message\n");
765 return RPC_E_CANTCALLOUT_ININPUTSYNCCALL;
768 message_state = (struct message_state *)msg->Handle;
769 /* restore the binding handle and the real start of data */
770 msg->Handle = message_state->binding_handle;
771 msg->Buffer = (char *)msg->Buffer - message_state->prefix_data_len;
772 msg->BufferLength += message_state->prefix_data_len;
774 message_state->params.msg = olemsg;
775 message_state->params.status = RPC_S_OK;
776 message_state->params.hr = S_OK;
778 /* Note: this is an optimization in the Microsoft OLE runtime that we need
779 * to copy, as shown by the test_no_couninitialize_client test. without
780 * short-circuiting the RPC runtime in the case below, the test will
781 * deadlock on the loader lock due to the RPC runtime needing to create
782 * a thread to process the RPC when this function is called indirectly
785 RpcBindingInqObject(message_state->binding_handle, &ipid);
786 hr = ipid_get_dispatch_params(&ipid, &apt, &message_state->params.stub,
787 &message_state->params.chan,
788 &message_state->params.iid,
789 &message_state->params.iface);
790 message_state->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,
796 (LPARAM)&message_state->params))
798 ERR("PostMessage failed with error %u\n", GetLastError());
800 IRpcStubBuffer_Release(message_state->params.stub);
801 message_state->params.stub = NULL;
802 IRpcChannelBuffer_Release(message_state->params.chan);
803 message_state->params.chan = NULL;
804 /* Note: message_state->params.iface doesn't have a reference and
805 * so doesn't need to be released */
807 hr = HRESULT_FROM_WIN32(GetLastError());
814 /* otherwise, we go via RPC runtime so the stub and channel aren't
816 IRpcStubBuffer_Release(message_state->params.stub);
817 message_state->params.stub = NULL;
818 IRpcChannelBuffer_Release(message_state->params.chan);
819 message_state->params.chan = NULL;
822 /* we use a separate thread here because we need to be able to
823 * pump the message loop in the application thread: if we do not,
824 * any windows created by this thread will hang and RPCs that try
825 * and re-enter this STA from an incoming server thread will
826 * deadlock. InstallShield is an example of that.
828 if (!QueueUserWorkItem(rpc_sendreceive_thread, &message_state->params, WT_EXECUTEDEFAULT))
830 ERR("QueueUserWorkItem failed with error %u\n", GetLastError());
836 if (apt) apartment_release(apt);
840 if (WaitForSingleObject(message_state->params.handle, 0))
842 COM_CurrentInfo()->pending_call_count_client++;
843 hr = CoWaitForMultipleHandles(0, INFINITE, 1, &message_state->params.handle, &index);
844 COM_CurrentInfo()->pending_call_count_client--;
847 ClientRpcChannelBuffer_ReleaseEventHandle(This, message_state->params.handle);
849 /* for WM shortcut, faults are returned in params->hr */
851 hrFault = message_state->params.hr;
853 status = message_state->params.status;
855 orpcthat.flags = ORPCF_NULL;
856 orpcthat.extensions = NULL;
858 /* for normal RPC calls, faults are returned in first 4 bytes of the
860 TRACE("RPC call status: 0x%lx\n", status);
861 if (status == RPC_S_CALL_FAILED)
862 hrFault = *(HRESULT *)olemsg->Buffer;
863 else if (status != RPC_S_OK)
864 hr = HRESULT_FROM_WIN32(status);
866 TRACE("hrFault = 0x%08x\n", hrFault);
868 /* FIXME: this condition should be
869 * "hr == S_OK && (!hrFault || msg->BufferLength > FIELD_OFFSET(ORPCTHAT, extensions) + 4)"
870 * but we don't currently reset the message length for PostMessage
871 * dispatched calls */
872 if (hr == S_OK && hrFault == S_OK)
875 char *original_buffer = msg->Buffer;
877 /* handle ORPCTHAT and client extensions */
879 hr2 = unmarshal_ORPCTHAT(msg, &orpcthat, &orpc_ext_array, &first_wire_orpc_extent);
883 message_state->prefix_data_len = (char *)msg->Buffer - original_buffer;
884 msg->BufferLength -= message_state->prefix_data_len;
887 message_state->prefix_data_len = 0;
891 ChannelHooks_ClientNotify(&message_state->channel_hook_info,
892 msg->DataRepresentation,
893 first_wire_orpc_extent,
894 orpcthat.extensions && first_wire_orpc_extent ? orpcthat.extensions->size : 0,
898 /* save away the message state again */
899 msg->Handle = message_state;
901 if (pstatus) *pstatus = status;
906 TRACE("-- 0x%08x\n", hr);
911 static HRESULT WINAPI ServerRpcChannelBuffer_FreeBuffer(LPRPCCHANNELBUFFER iface, RPCOLEMESSAGE* olemsg)
913 RPC_MESSAGE *msg = (RPC_MESSAGE *)olemsg;
915 struct message_state *message_state;
917 TRACE("(%p)\n", msg);
919 message_state = (struct message_state *)msg->Handle;
920 /* restore the binding handle and the real start of data */
921 msg->Handle = message_state->binding_handle;
922 msg->Buffer = (char *)msg->Buffer - message_state->prefix_data_len;
923 msg->BufferLength += message_state->prefix_data_len;
924 message_state->prefix_data_len = 0;
926 status = I_RpcFreeBuffer(msg);
928 msg->Handle = message_state;
930 TRACE("-- %ld\n", status);
932 return HRESULT_FROM_WIN32(status);
935 static HRESULT WINAPI ClientRpcChannelBuffer_FreeBuffer(LPRPCCHANNELBUFFER iface, RPCOLEMESSAGE* olemsg)
937 RPC_MESSAGE *msg = (RPC_MESSAGE *)olemsg;
939 struct message_state *message_state;
941 TRACE("(%p)\n", msg);
943 message_state = (struct message_state *)msg->Handle;
944 /* restore the binding handle and the real start of data */
945 msg->Handle = message_state->binding_handle;
946 msg->Buffer = (char *)msg->Buffer - message_state->prefix_data_len;
947 msg->BufferLength += message_state->prefix_data_len;
949 status = I_RpcFreeBuffer(msg);
951 HeapFree(GetProcessHeap(), 0, msg->RpcInterfaceInformation);
952 msg->RpcInterfaceInformation = NULL;
953 HeapFree(GetProcessHeap(), 0, message_state);
955 TRACE("-- %ld\n", status);
957 return HRESULT_FROM_WIN32(status);
960 static HRESULT WINAPI ClientRpcChannelBuffer_GetDestCtx(LPRPCCHANNELBUFFER iface, DWORD* pdwDestContext, void** ppvDestContext)
962 ClientRpcChannelBuffer *This = (ClientRpcChannelBuffer *)iface;
964 TRACE("(%p,%p)\n", pdwDestContext, ppvDestContext);
966 *pdwDestContext = This->dest_context;
967 *ppvDestContext = This->dest_context_data;
972 static HRESULT WINAPI ServerRpcChannelBuffer_GetDestCtx(LPRPCCHANNELBUFFER iface, DWORD* pdwDestContext, void** ppvDestContext)
974 FIXME("(%p,%p), stub!\n", pdwDestContext, ppvDestContext);
978 static HRESULT WINAPI RpcChannelBuffer_IsConnected(LPRPCCHANNELBUFFER iface)
981 /* native does nothing too */
985 static const IRpcChannelBufferVtbl ClientRpcChannelBufferVtbl =
987 RpcChannelBuffer_QueryInterface,
988 RpcChannelBuffer_AddRef,
989 ClientRpcChannelBuffer_Release,
990 ClientRpcChannelBuffer_GetBuffer,
991 ClientRpcChannelBuffer_SendReceive,
992 ClientRpcChannelBuffer_FreeBuffer,
993 ClientRpcChannelBuffer_GetDestCtx,
994 RpcChannelBuffer_IsConnected
997 static const IRpcChannelBufferVtbl ServerRpcChannelBufferVtbl =
999 RpcChannelBuffer_QueryInterface,
1000 RpcChannelBuffer_AddRef,
1001 ServerRpcChannelBuffer_Release,
1002 ServerRpcChannelBuffer_GetBuffer,
1003 ServerRpcChannelBuffer_SendReceive,
1004 ServerRpcChannelBuffer_FreeBuffer,
1005 ServerRpcChannelBuffer_GetDestCtx,
1006 RpcChannelBuffer_IsConnected
1009 /* returns a channel buffer for proxies */
1010 HRESULT RPC_CreateClientChannel(const OXID *oxid, const IPID *ipid,
1011 const OXID_INFO *oxid_info,
1012 DWORD dest_context, void *dest_context_data,
1013 IRpcChannelBuffer **chan)
1015 ClientRpcChannelBuffer *This;
1016 WCHAR endpoint[200];
1017 RPC_BINDING_HANDLE bind;
1019 LPWSTR string_binding;
1021 /* FIXME: get the endpoint from oxid_info->psa instead */
1022 get_rpc_endpoint(endpoint, oxid);
1024 TRACE("proxy pipe: connecting to endpoint: %s\n", debugstr_w(endpoint));
1026 status = RpcStringBindingComposeW(
1034 if (status == RPC_S_OK)
1036 status = RpcBindingFromStringBindingW(string_binding, &bind);
1038 if (status == RPC_S_OK)
1040 IPID ipid2 = *ipid; /* why can't RpcBindingSetObject take a const? */
1041 status = RpcBindingSetObject(bind, &ipid2);
1042 if (status != RPC_S_OK)
1043 RpcBindingFree(&bind);
1046 RpcStringFreeW(&string_binding);
1049 if (status != RPC_S_OK)
1051 ERR("Couldn't get binding for endpoint %s, status = %ld\n", debugstr_w(endpoint), status);
1052 return HRESULT_FROM_WIN32(status);
1055 This = HeapAlloc(GetProcessHeap(), 0, sizeof(*This));
1058 RpcBindingFree(&bind);
1059 return E_OUTOFMEMORY;
1062 This->super.lpVtbl = &ClientRpcChannelBufferVtbl;
1063 This->super.refs = 1;
1065 apartment_getoxid(COM_CurrentApt(), &This->oxid);
1066 This->server_pid = oxid_info->dwPid;
1067 This->dest_context = dest_context;
1068 This->dest_context_data = dest_context_data;
1071 *chan = (IRpcChannelBuffer*)This;
1076 HRESULT RPC_CreateServerChannel(IRpcChannelBuffer **chan)
1078 RpcChannelBuffer *This = HeapAlloc(GetProcessHeap(), 0, sizeof(*This));
1080 return E_OUTOFMEMORY;
1082 This->lpVtbl = &ServerRpcChannelBufferVtbl;
1085 *chan = (IRpcChannelBuffer*)This;
1090 /* unmarshals ORPC_EXTENT_ARRAY according to NDR rules, but doesn't allocate
1092 static HRESULT unmarshal_ORPC_EXTENT_ARRAY(RPC_MESSAGE *msg, const char *end,
1093 ORPC_EXTENT_ARRAY *extensions,
1094 WIRE_ORPC_EXTENT **first_wire_orpc_extent)
1099 memcpy(extensions, msg->Buffer, FIELD_OFFSET(ORPC_EXTENT_ARRAY, extent));
1100 msg->Buffer = (char *)msg->Buffer + FIELD_OFFSET(ORPC_EXTENT_ARRAY, extent);
1102 if ((const char *)msg->Buffer + 2 * sizeof(DWORD) > end)
1103 return RPC_E_INVALID_HEADER;
1105 pointer_id = *(DWORD *)msg->Buffer;
1106 msg->Buffer = (char *)msg->Buffer + sizeof(DWORD);
1107 extensions->extent = NULL;
1111 WIRE_ORPC_EXTENT *wire_orpc_extent;
1114 if (*(DWORD *)msg->Buffer != ((extensions->size+1)&~1))
1115 return RPC_S_INVALID_BOUND;
1117 msg->Buffer = (char *)msg->Buffer + sizeof(DWORD);
1119 /* arbritary limit for security (don't know what native does) */
1120 if (extensions->size > 256)
1122 ERR("too many extensions: %ld\n", extensions->size);
1123 return RPC_S_INVALID_BOUND;
1126 *first_wire_orpc_extent = wire_orpc_extent = (WIRE_ORPC_EXTENT *)msg->Buffer;
1127 for (i = 0; i < ((extensions->size+1)&~1); i++)
1129 if ((const char *)&wire_orpc_extent->data[0] > end)
1130 return RPC_S_INVALID_BOUND;
1131 if (wire_orpc_extent->conformance != ((wire_orpc_extent->size+7)&~7))
1132 return RPC_S_INVALID_BOUND;
1133 if ((const char *)&wire_orpc_extent->data[wire_orpc_extent->conformance] > end)
1134 return RPC_S_INVALID_BOUND;
1135 TRACE("size %u, guid %s\n", wire_orpc_extent->size, debugstr_guid(&wire_orpc_extent->id));
1136 wire_orpc_extent = (WIRE_ORPC_EXTENT *)&wire_orpc_extent->data[wire_orpc_extent->conformance];
1138 msg->Buffer = wire_orpc_extent;
1144 /* unmarshals ORPCTHIS according to NDR rules, but doesn't allocate any memory */
1145 static HRESULT unmarshal_ORPCTHIS(RPC_MESSAGE *msg, ORPCTHIS *orpcthis,
1146 ORPC_EXTENT_ARRAY *orpc_ext_array, WIRE_ORPC_EXTENT **first_wire_orpc_extent)
1148 const char *end = (char *)msg->Buffer + msg->BufferLength;
1150 *first_wire_orpc_extent = NULL;
1152 if (msg->BufferLength < FIELD_OFFSET(ORPCTHIS, extensions) + 4)
1154 ERR("invalid buffer length\n");
1155 return RPC_E_INVALID_HEADER;
1158 memcpy(orpcthis, msg->Buffer, FIELD_OFFSET(ORPCTHIS, extensions));
1159 msg->Buffer = (char *)msg->Buffer + FIELD_OFFSET(ORPCTHIS, extensions);
1161 if ((const char *)msg->Buffer + sizeof(DWORD) > end)
1162 return RPC_E_INVALID_HEADER;
1164 if (*(DWORD *)msg->Buffer)
1165 orpcthis->extensions = orpc_ext_array;
1167 orpcthis->extensions = NULL;
1169 msg->Buffer = (char *)msg->Buffer + sizeof(DWORD);
1171 if (orpcthis->extensions)
1173 HRESULT hr = unmarshal_ORPC_EXTENT_ARRAY(msg, end, orpc_ext_array,
1174 first_wire_orpc_extent);
1179 if ((orpcthis->version.MajorVersion != COM_MAJOR_VERSION) ||
1180 (orpcthis->version.MinorVersion > COM_MINOR_VERSION))
1182 ERR("COM version {%d, %d} not supported\n",
1183 orpcthis->version.MajorVersion, orpcthis->version.MinorVersion);
1184 return RPC_E_VERSION_MISMATCH;
1187 if (orpcthis->flags & ~(ORPCF_LOCAL|ORPCF_RESERVED1|ORPCF_RESERVED2|ORPCF_RESERVED3|ORPCF_RESERVED4))
1189 ERR("invalid flags 0x%lx\n", orpcthis->flags & ~(ORPCF_LOCAL|ORPCF_RESERVED1|ORPCF_RESERVED2|ORPCF_RESERVED3|ORPCF_RESERVED4));
1190 return RPC_E_INVALID_HEADER;
1196 static HRESULT unmarshal_ORPCTHAT(RPC_MESSAGE *msg, ORPCTHAT *orpcthat,
1197 ORPC_EXTENT_ARRAY *orpc_ext_array, WIRE_ORPC_EXTENT **first_wire_orpc_extent)
1199 const char *end = (char *)msg->Buffer + msg->BufferLength;
1201 *first_wire_orpc_extent = NULL;
1203 if (msg->BufferLength < FIELD_OFFSET(ORPCTHAT, extensions) + 4)
1205 ERR("invalid buffer length\n");
1206 return RPC_E_INVALID_HEADER;
1209 memcpy(orpcthat, msg->Buffer, FIELD_OFFSET(ORPCTHAT, extensions));
1210 msg->Buffer = (char *)msg->Buffer + FIELD_OFFSET(ORPCTHAT, extensions);
1212 if ((const char *)msg->Buffer + sizeof(DWORD) > end)
1213 return RPC_E_INVALID_HEADER;
1215 if (*(DWORD *)msg->Buffer)
1216 orpcthat->extensions = orpc_ext_array;
1218 orpcthat->extensions = NULL;
1220 msg->Buffer = (char *)msg->Buffer + sizeof(DWORD);
1222 if (orpcthat->extensions)
1224 HRESULT hr = unmarshal_ORPC_EXTENT_ARRAY(msg, end, orpc_ext_array,
1225 first_wire_orpc_extent);
1230 if (orpcthat->flags & ~(ORPCF_LOCAL|ORPCF_RESERVED1|ORPCF_RESERVED2|ORPCF_RESERVED3|ORPCF_RESERVED4))
1232 ERR("invalid flags 0x%lx\n", orpcthat->flags & ~(ORPCF_LOCAL|ORPCF_RESERVED1|ORPCF_RESERVED2|ORPCF_RESERVED3|ORPCF_RESERVED4));
1233 return RPC_E_INVALID_HEADER;
1239 void RPC_ExecuteCall(struct dispatch_params *params)
1241 struct message_state *message_state = NULL;
1242 RPC_MESSAGE *msg = (RPC_MESSAGE *)params->msg;
1243 char *original_buffer = msg->Buffer;
1245 ORPC_EXTENT_ARRAY orpc_ext_array;
1246 WIRE_ORPC_EXTENT *first_wire_orpc_extent;
1247 GUID old_causality_id;
1249 /* handle ORPCTHIS and server extensions */
1251 params->hr = unmarshal_ORPCTHIS(msg, &orpcthis, &orpc_ext_array, &first_wire_orpc_extent);
1252 if (params->hr != S_OK)
1254 msg->Buffer = original_buffer;
1258 message_state = HeapAlloc(GetProcessHeap(), 0, sizeof(*message_state));
1261 params->hr = E_OUTOFMEMORY;
1262 msg->Buffer = original_buffer;
1266 message_state->prefix_data_len = (char *)msg->Buffer - original_buffer;
1267 message_state->binding_handle = msg->Handle;
1269 message_state->channel_hook_info.iid = params->iid;
1270 message_state->channel_hook_info.cbSize = sizeof(message_state->channel_hook_info);
1271 message_state->channel_hook_info.uCausality = orpcthis.cid;
1272 message_state->channel_hook_info.dwServerPid = GetCurrentProcessId();
1273 message_state->channel_hook_info.iMethod = msg->ProcNum;
1274 message_state->channel_hook_info.pObject = params->iface;
1276 if (orpcthis.extensions && first_wire_orpc_extent &&
1277 orpcthis.extensions->size)
1278 ChannelHooks_ServerNotify(&message_state->channel_hook_info, msg->DataRepresentation, first_wire_orpc_extent, orpcthis.extensions->size);
1280 msg->Handle = message_state;
1281 msg->BufferLength -= message_state->prefix_data_len;
1283 /* call message filter */
1285 if (COM_CurrentApt()->filter)
1288 INTERFACEINFO interface_info;
1291 interface_info.pUnk = params->iface;
1292 interface_info.iid = params->iid;
1293 interface_info.wMethod = msg->ProcNum;
1295 if (IsEqualGUID(&orpcthis.cid, &COM_CurrentInfo()->causality_id))
1296 calltype = CALLTYPE_NESTED;
1297 else if (COM_CurrentInfo()->pending_call_count_server == 0)
1298 calltype = CALLTYPE_TOPLEVEL;
1300 calltype = CALLTYPE_TOPLEVEL_CALLPENDING;
1302 handlecall = IMessageFilter_HandleInComingCall(COM_CurrentApt()->filter,
1304 (HTASK)GetCurrentProcessId(),
1307 TRACE("IMessageFilter_HandleInComingCall returned %d\n", handlecall);
1310 case SERVERCALL_REJECTED:
1311 params->hr = RPC_E_CALL_REJECTED;
1312 goto exit_reset_state;
1313 case SERVERCALL_RETRYLATER:
1314 #if 0 /* FIXME: handle retries on the client side before enabling this code */
1315 params->hr = RPC_E_RETRY;
1316 goto exit_reset_state;
1318 FIXME("retry call later not implemented\n");
1321 case SERVERCALL_ISHANDLED:
1327 /* invoke the method */
1329 /* save the old causality ID - note: any calls executed while processing
1330 * messages received during the SendReceive will appear to originate from
1331 * this call - this should be checked with what Windows does */
1332 old_causality_id = COM_CurrentInfo()->causality_id;
1333 COM_CurrentInfo()->causality_id = orpcthis.cid;
1334 COM_CurrentInfo()->pending_call_count_server++;
1335 params->hr = IRpcStubBuffer_Invoke(params->stub, params->msg, params->chan);
1336 COM_CurrentInfo()->pending_call_count_server--;
1337 COM_CurrentInfo()->causality_id = old_causality_id;
1340 message_state = (struct message_state *)msg->Handle;
1341 msg->Handle = message_state->binding_handle;
1342 msg->Buffer = (char *)msg->Buffer - message_state->prefix_data_len;
1343 msg->BufferLength += message_state->prefix_data_len;
1346 HeapFree(GetProcessHeap(), 0, message_state);
1347 IRpcStubBuffer_Release(params->stub);
1348 IRpcChannelBuffer_Release(params->chan);
1349 if (params->handle) SetEvent(params->handle);
1352 static void __RPC_STUB dispatch_rpc(RPC_MESSAGE *msg)
1354 struct dispatch_params *params;
1359 RpcBindingInqObject(msg->Handle, &ipid);
1361 TRACE("ipid = %s, iMethod = %d\n", debugstr_guid(&ipid), msg->ProcNum);
1363 params = HeapAlloc(GetProcessHeap(), 0, sizeof(*params));
1366 RpcRaiseException(E_OUTOFMEMORY);
1370 hr = ipid_get_dispatch_params(&ipid, &apt, ¶ms->stub, ¶ms->chan,
1371 ¶ms->iid, ¶ms->iface);
1374 ERR("no apartment found for ipid %s\n", debugstr_guid(&ipid));
1375 HeapFree(GetProcessHeap(), 0, params);
1376 RpcRaiseException(hr);
1380 params->msg = (RPCOLEMESSAGE *)msg;
1381 params->status = RPC_S_OK;
1383 params->handle = NULL;
1385 /* Note: this is the important difference between STAs and MTAs - we
1386 * always execute RPCs to STAs in the thread that originally created the
1387 * apartment (i.e. the one that pumps messages to the window) */
1388 if (!apt->multi_threaded)
1390 params->handle = CreateEventW(NULL, FALSE, FALSE, NULL);
1392 TRACE("Calling apartment thread 0x%08x...\n", apt->tid);
1394 if (PostMessageW(apartment_getwindow(apt), DM_EXECUTERPC, 0, (LPARAM)params))
1395 WaitForSingleObject(params->handle, INFINITE);
1398 ERR("PostMessage failed with error %u\n", GetLastError());
1399 IRpcChannelBuffer_Release(params->chan);
1400 IRpcStubBuffer_Release(params->stub);
1402 CloseHandle(params->handle);
1406 BOOL joined = FALSE;
1407 if (!COM_CurrentInfo()->apt)
1409 apartment_joinmta();
1412 RPC_ExecuteCall(params);
1415 apartment_release(COM_CurrentInfo()->apt);
1416 COM_CurrentInfo()->apt = NULL;
1421 HeapFree(GetProcessHeap(), 0, params);
1423 apartment_release(apt);
1425 /* if IRpcStubBuffer_Invoke fails, we should raise an exception to tell
1426 * the RPC runtime that the call failed */
1427 if (hr) RpcRaiseException(hr);
1430 /* stub registration */
1431 HRESULT RPC_RegisterInterface(REFIID riid)
1433 struct registered_if *rif;
1437 TRACE("(%s)\n", debugstr_guid(riid));
1439 EnterCriticalSection(&csRegIf);
1440 LIST_FOR_EACH_ENTRY(rif, ®istered_interfaces, struct registered_if, entry)
1442 if (IsEqualGUID(&rif->If.InterfaceId.SyntaxGUID, riid))
1451 TRACE("Creating new interface\n");
1453 rif = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*rif));
1459 rif->If.Length = sizeof(RPC_SERVER_INTERFACE);
1460 /* RPC interface ID = COM interface ID */
1461 rif->If.InterfaceId.SyntaxGUID = *riid;
1462 rif->If.DispatchTable = &rpc_dispatch;
1463 /* all other fields are 0, including the version asCOM objects
1464 * always have a version of 0.0 */
1465 status = RpcServerRegisterIfEx(
1466 (RPC_IF_HANDLE)&rif->If,
1468 RPC_IF_OLE | RPC_IF_AUTOLISTEN,
1469 RPC_C_LISTEN_MAX_CALLS_DEFAULT,
1471 if (status == RPC_S_OK)
1472 list_add_tail(®istered_interfaces, &rif->entry);
1475 ERR("RpcServerRegisterIfEx failed with error %ld\n", status);
1476 HeapFree(GetProcessHeap(), 0, rif);
1477 hr = HRESULT_FROM_WIN32(status);
1483 LeaveCriticalSection(&csRegIf);
1487 /* stub unregistration */
1488 void RPC_UnregisterInterface(REFIID riid)
1490 struct registered_if *rif;
1491 EnterCriticalSection(&csRegIf);
1492 LIST_FOR_EACH_ENTRY(rif, ®istered_interfaces, struct registered_if, entry)
1494 if (IsEqualGUID(&rif->If.InterfaceId.SyntaxGUID, riid))
1498 RpcServerUnregisterIf((RPC_IF_HANDLE)&rif->If, NULL, TRUE);
1499 list_remove(&rif->entry);
1500 HeapFree(GetProcessHeap(), 0, rif);
1505 LeaveCriticalSection(&csRegIf);
1508 /* get the info for an OXID, including the IPID for the rem unknown interface
1509 * and the string binding */
1510 HRESULT RPC_ResolveOxid(OXID oxid, OXID_INFO *oxid_info)
1512 TRACE("%s\n", wine_dbgstr_longlong(oxid));
1514 oxid_info->dwTid = 0;
1515 oxid_info->dwPid = 0;
1516 oxid_info->dwAuthnHint = RPC_C_AUTHN_LEVEL_NONE;
1517 /* FIXME: this is a hack around not having an OXID resolver yet -
1518 * this function should contact the machine's OXID resolver and then it
1519 * should give us the IPID of the IRemUnknown interface */
1520 oxid_info->ipidRemUnknown.Data1 = 0xffffffff;
1521 oxid_info->ipidRemUnknown.Data2 = 0xffff;
1522 oxid_info->ipidRemUnknown.Data3 = 0xffff;
1523 memcpy(&oxid_info->ipidRemUnknown.Data4, &oxid, sizeof(OXID));
1524 oxid_info->psa = NULL /* FIXME */;
1529 /* make the apartment reachable by other threads and processes and create the
1530 * IRemUnknown object */
1531 void RPC_StartRemoting(struct apartment *apt)
1533 if (!InterlockedExchange(&apt->remoting_started, TRUE))
1535 WCHAR endpoint[200];
1538 get_rpc_endpoint(endpoint, &apt->oxid);
1540 status = RpcServerUseProtseqEpW(
1542 RPC_C_PROTSEQ_MAX_REQS_DEFAULT,
1545 if (status != RPC_S_OK)
1546 ERR("Couldn't register endpoint %s\n", debugstr_w(endpoint));
1548 /* FIXME: move remote unknown exporting into this function */
1550 start_apartment_remote_unknown();
1554 static HRESULT create_server(REFCLSID rclsid)
1556 static const WCHAR wszLocalServer32[] = { 'L','o','c','a','l','S','e','r','v','e','r','3','2',0 };
1557 static const WCHAR embedding[] = { ' ', '-','E','m','b','e','d','d','i','n','g',0 };
1560 WCHAR command[MAX_PATH+sizeof(embedding)/sizeof(WCHAR)];
1561 DWORD size = (MAX_PATH+1) * sizeof(WCHAR);
1563 PROCESS_INFORMATION pinfo;
1565 hres = COM_OpenKeyForCLSID(rclsid, wszLocalServer32, KEY_READ, &key);
1567 ERR("class %s not registered\n", debugstr_guid(rclsid));
1571 hres = RegQueryValueExW(key, NULL, NULL, NULL, (LPBYTE)command, &size);
1574 WARN("No default value for LocalServer32 key\n");
1575 return REGDB_E_CLASSNOTREG; /* FIXME: check retval */
1578 memset(&sinfo,0,sizeof(sinfo));
1579 sinfo.cb = sizeof(sinfo);
1581 /* EXE servers are started with the -Embedding switch. */
1583 strcatW(command, embedding);
1585 TRACE("activating local server %s for %s\n", debugstr_w(command), debugstr_guid(rclsid));
1587 /* FIXME: Win2003 supports a ServerExecutable value that is passed into
1589 if (!CreateProcessW(NULL, command, NULL, NULL, FALSE, 0, NULL, NULL, &sinfo, &pinfo)) {
1590 WARN("failed to run local server %s\n", debugstr_w(command));
1591 return HRESULT_FROM_WIN32(GetLastError());
1593 CloseHandle(pinfo.hProcess);
1594 CloseHandle(pinfo.hThread);
1600 * start_local_service() - start a service given its name and parameters
1602 static DWORD start_local_service(LPCWSTR name, DWORD num, LPCWSTR *params)
1604 SC_HANDLE handle, hsvc;
1605 DWORD r = ERROR_FUNCTION_FAILED;
1607 TRACE("Starting service %s %d params\n", debugstr_w(name), num);
1609 handle = OpenSCManagerW(NULL, NULL, SC_MANAGER_CONNECT);
1612 hsvc = OpenServiceW(handle, name, SERVICE_START);
1615 if(StartServiceW(hsvc, num, params))
1619 if (r == ERROR_SERVICE_ALREADY_RUNNING)
1621 CloseServiceHandle(hsvc);
1625 CloseServiceHandle(handle);
1627 TRACE("StartService returned error %u (%s)\n", r, (r == ERROR_SUCCESS) ? "ok":"failed");
1633 * create_local_service() - start a COM server in a service
1635 * To start a Local Service, we read the AppID value under
1636 * the class's CLSID key, then open the HKCR\\AppId key specified
1637 * there and check for a LocalService value.
1639 * Note: Local Services are not supported under Windows 9x
1641 static HRESULT create_local_service(REFCLSID rclsid)
1644 WCHAR buf[CHARS_IN_GUID];
1645 static const WCHAR szLocalService[] = { 'L','o','c','a','l','S','e','r','v','i','c','e',0 };
1646 static const WCHAR szServiceParams[] = {'S','e','r','v','i','c','e','P','a','r','a','m','s',0};
1651 TRACE("Attempting to start Local service for %s\n", debugstr_guid(rclsid));
1653 hres = COM_OpenKeyForAppIdFromCLSID(rclsid, KEY_READ, &hkey);
1657 /* read the LocalService and ServiceParameters values from the AppID key */
1659 r = RegQueryValueExW(hkey, szLocalService, NULL, &type, (LPBYTE)buf, &sz);
1660 if (r==ERROR_SUCCESS && type==REG_SZ)
1663 LPWSTR args[1] = { NULL };
1666 * FIXME: I'm not really sure how to deal with the service parameters.
1667 * I suspect that the string returned from RegQueryValueExW
1668 * should be split into a number of arguments by spaces.
1669 * It would make more sense if ServiceParams contained a
1670 * REG_MULTI_SZ here, but it's a REG_SZ for the services
1671 * that I'm interested in for the moment.
1673 r = RegQueryValueExW(hkey, szServiceParams, NULL, &type, NULL, &sz);
1674 if (r == ERROR_SUCCESS && type == REG_SZ && sz)
1676 args[0] = HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY,sz);
1678 RegQueryValueExW(hkey, szServiceParams, NULL, &type, (LPBYTE)args[0], &sz);
1680 r = start_local_service(buf, num_args, (LPCWSTR *)args);
1681 if (r != ERROR_SUCCESS)
1682 hres = REGDB_E_CLASSNOTREG; /* FIXME: check retval */
1683 HeapFree(GetProcessHeap(),0,args[0]);
1687 WARN("No LocalService value\n");
1688 hres = REGDB_E_CLASSNOTREG; /* FIXME: check retval */
1696 static void get_localserver_pipe_name(WCHAR *pipefn, REFCLSID rclsid)
1698 static const WCHAR wszPipeRef[] = {'\\','\\','.','\\','p','i','p','e','\\',0};
1699 strcpyW(pipefn, wszPipeRef);
1700 StringFromGUID2(rclsid, pipefn + sizeof(wszPipeRef)/sizeof(wszPipeRef[0]) - 1, CHARS_IN_GUID);
1703 /* FIXME: should call to rpcss instead */
1704 HRESULT RPC_GetLocalClassObject(REFCLSID rclsid, REFIID iid, LPVOID *ppv)
1709 DWORD res, bufferlen;
1710 char marshalbuffer[200];
1712 LARGE_INTEGER seekto;
1713 ULARGE_INTEGER newpos;
1716 static const int MAXTRIES = 30; /* 30 seconds */
1718 TRACE("rclsid=%s, iid=%s\n", debugstr_guid(rclsid), debugstr_guid(iid));
1720 get_localserver_pipe_name(pipefn, rclsid);
1722 while (tries++ < MAXTRIES) {
1723 TRACE("waiting for %s\n", debugstr_w(pipefn));
1725 WaitNamedPipeW( pipefn, NMPWAIT_WAIT_FOREVER );
1726 hPipe = CreateFileW(pipefn, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, 0);
1727 if (hPipe == INVALID_HANDLE_VALUE) {
1729 if ( (hres = create_local_service(rclsid)) &&
1730 (hres = create_server(rclsid)) )
1734 WARN("Connecting to %s, no response yet, retrying: le is %u\n", debugstr_w(pipefn), GetLastError());
1740 if (!ReadFile(hPipe,marshalbuffer,sizeof(marshalbuffer),&bufferlen,NULL)) {
1741 FIXME("Failed to read marshal id from classfactory of %s.\n",debugstr_guid(rclsid));
1745 TRACE("read marshal id from pipe\n");
1750 if (tries >= MAXTRIES)
1751 return E_NOINTERFACE;
1753 hres = CreateStreamOnHGlobal(0,TRUE,&pStm);
1754 if (hres) return hres;
1755 hres = IStream_Write(pStm,marshalbuffer,bufferlen,&res);
1757 seekto.u.LowPart = 0;seekto.u.HighPart = 0;
1758 hres = IStream_Seek(pStm,seekto,SEEK_SET,&newpos);
1760 TRACE("unmarshalling classfactory\n");
1761 hres = CoUnmarshalInterface(pStm,&IID_IClassFactory,ppv);
1763 IStream_Release(pStm);
1768 struct local_server_params
1778 /* FIXME: should call to rpcss instead */
1779 static DWORD WINAPI local_server_thread(LPVOID param)
1781 struct local_server_params * lsp = (struct local_server_params *)param;
1785 IStream *pStm = lsp->stream;
1787 unsigned char *buffer;
1789 LARGE_INTEGER seekto;
1790 ULARGE_INTEGER newpos;
1792 BOOL multi_use = lsp->multi_use;
1796 TRACE("Starting threader for %s.\n",debugstr_guid(&lsp->clsid));
1798 memset(&ovl, 0, sizeof(ovl));
1799 get_localserver_pipe_name(pipefn, &lsp->clsid);
1801 hPipe = CreateNamedPipeW( pipefn, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
1802 PIPE_TYPE_BYTE|PIPE_WAIT, PIPE_UNLIMITED_INSTANCES,
1803 4096, 4096, 500 /* 0.5 second timeout */, NULL );
1805 SetEvent(lsp->ready_event);
1807 if (hPipe == INVALID_HANDLE_VALUE)
1809 FIXME("pipe creation failed for %s, le is %u\n", debugstr_w(pipefn), GetLastError());
1813 ovl.hEvent = pipe_event = CreateEventW(NULL, FALSE, FALSE, NULL);
1816 if (!ConnectNamedPipe(hPipe, &ovl))
1818 DWORD error = GetLastError();
1819 if (error == ERROR_IO_PENDING)
1821 HANDLE handles[2] = { pipe_event, lsp->stop_event };
1823 ret = WaitForMultipleObjects(2, handles, FALSE, INFINITE);
1824 if (ret != WAIT_OBJECT_0)
1827 /* client already connected isn't an error */
1828 else if (error != ERROR_PIPE_CONNECTED)
1830 ERR("ConnectNamedPipe failed with error %d\n", GetLastError());
1835 TRACE("marshalling IClassFactory to client\n");
1837 hres = IStream_Stat(pStm,&ststg,0);
1838 if (hres) return hres;
1840 seekto.u.LowPart = 0;
1841 seekto.u.HighPart = 0;
1842 hres = IStream_Seek(pStm,seekto,SEEK_SET,&newpos);
1844 FIXME("IStream_Seek failed, %x\n",hres);
1846 CloseHandle(pipe_event);
1850 buflen = ststg.cbSize.u.LowPart;
1851 buffer = HeapAlloc(GetProcessHeap(),0,buflen);
1853 hres = IStream_Read(pStm,buffer,buflen,&res);
1855 FIXME("Stream Read failed, %x\n",hres);
1857 CloseHandle(pipe_event);
1858 HeapFree(GetProcessHeap(),0,buffer);
1862 WriteFile(hPipe,buffer,buflen,&res,&ovl);
1863 GetOverlappedResult(hPipe, &ovl, NULL, TRUE);
1864 HeapFree(GetProcessHeap(),0,buffer);
1866 FlushFileBuffers(hPipe);
1867 DisconnectNamedPipe(hPipe);
1869 TRACE("done marshalling IClassFactory\n");
1873 TRACE("single use object, shutting down pipe %s\n", debugstr_w(pipefn));
1878 CloseHandle(pipe_event);
1882 /* starts listening for a local server */
1883 HRESULT RPC_StartLocalServer(REFCLSID clsid, IStream *stream, BOOL multi_use, void **registration)
1886 struct local_server_params *lsp;
1888 lsp = HeapAlloc(GetProcessHeap(), 0, sizeof(*lsp));
1890 return E_OUTOFMEMORY;
1892 lsp->clsid = *clsid;
1893 lsp->stream = stream;
1894 IStream_AddRef(stream);
1895 lsp->ready_event = CreateEventW(NULL, FALSE, FALSE, NULL);
1896 if (!lsp->ready_event)
1898 HeapFree(GetProcessHeap(), 0, lsp);
1899 return HRESULT_FROM_WIN32(GetLastError());
1901 lsp->stop_event = CreateEventW(NULL, FALSE, FALSE, NULL);
1902 if (!lsp->stop_event)
1904 CloseHandle(lsp->ready_event);
1905 HeapFree(GetProcessHeap(), 0, lsp);
1906 return HRESULT_FROM_WIN32(GetLastError());
1908 lsp->multi_use = multi_use;
1910 lsp->thread = CreateThread(NULL, 0, local_server_thread, lsp, 0, &tid);
1913 CloseHandle(lsp->ready_event);
1914 CloseHandle(lsp->stop_event);
1915 HeapFree(GetProcessHeap(), 0, lsp);
1916 return HRESULT_FROM_WIN32(GetLastError());
1919 WaitForSingleObject(lsp->ready_event, INFINITE);
1920 CloseHandle(lsp->ready_event);
1921 lsp->ready_event = NULL;
1923 *registration = lsp;
1927 /* stops listening for a local server */
1928 void RPC_StopLocalServer(void *registration)
1930 struct local_server_params *lsp = registration;
1932 /* signal local_server_thread to stop */
1933 SetEvent(lsp->stop_event);
1934 /* wait for it to exit */
1935 WaitForSingleObject(lsp->thread, INFINITE);
1937 IStream_Release(lsp->stream);
1938 CloseHandle(lsp->stop_event);
1939 CloseHandle(lsp->thread);
1940 HeapFree(GetProcessHeap(), 0, lsp);