kernel32/tests: Add a test to check some fields in fake dlls.
[wine.git] / dlls / ole32 / rpc.c
blobbd4611d7d5f8a579ad52d1ec8563a9656f3f4090
1 /*
2 * RPC Manager
4 * Copyright 2001 Ove Kåven, TransGaming Technologies
5 * Copyright 2002 Marcus Meissner
6 * Copyright 2005 Mike Hearn, Rob Shearman for CodeWeavers
8 * This library is free software; you can redistribute it and/or
9 * modify it under the terms of the GNU Lesser General Public
10 * License as published by the Free Software Foundation; either
11 * version 2.1 of the License, or (at your option) any later version.
13 * This library is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 * Lesser General Public License for more details.
18 * You should have received a copy of the GNU Lesser General Public
19 * License along with this library; if not, write to the Free Software
20 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
23 #include "config.h"
24 #include "wine/port.h"
26 #include <stdarg.h>
27 #include <string.h>
29 #define COBJMACROS
30 #define NONAMELESSUNION
32 #include "windef.h"
33 #include "winbase.h"
34 #include "winuser.h"
35 #include "winsvc.h"
36 #include "objbase.h"
37 #include "ole2.h"
38 #include "rpc.h"
39 #include "winerror.h"
40 #include "winreg.h"
41 #include "servprov.h"
42 #include "wine/unicode.h"
44 #include "compobj_private.h"
46 #include "wine/debug.h"
48 WINE_DEFAULT_DEBUG_CHANNEL(ole);
50 static void __RPC_STUB dispatch_rpc(RPC_MESSAGE *msg);
52 /* we only use one function to dispatch calls for all methods - we use the
53 * RPC_IF_OLE flag to tell the RPC runtime that this is the case */
54 static RPC_DISPATCH_FUNCTION rpc_dispatch_table[1] = { dispatch_rpc }; /* (RO) */
55 static RPC_DISPATCH_TABLE rpc_dispatch = { 1, rpc_dispatch_table }; /* (RO) */
57 static struct list registered_interfaces = LIST_INIT(registered_interfaces); /* (CS csRegIf) */
58 static CRITICAL_SECTION csRegIf;
59 static CRITICAL_SECTION_DEBUG csRegIf_debug =
61 0, 0, &csRegIf,
62 { &csRegIf_debug.ProcessLocksList, &csRegIf_debug.ProcessLocksList },
63 0, 0, { (DWORD_PTR)(__FILE__ ": dcom registered server interfaces") }
65 static CRITICAL_SECTION csRegIf = { &csRegIf_debug, -1, 0, 0, 0, 0 };
67 static struct list channel_hooks = LIST_INIT(channel_hooks); /* (CS csChannelHook) */
68 static CRITICAL_SECTION csChannelHook;
69 static CRITICAL_SECTION_DEBUG csChannelHook_debug =
71 0, 0, &csChannelHook,
72 { &csChannelHook_debug.ProcessLocksList, &csChannelHook_debug.ProcessLocksList },
73 0, 0, { (DWORD_PTR)(__FILE__ ": channel hooks") }
75 static CRITICAL_SECTION csChannelHook = { &csChannelHook_debug, -1, 0, 0, 0, 0 };
77 static WCHAR wszRpcTransport[] = {'n','c','a','l','r','p','c',0};
80 struct registered_if
82 struct list entry;
83 DWORD refs; /* ref count */
84 RPC_SERVER_INTERFACE If; /* interface registered with the RPC runtime */
87 /* get the pipe endpoint specified of the specified apartment */
88 static inline void get_rpc_endpoint(LPWSTR endpoint, const OXID *oxid)
90 /* FIXME: should get endpoint from rpcss */
91 static const WCHAR wszEndpointFormat[] = {'\\','p','i','p','e','\\','O','L','E','_','%','0','8','l','x','%','0','8','l','x',0};
92 wsprintfW(endpoint, wszEndpointFormat, (DWORD)(*oxid >> 32),(DWORD)*oxid);
95 typedef struct
97 IRpcChannelBuffer IRpcChannelBuffer_iface;
98 LONG refs;
100 DWORD dest_context; /* returned from GetDestCtx */
101 void *dest_context_data; /* returned from GetDestCtx */
102 } RpcChannelBuffer;
104 typedef struct
106 RpcChannelBuffer super; /* superclass */
108 RPC_BINDING_HANDLE bind; /* handle to the remote server */
109 OXID oxid; /* apartment in which the channel is valid */
110 DWORD server_pid; /* id of server process */
111 HANDLE event; /* cached event handle */
112 IID iid; /* IID of the proxy this belongs to */
113 } ClientRpcChannelBuffer;
115 struct dispatch_params
117 RPCOLEMESSAGE *msg; /* message */
118 IRpcStubBuffer *stub; /* stub buffer, if applicable */
119 IRpcChannelBuffer *chan; /* server channel buffer, if applicable */
120 IID iid; /* ID of interface being called */
121 IUnknown *iface; /* interface being called */
122 HANDLE handle; /* handle that will become signaled when call finishes */
123 BOOL bypass_rpcrt; /* bypass RPC runtime? */
124 RPC_STATUS status; /* status (out) */
125 HRESULT hr; /* hresult (out) */
128 struct message_state
130 RPC_BINDING_HANDLE binding_handle;
131 ULONG prefix_data_len;
132 SChannelHookCallInfo channel_hook_info;
133 BOOL bypass_rpcrt;
135 /* client only */
136 HWND target_hwnd;
137 DWORD target_tid;
138 struct dispatch_params params;
141 typedef struct
143 ULONG conformance; /* NDR */
144 GUID id;
145 ULONG size;
146 /* [size_is((size+7)&~7)] */ unsigned char data[1];
147 } WIRE_ORPC_EXTENT;
149 typedef struct
151 ULONG size;
152 ULONG reserved;
153 unsigned char extent[1];
154 } WIRE_ORPC_EXTENT_ARRAY;
156 typedef struct
158 ULONG version;
159 ULONG flags;
160 ULONG reserved1;
161 GUID cid;
162 unsigned char extensions[1];
163 } WIRE_ORPCTHIS;
165 typedef struct
167 ULONG flags;
168 unsigned char extensions[1];
169 } WIRE_ORPCTHAT;
171 struct channel_hook_entry
173 struct list entry;
174 GUID id;
175 IChannelHook *hook;
178 struct channel_hook_buffer_data
180 GUID id;
181 ULONG extension_size;
185 static HRESULT unmarshal_ORPCTHAT(RPC_MESSAGE *msg, ORPCTHAT *orpcthat,
186 ORPC_EXTENT_ARRAY *orpc_ext_array, WIRE_ORPC_EXTENT **first_wire_orpc_extent);
188 /* Channel Hook Functions */
190 static ULONG ChannelHooks_ClientGetSize(SChannelHookCallInfo *info,
191 struct channel_hook_buffer_data **data, unsigned int *hook_count,
192 ULONG *extension_count)
194 struct channel_hook_entry *entry;
195 ULONG total_size = 0;
196 unsigned int hook_index = 0;
198 *hook_count = 0;
199 *extension_count = 0;
201 EnterCriticalSection(&csChannelHook);
203 LIST_FOR_EACH_ENTRY(entry, &channel_hooks, struct channel_hook_entry, entry)
204 (*hook_count)++;
206 if (*hook_count)
207 *data = HeapAlloc(GetProcessHeap(), 0, *hook_count * sizeof(struct channel_hook_buffer_data));
208 else
209 *data = NULL;
211 LIST_FOR_EACH_ENTRY(entry, &channel_hooks, struct channel_hook_entry, entry)
213 ULONG extension_size = 0;
215 IChannelHook_ClientGetSize(entry->hook, &entry->id, &info->iid, &extension_size);
217 TRACE("%s: extension_size = %u\n", debugstr_guid(&entry->id), extension_size);
219 extension_size = (extension_size+7)&~7;
220 (*data)[hook_index].id = entry->id;
221 (*data)[hook_index].extension_size = extension_size;
223 /* an extension is only put onto the wire if it has data to write */
224 if (extension_size)
226 total_size += FIELD_OFFSET(WIRE_ORPC_EXTENT, data[extension_size]);
227 (*extension_count)++;
230 hook_index++;
233 LeaveCriticalSection(&csChannelHook);
235 return total_size;
238 static unsigned char * ChannelHooks_ClientFillBuffer(SChannelHookCallInfo *info,
239 unsigned char *buffer, struct channel_hook_buffer_data *data,
240 unsigned int hook_count)
242 struct channel_hook_entry *entry;
244 EnterCriticalSection(&csChannelHook);
246 LIST_FOR_EACH_ENTRY(entry, &channel_hooks, struct channel_hook_entry, entry)
248 unsigned int i;
249 ULONG extension_size = 0;
250 WIRE_ORPC_EXTENT *wire_orpc_extent = (WIRE_ORPC_EXTENT *)buffer;
252 for (i = 0; i < hook_count; i++)
253 if (IsEqualGUID(&entry->id, &data[i].id))
254 extension_size = data[i].extension_size;
256 /* an extension is only put onto the wire if it has data to write */
257 if (!extension_size)
258 continue;
260 IChannelHook_ClientFillBuffer(entry->hook, &entry->id, &info->iid,
261 &extension_size, buffer + FIELD_OFFSET(WIRE_ORPC_EXTENT, data[0]));
263 TRACE("%s: extension_size = %u\n", debugstr_guid(&entry->id), extension_size);
265 /* FIXME: set unused portion of wire_orpc_extent->data to 0? */
267 wire_orpc_extent->conformance = (extension_size+7)&~7;
268 wire_orpc_extent->size = extension_size;
269 wire_orpc_extent->id = entry->id;
270 buffer += FIELD_OFFSET(WIRE_ORPC_EXTENT, data[wire_orpc_extent->conformance]);
273 LeaveCriticalSection(&csChannelHook);
275 return buffer;
278 static void ChannelHooks_ServerNotify(SChannelHookCallInfo *info,
279 DWORD lDataRep, WIRE_ORPC_EXTENT *first_wire_orpc_extent,
280 ULONG extension_count)
282 struct channel_hook_entry *entry;
283 ULONG i;
285 EnterCriticalSection(&csChannelHook);
287 LIST_FOR_EACH_ENTRY(entry, &channel_hooks, struct channel_hook_entry, entry)
289 WIRE_ORPC_EXTENT *wire_orpc_extent;
290 for (i = 0, wire_orpc_extent = first_wire_orpc_extent;
291 i < extension_count;
292 i++, wire_orpc_extent = (WIRE_ORPC_EXTENT *)&wire_orpc_extent->data[wire_orpc_extent->conformance])
294 if (IsEqualGUID(&entry->id, &wire_orpc_extent->id))
295 break;
297 if (i == extension_count) wire_orpc_extent = NULL;
299 IChannelHook_ServerNotify(entry->hook, &entry->id, &info->iid,
300 wire_orpc_extent ? wire_orpc_extent->size : 0,
301 wire_orpc_extent ? wire_orpc_extent->data : NULL,
302 lDataRep);
305 LeaveCriticalSection(&csChannelHook);
308 static ULONG ChannelHooks_ServerGetSize(SChannelHookCallInfo *info,
309 struct channel_hook_buffer_data **data, unsigned int *hook_count,
310 ULONG *extension_count)
312 struct channel_hook_entry *entry;
313 ULONG total_size = 0;
314 unsigned int hook_index = 0;
316 *hook_count = 0;
317 *extension_count = 0;
319 EnterCriticalSection(&csChannelHook);
321 LIST_FOR_EACH_ENTRY(entry, &channel_hooks, struct channel_hook_entry, entry)
322 (*hook_count)++;
324 if (*hook_count)
325 *data = HeapAlloc(GetProcessHeap(), 0, *hook_count * sizeof(struct channel_hook_buffer_data));
326 else
327 *data = NULL;
329 LIST_FOR_EACH_ENTRY(entry, &channel_hooks, struct channel_hook_entry, entry)
331 ULONG extension_size = 0;
333 IChannelHook_ServerGetSize(entry->hook, &entry->id, &info->iid, S_OK,
334 &extension_size);
336 TRACE("%s: extension_size = %u\n", debugstr_guid(&entry->id), extension_size);
338 extension_size = (extension_size+7)&~7;
339 (*data)[hook_index].id = entry->id;
340 (*data)[hook_index].extension_size = extension_size;
342 /* an extension is only put onto the wire if it has data to write */
343 if (extension_size)
345 total_size += FIELD_OFFSET(WIRE_ORPC_EXTENT, data[extension_size]);
346 (*extension_count)++;
349 hook_index++;
352 LeaveCriticalSection(&csChannelHook);
354 return total_size;
357 static unsigned char * ChannelHooks_ServerFillBuffer(SChannelHookCallInfo *info,
358 unsigned char *buffer, struct channel_hook_buffer_data *data,
359 unsigned int hook_count)
361 struct channel_hook_entry *entry;
363 EnterCriticalSection(&csChannelHook);
365 LIST_FOR_EACH_ENTRY(entry, &channel_hooks, struct channel_hook_entry, entry)
367 unsigned int i;
368 ULONG extension_size = 0;
369 WIRE_ORPC_EXTENT *wire_orpc_extent = (WIRE_ORPC_EXTENT *)buffer;
371 for (i = 0; i < hook_count; i++)
372 if (IsEqualGUID(&entry->id, &data[i].id))
373 extension_size = data[i].extension_size;
375 /* an extension is only put onto the wire if it has data to write */
376 if (!extension_size)
377 continue;
379 IChannelHook_ServerFillBuffer(entry->hook, &entry->id, &info->iid,
380 &extension_size, buffer + FIELD_OFFSET(WIRE_ORPC_EXTENT, data[0]),
381 S_OK);
383 TRACE("%s: extension_size = %u\n", debugstr_guid(&entry->id), extension_size);
385 /* FIXME: set unused portion of wire_orpc_extent->data to 0? */
387 wire_orpc_extent->conformance = (extension_size+7)&~7;
388 wire_orpc_extent->size = extension_size;
389 wire_orpc_extent->id = entry->id;
390 buffer += FIELD_OFFSET(WIRE_ORPC_EXTENT, data[wire_orpc_extent->conformance]);
393 LeaveCriticalSection(&csChannelHook);
395 return buffer;
398 static void ChannelHooks_ClientNotify(SChannelHookCallInfo *info,
399 DWORD lDataRep, WIRE_ORPC_EXTENT *first_wire_orpc_extent,
400 ULONG extension_count, HRESULT hrFault)
402 struct channel_hook_entry *entry;
403 ULONG i;
405 EnterCriticalSection(&csChannelHook);
407 LIST_FOR_EACH_ENTRY(entry, &channel_hooks, struct channel_hook_entry, entry)
409 WIRE_ORPC_EXTENT *wire_orpc_extent;
410 for (i = 0, wire_orpc_extent = first_wire_orpc_extent;
411 i < extension_count;
412 i++, wire_orpc_extent = (WIRE_ORPC_EXTENT *)&wire_orpc_extent->data[wire_orpc_extent->conformance])
414 if (IsEqualGUID(&entry->id, &wire_orpc_extent->id))
415 break;
417 if (i == extension_count) wire_orpc_extent = NULL;
419 IChannelHook_ClientNotify(entry->hook, &entry->id, &info->iid,
420 wire_orpc_extent ? wire_orpc_extent->size : 0,
421 wire_orpc_extent ? wire_orpc_extent->data : NULL,
422 lDataRep, hrFault);
425 LeaveCriticalSection(&csChannelHook);
428 HRESULT RPC_RegisterChannelHook(REFGUID rguid, IChannelHook *hook)
430 struct channel_hook_entry *entry;
432 TRACE("(%s, %p)\n", debugstr_guid(rguid), hook);
434 entry = HeapAlloc(GetProcessHeap(), 0, sizeof(*entry));
435 if (!entry)
436 return E_OUTOFMEMORY;
438 entry->id = *rguid;
439 entry->hook = hook;
440 IChannelHook_AddRef(hook);
442 EnterCriticalSection(&csChannelHook);
443 list_add_tail(&channel_hooks, &entry->entry);
444 LeaveCriticalSection(&csChannelHook);
446 return S_OK;
449 void RPC_UnregisterAllChannelHooks(void)
451 struct channel_hook_entry *cursor;
452 struct channel_hook_entry *cursor2;
454 EnterCriticalSection(&csChannelHook);
455 LIST_FOR_EACH_ENTRY_SAFE(cursor, cursor2, &channel_hooks, struct channel_hook_entry, entry)
456 HeapFree(GetProcessHeap(), 0, cursor);
457 LeaveCriticalSection(&csChannelHook);
458 DeleteCriticalSection(&csChannelHook);
459 DeleteCriticalSection(&csRegIf);
462 /* RPC Channel Buffer Functions */
464 static HRESULT WINAPI RpcChannelBuffer_QueryInterface(IRpcChannelBuffer *iface, REFIID riid, LPVOID *ppv)
466 *ppv = NULL;
467 if (IsEqualIID(riid,&IID_IRpcChannelBuffer) || IsEqualIID(riid,&IID_IUnknown))
469 *ppv = iface;
470 IRpcChannelBuffer_AddRef(iface);
471 return S_OK;
473 return E_NOINTERFACE;
476 static ULONG WINAPI RpcChannelBuffer_AddRef(LPRPCCHANNELBUFFER iface)
478 RpcChannelBuffer *This = (RpcChannelBuffer *)iface;
479 return InterlockedIncrement(&This->refs);
482 static ULONG WINAPI ServerRpcChannelBuffer_Release(LPRPCCHANNELBUFFER iface)
484 RpcChannelBuffer *This = (RpcChannelBuffer *)iface;
485 ULONG ref;
487 ref = InterlockedDecrement(&This->refs);
488 if (ref)
489 return ref;
491 HeapFree(GetProcessHeap(), 0, This);
492 return 0;
495 static ULONG WINAPI ClientRpcChannelBuffer_Release(LPRPCCHANNELBUFFER iface)
497 ClientRpcChannelBuffer *This = (ClientRpcChannelBuffer *)iface;
498 ULONG ref;
500 ref = InterlockedDecrement(&This->super.refs);
501 if (ref)
502 return ref;
504 if (This->event) CloseHandle(This->event);
505 RpcBindingFree(&This->bind);
506 HeapFree(GetProcessHeap(), 0, This);
507 return 0;
510 static HRESULT WINAPI ServerRpcChannelBuffer_GetBuffer(LPRPCCHANNELBUFFER iface, RPCOLEMESSAGE* olemsg, REFIID riid)
512 RpcChannelBuffer *This = (RpcChannelBuffer *)iface;
513 RPC_MESSAGE *msg = (RPC_MESSAGE *)olemsg;
514 RPC_STATUS status;
515 ORPCTHAT *orpcthat;
516 struct message_state *message_state;
517 ULONG extensions_size;
518 struct channel_hook_buffer_data *channel_hook_data;
519 unsigned int channel_hook_count;
520 ULONG extension_count;
522 TRACE("(%p)->(%p,%s)\n", This, olemsg, debugstr_guid(riid));
524 message_state = msg->Handle;
525 /* restore the binding handle and the real start of data */
526 msg->Handle = message_state->binding_handle;
527 msg->Buffer = (char *)msg->Buffer - message_state->prefix_data_len;
529 extensions_size = ChannelHooks_ServerGetSize(&message_state->channel_hook_info,
530 &channel_hook_data, &channel_hook_count, &extension_count);
532 msg->BufferLength += FIELD_OFFSET(WIRE_ORPCTHAT, extensions) + sizeof(DWORD);
533 if (extensions_size)
535 msg->BufferLength += FIELD_OFFSET(WIRE_ORPC_EXTENT_ARRAY, extent[2*sizeof(DWORD) + extensions_size]);
536 if (extension_count & 1)
537 msg->BufferLength += FIELD_OFFSET(WIRE_ORPC_EXTENT, data[0]);
540 if (message_state->bypass_rpcrt)
542 msg->Buffer = HeapAlloc(GetProcessHeap(), 0, msg->BufferLength);
543 if (msg->Buffer)
544 status = RPC_S_OK;
545 else
547 HeapFree(GetProcessHeap(), 0, channel_hook_data);
548 return E_OUTOFMEMORY;
551 else
552 status = I_RpcGetBuffer(msg);
554 orpcthat = msg->Buffer;
555 msg->Buffer = (char *)msg->Buffer + FIELD_OFFSET(WIRE_ORPCTHAT, extensions);
557 orpcthat->flags = ORPCF_NULL /* FIXME? */;
559 /* NDR representation of orpcthat->extensions */
560 *(DWORD *)msg->Buffer = extensions_size ? 1 : 0;
561 msg->Buffer = (char *)msg->Buffer + sizeof(DWORD);
563 if (extensions_size)
565 WIRE_ORPC_EXTENT_ARRAY *orpc_extent_array = msg->Buffer;
566 orpc_extent_array->size = extension_count;
567 orpc_extent_array->reserved = 0;
568 msg->Buffer = (char *)msg->Buffer + FIELD_OFFSET(WIRE_ORPC_EXTENT_ARRAY, extent);
569 /* NDR representation of orpc_extent_array->extent */
570 *(DWORD *)msg->Buffer = 1;
571 msg->Buffer = (char *)msg->Buffer + sizeof(DWORD);
572 /* NDR representation of [size_is] attribute of orpc_extent_array->extent */
573 *(DWORD *)msg->Buffer = (extension_count + 1) & ~1;
574 msg->Buffer = (char *)msg->Buffer + sizeof(DWORD);
576 msg->Buffer = ChannelHooks_ServerFillBuffer(&message_state->channel_hook_info,
577 msg->Buffer, channel_hook_data, channel_hook_count);
579 /* we must add a dummy extension if there is an odd extension
580 * count to meet the contract specified by the size_is attribute */
581 if (extension_count & 1)
583 WIRE_ORPC_EXTENT *wire_orpc_extent = msg->Buffer;
584 wire_orpc_extent->conformance = 0;
585 wire_orpc_extent->id = GUID_NULL;
586 wire_orpc_extent->size = 0;
587 msg->Buffer = (char *)msg->Buffer + FIELD_OFFSET(WIRE_ORPC_EXTENT, data[0]);
591 HeapFree(GetProcessHeap(), 0, channel_hook_data);
593 /* store the prefixed data length so that we can restore the real buffer
594 * later */
595 message_state->prefix_data_len = (char *)msg->Buffer - (char *)orpcthat;
596 msg->BufferLength -= message_state->prefix_data_len;
597 /* save away the message state again */
598 msg->Handle = message_state;
600 TRACE("-- %d\n", status);
602 return HRESULT_FROM_WIN32(status);
605 static HANDLE ClientRpcChannelBuffer_GetEventHandle(ClientRpcChannelBuffer *This)
607 HANDLE event = InterlockedExchangePointer(&This->event, NULL);
609 /* Note: must be auto-reset event so we can reuse it without a call
610 * to ResetEvent */
611 if (!event) event = CreateEventW(NULL, FALSE, FALSE, NULL);
613 return event;
616 static void ClientRpcChannelBuffer_ReleaseEventHandle(ClientRpcChannelBuffer *This, HANDLE event)
618 if (InterlockedCompareExchangePointer(&This->event, event, NULL))
619 /* already a handle cached in This */
620 CloseHandle(event);
623 static HRESULT WINAPI ClientRpcChannelBuffer_GetBuffer(LPRPCCHANNELBUFFER iface, RPCOLEMESSAGE* olemsg, REFIID riid)
625 ClientRpcChannelBuffer *This = (ClientRpcChannelBuffer *)iface;
626 RPC_MESSAGE *msg = (RPC_MESSAGE *)olemsg;
627 RPC_CLIENT_INTERFACE *cif;
628 RPC_STATUS status;
629 ORPCTHIS *orpcthis;
630 struct message_state *message_state;
631 ULONG extensions_size;
632 struct channel_hook_buffer_data *channel_hook_data;
633 unsigned int channel_hook_count;
634 ULONG extension_count;
635 IPID ipid;
636 HRESULT hr;
637 APARTMENT *apt = NULL;
639 TRACE("(%p)->(%p,%s)\n", This, olemsg, debugstr_guid(riid));
641 cif = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(RPC_CLIENT_INTERFACE));
642 if (!cif)
643 return E_OUTOFMEMORY;
645 message_state = HeapAlloc(GetProcessHeap(), 0, sizeof(*message_state));
646 if (!message_state)
648 HeapFree(GetProcessHeap(), 0, cif);
649 return E_OUTOFMEMORY;
652 cif->Length = sizeof(RPC_CLIENT_INTERFACE);
653 /* RPC interface ID = COM interface ID */
654 cif->InterfaceId.SyntaxGUID = This->iid;
655 /* COM objects always have a version of 0.0 */
656 cif->InterfaceId.SyntaxVersion.MajorVersion = 0;
657 cif->InterfaceId.SyntaxVersion.MinorVersion = 0;
658 msg->Handle = This->bind;
659 msg->RpcInterfaceInformation = cif;
661 message_state->prefix_data_len = 0;
662 message_state->binding_handle = This->bind;
664 message_state->channel_hook_info.iid = *riid;
665 message_state->channel_hook_info.cbSize = sizeof(message_state->channel_hook_info);
666 message_state->channel_hook_info.uCausality = COM_CurrentCausalityId();
667 message_state->channel_hook_info.dwServerPid = This->server_pid;
668 message_state->channel_hook_info.iMethod = msg->ProcNum & ~RPC_FLAGS_VALID_BIT;
669 message_state->channel_hook_info.pObject = NULL; /* only present on server-side */
670 message_state->target_hwnd = NULL;
671 message_state->target_tid = 0;
672 memset(&message_state->params, 0, sizeof(message_state->params));
674 extensions_size = ChannelHooks_ClientGetSize(&message_state->channel_hook_info,
675 &channel_hook_data, &channel_hook_count, &extension_count);
677 msg->BufferLength += FIELD_OFFSET(WIRE_ORPCTHIS, extensions) + sizeof(DWORD);
678 if (extensions_size)
680 msg->BufferLength += FIELD_OFFSET(WIRE_ORPC_EXTENT_ARRAY, extent[2*sizeof(DWORD) + extensions_size]);
681 if (extension_count & 1)
682 msg->BufferLength += FIELD_OFFSET(WIRE_ORPC_EXTENT, data[0]);
685 RpcBindingInqObject(message_state->binding_handle, &ipid);
686 hr = ipid_get_dispatch_params(&ipid, &apt, NULL, &message_state->params.stub,
687 &message_state->params.chan,
688 &message_state->params.iid,
689 &message_state->params.iface);
690 if (hr == S_OK)
692 /* stub, chan, iface and iid are unneeded in multi-threaded case as we go
693 * via the RPC runtime */
694 if (apt->multi_threaded)
696 IRpcStubBuffer_Release(message_state->params.stub);
697 message_state->params.stub = NULL;
698 IRpcChannelBuffer_Release(message_state->params.chan);
699 message_state->params.chan = NULL;
700 message_state->params.iface = NULL;
702 else
704 message_state->params.bypass_rpcrt = TRUE;
705 message_state->target_hwnd = apartment_getwindow(apt);
706 message_state->target_tid = apt->tid;
707 /* we assume later on that this being non-NULL is the indicator that
708 * means call directly instead of going through RPC runtime */
709 if (!message_state->target_hwnd)
710 ERR("window for apartment %s is NULL\n", wine_dbgstr_longlong(apt->oxid));
713 if (apt) apartment_release(apt);
714 message_state->params.handle = ClientRpcChannelBuffer_GetEventHandle(This);
715 /* Note: message_state->params.msg is initialised in
716 * ClientRpcChannelBuffer_SendReceive */
718 /* shortcut the RPC runtime */
719 if (message_state->target_hwnd)
721 msg->Buffer = HeapAlloc(GetProcessHeap(), 0, msg->BufferLength);
722 if (msg->Buffer)
723 status = RPC_S_OK;
724 else
725 status = ERROR_OUTOFMEMORY;
727 else
728 status = I_RpcGetBuffer(msg);
730 msg->Handle = message_state;
732 if (status == RPC_S_OK)
734 orpcthis = msg->Buffer;
735 msg->Buffer = (char *)msg->Buffer + FIELD_OFFSET(WIRE_ORPCTHIS, extensions);
737 orpcthis->version.MajorVersion = COM_MAJOR_VERSION;
738 orpcthis->version.MinorVersion = COM_MINOR_VERSION;
739 orpcthis->flags = message_state->channel_hook_info.dwServerPid ? ORPCF_LOCAL : ORPCF_NULL;
740 orpcthis->reserved1 = 0;
741 orpcthis->cid = message_state->channel_hook_info.uCausality;
743 /* NDR representation of orpcthis->extensions */
744 *(DWORD *)msg->Buffer = extensions_size ? 1 : 0;
745 msg->Buffer = (char *)msg->Buffer + sizeof(DWORD);
747 if (extensions_size)
749 ORPC_EXTENT_ARRAY *orpc_extent_array = msg->Buffer;
750 orpc_extent_array->size = extension_count;
751 orpc_extent_array->reserved = 0;
752 msg->Buffer = (char *)msg->Buffer + FIELD_OFFSET(WIRE_ORPC_EXTENT_ARRAY, extent);
753 /* NDR representation of orpc_extent_array->extent */
754 *(DWORD *)msg->Buffer = 1;
755 msg->Buffer = (char *)msg->Buffer + sizeof(DWORD);
756 /* NDR representation of [size_is] attribute of orpc_extent_array->extent */
757 *(DWORD *)msg->Buffer = (extension_count + 1) & ~1;
758 msg->Buffer = (char *)msg->Buffer + sizeof(DWORD);
760 msg->Buffer = ChannelHooks_ClientFillBuffer(&message_state->channel_hook_info,
761 msg->Buffer, channel_hook_data, channel_hook_count);
763 /* we must add a dummy extension if there is an odd extension
764 * count to meet the contract specified by the size_is attribute */
765 if (extension_count & 1)
767 WIRE_ORPC_EXTENT *wire_orpc_extent = msg->Buffer;
768 wire_orpc_extent->conformance = 0;
769 wire_orpc_extent->id = GUID_NULL;
770 wire_orpc_extent->size = 0;
771 msg->Buffer = (char *)msg->Buffer + FIELD_OFFSET(WIRE_ORPC_EXTENT, data[0]);
775 /* store the prefixed data length so that we can restore the real buffer
776 * pointer in ClientRpcChannelBuffer_SendReceive. */
777 message_state->prefix_data_len = (char *)msg->Buffer - (char *)orpcthis;
778 msg->BufferLength -= message_state->prefix_data_len;
781 HeapFree(GetProcessHeap(), 0, channel_hook_data);
783 TRACE("-- %d\n", status);
785 return HRESULT_FROM_WIN32(status);
788 static HRESULT WINAPI ServerRpcChannelBuffer_SendReceive(LPRPCCHANNELBUFFER iface, RPCOLEMESSAGE *olemsg, ULONG *pstatus)
790 FIXME("stub\n");
791 return E_NOTIMPL;
794 /* this thread runs an outgoing RPC */
795 static DWORD WINAPI rpc_sendreceive_thread(LPVOID param)
797 struct dispatch_params *data = param;
799 /* Note: I_RpcSendReceive doesn't raise exceptions like the higher-level
800 * RPC functions do */
801 data->status = I_RpcSendReceive((RPC_MESSAGE *)data->msg);
803 TRACE("completed with status 0x%x\n", data->status);
805 SetEvent(data->handle);
807 return 0;
810 static inline HRESULT ClientRpcChannelBuffer_IsCorrectApartment(ClientRpcChannelBuffer *This, APARTMENT *apt)
812 OXID oxid;
813 if (!apt)
814 return S_FALSE;
815 if (apartment_getoxid(apt, &oxid) != S_OK)
816 return S_FALSE;
817 if (This->oxid != oxid)
818 return S_FALSE;
819 return S_OK;
822 static HRESULT WINAPI ClientRpcChannelBuffer_SendReceive(LPRPCCHANNELBUFFER iface, RPCOLEMESSAGE *olemsg, ULONG *pstatus)
824 ClientRpcChannelBuffer *This = (ClientRpcChannelBuffer *)iface;
825 HRESULT hr;
826 RPC_MESSAGE *msg = (RPC_MESSAGE *)olemsg;
827 RPC_STATUS status;
828 DWORD index;
829 struct message_state *message_state;
830 ORPCTHAT orpcthat;
831 ORPC_EXTENT_ARRAY orpc_ext_array;
832 WIRE_ORPC_EXTENT *first_wire_orpc_extent = NULL;
833 HRESULT hrFault = S_OK;
834 APARTMENT *apt = apartment_get_current_or_mta();
836 TRACE("(%p) iMethod=%d\n", olemsg, olemsg->iMethod);
838 hr = ClientRpcChannelBuffer_IsCorrectApartment(This, apt);
839 if (hr != S_OK)
841 ERR("called from wrong apartment, should have been 0x%s\n",
842 wine_dbgstr_longlong(This->oxid));
843 if (apt) apartment_release(apt);
844 return RPC_E_WRONG_THREAD;
846 /* This situation should be impossible in multi-threaded apartments,
847 * because the calling thread isn't re-enterable.
848 * Note: doing a COM call during the processing of a sent message is
849 * only disallowed if a client call is already being waited for
850 * completion */
851 if (!apt->multi_threaded &&
852 COM_CurrentInfo()->pending_call_count_client &&
853 InSendMessage())
855 ERR("can't make an outgoing COM call in response to a sent message\n");
856 apartment_release(apt);
857 return RPC_E_CANTCALLOUT_ININPUTSYNCCALL;
860 message_state = msg->Handle;
861 /* restore the binding handle and the real start of data */
862 msg->Handle = message_state->binding_handle;
863 msg->Buffer = (char *)msg->Buffer - message_state->prefix_data_len;
864 msg->BufferLength += message_state->prefix_data_len;
866 /* Note: this is an optimization in the Microsoft OLE runtime that we need
867 * to copy, as shown by the test_no_couninitialize_client test. without
868 * short-circuiting the RPC runtime in the case below, the test will
869 * deadlock on the loader lock due to the RPC runtime needing to create
870 * a thread to process the RPC when this function is called indirectly
871 * from DllMain */
873 message_state->params.msg = olemsg;
874 if (message_state->params.bypass_rpcrt)
876 TRACE("Calling apartment thread 0x%08x...\n", message_state->target_tid);
878 msg->ProcNum &= ~RPC_FLAGS_VALID_BIT;
880 if (!PostMessageW(message_state->target_hwnd, DM_EXECUTERPC, 0,
881 (LPARAM)&message_state->params))
883 ERR("PostMessage failed with error %u\n", GetLastError());
885 /* Note: message_state->params.iface doesn't have a reference and
886 * so doesn't need to be released */
888 hr = HRESULT_FROM_WIN32(GetLastError());
891 else
893 /* we use a separate thread here because we need to be able to
894 * pump the message loop in the application thread: if we do not,
895 * any windows created by this thread will hang and RPCs that try
896 * and re-enter this STA from an incoming server thread will
897 * deadlock. InstallShield is an example of that.
899 if (!QueueUserWorkItem(rpc_sendreceive_thread, &message_state->params, WT_EXECUTEDEFAULT))
901 ERR("QueueUserWorkItem failed with error %u\n", GetLastError());
902 hr = E_UNEXPECTED;
904 else
905 hr = S_OK;
908 if (hr == S_OK)
910 if (WaitForSingleObject(message_state->params.handle, 0))
912 COM_CurrentInfo()->pending_call_count_client++;
913 hr = CoWaitForMultipleHandles(0, INFINITE, 1, &message_state->params.handle, &index);
914 COM_CurrentInfo()->pending_call_count_client--;
917 ClientRpcChannelBuffer_ReleaseEventHandle(This, message_state->params.handle);
919 /* for WM shortcut, faults are returned in params->hr */
920 if (hr == S_OK)
921 hrFault = message_state->params.hr;
923 status = message_state->params.status;
925 orpcthat.flags = ORPCF_NULL;
926 orpcthat.extensions = NULL;
928 TRACE("RPC call status: 0x%x\n", status);
929 if (status != RPC_S_OK)
930 hr = HRESULT_FROM_WIN32(status);
932 TRACE("hrFault = 0x%08x\n", hrFault);
934 /* FIXME: this condition should be
935 * "hr == S_OK && (!hrFault || msg->BufferLength > FIELD_OFFSET(ORPCTHAT, extensions) + 4)"
936 * but we don't currently reset the message length for PostMessage
937 * dispatched calls */
938 if (hr == S_OK && hrFault == S_OK)
940 HRESULT hr2;
941 char *original_buffer = msg->Buffer;
943 /* handle ORPCTHAT and client extensions */
945 hr2 = unmarshal_ORPCTHAT(msg, &orpcthat, &orpc_ext_array, &first_wire_orpc_extent);
946 if (FAILED(hr2))
947 hr = hr2;
949 message_state->prefix_data_len = (char *)msg->Buffer - original_buffer;
950 msg->BufferLength -= message_state->prefix_data_len;
952 else
953 message_state->prefix_data_len = 0;
955 if (hr == S_OK)
957 ChannelHooks_ClientNotify(&message_state->channel_hook_info,
958 msg->DataRepresentation,
959 first_wire_orpc_extent,
960 orpcthat.extensions && first_wire_orpc_extent ? orpcthat.extensions->size : 0,
961 hrFault);
964 /* save away the message state again */
965 msg->Handle = message_state;
967 if (pstatus) *pstatus = status;
969 if (hr == S_OK)
970 hr = hrFault;
972 TRACE("-- 0x%08x\n", hr);
974 apartment_release(apt);
975 return hr;
978 static HRESULT WINAPI ServerRpcChannelBuffer_FreeBuffer(LPRPCCHANNELBUFFER iface, RPCOLEMESSAGE* olemsg)
980 RPC_MESSAGE *msg = (RPC_MESSAGE *)olemsg;
981 RPC_STATUS status;
982 struct message_state *message_state;
984 TRACE("(%p)\n", msg);
986 message_state = msg->Handle;
987 /* restore the binding handle and the real start of data */
988 msg->Handle = message_state->binding_handle;
989 msg->Buffer = (char *)msg->Buffer - message_state->prefix_data_len;
990 msg->BufferLength += message_state->prefix_data_len;
991 message_state->prefix_data_len = 0;
993 if (message_state->bypass_rpcrt)
995 HeapFree(GetProcessHeap(), 0, msg->Buffer);
996 status = RPC_S_OK;
998 else
999 status = I_RpcFreeBuffer(msg);
1001 msg->Handle = message_state;
1003 TRACE("-- %d\n", status);
1005 return HRESULT_FROM_WIN32(status);
1008 static HRESULT WINAPI ClientRpcChannelBuffer_FreeBuffer(LPRPCCHANNELBUFFER iface, RPCOLEMESSAGE* olemsg)
1010 RPC_MESSAGE *msg = (RPC_MESSAGE *)olemsg;
1011 RPC_STATUS status;
1012 struct message_state *message_state;
1014 TRACE("(%p)\n", msg);
1016 message_state = msg->Handle;
1017 /* restore the binding handle and the real start of data */
1018 msg->Handle = message_state->binding_handle;
1019 msg->Buffer = (char *)msg->Buffer - message_state->prefix_data_len;
1020 msg->BufferLength += message_state->prefix_data_len;
1022 if (message_state->params.bypass_rpcrt)
1024 HeapFree(GetProcessHeap(), 0, msg->Buffer);
1025 status = RPC_S_OK;
1027 else
1028 status = I_RpcFreeBuffer(msg);
1030 HeapFree(GetProcessHeap(), 0, msg->RpcInterfaceInformation);
1031 msg->RpcInterfaceInformation = NULL;
1033 if (message_state->params.stub)
1034 IRpcStubBuffer_Release(message_state->params.stub);
1035 if (message_state->params.chan)
1036 IRpcChannelBuffer_Release(message_state->params.chan);
1037 HeapFree(GetProcessHeap(), 0, message_state);
1039 TRACE("-- %d\n", status);
1041 return HRESULT_FROM_WIN32(status);
1044 static HRESULT WINAPI ClientRpcChannelBuffer_GetDestCtx(LPRPCCHANNELBUFFER iface, DWORD* pdwDestContext, void** ppvDestContext)
1046 ClientRpcChannelBuffer *This = (ClientRpcChannelBuffer *)iface;
1048 TRACE("(%p,%p)\n", pdwDestContext, ppvDestContext);
1050 *pdwDestContext = This->super.dest_context;
1051 *ppvDestContext = This->super.dest_context_data;
1053 return S_OK;
1056 static HRESULT WINAPI ServerRpcChannelBuffer_GetDestCtx(LPRPCCHANNELBUFFER iface, DWORD* dest_context, void** dest_context_data)
1058 RpcChannelBuffer *This = (RpcChannelBuffer *)iface;
1060 TRACE("(%p,%p)\n", dest_context, dest_context_data);
1062 *dest_context = This->dest_context;
1063 *dest_context_data = This->dest_context_data;
1064 return S_OK;
1067 static HRESULT WINAPI RpcChannelBuffer_IsConnected(LPRPCCHANNELBUFFER iface)
1069 TRACE("()\n");
1070 /* native does nothing too */
1071 return S_OK;
1074 static const IRpcChannelBufferVtbl ClientRpcChannelBufferVtbl =
1076 RpcChannelBuffer_QueryInterface,
1077 RpcChannelBuffer_AddRef,
1078 ClientRpcChannelBuffer_Release,
1079 ClientRpcChannelBuffer_GetBuffer,
1080 ClientRpcChannelBuffer_SendReceive,
1081 ClientRpcChannelBuffer_FreeBuffer,
1082 ClientRpcChannelBuffer_GetDestCtx,
1083 RpcChannelBuffer_IsConnected
1086 static const IRpcChannelBufferVtbl ServerRpcChannelBufferVtbl =
1088 RpcChannelBuffer_QueryInterface,
1089 RpcChannelBuffer_AddRef,
1090 ServerRpcChannelBuffer_Release,
1091 ServerRpcChannelBuffer_GetBuffer,
1092 ServerRpcChannelBuffer_SendReceive,
1093 ServerRpcChannelBuffer_FreeBuffer,
1094 ServerRpcChannelBuffer_GetDestCtx,
1095 RpcChannelBuffer_IsConnected
1098 /* returns a channel buffer for proxies */
1099 HRESULT RPC_CreateClientChannel(const OXID *oxid, const IPID *ipid,
1100 const OXID_INFO *oxid_info, const IID *iid,
1101 DWORD dest_context, void *dest_context_data,
1102 IRpcChannelBuffer **chan, APARTMENT *apt)
1104 ClientRpcChannelBuffer *This;
1105 WCHAR endpoint[200];
1106 RPC_BINDING_HANDLE bind;
1107 RPC_STATUS status;
1108 LPWSTR string_binding;
1110 /* FIXME: get the endpoint from oxid_info->psa instead */
1111 get_rpc_endpoint(endpoint, oxid);
1113 TRACE("proxy pipe: connecting to endpoint: %s\n", debugstr_w(endpoint));
1115 status = RpcStringBindingComposeW(
1116 NULL,
1117 wszRpcTransport,
1118 NULL,
1119 endpoint,
1120 NULL,
1121 &string_binding);
1123 if (status == RPC_S_OK)
1125 status = RpcBindingFromStringBindingW(string_binding, &bind);
1127 if (status == RPC_S_OK)
1129 IPID ipid2 = *ipid; /* why can't RpcBindingSetObject take a const? */
1130 status = RpcBindingSetObject(bind, &ipid2);
1131 if (status != RPC_S_OK)
1132 RpcBindingFree(&bind);
1135 RpcStringFreeW(&string_binding);
1138 if (status != RPC_S_OK)
1140 ERR("Couldn't get binding for endpoint %s, status = %d\n", debugstr_w(endpoint), status);
1141 return HRESULT_FROM_WIN32(status);
1144 This = HeapAlloc(GetProcessHeap(), 0, sizeof(*This));
1145 if (!This)
1147 RpcBindingFree(&bind);
1148 return E_OUTOFMEMORY;
1151 This->super.IRpcChannelBuffer_iface.lpVtbl = &ClientRpcChannelBufferVtbl;
1152 This->super.refs = 1;
1153 This->super.dest_context = dest_context;
1154 This->super.dest_context_data = dest_context_data;
1155 This->bind = bind;
1156 apartment_getoxid(apt, &This->oxid);
1157 This->server_pid = oxid_info->dwPid;
1158 This->event = NULL;
1159 This->iid = *iid;
1161 *chan = &This->super.IRpcChannelBuffer_iface;
1163 return S_OK;
1166 HRESULT RPC_CreateServerChannel(DWORD dest_context, void *dest_context_data, IRpcChannelBuffer **chan)
1168 RpcChannelBuffer *This = HeapAlloc(GetProcessHeap(), 0, sizeof(*This));
1169 if (!This)
1170 return E_OUTOFMEMORY;
1172 This->IRpcChannelBuffer_iface.lpVtbl = &ServerRpcChannelBufferVtbl;
1173 This->refs = 1;
1174 This->dest_context = dest_context;
1175 This->dest_context_data = dest_context_data;
1177 *chan = &This->IRpcChannelBuffer_iface;
1179 return S_OK;
1182 /* unmarshals ORPC_EXTENT_ARRAY according to NDR rules, but doesn't allocate
1183 * any memory */
1184 static HRESULT unmarshal_ORPC_EXTENT_ARRAY(RPC_MESSAGE *msg, const char *end,
1185 ORPC_EXTENT_ARRAY *extensions,
1186 WIRE_ORPC_EXTENT **first_wire_orpc_extent)
1188 DWORD pointer_id;
1189 DWORD i;
1191 memcpy(extensions, msg->Buffer, FIELD_OFFSET(WIRE_ORPC_EXTENT_ARRAY, extent));
1192 msg->Buffer = (char *)msg->Buffer + FIELD_OFFSET(WIRE_ORPC_EXTENT_ARRAY, extent);
1194 if ((const char *)msg->Buffer + 2 * sizeof(DWORD) > end)
1195 return RPC_E_INVALID_HEADER;
1197 pointer_id = *(DWORD *)msg->Buffer;
1198 msg->Buffer = (char *)msg->Buffer + sizeof(DWORD);
1199 extensions->extent = NULL;
1201 if (pointer_id)
1203 WIRE_ORPC_EXTENT *wire_orpc_extent;
1205 /* conformance */
1206 if (*(DWORD *)msg->Buffer != ((extensions->size+1)&~1))
1207 return RPC_S_INVALID_BOUND;
1209 msg->Buffer = (char *)msg->Buffer + sizeof(DWORD);
1211 /* arbitrary limit for security (don't know what native does) */
1212 if (extensions->size > 256)
1214 ERR("too many extensions: %d\n", extensions->size);
1215 return RPC_S_INVALID_BOUND;
1218 *first_wire_orpc_extent = wire_orpc_extent = msg->Buffer;
1219 for (i = 0; i < ((extensions->size+1)&~1); i++)
1221 if ((const char *)&wire_orpc_extent->data[0] > end)
1222 return RPC_S_INVALID_BOUND;
1223 if (wire_orpc_extent->conformance != ((wire_orpc_extent->size+7)&~7))
1224 return RPC_S_INVALID_BOUND;
1225 if ((const char *)&wire_orpc_extent->data[wire_orpc_extent->conformance] > end)
1226 return RPC_S_INVALID_BOUND;
1227 TRACE("size %u, guid %s\n", wire_orpc_extent->size, debugstr_guid(&wire_orpc_extent->id));
1228 wire_orpc_extent = (WIRE_ORPC_EXTENT *)&wire_orpc_extent->data[wire_orpc_extent->conformance];
1230 msg->Buffer = wire_orpc_extent;
1233 return S_OK;
1236 /* unmarshals ORPCTHIS according to NDR rules, but doesn't allocate any memory */
1237 static HRESULT unmarshal_ORPCTHIS(RPC_MESSAGE *msg, ORPCTHIS *orpcthis,
1238 ORPC_EXTENT_ARRAY *orpc_ext_array, WIRE_ORPC_EXTENT **first_wire_orpc_extent)
1240 const char *end = (char *)msg->Buffer + msg->BufferLength;
1242 *first_wire_orpc_extent = NULL;
1244 if (msg->BufferLength < FIELD_OFFSET(WIRE_ORPCTHIS, extensions) + sizeof(DWORD))
1246 ERR("invalid buffer length\n");
1247 return RPC_E_INVALID_HEADER;
1250 memcpy(orpcthis, msg->Buffer, FIELD_OFFSET(WIRE_ORPCTHIS, extensions));
1251 msg->Buffer = (char *)msg->Buffer + FIELD_OFFSET(WIRE_ORPCTHIS, extensions);
1253 if ((const char *)msg->Buffer + sizeof(DWORD) > end)
1254 return RPC_E_INVALID_HEADER;
1256 if (*(DWORD *)msg->Buffer)
1257 orpcthis->extensions = orpc_ext_array;
1258 else
1259 orpcthis->extensions = NULL;
1261 msg->Buffer = (char *)msg->Buffer + sizeof(DWORD);
1263 if (orpcthis->extensions)
1265 HRESULT hr = unmarshal_ORPC_EXTENT_ARRAY(msg, end, orpc_ext_array,
1266 first_wire_orpc_extent);
1267 if (FAILED(hr))
1268 return hr;
1271 if ((orpcthis->version.MajorVersion != COM_MAJOR_VERSION) ||
1272 (orpcthis->version.MinorVersion > COM_MINOR_VERSION))
1274 ERR("COM version {%d, %d} not supported\n",
1275 orpcthis->version.MajorVersion, orpcthis->version.MinorVersion);
1276 return RPC_E_VERSION_MISMATCH;
1279 if (orpcthis->flags & ~(ORPCF_LOCAL|ORPCF_RESERVED1|ORPCF_RESERVED2|ORPCF_RESERVED3|ORPCF_RESERVED4))
1281 ERR("invalid flags 0x%x\n", orpcthis->flags & ~(ORPCF_LOCAL|ORPCF_RESERVED1|ORPCF_RESERVED2|ORPCF_RESERVED3|ORPCF_RESERVED4));
1282 return RPC_E_INVALID_HEADER;
1285 return S_OK;
1288 static HRESULT unmarshal_ORPCTHAT(RPC_MESSAGE *msg, ORPCTHAT *orpcthat,
1289 ORPC_EXTENT_ARRAY *orpc_ext_array, WIRE_ORPC_EXTENT **first_wire_orpc_extent)
1291 const char *end = (char *)msg->Buffer + msg->BufferLength;
1293 *first_wire_orpc_extent = NULL;
1295 if (msg->BufferLength < FIELD_OFFSET(WIRE_ORPCTHAT, extensions) + sizeof(DWORD))
1297 ERR("invalid buffer length\n");
1298 return RPC_E_INVALID_HEADER;
1301 memcpy(orpcthat, msg->Buffer, FIELD_OFFSET(WIRE_ORPCTHAT, extensions));
1302 msg->Buffer = (char *)msg->Buffer + FIELD_OFFSET(WIRE_ORPCTHAT, extensions);
1304 if ((const char *)msg->Buffer + sizeof(DWORD) > end)
1305 return RPC_E_INVALID_HEADER;
1307 if (*(DWORD *)msg->Buffer)
1308 orpcthat->extensions = orpc_ext_array;
1309 else
1310 orpcthat->extensions = NULL;
1312 msg->Buffer = (char *)msg->Buffer + sizeof(DWORD);
1314 if (orpcthat->extensions)
1316 HRESULT hr = unmarshal_ORPC_EXTENT_ARRAY(msg, end, orpc_ext_array,
1317 first_wire_orpc_extent);
1318 if (FAILED(hr))
1319 return hr;
1322 if (orpcthat->flags & ~(ORPCF_LOCAL|ORPCF_RESERVED1|ORPCF_RESERVED2|ORPCF_RESERVED3|ORPCF_RESERVED4))
1324 ERR("invalid flags 0x%x\n", orpcthat->flags & ~(ORPCF_LOCAL|ORPCF_RESERVED1|ORPCF_RESERVED2|ORPCF_RESERVED3|ORPCF_RESERVED4));
1325 return RPC_E_INVALID_HEADER;
1328 return S_OK;
1331 void RPC_ExecuteCall(struct dispatch_params *params)
1333 struct message_state *message_state = NULL;
1334 RPC_MESSAGE *msg = (RPC_MESSAGE *)params->msg;
1335 char *original_buffer = msg->Buffer;
1336 ORPCTHIS orpcthis;
1337 ORPC_EXTENT_ARRAY orpc_ext_array;
1338 WIRE_ORPC_EXTENT *first_wire_orpc_extent;
1339 GUID old_causality_id;
1341 /* handle ORPCTHIS and server extensions */
1343 params->hr = unmarshal_ORPCTHIS(msg, &orpcthis, &orpc_ext_array, &first_wire_orpc_extent);
1344 if (params->hr != S_OK)
1346 msg->Buffer = original_buffer;
1347 goto exit;
1350 message_state = HeapAlloc(GetProcessHeap(), 0, sizeof(*message_state));
1351 if (!message_state)
1353 params->hr = E_OUTOFMEMORY;
1354 msg->Buffer = original_buffer;
1355 goto exit;
1358 message_state->prefix_data_len = (char *)msg->Buffer - original_buffer;
1359 message_state->binding_handle = msg->Handle;
1360 message_state->bypass_rpcrt = params->bypass_rpcrt;
1362 message_state->channel_hook_info.iid = params->iid;
1363 message_state->channel_hook_info.cbSize = sizeof(message_state->channel_hook_info);
1364 message_state->channel_hook_info.uCausality = orpcthis.cid;
1365 message_state->channel_hook_info.dwServerPid = GetCurrentProcessId();
1366 message_state->channel_hook_info.iMethod = msg->ProcNum;
1367 message_state->channel_hook_info.pObject = params->iface;
1369 if (orpcthis.extensions && first_wire_orpc_extent &&
1370 orpcthis.extensions->size)
1371 ChannelHooks_ServerNotify(&message_state->channel_hook_info, msg->DataRepresentation, first_wire_orpc_extent, orpcthis.extensions->size);
1373 msg->Handle = message_state;
1374 msg->BufferLength -= message_state->prefix_data_len;
1376 /* call message filter */
1378 if (COM_CurrentApt()->filter)
1380 DWORD handlecall;
1381 INTERFACEINFO interface_info;
1382 CALLTYPE calltype;
1384 interface_info.pUnk = params->iface;
1385 interface_info.iid = params->iid;
1386 interface_info.wMethod = msg->ProcNum;
1388 if (IsEqualGUID(&orpcthis.cid, &COM_CurrentInfo()->causality_id))
1389 calltype = CALLTYPE_NESTED;
1390 else if (COM_CurrentInfo()->pending_call_count_server == 0)
1391 calltype = CALLTYPE_TOPLEVEL;
1392 else
1393 calltype = CALLTYPE_TOPLEVEL_CALLPENDING;
1395 handlecall = IMessageFilter_HandleInComingCall(COM_CurrentApt()->filter,
1396 calltype,
1397 UlongToHandle(GetCurrentProcessId()),
1398 0 /* FIXME */,
1399 &interface_info);
1400 TRACE("IMessageFilter_HandleInComingCall returned %d\n", handlecall);
1401 switch (handlecall)
1403 case SERVERCALL_REJECTED:
1404 params->hr = RPC_E_CALL_REJECTED;
1405 goto exit_reset_state;
1406 case SERVERCALL_RETRYLATER:
1407 #if 0 /* FIXME: handle retries on the client side before enabling this code */
1408 params->hr = RPC_E_RETRY;
1409 goto exit_reset_state;
1410 #else
1411 FIXME("retry call later not implemented\n");
1412 break;
1413 #endif
1414 case SERVERCALL_ISHANDLED:
1415 default:
1416 break;
1420 /* invoke the method */
1422 /* save the old causality ID - note: any calls executed while processing
1423 * messages received during the SendReceive will appear to originate from
1424 * this call - this should be checked with what Windows does */
1425 old_causality_id = COM_CurrentInfo()->causality_id;
1426 COM_CurrentInfo()->causality_id = orpcthis.cid;
1427 COM_CurrentInfo()->pending_call_count_server++;
1428 params->hr = IRpcStubBuffer_Invoke(params->stub, params->msg, params->chan);
1429 COM_CurrentInfo()->pending_call_count_server--;
1430 COM_CurrentInfo()->causality_id = old_causality_id;
1432 /* the invoke allocated a new buffer, so free the old one */
1433 if (message_state->bypass_rpcrt && original_buffer != msg->Buffer)
1434 HeapFree(GetProcessHeap(), 0, original_buffer);
1436 exit_reset_state:
1437 message_state = msg->Handle;
1438 msg->Handle = message_state->binding_handle;
1439 msg->Buffer = (char *)msg->Buffer - message_state->prefix_data_len;
1440 msg->BufferLength += message_state->prefix_data_len;
1442 exit:
1443 HeapFree(GetProcessHeap(), 0, message_state);
1444 if (params->handle) SetEvent(params->handle);
1447 static void __RPC_STUB dispatch_rpc(RPC_MESSAGE *msg)
1449 struct dispatch_params *params;
1450 struct stub_manager *stub_manager;
1451 APARTMENT *apt;
1452 IPID ipid;
1453 HRESULT hr;
1455 RpcBindingInqObject(msg->Handle, &ipid);
1457 TRACE("ipid = %s, iMethod = %d\n", debugstr_guid(&ipid), msg->ProcNum);
1459 params = HeapAlloc(GetProcessHeap(), 0, sizeof(*params));
1460 if (!params)
1462 RpcRaiseException(E_OUTOFMEMORY);
1463 return;
1466 hr = ipid_get_dispatch_params(&ipid, &apt, &stub_manager, &params->stub, &params->chan,
1467 &params->iid, &params->iface);
1468 if (hr != S_OK)
1470 ERR("no apartment found for ipid %s\n", debugstr_guid(&ipid));
1471 HeapFree(GetProcessHeap(), 0, params);
1472 RpcRaiseException(hr);
1473 return;
1476 params->msg = (RPCOLEMESSAGE *)msg;
1477 params->status = RPC_S_OK;
1478 params->hr = S_OK;
1479 params->handle = NULL;
1480 params->bypass_rpcrt = FALSE;
1482 /* Note: this is the important difference between STAs and MTAs - we
1483 * always execute RPCs to STAs in the thread that originally created the
1484 * apartment (i.e. the one that pumps messages to the window) */
1485 if (!apt->multi_threaded)
1487 params->handle = CreateEventW(NULL, FALSE, FALSE, NULL);
1489 TRACE("Calling apartment thread 0x%08x...\n", apt->tid);
1491 if (PostMessageW(apartment_getwindow(apt), DM_EXECUTERPC, 0, (LPARAM)params))
1492 WaitForSingleObject(params->handle, INFINITE);
1493 else
1495 ERR("PostMessage failed with error %u\n", GetLastError());
1496 IRpcChannelBuffer_Release(params->chan);
1497 IRpcStubBuffer_Release(params->stub);
1499 CloseHandle(params->handle);
1501 else
1503 BOOL joined = FALSE;
1504 struct oletls *info = COM_CurrentInfo();
1506 if (!info->apt)
1508 enter_apartment(info, COINIT_MULTITHREADED);
1509 joined = TRUE;
1511 RPC_ExecuteCall(params);
1512 if (joined)
1514 leave_apartment(info);
1518 hr = params->hr;
1519 if (params->chan)
1520 IRpcChannelBuffer_Release(params->chan);
1521 if (params->stub)
1522 IRpcStubBuffer_Release(params->stub);
1523 HeapFree(GetProcessHeap(), 0, params);
1525 stub_manager_int_release(stub_manager);
1526 apartment_release(apt);
1528 /* if IRpcStubBuffer_Invoke fails, we should raise an exception to tell
1529 * the RPC runtime that the call failed */
1530 if (hr != S_OK) RpcRaiseException(hr);
1533 /* stub registration */
1534 HRESULT RPC_RegisterInterface(REFIID riid)
1536 struct registered_if *rif;
1537 BOOL found = FALSE;
1538 HRESULT hr = S_OK;
1540 TRACE("(%s)\n", debugstr_guid(riid));
1542 EnterCriticalSection(&csRegIf);
1543 LIST_FOR_EACH_ENTRY(rif, &registered_interfaces, struct registered_if, entry)
1545 if (IsEqualGUID(&rif->If.InterfaceId.SyntaxGUID, riid))
1547 rif->refs++;
1548 found = TRUE;
1549 break;
1552 if (!found)
1554 TRACE("Creating new interface\n");
1556 rif = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*rif));
1557 if (rif)
1559 RPC_STATUS status;
1561 rif->refs = 1;
1562 rif->If.Length = sizeof(RPC_SERVER_INTERFACE);
1563 /* RPC interface ID = COM interface ID */
1564 rif->If.InterfaceId.SyntaxGUID = *riid;
1565 rif->If.DispatchTable = &rpc_dispatch;
1566 /* all other fields are 0, including the version asCOM objects
1567 * always have a version of 0.0 */
1568 status = RpcServerRegisterIfEx(
1569 (RPC_IF_HANDLE)&rif->If,
1570 NULL, NULL,
1571 RPC_IF_OLE | RPC_IF_AUTOLISTEN,
1572 RPC_C_LISTEN_MAX_CALLS_DEFAULT,
1573 NULL);
1574 if (status == RPC_S_OK)
1575 list_add_tail(&registered_interfaces, &rif->entry);
1576 else
1578 ERR("RpcServerRegisterIfEx failed with error %d\n", status);
1579 HeapFree(GetProcessHeap(), 0, rif);
1580 hr = HRESULT_FROM_WIN32(status);
1583 else
1584 hr = E_OUTOFMEMORY;
1586 LeaveCriticalSection(&csRegIf);
1587 return hr;
1590 /* stub unregistration */
1591 void RPC_UnregisterInterface(REFIID riid, BOOL wait)
1593 struct registered_if *rif;
1594 EnterCriticalSection(&csRegIf);
1595 LIST_FOR_EACH_ENTRY(rif, &registered_interfaces, struct registered_if, entry)
1597 if (IsEqualGUID(&rif->If.InterfaceId.SyntaxGUID, riid))
1599 if (!--rif->refs)
1601 RpcServerUnregisterIf((RPC_IF_HANDLE)&rif->If, NULL, wait);
1602 list_remove(&rif->entry);
1603 HeapFree(GetProcessHeap(), 0, rif);
1605 break;
1608 LeaveCriticalSection(&csRegIf);
1611 /* get the info for an OXID, including the IPID for the rem unknown interface
1612 * and the string binding */
1613 HRESULT RPC_ResolveOxid(OXID oxid, OXID_INFO *oxid_info)
1615 TRACE("%s\n", wine_dbgstr_longlong(oxid));
1617 oxid_info->dwTid = 0;
1618 oxid_info->dwPid = 0;
1619 oxid_info->dwAuthnHint = RPC_C_AUTHN_LEVEL_NONE;
1620 /* FIXME: this is a hack around not having an OXID resolver yet -
1621 * this function should contact the machine's OXID resolver and then it
1622 * should give us the IPID of the IRemUnknown interface */
1623 oxid_info->ipidRemUnknown.Data1 = 0xffffffff;
1624 oxid_info->ipidRemUnknown.Data2 = 0xffff;
1625 oxid_info->ipidRemUnknown.Data3 = 0xffff;
1626 memcpy(oxid_info->ipidRemUnknown.Data4, &oxid, sizeof(OXID));
1627 oxid_info->psa = NULL /* FIXME */;
1629 return S_OK;
1632 /* make the apartment reachable by other threads and processes and create the
1633 * IRemUnknown object */
1634 void RPC_StartRemoting(struct apartment *apt)
1636 if (!InterlockedExchange(&apt->remoting_started, TRUE))
1638 WCHAR endpoint[200];
1639 RPC_STATUS status;
1641 get_rpc_endpoint(endpoint, &apt->oxid);
1643 status = RpcServerUseProtseqEpW(
1644 wszRpcTransport,
1645 RPC_C_PROTSEQ_MAX_REQS_DEFAULT,
1646 endpoint,
1647 NULL);
1648 if (status != RPC_S_OK)
1649 ERR("Couldn't register endpoint %s\n", debugstr_w(endpoint));
1651 /* FIXME: move remote unknown exporting into this function */
1653 start_apartment_remote_unknown(apt);
1657 static HRESULT create_server(REFCLSID rclsid, HANDLE *process)
1659 static const WCHAR wszLocalServer32[] = { 'L','o','c','a','l','S','e','r','v','e','r','3','2',0 };
1660 static const WCHAR embedding[] = { ' ', '-','E','m','b','e','d','d','i','n','g',0 };
1661 HKEY key;
1662 HRESULT hres;
1663 WCHAR command[MAX_PATH+ARRAY_SIZE(embedding)];
1664 DWORD size = (MAX_PATH+1) * sizeof(WCHAR);
1665 STARTUPINFOW sinfo;
1666 PROCESS_INFORMATION pinfo;
1667 LONG ret;
1669 hres = COM_OpenKeyForCLSID(rclsid, wszLocalServer32, KEY_READ, &key);
1670 if (FAILED(hres)) {
1671 ERR("class %s not registered\n", debugstr_guid(rclsid));
1672 return hres;
1675 ret = RegQueryValueExW(key, NULL, NULL, NULL, (LPBYTE)command, &size);
1676 RegCloseKey(key);
1677 if (ret) {
1678 WARN("No default value for LocalServer32 key\n");
1679 return REGDB_E_CLASSNOTREG; /* FIXME: check retval */
1682 memset(&sinfo,0,sizeof(sinfo));
1683 sinfo.cb = sizeof(sinfo);
1685 /* EXE servers are started with the -Embedding switch. */
1687 strcatW(command, embedding);
1689 TRACE("activating local server %s for %s\n", debugstr_w(command), debugstr_guid(rclsid));
1691 /* FIXME: Win2003 supports a ServerExecutable value that is passed into
1692 * CreateProcess */
1693 if (!CreateProcessW(NULL, command, NULL, NULL, FALSE, DETACHED_PROCESS, NULL, NULL, &sinfo, &pinfo)) {
1694 WARN("failed to run local server %s\n", debugstr_w(command));
1695 return HRESULT_FROM_WIN32(GetLastError());
1697 *process = pinfo.hProcess;
1698 CloseHandle(pinfo.hThread);
1700 return S_OK;
1704 * start_local_service() - start a service given its name and parameters
1706 static DWORD start_local_service(LPCWSTR name, DWORD num, LPCWSTR *params)
1708 SC_HANDLE handle, hsvc;
1709 DWORD r = ERROR_FUNCTION_FAILED;
1711 TRACE("Starting service %s %d params\n", debugstr_w(name), num);
1713 handle = OpenSCManagerW(NULL, NULL, SC_MANAGER_CONNECT);
1714 if (!handle)
1715 return r;
1716 hsvc = OpenServiceW(handle, name, SERVICE_START);
1717 if (hsvc)
1719 if(StartServiceW(hsvc, num, params))
1720 r = ERROR_SUCCESS;
1721 else
1722 r = GetLastError();
1723 if (r == ERROR_SERVICE_ALREADY_RUNNING)
1724 r = ERROR_SUCCESS;
1725 CloseServiceHandle(hsvc);
1727 else
1728 r = GetLastError();
1729 CloseServiceHandle(handle);
1731 TRACE("StartService returned error %u (%s)\n", r, (r == ERROR_SUCCESS) ? "ok":"failed");
1733 return r;
1737 * create_local_service() - start a COM server in a service
1739 * To start a Local Service, we read the AppID value under
1740 * the class's CLSID key, then open the HKCR\\AppId key specified
1741 * there and check for a LocalService value.
1743 * Note: Local Services are not supported under Windows 9x
1745 static HRESULT create_local_service(REFCLSID rclsid)
1747 HRESULT hres;
1748 WCHAR buf[CHARS_IN_GUID];
1749 static const WCHAR szLocalService[] = { 'L','o','c','a','l','S','e','r','v','i','c','e',0 };
1750 static const WCHAR szServiceParams[] = {'S','e','r','v','i','c','e','P','a','r','a','m','s',0};
1751 HKEY hkey;
1752 LONG r;
1753 DWORD type, sz;
1755 TRACE("Attempting to start Local service for %s\n", debugstr_guid(rclsid));
1757 hres = COM_OpenKeyForAppIdFromCLSID(rclsid, KEY_READ, &hkey);
1758 if (FAILED(hres))
1759 return hres;
1761 /* read the LocalService and ServiceParameters values from the AppID key */
1762 sz = sizeof buf;
1763 r = RegQueryValueExW(hkey, szLocalService, NULL, &type, (LPBYTE)buf, &sz);
1764 if (r==ERROR_SUCCESS && type==REG_SZ)
1766 DWORD num_args = 0;
1767 LPWSTR args[1] = { NULL };
1770 * FIXME: I'm not really sure how to deal with the service parameters.
1771 * I suspect that the string returned from RegQueryValueExW
1772 * should be split into a number of arguments by spaces.
1773 * It would make more sense if ServiceParams contained a
1774 * REG_MULTI_SZ here, but it's a REG_SZ for the services
1775 * that I'm interested in for the moment.
1777 r = RegQueryValueExW(hkey, szServiceParams, NULL, &type, NULL, &sz);
1778 if (r == ERROR_SUCCESS && type == REG_SZ && sz)
1780 args[0] = HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY,sz);
1781 num_args++;
1782 RegQueryValueExW(hkey, szServiceParams, NULL, &type, (LPBYTE)args[0], &sz);
1784 r = start_local_service(buf, num_args, (LPCWSTR *)args);
1785 if (r != ERROR_SUCCESS)
1786 hres = REGDB_E_CLASSNOTREG; /* FIXME: check retval */
1787 HeapFree(GetProcessHeap(),0,args[0]);
1789 else
1791 WARN("No LocalService value\n");
1792 hres = REGDB_E_CLASSNOTREG; /* FIXME: check retval */
1794 RegCloseKey(hkey);
1796 return hres;
1800 static void get_localserver_pipe_name(WCHAR *pipefn, REFCLSID rclsid)
1802 static const WCHAR wszPipeRef[] = {'\\','\\','.','\\','p','i','p','e','\\',0};
1803 strcpyW(pipefn, wszPipeRef);
1804 StringFromGUID2(rclsid, pipefn + ARRAY_SIZE(wszPipeRef) - 1, CHARS_IN_GUID);
1807 /* FIXME: should call to rpcss instead */
1808 HRESULT RPC_GetLocalClassObject(REFCLSID rclsid, REFIID iid, LPVOID *ppv)
1810 HRESULT hres;
1811 HANDLE hPipe;
1812 WCHAR pipefn[100];
1813 DWORD res, bufferlen;
1814 char marshalbuffer[200];
1815 IStream *pStm;
1816 LARGE_INTEGER seekto;
1817 ULARGE_INTEGER newpos;
1818 int tries = 0;
1819 IServiceProvider *local_server;
1821 static const int MAXTRIES = 30; /* 30 seconds */
1823 TRACE("rclsid=%s, iid=%s\n", debugstr_guid(rclsid), debugstr_guid(iid));
1825 get_localserver_pipe_name(pipefn, rclsid);
1827 while (tries++ < MAXTRIES) {
1828 TRACE("waiting for %s\n", debugstr_w(pipefn));
1830 WaitNamedPipeW( pipefn, NMPWAIT_WAIT_FOREVER );
1831 hPipe = CreateFileW(pipefn, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, 0);
1832 if (hPipe == INVALID_HANDLE_VALUE) {
1833 DWORD index;
1834 DWORD start_ticks;
1835 HANDLE process = 0;
1836 if (tries == 1) {
1837 if ( (hres = create_local_service(rclsid)) &&
1838 (hres = create_server(rclsid, &process)) )
1839 return hres;
1840 } else {
1841 WARN("Connecting to %s, no response yet, retrying: le is %u\n", debugstr_w(pipefn), GetLastError());
1843 /* wait for one second, even if messages arrive */
1844 start_ticks = GetTickCount();
1845 do {
1846 if (SUCCEEDED(CoWaitForMultipleHandles(0, 1000, (process != 0),
1847 &process, &index)) && process && !index)
1849 WARN( "server for %s failed to start\n", debugstr_guid(rclsid) );
1850 CloseHandle( hPipe );
1851 CloseHandle( process );
1852 return E_NOINTERFACE;
1854 } while (GetTickCount() - start_ticks < 1000);
1855 if (process) CloseHandle( process );
1856 continue;
1858 bufferlen = 0;
1859 if (!ReadFile(hPipe,marshalbuffer,sizeof(marshalbuffer),&bufferlen,NULL)) {
1860 FIXME("Failed to read marshal id from classfactory of %s.\n",debugstr_guid(rclsid));
1861 CloseHandle(hPipe);
1862 Sleep(1000);
1863 continue;
1865 TRACE("read marshal id from pipe\n");
1866 CloseHandle(hPipe);
1867 break;
1870 if (tries >= MAXTRIES)
1871 return E_NOINTERFACE;
1873 hres = CreateStreamOnHGlobal(0,TRUE,&pStm);
1874 if (hres != S_OK) return hres;
1875 hres = IStream_Write(pStm,marshalbuffer,bufferlen,&res);
1876 if (hres != S_OK) goto out;
1877 seekto.u.LowPart = 0;seekto.u.HighPart = 0;
1878 hres = IStream_Seek(pStm,seekto,STREAM_SEEK_SET,&newpos);
1880 TRACE("unmarshalling local server\n");
1881 hres = CoUnmarshalInterface(pStm, &IID_IServiceProvider, (void**)&local_server);
1882 if(SUCCEEDED(hres))
1883 hres = IServiceProvider_QueryService(local_server, rclsid, iid, ppv);
1884 IServiceProvider_Release(local_server);
1885 out:
1886 IStream_Release(pStm);
1887 return hres;
1891 struct local_server_params
1893 CLSID clsid;
1894 IStream *stream;
1895 HANDLE pipe;
1896 HANDLE stop_event;
1897 HANDLE thread;
1898 BOOL multi_use;
1901 /* FIXME: should call to rpcss instead */
1902 static DWORD WINAPI local_server_thread(LPVOID param)
1904 struct local_server_params * lsp = param;
1905 WCHAR pipefn[100];
1906 HRESULT hres;
1907 IStream *pStm = lsp->stream;
1908 STATSTG ststg;
1909 unsigned char *buffer;
1910 int buflen;
1911 LARGE_INTEGER seekto;
1912 ULARGE_INTEGER newpos;
1913 ULONG res;
1914 BOOL multi_use = lsp->multi_use;
1915 OVERLAPPED ovl;
1916 HANDLE pipe_event, hPipe = lsp->pipe, new_pipe;
1917 DWORD bytes;
1919 TRACE("Starting threader for %s.\n",debugstr_guid(&lsp->clsid));
1921 memset(&ovl, 0, sizeof(ovl));
1922 get_localserver_pipe_name(pipefn, &lsp->clsid);
1923 ovl.hEvent = pipe_event = CreateEventW(NULL, FALSE, FALSE, NULL);
1925 while (1) {
1926 if (!ConnectNamedPipe(hPipe, &ovl))
1928 DWORD error = GetLastError();
1929 if (error == ERROR_IO_PENDING)
1931 HANDLE handles[2] = { pipe_event, lsp->stop_event };
1932 DWORD ret;
1933 ret = WaitForMultipleObjects(2, handles, FALSE, INFINITE);
1934 if (ret != WAIT_OBJECT_0)
1935 break;
1937 /* client already connected isn't an error */
1938 else if (error != ERROR_PIPE_CONNECTED)
1940 ERR("ConnectNamedPipe failed with error %d\n", GetLastError());
1941 break;
1945 TRACE("marshalling LocalServer to client\n");
1947 hres = IStream_Stat(pStm,&ststg,STATFLAG_NONAME);
1948 if (hres != S_OK)
1949 break;
1951 seekto.u.LowPart = 0;
1952 seekto.u.HighPart = 0;
1953 hres = IStream_Seek(pStm,seekto,STREAM_SEEK_SET,&newpos);
1954 if (hres != S_OK) {
1955 FIXME("IStream_Seek failed, %x\n",hres);
1956 break;
1959 buflen = ststg.cbSize.u.LowPart;
1960 buffer = HeapAlloc(GetProcessHeap(),0,buflen);
1962 hres = IStream_Read(pStm,buffer,buflen,&res);
1963 if (hres != S_OK) {
1964 FIXME("Stream Read failed, %x\n",hres);
1965 HeapFree(GetProcessHeap(),0,buffer);
1966 break;
1969 WriteFile(hPipe,buffer,buflen,&res,&ovl);
1970 GetOverlappedResult(hPipe, &ovl, &bytes, TRUE);
1971 HeapFree(GetProcessHeap(),0,buffer);
1973 FlushFileBuffers(hPipe);
1974 DisconnectNamedPipe(hPipe);
1975 TRACE("done marshalling LocalServer\n");
1977 if (!multi_use)
1979 TRACE("single use object, shutting down pipe %s\n", debugstr_w(pipefn));
1980 break;
1982 new_pipe = CreateNamedPipeW( pipefn, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
1983 PIPE_TYPE_BYTE|PIPE_WAIT, PIPE_UNLIMITED_INSTANCES,
1984 4096, 4096, 500 /* 0.5 second timeout */, NULL );
1985 if (new_pipe == INVALID_HANDLE_VALUE)
1987 FIXME("pipe creation failed for %s, le is %u\n", debugstr_w(pipefn), GetLastError());
1988 break;
1990 CloseHandle(hPipe);
1991 hPipe = new_pipe;
1994 CloseHandle(pipe_event);
1995 CloseHandle(hPipe);
1996 return 0;
1999 /* starts listening for a local server */
2000 HRESULT RPC_StartLocalServer(REFCLSID clsid, IStream *stream, BOOL multi_use, void **registration)
2002 DWORD tid, err;
2003 struct local_server_params *lsp;
2004 WCHAR pipefn[100];
2006 lsp = HeapAlloc(GetProcessHeap(), 0, sizeof(*lsp));
2007 if (!lsp)
2008 return E_OUTOFMEMORY;
2010 lsp->clsid = *clsid;
2011 lsp->stream = stream;
2012 IStream_AddRef(stream);
2013 lsp->stop_event = CreateEventW(NULL, FALSE, FALSE, NULL);
2014 if (!lsp->stop_event)
2016 HeapFree(GetProcessHeap(), 0, lsp);
2017 return HRESULT_FROM_WIN32(GetLastError());
2019 lsp->multi_use = multi_use;
2021 get_localserver_pipe_name(pipefn, &lsp->clsid);
2022 lsp->pipe = CreateNamedPipeW(pipefn, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
2023 PIPE_TYPE_BYTE|PIPE_WAIT, PIPE_UNLIMITED_INSTANCES,
2024 4096, 4096, 500 /* 0.5 second timeout */, NULL);
2025 if (lsp->pipe == INVALID_HANDLE_VALUE)
2027 err = GetLastError();
2028 FIXME("pipe creation failed for %s, le is %u\n", debugstr_w(pipefn), GetLastError());
2029 CloseHandle(lsp->stop_event);
2030 HeapFree(GetProcessHeap(), 0, lsp);
2031 return HRESULT_FROM_WIN32(err);
2034 lsp->thread = CreateThread(NULL, 0, local_server_thread, lsp, 0, &tid);
2035 if (!lsp->thread)
2037 CloseHandle(lsp->pipe);
2038 CloseHandle(lsp->stop_event);
2039 HeapFree(GetProcessHeap(), 0, lsp);
2040 return HRESULT_FROM_WIN32(GetLastError());
2043 *registration = lsp;
2044 return S_OK;
2047 /* stops listening for a local server */
2048 void RPC_StopLocalServer(void *registration)
2050 struct local_server_params *lsp = registration;
2052 /* signal local_server_thread to stop */
2053 SetEvent(lsp->stop_event);
2054 /* wait for it to exit */
2055 WaitForSingleObject(lsp->thread, INFINITE);
2057 IStream_Release(lsp->stream);
2058 CloseHandle(lsp->stop_event);
2059 CloseHandle(lsp->thread);
2060 HeapFree(GetProcessHeap(), 0, lsp);