d3d8: Get rid of the format switching code in d3d8_device_CopyRects().
[wine.git] / dlls / ole32 / rpc.c
blobdd675468e0459cda3fe03eb1d5e6e29432ad6848
1 /*
2 * RPC Manager
4 * Copyright 2001 Ove Kåven, TransGaming Technologies
5 * Copyright 2002 Marcus Meissner
6 * Copyright 2005 Mike Hearn, Rob Shearman for CodeWeavers
8 * This library is free software; you can redistribute it and/or
9 * modify it under the terms of the GNU Lesser General Public
10 * License as published by the Free Software Foundation; either
11 * version 2.1 of the License, or (at your option) any later version.
13 * This library is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 * Lesser General Public License for more details.
18 * You should have received a copy of the GNU Lesser General Public
19 * License along with this library; if not, write to the Free Software
20 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
23 #include "config.h"
24 #include "wine/port.h"
26 #include <stdarg.h>
27 #include <string.h>
29 #define COBJMACROS
30 #define NONAMELESSUNION
31 #define NONAMELESSSTRUCT
33 #include "windef.h"
34 #include "winbase.h"
35 #include "winuser.h"
36 #include "winsvc.h"
37 #include "objbase.h"
38 #include "ole2.h"
39 #include "rpc.h"
40 #include "winerror.h"
41 #include "winreg.h"
42 #include "servprov.h"
43 #include "wine/unicode.h"
45 #include "compobj_private.h"
47 #include "wine/debug.h"
49 WINE_DEFAULT_DEBUG_CHANNEL(ole);
51 static void __RPC_STUB dispatch_rpc(RPC_MESSAGE *msg);
53 /* we only use one function to dispatch calls for all methods - we use the
54 * RPC_IF_OLE flag to tell the RPC runtime that this is the case */
55 static RPC_DISPATCH_FUNCTION rpc_dispatch_table[1] = { dispatch_rpc }; /* (RO) */
56 static RPC_DISPATCH_TABLE rpc_dispatch = { 1, rpc_dispatch_table }; /* (RO) */
58 static struct list registered_interfaces = LIST_INIT(registered_interfaces); /* (CS csRegIf) */
59 static CRITICAL_SECTION csRegIf;
60 static CRITICAL_SECTION_DEBUG csRegIf_debug =
62 0, 0, &csRegIf,
63 { &csRegIf_debug.ProcessLocksList, &csRegIf_debug.ProcessLocksList },
64 0, 0, { (DWORD_PTR)(__FILE__ ": dcom registered server interfaces") }
66 static CRITICAL_SECTION csRegIf = { &csRegIf_debug, -1, 0, 0, 0, 0 };
68 static struct list channel_hooks = LIST_INIT(channel_hooks); /* (CS csChannelHook) */
69 static CRITICAL_SECTION csChannelHook;
70 static CRITICAL_SECTION_DEBUG csChannelHook_debug =
72 0, 0, &csChannelHook,
73 { &csChannelHook_debug.ProcessLocksList, &csChannelHook_debug.ProcessLocksList },
74 0, 0, { (DWORD_PTR)(__FILE__ ": channel hooks") }
76 static CRITICAL_SECTION csChannelHook = { &csChannelHook_debug, -1, 0, 0, 0, 0 };
78 static WCHAR wszRpcTransport[] = {'n','c','a','l','r','p','c',0};
81 struct registered_if
83 struct list entry;
84 DWORD refs; /* ref count */
85 RPC_SERVER_INTERFACE If; /* interface registered with the RPC runtime */
88 /* get the pipe endpoint specified of the specified apartment */
89 static inline void get_rpc_endpoint(LPWSTR endpoint, const OXID *oxid)
91 /* FIXME: should get endpoint from rpcss */
92 static const WCHAR wszEndpointFormat[] = {'\\','p','i','p','e','\\','O','L','E','_','%','0','8','l','x','%','0','8','l','x',0};
93 wsprintfW(endpoint, wszEndpointFormat, (DWORD)(*oxid >> 32),(DWORD)*oxid);
96 typedef struct
98 IRpcChannelBuffer IRpcChannelBuffer_iface;
99 LONG refs;
101 DWORD dest_context; /* returned from GetDestCtx */
102 void *dest_context_data; /* returned from GetDestCtx */
103 } RpcChannelBuffer;
105 typedef struct
107 RpcChannelBuffer super; /* superclass */
109 RPC_BINDING_HANDLE bind; /* handle to the remote server */
110 OXID oxid; /* apartment in which the channel is valid */
111 DWORD server_pid; /* id of server process */
112 HANDLE event; /* cached event handle */
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 = *riid;
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;
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, &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;
835 TRACE("(%p) iMethod=%d\n", olemsg, olemsg->iMethod);
837 hr = ClientRpcChannelBuffer_IsCorrectApartment(This, COM_CurrentApt());
838 if (hr != S_OK)
840 ERR("called from wrong apartment, should have been 0x%s\n",
841 wine_dbgstr_longlong(This->oxid));
842 return RPC_E_WRONG_THREAD;
844 /* This situation should be impossible in multi-threaded apartments,
845 * because the calling thread isn't re-enterable.
846 * Note: doing a COM call during the processing of a sent message is
847 * only disallowed if a client call is already being waited for
848 * completion */
849 if (!COM_CurrentApt()->multi_threaded &&
850 COM_CurrentInfo()->pending_call_count_client &&
851 InSendMessage())
853 ERR("can't make an outgoing COM call in response to a sent message\n");
854 return RPC_E_CANTCALLOUT_ININPUTSYNCCALL;
857 message_state = msg->Handle;
858 /* restore the binding handle and the real start of data */
859 msg->Handle = message_state->binding_handle;
860 msg->Buffer = (char *)msg->Buffer - message_state->prefix_data_len;
861 msg->BufferLength += message_state->prefix_data_len;
863 /* Note: this is an optimization in the Microsoft OLE runtime that we need
864 * to copy, as shown by the test_no_couninitialize_client test. without
865 * short-circuiting the RPC runtime in the case below, the test will
866 * deadlock on the loader lock due to the RPC runtime needing to create
867 * a thread to process the RPC when this function is called indirectly
868 * from DllMain */
870 message_state->params.msg = olemsg;
871 if (message_state->params.bypass_rpcrt)
873 TRACE("Calling apartment thread 0x%08x...\n", message_state->target_tid);
875 msg->ProcNum &= ~RPC_FLAGS_VALID_BIT;
877 if (!PostMessageW(message_state->target_hwnd, DM_EXECUTERPC, 0,
878 (LPARAM)&message_state->params))
880 ERR("PostMessage failed with error %u\n", GetLastError());
882 /* Note: message_state->params.iface doesn't have a reference and
883 * so doesn't need to be released */
885 hr = HRESULT_FROM_WIN32(GetLastError());
888 else
890 /* we use a separate thread here because we need to be able to
891 * pump the message loop in the application thread: if we do not,
892 * any windows created by this thread will hang and RPCs that try
893 * and re-enter this STA from an incoming server thread will
894 * deadlock. InstallShield is an example of that.
896 if (!QueueUserWorkItem(rpc_sendreceive_thread, &message_state->params, WT_EXECUTEDEFAULT))
898 ERR("QueueUserWorkItem failed with error %u\n", GetLastError());
899 hr = E_UNEXPECTED;
901 else
902 hr = S_OK;
905 if (hr == S_OK)
907 if (WaitForSingleObject(message_state->params.handle, 0))
909 COM_CurrentInfo()->pending_call_count_client++;
910 hr = CoWaitForMultipleHandles(0, INFINITE, 1, &message_state->params.handle, &index);
911 COM_CurrentInfo()->pending_call_count_client--;
914 ClientRpcChannelBuffer_ReleaseEventHandle(This, message_state->params.handle);
916 /* for WM shortcut, faults are returned in params->hr */
917 if (hr == S_OK)
918 hrFault = message_state->params.hr;
920 status = message_state->params.status;
922 orpcthat.flags = ORPCF_NULL;
923 orpcthat.extensions = NULL;
925 TRACE("RPC call status: 0x%x\n", status);
926 if (status != RPC_S_OK)
927 hr = HRESULT_FROM_WIN32(status);
929 TRACE("hrFault = 0x%08x\n", hrFault);
931 /* FIXME: this condition should be
932 * "hr == S_OK && (!hrFault || msg->BufferLength > FIELD_OFFSET(ORPCTHAT, extensions) + 4)"
933 * but we don't currently reset the message length for PostMessage
934 * dispatched calls */
935 if (hr == S_OK && hrFault == S_OK)
937 HRESULT hr2;
938 char *original_buffer = msg->Buffer;
940 /* handle ORPCTHAT and client extensions */
942 hr2 = unmarshal_ORPCTHAT(msg, &orpcthat, &orpc_ext_array, &first_wire_orpc_extent);
943 if (FAILED(hr2))
944 hr = hr2;
946 message_state->prefix_data_len = (char *)msg->Buffer - original_buffer;
947 msg->BufferLength -= message_state->prefix_data_len;
949 else
950 message_state->prefix_data_len = 0;
952 if (hr == S_OK)
954 ChannelHooks_ClientNotify(&message_state->channel_hook_info,
955 msg->DataRepresentation,
956 first_wire_orpc_extent,
957 orpcthat.extensions && first_wire_orpc_extent ? orpcthat.extensions->size : 0,
958 hrFault);
961 /* save away the message state again */
962 msg->Handle = message_state;
964 if (pstatus) *pstatus = status;
966 if (hr == S_OK)
967 hr = hrFault;
969 TRACE("-- 0x%08x\n", hr);
971 return hr;
974 static HRESULT WINAPI ServerRpcChannelBuffer_FreeBuffer(LPRPCCHANNELBUFFER iface, RPCOLEMESSAGE* olemsg)
976 RPC_MESSAGE *msg = (RPC_MESSAGE *)olemsg;
977 RPC_STATUS status;
978 struct message_state *message_state;
980 TRACE("(%p)\n", msg);
982 message_state = msg->Handle;
983 /* restore the binding handle and the real start of data */
984 msg->Handle = message_state->binding_handle;
985 msg->Buffer = (char *)msg->Buffer - message_state->prefix_data_len;
986 msg->BufferLength += message_state->prefix_data_len;
987 message_state->prefix_data_len = 0;
989 if (message_state->bypass_rpcrt)
991 HeapFree(GetProcessHeap(), 0, msg->Buffer);
992 status = RPC_S_OK;
994 else
995 status = I_RpcFreeBuffer(msg);
997 msg->Handle = message_state;
999 TRACE("-- %d\n", status);
1001 return HRESULT_FROM_WIN32(status);
1004 static HRESULT WINAPI ClientRpcChannelBuffer_FreeBuffer(LPRPCCHANNELBUFFER iface, RPCOLEMESSAGE* olemsg)
1006 RPC_MESSAGE *msg = (RPC_MESSAGE *)olemsg;
1007 RPC_STATUS status;
1008 struct message_state *message_state;
1010 TRACE("(%p)\n", msg);
1012 message_state = msg->Handle;
1013 /* restore the binding handle and the real start of data */
1014 msg->Handle = message_state->binding_handle;
1015 msg->Buffer = (char *)msg->Buffer - message_state->prefix_data_len;
1016 msg->BufferLength += message_state->prefix_data_len;
1018 if (message_state->params.bypass_rpcrt)
1020 HeapFree(GetProcessHeap(), 0, msg->Buffer);
1021 status = RPC_S_OK;
1023 else
1024 status = I_RpcFreeBuffer(msg);
1026 HeapFree(GetProcessHeap(), 0, msg->RpcInterfaceInformation);
1027 msg->RpcInterfaceInformation = NULL;
1029 if (message_state->params.stub)
1030 IRpcStubBuffer_Release(message_state->params.stub);
1031 if (message_state->params.chan)
1032 IRpcChannelBuffer_Release(message_state->params.chan);
1033 HeapFree(GetProcessHeap(), 0, message_state);
1035 TRACE("-- %d\n", status);
1037 return HRESULT_FROM_WIN32(status);
1040 static HRESULT WINAPI ClientRpcChannelBuffer_GetDestCtx(LPRPCCHANNELBUFFER iface, DWORD* pdwDestContext, void** ppvDestContext)
1042 ClientRpcChannelBuffer *This = (ClientRpcChannelBuffer *)iface;
1044 TRACE("(%p,%p)\n", pdwDestContext, ppvDestContext);
1046 *pdwDestContext = This->super.dest_context;
1047 *ppvDestContext = This->super.dest_context_data;
1049 return S_OK;
1052 static HRESULT WINAPI ServerRpcChannelBuffer_GetDestCtx(LPRPCCHANNELBUFFER iface, DWORD* dest_context, void** dest_context_data)
1054 RpcChannelBuffer *This = (RpcChannelBuffer *)iface;
1056 TRACE("(%p,%p)\n", dest_context, dest_context_data);
1058 *dest_context = This->dest_context;
1059 *dest_context_data = This->dest_context_data;
1060 return S_OK;
1063 static HRESULT WINAPI RpcChannelBuffer_IsConnected(LPRPCCHANNELBUFFER iface)
1065 TRACE("()\n");
1066 /* native does nothing too */
1067 return S_OK;
1070 static const IRpcChannelBufferVtbl ClientRpcChannelBufferVtbl =
1072 RpcChannelBuffer_QueryInterface,
1073 RpcChannelBuffer_AddRef,
1074 ClientRpcChannelBuffer_Release,
1075 ClientRpcChannelBuffer_GetBuffer,
1076 ClientRpcChannelBuffer_SendReceive,
1077 ClientRpcChannelBuffer_FreeBuffer,
1078 ClientRpcChannelBuffer_GetDestCtx,
1079 RpcChannelBuffer_IsConnected
1082 static const IRpcChannelBufferVtbl ServerRpcChannelBufferVtbl =
1084 RpcChannelBuffer_QueryInterface,
1085 RpcChannelBuffer_AddRef,
1086 ServerRpcChannelBuffer_Release,
1087 ServerRpcChannelBuffer_GetBuffer,
1088 ServerRpcChannelBuffer_SendReceive,
1089 ServerRpcChannelBuffer_FreeBuffer,
1090 ServerRpcChannelBuffer_GetDestCtx,
1091 RpcChannelBuffer_IsConnected
1094 /* returns a channel buffer for proxies */
1095 HRESULT RPC_CreateClientChannel(const OXID *oxid, const IPID *ipid,
1096 const OXID_INFO *oxid_info,
1097 DWORD dest_context, void *dest_context_data,
1098 IRpcChannelBuffer **chan)
1100 ClientRpcChannelBuffer *This;
1101 WCHAR endpoint[200];
1102 RPC_BINDING_HANDLE bind;
1103 RPC_STATUS status;
1104 LPWSTR string_binding;
1106 /* FIXME: get the endpoint from oxid_info->psa instead */
1107 get_rpc_endpoint(endpoint, oxid);
1109 TRACE("proxy pipe: connecting to endpoint: %s\n", debugstr_w(endpoint));
1111 status = RpcStringBindingComposeW(
1112 NULL,
1113 wszRpcTransport,
1114 NULL,
1115 endpoint,
1116 NULL,
1117 &string_binding);
1119 if (status == RPC_S_OK)
1121 status = RpcBindingFromStringBindingW(string_binding, &bind);
1123 if (status == RPC_S_OK)
1125 IPID ipid2 = *ipid; /* why can't RpcBindingSetObject take a const? */
1126 status = RpcBindingSetObject(bind, &ipid2);
1127 if (status != RPC_S_OK)
1128 RpcBindingFree(&bind);
1131 RpcStringFreeW(&string_binding);
1134 if (status != RPC_S_OK)
1136 ERR("Couldn't get binding for endpoint %s, status = %d\n", debugstr_w(endpoint), status);
1137 return HRESULT_FROM_WIN32(status);
1140 This = HeapAlloc(GetProcessHeap(), 0, sizeof(*This));
1141 if (!This)
1143 RpcBindingFree(&bind);
1144 return E_OUTOFMEMORY;
1147 This->super.IRpcChannelBuffer_iface.lpVtbl = &ClientRpcChannelBufferVtbl;
1148 This->super.refs = 1;
1149 This->super.dest_context = dest_context;
1150 This->super.dest_context_data = dest_context_data;
1151 This->bind = bind;
1152 apartment_getoxid(COM_CurrentApt(), &This->oxid);
1153 This->server_pid = oxid_info->dwPid;
1154 This->event = NULL;
1156 *chan = &This->super.IRpcChannelBuffer_iface;
1158 return S_OK;
1161 HRESULT RPC_CreateServerChannel(DWORD dest_context, void *dest_context_data, IRpcChannelBuffer **chan)
1163 RpcChannelBuffer *This = HeapAlloc(GetProcessHeap(), 0, sizeof(*This));
1164 if (!This)
1165 return E_OUTOFMEMORY;
1167 This->IRpcChannelBuffer_iface.lpVtbl = &ServerRpcChannelBufferVtbl;
1168 This->refs = 1;
1169 This->dest_context = dest_context;
1170 This->dest_context_data = dest_context_data;
1172 *chan = &This->IRpcChannelBuffer_iface;
1174 return S_OK;
1177 /* unmarshals ORPC_EXTENT_ARRAY according to NDR rules, but doesn't allocate
1178 * any memory */
1179 static HRESULT unmarshal_ORPC_EXTENT_ARRAY(RPC_MESSAGE *msg, const char *end,
1180 ORPC_EXTENT_ARRAY *extensions,
1181 WIRE_ORPC_EXTENT **first_wire_orpc_extent)
1183 DWORD pointer_id;
1184 DWORD i;
1186 memcpy(extensions, msg->Buffer, FIELD_OFFSET(WIRE_ORPC_EXTENT_ARRAY, extent));
1187 msg->Buffer = (char *)msg->Buffer + FIELD_OFFSET(WIRE_ORPC_EXTENT_ARRAY, extent);
1189 if ((const char *)msg->Buffer + 2 * sizeof(DWORD) > end)
1190 return RPC_E_INVALID_HEADER;
1192 pointer_id = *(DWORD *)msg->Buffer;
1193 msg->Buffer = (char *)msg->Buffer + sizeof(DWORD);
1194 extensions->extent = NULL;
1196 if (pointer_id)
1198 WIRE_ORPC_EXTENT *wire_orpc_extent;
1200 /* conformance */
1201 if (*(DWORD *)msg->Buffer != ((extensions->size+1)&~1))
1202 return RPC_S_INVALID_BOUND;
1204 msg->Buffer = (char *)msg->Buffer + sizeof(DWORD);
1206 /* arbitrary limit for security (don't know what native does) */
1207 if (extensions->size > 256)
1209 ERR("too many extensions: %d\n", extensions->size);
1210 return RPC_S_INVALID_BOUND;
1213 *first_wire_orpc_extent = wire_orpc_extent = msg->Buffer;
1214 for (i = 0; i < ((extensions->size+1)&~1); i++)
1216 if ((const char *)&wire_orpc_extent->data[0] > end)
1217 return RPC_S_INVALID_BOUND;
1218 if (wire_orpc_extent->conformance != ((wire_orpc_extent->size+7)&~7))
1219 return RPC_S_INVALID_BOUND;
1220 if ((const char *)&wire_orpc_extent->data[wire_orpc_extent->conformance] > end)
1221 return RPC_S_INVALID_BOUND;
1222 TRACE("size %u, guid %s\n", wire_orpc_extent->size, debugstr_guid(&wire_orpc_extent->id));
1223 wire_orpc_extent = (WIRE_ORPC_EXTENT *)&wire_orpc_extent->data[wire_orpc_extent->conformance];
1225 msg->Buffer = wire_orpc_extent;
1228 return S_OK;
1231 /* unmarshals ORPCTHIS according to NDR rules, but doesn't allocate any memory */
1232 static HRESULT unmarshal_ORPCTHIS(RPC_MESSAGE *msg, ORPCTHIS *orpcthis,
1233 ORPC_EXTENT_ARRAY *orpc_ext_array, WIRE_ORPC_EXTENT **first_wire_orpc_extent)
1235 const char *end = (char *)msg->Buffer + msg->BufferLength;
1237 *first_wire_orpc_extent = NULL;
1239 if (msg->BufferLength < FIELD_OFFSET(WIRE_ORPCTHIS, extensions) + sizeof(DWORD))
1241 ERR("invalid buffer length\n");
1242 return RPC_E_INVALID_HEADER;
1245 memcpy(orpcthis, msg->Buffer, FIELD_OFFSET(WIRE_ORPCTHIS, extensions));
1246 msg->Buffer = (char *)msg->Buffer + FIELD_OFFSET(WIRE_ORPCTHIS, extensions);
1248 if ((const char *)msg->Buffer + sizeof(DWORD) > end)
1249 return RPC_E_INVALID_HEADER;
1251 if (*(DWORD *)msg->Buffer)
1252 orpcthis->extensions = orpc_ext_array;
1253 else
1254 orpcthis->extensions = NULL;
1256 msg->Buffer = (char *)msg->Buffer + sizeof(DWORD);
1258 if (orpcthis->extensions)
1260 HRESULT hr = unmarshal_ORPC_EXTENT_ARRAY(msg, end, orpc_ext_array,
1261 first_wire_orpc_extent);
1262 if (FAILED(hr))
1263 return hr;
1266 if ((orpcthis->version.MajorVersion != COM_MAJOR_VERSION) ||
1267 (orpcthis->version.MinorVersion > COM_MINOR_VERSION))
1269 ERR("COM version {%d, %d} not supported\n",
1270 orpcthis->version.MajorVersion, orpcthis->version.MinorVersion);
1271 return RPC_E_VERSION_MISMATCH;
1274 if (orpcthis->flags & ~(ORPCF_LOCAL|ORPCF_RESERVED1|ORPCF_RESERVED2|ORPCF_RESERVED3|ORPCF_RESERVED4))
1276 ERR("invalid flags 0x%x\n", orpcthis->flags & ~(ORPCF_LOCAL|ORPCF_RESERVED1|ORPCF_RESERVED2|ORPCF_RESERVED3|ORPCF_RESERVED4));
1277 return RPC_E_INVALID_HEADER;
1280 return S_OK;
1283 static HRESULT unmarshal_ORPCTHAT(RPC_MESSAGE *msg, ORPCTHAT *orpcthat,
1284 ORPC_EXTENT_ARRAY *orpc_ext_array, WIRE_ORPC_EXTENT **first_wire_orpc_extent)
1286 const char *end = (char *)msg->Buffer + msg->BufferLength;
1288 *first_wire_orpc_extent = NULL;
1290 if (msg->BufferLength < FIELD_OFFSET(WIRE_ORPCTHAT, extensions) + sizeof(DWORD))
1292 ERR("invalid buffer length\n");
1293 return RPC_E_INVALID_HEADER;
1296 memcpy(orpcthat, msg->Buffer, FIELD_OFFSET(WIRE_ORPCTHAT, extensions));
1297 msg->Buffer = (char *)msg->Buffer + FIELD_OFFSET(WIRE_ORPCTHAT, extensions);
1299 if ((const char *)msg->Buffer + sizeof(DWORD) > end)
1300 return RPC_E_INVALID_HEADER;
1302 if (*(DWORD *)msg->Buffer)
1303 orpcthat->extensions = orpc_ext_array;
1304 else
1305 orpcthat->extensions = NULL;
1307 msg->Buffer = (char *)msg->Buffer + sizeof(DWORD);
1309 if (orpcthat->extensions)
1311 HRESULT hr = unmarshal_ORPC_EXTENT_ARRAY(msg, end, orpc_ext_array,
1312 first_wire_orpc_extent);
1313 if (FAILED(hr))
1314 return hr;
1317 if (orpcthat->flags & ~(ORPCF_LOCAL|ORPCF_RESERVED1|ORPCF_RESERVED2|ORPCF_RESERVED3|ORPCF_RESERVED4))
1319 ERR("invalid flags 0x%x\n", orpcthat->flags & ~(ORPCF_LOCAL|ORPCF_RESERVED1|ORPCF_RESERVED2|ORPCF_RESERVED3|ORPCF_RESERVED4));
1320 return RPC_E_INVALID_HEADER;
1323 return S_OK;
1326 void RPC_ExecuteCall(struct dispatch_params *params)
1328 struct message_state *message_state = NULL;
1329 RPC_MESSAGE *msg = (RPC_MESSAGE *)params->msg;
1330 char *original_buffer = msg->Buffer;
1331 ORPCTHIS orpcthis;
1332 ORPC_EXTENT_ARRAY orpc_ext_array;
1333 WIRE_ORPC_EXTENT *first_wire_orpc_extent;
1334 GUID old_causality_id;
1336 /* handle ORPCTHIS and server extensions */
1338 params->hr = unmarshal_ORPCTHIS(msg, &orpcthis, &orpc_ext_array, &first_wire_orpc_extent);
1339 if (params->hr != S_OK)
1341 msg->Buffer = original_buffer;
1342 goto exit;
1345 message_state = HeapAlloc(GetProcessHeap(), 0, sizeof(*message_state));
1346 if (!message_state)
1348 params->hr = E_OUTOFMEMORY;
1349 msg->Buffer = original_buffer;
1350 goto exit;
1353 message_state->prefix_data_len = (char *)msg->Buffer - original_buffer;
1354 message_state->binding_handle = msg->Handle;
1355 message_state->bypass_rpcrt = params->bypass_rpcrt;
1357 message_state->channel_hook_info.iid = params->iid;
1358 message_state->channel_hook_info.cbSize = sizeof(message_state->channel_hook_info);
1359 message_state->channel_hook_info.uCausality = orpcthis.cid;
1360 message_state->channel_hook_info.dwServerPid = GetCurrentProcessId();
1361 message_state->channel_hook_info.iMethod = msg->ProcNum;
1362 message_state->channel_hook_info.pObject = params->iface;
1364 if (orpcthis.extensions && first_wire_orpc_extent &&
1365 orpcthis.extensions->size)
1366 ChannelHooks_ServerNotify(&message_state->channel_hook_info, msg->DataRepresentation, first_wire_orpc_extent, orpcthis.extensions->size);
1368 msg->Handle = message_state;
1369 msg->BufferLength -= message_state->prefix_data_len;
1371 /* call message filter */
1373 if (COM_CurrentApt()->filter)
1375 DWORD handlecall;
1376 INTERFACEINFO interface_info;
1377 CALLTYPE calltype;
1379 interface_info.pUnk = params->iface;
1380 interface_info.iid = params->iid;
1381 interface_info.wMethod = msg->ProcNum;
1383 if (IsEqualGUID(&orpcthis.cid, &COM_CurrentInfo()->causality_id))
1384 calltype = CALLTYPE_NESTED;
1385 else if (COM_CurrentInfo()->pending_call_count_server == 0)
1386 calltype = CALLTYPE_TOPLEVEL;
1387 else
1388 calltype = CALLTYPE_TOPLEVEL_CALLPENDING;
1390 handlecall = IMessageFilter_HandleInComingCall(COM_CurrentApt()->filter,
1391 calltype,
1392 UlongToHandle(GetCurrentProcessId()),
1393 0 /* FIXME */,
1394 &interface_info);
1395 TRACE("IMessageFilter_HandleInComingCall returned %d\n", handlecall);
1396 switch (handlecall)
1398 case SERVERCALL_REJECTED:
1399 params->hr = RPC_E_CALL_REJECTED;
1400 goto exit_reset_state;
1401 case SERVERCALL_RETRYLATER:
1402 #if 0 /* FIXME: handle retries on the client side before enabling this code */
1403 params->hr = RPC_E_RETRY;
1404 goto exit_reset_state;
1405 #else
1406 FIXME("retry call later not implemented\n");
1407 break;
1408 #endif
1409 case SERVERCALL_ISHANDLED:
1410 default:
1411 break;
1415 /* invoke the method */
1417 /* save the old causality ID - note: any calls executed while processing
1418 * messages received during the SendReceive will appear to originate from
1419 * this call - this should be checked with what Windows does */
1420 old_causality_id = COM_CurrentInfo()->causality_id;
1421 COM_CurrentInfo()->causality_id = orpcthis.cid;
1422 COM_CurrentInfo()->pending_call_count_server++;
1423 params->hr = IRpcStubBuffer_Invoke(params->stub, params->msg, params->chan);
1424 COM_CurrentInfo()->pending_call_count_server--;
1425 COM_CurrentInfo()->causality_id = old_causality_id;
1427 /* the invoke allocated a new buffer, so free the old one */
1428 if (message_state->bypass_rpcrt && original_buffer != msg->Buffer)
1429 HeapFree(GetProcessHeap(), 0, original_buffer);
1431 exit_reset_state:
1432 message_state = msg->Handle;
1433 msg->Handle = message_state->binding_handle;
1434 msg->Buffer = (char *)msg->Buffer - message_state->prefix_data_len;
1435 msg->BufferLength += message_state->prefix_data_len;
1437 exit:
1438 HeapFree(GetProcessHeap(), 0, message_state);
1439 if (params->handle) SetEvent(params->handle);
1442 static void __RPC_STUB dispatch_rpc(RPC_MESSAGE *msg)
1444 struct dispatch_params *params;
1445 APARTMENT *apt;
1446 IPID ipid;
1447 HRESULT hr;
1449 RpcBindingInqObject(msg->Handle, &ipid);
1451 TRACE("ipid = %s, iMethod = %d\n", debugstr_guid(&ipid), msg->ProcNum);
1453 params = HeapAlloc(GetProcessHeap(), 0, sizeof(*params));
1454 if (!params)
1456 RpcRaiseException(E_OUTOFMEMORY);
1457 return;
1460 hr = ipid_get_dispatch_params(&ipid, &apt, &params->stub, &params->chan,
1461 &params->iid, &params->iface);
1462 if (hr != S_OK)
1464 ERR("no apartment found for ipid %s\n", debugstr_guid(&ipid));
1465 HeapFree(GetProcessHeap(), 0, params);
1466 RpcRaiseException(hr);
1467 return;
1470 params->msg = (RPCOLEMESSAGE *)msg;
1471 params->status = RPC_S_OK;
1472 params->hr = S_OK;
1473 params->handle = NULL;
1474 params->bypass_rpcrt = FALSE;
1476 /* Note: this is the important difference between STAs and MTAs - we
1477 * always execute RPCs to STAs in the thread that originally created the
1478 * apartment (i.e. the one that pumps messages to the window) */
1479 if (!apt->multi_threaded)
1481 params->handle = CreateEventW(NULL, FALSE, FALSE, NULL);
1483 TRACE("Calling apartment thread 0x%08x...\n", apt->tid);
1485 if (PostMessageW(apartment_getwindow(apt), DM_EXECUTERPC, 0, (LPARAM)params))
1486 WaitForSingleObject(params->handle, INFINITE);
1487 else
1489 ERR("PostMessage failed with error %u\n", GetLastError());
1490 IRpcChannelBuffer_Release(params->chan);
1491 IRpcStubBuffer_Release(params->stub);
1493 CloseHandle(params->handle);
1495 else
1497 BOOL joined = FALSE;
1498 if (!COM_CurrentInfo()->apt)
1500 apartment_joinmta();
1501 joined = TRUE;
1503 RPC_ExecuteCall(params);
1504 if (joined)
1506 apartment_release(COM_CurrentInfo()->apt);
1507 COM_CurrentInfo()->apt = NULL;
1511 hr = params->hr;
1512 if (params->chan)
1513 IRpcChannelBuffer_Release(params->chan);
1514 if (params->stub)
1515 IRpcStubBuffer_Release(params->stub);
1516 HeapFree(GetProcessHeap(), 0, params);
1518 apartment_release(apt);
1520 /* if IRpcStubBuffer_Invoke fails, we should raise an exception to tell
1521 * the RPC runtime that the call failed */
1522 if (hr != S_OK) RpcRaiseException(hr);
1525 /* stub registration */
1526 HRESULT RPC_RegisterInterface(REFIID riid)
1528 struct registered_if *rif;
1529 BOOL found = FALSE;
1530 HRESULT hr = S_OK;
1532 TRACE("(%s)\n", debugstr_guid(riid));
1534 EnterCriticalSection(&csRegIf);
1535 LIST_FOR_EACH_ENTRY(rif, &registered_interfaces, struct registered_if, entry)
1537 if (IsEqualGUID(&rif->If.InterfaceId.SyntaxGUID, riid))
1539 rif->refs++;
1540 found = TRUE;
1541 break;
1544 if (!found)
1546 TRACE("Creating new interface\n");
1548 rif = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*rif));
1549 if (rif)
1551 RPC_STATUS status;
1553 rif->refs = 1;
1554 rif->If.Length = sizeof(RPC_SERVER_INTERFACE);
1555 /* RPC interface ID = COM interface ID */
1556 rif->If.InterfaceId.SyntaxGUID = *riid;
1557 rif->If.DispatchTable = &rpc_dispatch;
1558 /* all other fields are 0, including the version asCOM objects
1559 * always have a version of 0.0 */
1560 status = RpcServerRegisterIfEx(
1561 (RPC_IF_HANDLE)&rif->If,
1562 NULL, NULL,
1563 RPC_IF_OLE | RPC_IF_AUTOLISTEN,
1564 RPC_C_LISTEN_MAX_CALLS_DEFAULT,
1565 NULL);
1566 if (status == RPC_S_OK)
1567 list_add_tail(&registered_interfaces, &rif->entry);
1568 else
1570 ERR("RpcServerRegisterIfEx failed with error %d\n", status);
1571 HeapFree(GetProcessHeap(), 0, rif);
1572 hr = HRESULT_FROM_WIN32(status);
1575 else
1576 hr = E_OUTOFMEMORY;
1578 LeaveCriticalSection(&csRegIf);
1579 return hr;
1582 /* stub unregistration */
1583 void RPC_UnregisterInterface(REFIID riid)
1585 struct registered_if *rif;
1586 EnterCriticalSection(&csRegIf);
1587 LIST_FOR_EACH_ENTRY(rif, &registered_interfaces, struct registered_if, entry)
1589 if (IsEqualGUID(&rif->If.InterfaceId.SyntaxGUID, riid))
1591 if (!--rif->refs)
1593 RpcServerUnregisterIf((RPC_IF_HANDLE)&rif->If, NULL, TRUE);
1594 list_remove(&rif->entry);
1595 HeapFree(GetProcessHeap(), 0, rif);
1597 break;
1600 LeaveCriticalSection(&csRegIf);
1603 /* get the info for an OXID, including the IPID for the rem unknown interface
1604 * and the string binding */
1605 HRESULT RPC_ResolveOxid(OXID oxid, OXID_INFO *oxid_info)
1607 TRACE("%s\n", wine_dbgstr_longlong(oxid));
1609 oxid_info->dwTid = 0;
1610 oxid_info->dwPid = 0;
1611 oxid_info->dwAuthnHint = RPC_C_AUTHN_LEVEL_NONE;
1612 /* FIXME: this is a hack around not having an OXID resolver yet -
1613 * this function should contact the machine's OXID resolver and then it
1614 * should give us the IPID of the IRemUnknown interface */
1615 oxid_info->ipidRemUnknown.Data1 = 0xffffffff;
1616 oxid_info->ipidRemUnknown.Data2 = 0xffff;
1617 oxid_info->ipidRemUnknown.Data3 = 0xffff;
1618 memcpy(oxid_info->ipidRemUnknown.Data4, &oxid, sizeof(OXID));
1619 oxid_info->psa = NULL /* FIXME */;
1621 return S_OK;
1624 /* make the apartment reachable by other threads and processes and create the
1625 * IRemUnknown object */
1626 void RPC_StartRemoting(struct apartment *apt)
1628 if (!InterlockedExchange(&apt->remoting_started, TRUE))
1630 WCHAR endpoint[200];
1631 RPC_STATUS status;
1633 get_rpc_endpoint(endpoint, &apt->oxid);
1635 status = RpcServerUseProtseqEpW(
1636 wszRpcTransport,
1637 RPC_C_PROTSEQ_MAX_REQS_DEFAULT,
1638 endpoint,
1639 NULL);
1640 if (status != RPC_S_OK)
1641 ERR("Couldn't register endpoint %s\n", debugstr_w(endpoint));
1643 /* FIXME: move remote unknown exporting into this function */
1645 start_apartment_remote_unknown();
1649 static HRESULT create_server(REFCLSID rclsid, HANDLE *process)
1651 static const WCHAR wszLocalServer32[] = { 'L','o','c','a','l','S','e','r','v','e','r','3','2',0 };
1652 static const WCHAR embedding[] = { ' ', '-','E','m','b','e','d','d','i','n','g',0 };
1653 HKEY key;
1654 HRESULT hres;
1655 WCHAR command[MAX_PATH+sizeof(embedding)/sizeof(WCHAR)];
1656 DWORD size = (MAX_PATH+1) * sizeof(WCHAR);
1657 STARTUPINFOW sinfo;
1658 PROCESS_INFORMATION pinfo;
1659 LONG ret;
1661 hres = COM_OpenKeyForCLSID(rclsid, wszLocalServer32, KEY_READ, &key);
1662 if (FAILED(hres)) {
1663 ERR("class %s not registered\n", debugstr_guid(rclsid));
1664 return hres;
1667 ret = RegQueryValueExW(key, NULL, NULL, NULL, (LPBYTE)command, &size);
1668 RegCloseKey(key);
1669 if (ret) {
1670 WARN("No default value for LocalServer32 key\n");
1671 return REGDB_E_CLASSNOTREG; /* FIXME: check retval */
1674 memset(&sinfo,0,sizeof(sinfo));
1675 sinfo.cb = sizeof(sinfo);
1677 /* EXE servers are started with the -Embedding switch. */
1679 strcatW(command, embedding);
1681 TRACE("activating local server %s for %s\n", debugstr_w(command), debugstr_guid(rclsid));
1683 /* FIXME: Win2003 supports a ServerExecutable value that is passed into
1684 * CreateProcess */
1685 if (!CreateProcessW(NULL, command, NULL, NULL, FALSE, DETACHED_PROCESS, NULL, NULL, &sinfo, &pinfo)) {
1686 WARN("failed to run local server %s\n", debugstr_w(command));
1687 return HRESULT_FROM_WIN32(GetLastError());
1689 *process = pinfo.hProcess;
1690 CloseHandle(pinfo.hThread);
1692 return S_OK;
1696 * start_local_service() - start a service given its name and parameters
1698 static DWORD start_local_service(LPCWSTR name, DWORD num, LPCWSTR *params)
1700 SC_HANDLE handle, hsvc;
1701 DWORD r = ERROR_FUNCTION_FAILED;
1703 TRACE("Starting service %s %d params\n", debugstr_w(name), num);
1705 handle = OpenSCManagerW(NULL, NULL, SC_MANAGER_CONNECT);
1706 if (!handle)
1707 return r;
1708 hsvc = OpenServiceW(handle, name, SERVICE_START);
1709 if (hsvc)
1711 if(StartServiceW(hsvc, num, params))
1712 r = ERROR_SUCCESS;
1713 else
1714 r = GetLastError();
1715 if (r == ERROR_SERVICE_ALREADY_RUNNING)
1716 r = ERROR_SUCCESS;
1717 CloseServiceHandle(hsvc);
1719 else
1720 r = GetLastError();
1721 CloseServiceHandle(handle);
1723 TRACE("StartService returned error %u (%s)\n", r, (r == ERROR_SUCCESS) ? "ok":"failed");
1725 return r;
1729 * create_local_service() - start a COM server in a service
1731 * To start a Local Service, we read the AppID value under
1732 * the class's CLSID key, then open the HKCR\\AppId key specified
1733 * there and check for a LocalService value.
1735 * Note: Local Services are not supported under Windows 9x
1737 static HRESULT create_local_service(REFCLSID rclsid)
1739 HRESULT hres;
1740 WCHAR buf[CHARS_IN_GUID];
1741 static const WCHAR szLocalService[] = { 'L','o','c','a','l','S','e','r','v','i','c','e',0 };
1742 static const WCHAR szServiceParams[] = {'S','e','r','v','i','c','e','P','a','r','a','m','s',0};
1743 HKEY hkey;
1744 LONG r;
1745 DWORD type, sz;
1747 TRACE("Attempting to start Local service for %s\n", debugstr_guid(rclsid));
1749 hres = COM_OpenKeyForAppIdFromCLSID(rclsid, KEY_READ, &hkey);
1750 if (FAILED(hres))
1751 return hres;
1753 /* read the LocalService and ServiceParameters values from the AppID key */
1754 sz = sizeof buf;
1755 r = RegQueryValueExW(hkey, szLocalService, NULL, &type, (LPBYTE)buf, &sz);
1756 if (r==ERROR_SUCCESS && type==REG_SZ)
1758 DWORD num_args = 0;
1759 LPWSTR args[1] = { NULL };
1762 * FIXME: I'm not really sure how to deal with the service parameters.
1763 * I suspect that the string returned from RegQueryValueExW
1764 * should be split into a number of arguments by spaces.
1765 * It would make more sense if ServiceParams contained a
1766 * REG_MULTI_SZ here, but it's a REG_SZ for the services
1767 * that I'm interested in for the moment.
1769 r = RegQueryValueExW(hkey, szServiceParams, NULL, &type, NULL, &sz);
1770 if (r == ERROR_SUCCESS && type == REG_SZ && sz)
1772 args[0] = HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY,sz);
1773 num_args++;
1774 RegQueryValueExW(hkey, szServiceParams, NULL, &type, (LPBYTE)args[0], &sz);
1776 r = start_local_service(buf, num_args, (LPCWSTR *)args);
1777 if (r != ERROR_SUCCESS)
1778 hres = REGDB_E_CLASSNOTREG; /* FIXME: check retval */
1779 HeapFree(GetProcessHeap(),0,args[0]);
1781 else
1783 WARN("No LocalService value\n");
1784 hres = REGDB_E_CLASSNOTREG; /* FIXME: check retval */
1786 RegCloseKey(hkey);
1788 return hres;
1792 static void get_localserver_pipe_name(WCHAR *pipefn, REFCLSID rclsid)
1794 static const WCHAR wszPipeRef[] = {'\\','\\','.','\\','p','i','p','e','\\',0};
1795 strcpyW(pipefn, wszPipeRef);
1796 StringFromGUID2(rclsid, pipefn + sizeof(wszPipeRef)/sizeof(wszPipeRef[0]) - 1, CHARS_IN_GUID);
1799 /* FIXME: should call to rpcss instead */
1800 HRESULT RPC_GetLocalClassObject(REFCLSID rclsid, REFIID iid, LPVOID *ppv)
1802 HRESULT hres;
1803 HANDLE hPipe;
1804 WCHAR pipefn[100];
1805 DWORD res, bufferlen;
1806 char marshalbuffer[200];
1807 IStream *pStm;
1808 LARGE_INTEGER seekto;
1809 ULARGE_INTEGER newpos;
1810 int tries = 0;
1811 IServiceProvider *local_server;
1813 static const int MAXTRIES = 30; /* 30 seconds */
1815 TRACE("rclsid=%s, iid=%s\n", debugstr_guid(rclsid), debugstr_guid(iid));
1817 get_localserver_pipe_name(pipefn, rclsid);
1819 while (tries++ < MAXTRIES) {
1820 TRACE("waiting for %s\n", debugstr_w(pipefn));
1822 WaitNamedPipeW( pipefn, NMPWAIT_WAIT_FOREVER );
1823 hPipe = CreateFileW(pipefn, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, 0);
1824 if (hPipe == INVALID_HANDLE_VALUE) {
1825 DWORD index;
1826 DWORD start_ticks;
1827 HANDLE process = 0;
1828 if (tries == 1) {
1829 if ( (hres = create_local_service(rclsid)) &&
1830 (hres = create_server(rclsid, &process)) )
1831 return hres;
1832 } else {
1833 WARN("Connecting to %s, no response yet, retrying: le is %u\n", debugstr_w(pipefn), GetLastError());
1835 /* wait for one second, even if messages arrive */
1836 start_ticks = GetTickCount();
1837 do {
1838 if (SUCCEEDED(CoWaitForMultipleHandles(0, 1000, (process != 0),
1839 &process, &index)) && process && !index)
1841 WARN( "server for %s failed to start\n", debugstr_guid(rclsid) );
1842 CloseHandle( hPipe );
1843 CloseHandle( process );
1844 return E_NOINTERFACE;
1846 } while (GetTickCount() - start_ticks < 1000);
1847 if (process) CloseHandle( process );
1848 continue;
1850 bufferlen = 0;
1851 if (!ReadFile(hPipe,marshalbuffer,sizeof(marshalbuffer),&bufferlen,NULL)) {
1852 FIXME("Failed to read marshal id from classfactory of %s.\n",debugstr_guid(rclsid));
1853 Sleep(1000);
1854 continue;
1856 TRACE("read marshal id from pipe\n");
1857 CloseHandle(hPipe);
1858 break;
1861 if (tries >= MAXTRIES)
1862 return E_NOINTERFACE;
1864 hres = CreateStreamOnHGlobal(0,TRUE,&pStm);
1865 if (hres != S_OK) return hres;
1866 hres = IStream_Write(pStm,marshalbuffer,bufferlen,&res);
1867 if (hres != S_OK) goto out;
1868 seekto.u.LowPart = 0;seekto.u.HighPart = 0;
1869 hres = IStream_Seek(pStm,seekto,STREAM_SEEK_SET,&newpos);
1871 TRACE("unmarshalling local server\n");
1872 hres = CoUnmarshalInterface(pStm, &IID_IServiceProvider, (void**)&local_server);
1873 if(SUCCEEDED(hres))
1874 hres = IServiceProvider_QueryService(local_server, rclsid, iid, ppv);
1875 IServiceProvider_Release(local_server);
1876 out:
1877 IStream_Release(pStm);
1878 return hres;
1882 struct local_server_params
1884 CLSID clsid;
1885 IStream *stream;
1886 HANDLE pipe;
1887 HANDLE stop_event;
1888 HANDLE thread;
1889 BOOL multi_use;
1892 /* FIXME: should call to rpcss instead */
1893 static DWORD WINAPI local_server_thread(LPVOID param)
1895 struct local_server_params * lsp = param;
1896 WCHAR pipefn[100];
1897 HRESULT hres;
1898 IStream *pStm = lsp->stream;
1899 STATSTG ststg;
1900 unsigned char *buffer;
1901 int buflen;
1902 LARGE_INTEGER seekto;
1903 ULARGE_INTEGER newpos;
1904 ULONG res;
1905 BOOL multi_use = lsp->multi_use;
1906 OVERLAPPED ovl;
1907 HANDLE pipe_event, hPipe = lsp->pipe, new_pipe;
1908 DWORD bytes;
1910 TRACE("Starting threader for %s.\n",debugstr_guid(&lsp->clsid));
1912 memset(&ovl, 0, sizeof(ovl));
1913 get_localserver_pipe_name(pipefn, &lsp->clsid);
1914 ovl.hEvent = pipe_event = CreateEventW(NULL, FALSE, FALSE, NULL);
1916 while (1) {
1917 if (!ConnectNamedPipe(hPipe, &ovl))
1919 DWORD error = GetLastError();
1920 if (error == ERROR_IO_PENDING)
1922 HANDLE handles[2] = { pipe_event, lsp->stop_event };
1923 DWORD ret;
1924 ret = WaitForMultipleObjects(2, handles, FALSE, INFINITE);
1925 if (ret != WAIT_OBJECT_0)
1926 break;
1928 /* client already connected isn't an error */
1929 else if (error != ERROR_PIPE_CONNECTED)
1931 ERR("ConnectNamedPipe failed with error %d\n", GetLastError());
1932 break;
1936 TRACE("marshalling LocalServer to client\n");
1938 hres = IStream_Stat(pStm,&ststg,STATFLAG_NONAME);
1939 if (hres != S_OK)
1940 break;
1942 seekto.u.LowPart = 0;
1943 seekto.u.HighPart = 0;
1944 hres = IStream_Seek(pStm,seekto,STREAM_SEEK_SET,&newpos);
1945 if (hres != S_OK) {
1946 FIXME("IStream_Seek failed, %x\n",hres);
1947 break;
1950 buflen = ststg.cbSize.u.LowPart;
1951 buffer = HeapAlloc(GetProcessHeap(),0,buflen);
1953 hres = IStream_Read(pStm,buffer,buflen,&res);
1954 if (hres != S_OK) {
1955 FIXME("Stream Read failed, %x\n",hres);
1956 HeapFree(GetProcessHeap(),0,buffer);
1957 break;
1960 WriteFile(hPipe,buffer,buflen,&res,&ovl);
1961 GetOverlappedResult(hPipe, &ovl, &bytes, TRUE);
1962 HeapFree(GetProcessHeap(),0,buffer);
1964 FlushFileBuffers(hPipe);
1965 DisconnectNamedPipe(hPipe);
1966 TRACE("done marshalling LocalServer\n");
1968 if (!multi_use)
1970 TRACE("single use object, shutting down pipe %s\n", debugstr_w(pipefn));
1971 break;
1973 new_pipe = CreateNamedPipeW( pipefn, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
1974 PIPE_TYPE_BYTE|PIPE_WAIT, PIPE_UNLIMITED_INSTANCES,
1975 4096, 4096, 500 /* 0.5 second timeout */, NULL );
1976 if (new_pipe == INVALID_HANDLE_VALUE)
1978 FIXME("pipe creation failed for %s, le is %u\n", debugstr_w(pipefn), GetLastError());
1979 break;
1981 CloseHandle(hPipe);
1982 hPipe = new_pipe;
1985 CloseHandle(pipe_event);
1986 CloseHandle(hPipe);
1987 return 0;
1990 /* starts listening for a local server */
1991 HRESULT RPC_StartLocalServer(REFCLSID clsid, IStream *stream, BOOL multi_use, void **registration)
1993 DWORD tid, err;
1994 struct local_server_params *lsp;
1995 WCHAR pipefn[100];
1997 lsp = HeapAlloc(GetProcessHeap(), 0, sizeof(*lsp));
1998 if (!lsp)
1999 return E_OUTOFMEMORY;
2001 lsp->clsid = *clsid;
2002 lsp->stream = stream;
2003 IStream_AddRef(stream);
2004 lsp->stop_event = CreateEventW(NULL, FALSE, FALSE, NULL);
2005 if (!lsp->stop_event)
2007 HeapFree(GetProcessHeap(), 0, lsp);
2008 return HRESULT_FROM_WIN32(GetLastError());
2010 lsp->multi_use = multi_use;
2012 get_localserver_pipe_name(pipefn, &lsp->clsid);
2013 lsp->pipe = CreateNamedPipeW(pipefn, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
2014 PIPE_TYPE_BYTE|PIPE_WAIT, PIPE_UNLIMITED_INSTANCES,
2015 4096, 4096, 500 /* 0.5 second timeout */, NULL);
2016 if (lsp->pipe == INVALID_HANDLE_VALUE)
2018 err = GetLastError();
2019 FIXME("pipe creation failed for %s, le is %u\n", debugstr_w(pipefn), GetLastError());
2020 CloseHandle(lsp->stop_event);
2021 HeapFree(GetProcessHeap(), 0, lsp);
2022 return HRESULT_FROM_WIN32(err);
2025 lsp->thread = CreateThread(NULL, 0, local_server_thread, lsp, 0, &tid);
2026 if (!lsp->thread)
2028 CloseHandle(lsp->pipe);
2029 CloseHandle(lsp->stop_event);
2030 HeapFree(GetProcessHeap(), 0, lsp);
2031 return HRESULT_FROM_WIN32(GetLastError());
2034 *registration = lsp;
2035 return S_OK;
2038 /* stops listening for a local server */
2039 void RPC_StopLocalServer(void *registration)
2041 struct local_server_params *lsp = registration;
2043 /* signal local_server_thread to stop */
2044 SetEvent(lsp->stop_event);
2045 /* wait for it to exit */
2046 WaitForSingleObject(lsp->thread, INFINITE);
2048 IStream_Release(lsp->stream);
2049 CloseHandle(lsp->stop_event);
2050 CloseHandle(lsp->thread);
2051 HeapFree(GetProcessHeap(), 0, lsp);