api-ms-win-core-console-l1-2-0: Add dll.
[wine.git] / dlls / combase / rpc.c
blob55450ad7f140ab8dcf6a6acc7141e63acb47cda3
1 /*
2 * Copyright 2001 Ove Kåven, TransGaming Technologies
3 * Copyright 2002 Marcus Meissner
4 * Copyright 2005 Mike Hearn, Rob Shearman for CodeWeavers
6 * This library is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2.1 of the License, or (at your option) any later version.
11 * This library is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with this library; if not, write to the Free Software
18 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
21 #include <stdarg.h>
23 #define COBJMACROS
25 #include "windef.h"
26 #include "winbase.h"
27 #include "winsvc.h"
28 #include "servprov.h"
30 #include "wine/debug.h"
31 #include "wine/exception.h"
32 #include "wine/heap.h"
34 #include "combase_private.h"
36 #include "irpcss.h"
38 WINE_DEFAULT_DEBUG_CHANNEL(ole);
40 static void __RPC_STUB dispatch_rpc(RPC_MESSAGE *msg);
42 /* we only use one function to dispatch calls for all methods - we use the
43 * RPC_IF_OLE flag to tell the RPC runtime that this is the case */
44 static RPC_DISPATCH_FUNCTION rpc_dispatch_table[1] = { dispatch_rpc }; /* (RO) */
45 static RPC_DISPATCH_TABLE rpc_dispatch = { 1, rpc_dispatch_table }; /* (RO) */
47 static struct list registered_interfaces = LIST_INIT(registered_interfaces); /* (CS csRegIf) */
48 static CRITICAL_SECTION csRegIf;
49 static CRITICAL_SECTION_DEBUG csRegIf_debug =
51 0, 0, &csRegIf,
52 { &csRegIf_debug.ProcessLocksList, &csRegIf_debug.ProcessLocksList },
53 0, 0, { (DWORD_PTR)(__FILE__ ": dcom registered server interfaces") }
55 static CRITICAL_SECTION csRegIf = { &csRegIf_debug, -1, 0, 0, 0, 0 };
57 static struct list channel_hooks = LIST_INIT(channel_hooks); /* (CS csChannelHook) */
58 static CRITICAL_SECTION csChannelHook;
59 static CRITICAL_SECTION_DEBUG csChannelHook_debug =
61 0, 0, &csChannelHook,
62 { &csChannelHook_debug.ProcessLocksList, &csChannelHook_debug.ProcessLocksList },
63 0, 0, { (DWORD_PTR)(__FILE__ ": channel hooks") }
65 static CRITICAL_SECTION csChannelHook = { &csChannelHook_debug, -1, 0, 0, 0, 0 };
67 static WCHAR rpctransportW[] = L"ncalrpc";
69 struct registered_if
71 struct list entry;
72 DWORD refs; /* ref count */
73 RPC_SERVER_INTERFACE If; /* interface registered with the RPC runtime */
76 /* get the pipe endpoint specified of the specified apartment */
77 static inline void get_rpc_endpoint(LPWSTR endpoint, const OXID *oxid)
79 /* FIXME: should get endpoint from rpcss */
80 wsprintfW(endpoint, L"\\pipe\\OLE_%08lx%08lx", (DWORD)(*oxid >> 32), (DWORD)*oxid);
83 typedef struct
85 IRpcChannelBuffer IRpcChannelBuffer_iface;
86 LONG refs;
88 DWORD dest_context; /* returned from GetDestCtx */
89 void *dest_context_data; /* returned from GetDestCtx */
90 } RpcChannelBuffer;
92 typedef struct
94 RpcChannelBuffer super; /* superclass */
96 RPC_BINDING_HANDLE bind; /* handle to the remote server */
97 OXID oxid; /* apartment in which the channel is valid */
98 DWORD server_pid; /* id of server process */
99 HANDLE event; /* cached event handle */
100 IID iid; /* IID of the proxy this belongs to */
101 } ClientRpcChannelBuffer;
103 struct dispatch_params
105 RPCOLEMESSAGE *msg; /* message */
106 IRpcStubBuffer *stub; /* stub buffer, if applicable */
107 IRpcChannelBuffer *chan; /* server channel buffer, if applicable */
108 IID iid; /* ID of interface being called */
109 IUnknown *iface; /* interface being called */
110 HANDLE handle; /* handle that will become signaled when call finishes */
111 BOOL bypass_rpcrt; /* bypass RPC runtime? */
112 RPC_STATUS status; /* status (out) */
113 HRESULT hr; /* hresult (out) */
116 struct message_state
118 RPC_BINDING_HANDLE binding_handle;
119 ULONG prefix_data_len;
120 SChannelHookCallInfo channel_hook_info;
121 BOOL bypass_rpcrt;
123 /* client only */
124 HWND target_hwnd;
125 DWORD target_tid;
126 struct dispatch_params params;
129 typedef struct
131 ULONG conformance; /* NDR */
132 GUID id;
133 ULONG size;
134 /* [size_is((size+7)&~7)] */ unsigned char data[1];
135 } WIRE_ORPC_EXTENT;
137 typedef struct
139 ULONG size;
140 ULONG reserved;
141 unsigned char extent[1];
142 } WIRE_ORPC_EXTENT_ARRAY;
144 typedef struct
146 ULONG version;
147 ULONG flags;
148 ULONG reserved1;
149 GUID cid;
150 unsigned char extensions[1];
151 } WIRE_ORPCTHIS;
153 typedef struct
155 ULONG flags;
156 unsigned char extensions[1];
157 } WIRE_ORPCTHAT;
159 struct channel_hook_entry
161 struct list entry;
162 GUID id;
163 IChannelHook *hook;
166 struct channel_hook_buffer_data
168 GUID id;
169 ULONG extension_size;
171 void * __RPC_USER MIDL_user_allocate(SIZE_T size)
173 return heap_alloc(size);
176 void __RPC_USER MIDL_user_free(void *p)
178 heap_free(p);
181 static LONG WINAPI rpc_filter(EXCEPTION_POINTERS *eptr)
183 return I_RpcExceptionFilter(eptr->ExceptionRecord->ExceptionCode);
186 static BOOL start_rpcss(void)
188 SERVICE_STATUS_PROCESS status;
189 SC_HANDLE scm, service;
190 BOOL ret = FALSE;
192 TRACE("\n");
194 if (!(scm = OpenSCManagerW(NULL, NULL, 0)))
196 ERR("Failed to open service manager\n");
197 return FALSE;
200 if (!(service = OpenServiceW(scm, L"RpcSs", SERVICE_START | SERVICE_QUERY_STATUS)))
202 ERR("Failed to open RpcSs service\n");
203 CloseServiceHandle( scm );
204 return FALSE;
207 if (StartServiceW(service, 0, NULL) || GetLastError() == ERROR_SERVICE_ALREADY_RUNNING)
209 ULONGLONG start_time = GetTickCount64();
212 DWORD dummy;
214 if (!QueryServiceStatusEx(service, SC_STATUS_PROCESS_INFO, (BYTE *)&status, sizeof(status), &dummy))
215 break;
216 if (status.dwCurrentState == SERVICE_RUNNING)
218 ret = TRUE;
219 break;
221 if (GetTickCount64() - start_time > 30000) break;
222 Sleep( 100 );
224 } while (status.dwCurrentState == SERVICE_START_PENDING);
226 if (status.dwCurrentState != SERVICE_RUNNING)
227 WARN("RpcSs failed to start %u\n", status.dwCurrentState);
229 else
230 ERR("Failed to start RpcSs service\n");
232 CloseServiceHandle(service);
233 CloseServiceHandle(scm);
234 return ret;
237 static RPC_BINDING_HANDLE get_rpc_handle(unsigned short *protseq, unsigned short *endpoint)
239 RPC_BINDING_HANDLE handle = NULL;
240 RPC_STATUS status;
241 RPC_WSTR binding;
243 status = RpcStringBindingComposeW(NULL, protseq, NULL, endpoint, NULL, &binding);
244 if (status == RPC_S_OK)
246 status = RpcBindingFromStringBindingW(binding, &handle);
247 RpcStringFreeW(&binding);
250 return handle;
253 static RPC_BINDING_HANDLE get_irpcss_handle(void)
255 static RPC_BINDING_HANDLE irpcss_handle;
257 if (!irpcss_handle)
259 unsigned short protseq[] = IRPCSS_PROTSEQ;
260 unsigned short endpoint[] = IRPCSS_ENDPOINT;
262 RPC_BINDING_HANDLE new_handle = get_rpc_handle(protseq, endpoint);
263 if (InterlockedCompareExchangePointer(&irpcss_handle, new_handle, NULL))
264 /* another thread beat us to it */
265 RpcBindingFree(&new_handle);
267 return irpcss_handle;
270 static RPC_BINDING_HANDLE get_irot_handle(void)
272 static RPC_BINDING_HANDLE irot_handle;
274 if (!irot_handle)
276 unsigned short protseq[] = IROT_PROTSEQ;
277 unsigned short endpoint[] = IROT_ENDPOINT;
279 RPC_BINDING_HANDLE new_handle = get_rpc_handle(protseq, endpoint);
280 if (InterlockedCompareExchangePointer(&irot_handle, new_handle, NULL))
281 /* another thread beat us to it */
282 RpcBindingFree(&new_handle);
284 return irot_handle;
287 #define RPCSS_CALL_START \
288 HRESULT hr; \
289 for (;;) { \
290 __TRY {
292 #define RPCSS_CALL_END \
293 } __EXCEPT(rpc_filter) { \
294 hr = HRESULT_FROM_WIN32(GetExceptionCode()); \
296 __ENDTRY \
297 if (hr == HRESULT_FROM_WIN32(RPC_S_SERVER_UNAVAILABLE)) { \
298 if (start_rpcss()) \
299 continue; \
301 break; \
303 return hr;
305 HRESULT rpcss_get_next_seqid(DWORD *id)
307 RPCSS_CALL_START
308 hr = irpcss_get_thread_seq_id(get_irpcss_handle(), id);
309 RPCSS_CALL_END
312 HRESULT WINAPI InternalIrotRegister(const MonikerComparisonData *moniker_data,
313 const InterfaceData *object, const InterfaceData *moniker,
314 const FILETIME *time, DWORD flags, IrotCookie *cookie, IrotContextHandle *ctxt_handle)
316 RPCSS_CALL_START
317 hr = IrotRegister(get_irot_handle(), moniker_data, object, moniker, time, flags, cookie, ctxt_handle);
318 RPCSS_CALL_END
321 HRESULT WINAPI InternalIrotIsRunning(const MonikerComparisonData *moniker_data)
323 RPCSS_CALL_START
324 hr = IrotIsRunning(get_irot_handle(), moniker_data);
325 RPCSS_CALL_END
328 HRESULT WINAPI InternalIrotGetObject(const MonikerComparisonData *moniker_data, PInterfaceData *obj,
329 IrotCookie *cookie)
331 RPCSS_CALL_START
332 hr = IrotGetObject(get_irot_handle(), moniker_data, obj, cookie);
333 RPCSS_CALL_END
336 HRESULT WINAPI InternalIrotNoteChangeTime(IrotCookie cookie, const FILETIME *time)
338 RPCSS_CALL_START
339 hr = IrotNoteChangeTime(get_irot_handle(), cookie, time);
340 RPCSS_CALL_END
343 HRESULT WINAPI InternalIrotGetTimeOfLastChange(const MonikerComparisonData *moniker_data, FILETIME *time)
345 RPCSS_CALL_START
346 hr = IrotGetTimeOfLastChange(get_irot_handle(), moniker_data, time);
347 RPCSS_CALL_END
350 HRESULT WINAPI InternalIrotEnumRunning(PInterfaceList *list)
352 RPCSS_CALL_START
353 hr = IrotEnumRunning(get_irot_handle(), list);
354 RPCSS_CALL_END
357 HRESULT WINAPI InternalIrotRevoke(IrotCookie cookie, IrotContextHandle *ctxt_handle, PInterfaceData *object,
358 PInterfaceData *moniker)
360 RPCSS_CALL_START
361 hr = IrotRevoke(get_irot_handle(), cookie, ctxt_handle, object, moniker);
362 RPCSS_CALL_END
365 static HRESULT rpcss_server_register(REFCLSID clsid, DWORD flags, MInterfacePointer *obj, unsigned int *cookie)
367 RPCSS_CALL_START
368 hr = irpcss_server_register(get_irpcss_handle(), clsid, flags, obj, cookie);
369 RPCSS_CALL_END
372 HRESULT rpc_revoke_local_server(unsigned int cookie)
374 RPCSS_CALL_START
375 hr = irpcss_server_revoke(get_irpcss_handle(), cookie);
376 RPCSS_CALL_END
379 static HRESULT rpcss_get_class_object(REFCLSID rclsid, PMInterfacePointer *objref)
381 RPCSS_CALL_START
382 hr = irpcss_get_class_object(get_irpcss_handle(), rclsid, objref);
383 RPCSS_CALL_END
386 static DWORD start_local_service(const WCHAR *name, DWORD num, LPCWSTR *params)
388 SC_HANDLE handle, hsvc;
389 DWORD r = ERROR_FUNCTION_FAILED;
391 TRACE("Starting service %s %d params\n", debugstr_w(name), num);
393 handle = OpenSCManagerW(NULL, NULL, SC_MANAGER_CONNECT);
394 if (!handle)
395 return r;
396 hsvc = OpenServiceW(handle, name, SERVICE_START);
397 if (hsvc)
399 if(StartServiceW(hsvc, num, params))
400 r = ERROR_SUCCESS;
401 else
402 r = GetLastError();
403 if (r == ERROR_SERVICE_ALREADY_RUNNING)
404 r = ERROR_SUCCESS;
405 CloseServiceHandle(hsvc);
407 else
408 r = GetLastError();
409 CloseServiceHandle(handle);
411 TRACE("StartService returned error %u (%s)\n", r, (r == ERROR_SUCCESS) ? "ok":"failed");
413 return r;
417 * create_local_service() - start a COM server in a service
419 * To start a Local Service, we read the AppID value under
420 * the class's CLSID key, then open the HKCR\\AppId key specified
421 * there and check for a LocalService value.
423 * Note: Local Services are not supported under Windows 9x
425 static HRESULT create_local_service(REFCLSID rclsid)
427 HRESULT hr;
428 WCHAR buf[CHARS_IN_GUID];
429 HKEY hkey;
430 LONG r;
431 DWORD type, sz;
433 TRACE("Attempting to start Local service for %s\n", debugstr_guid(rclsid));
435 hr = open_appidkey_from_clsid(rclsid, KEY_READ, &hkey);
436 if (FAILED(hr))
437 return hr;
439 /* read the LocalService and ServiceParameters values from the AppID key */
440 sz = sizeof buf;
441 r = RegQueryValueExW(hkey, L"LocalService", NULL, &type, (LPBYTE)buf, &sz);
442 if (r == ERROR_SUCCESS && type == REG_SZ)
444 DWORD num_args = 0;
445 LPWSTR args[1] = { NULL };
448 * FIXME: I'm not really sure how to deal with the service parameters.
449 * I suspect that the string returned from RegQueryValueExW
450 * should be split into a number of arguments by spaces.
451 * It would make more sense if ServiceParams contained a
452 * REG_MULTI_SZ here, but it's a REG_SZ for the services
453 * that I'm interested in for the moment.
455 r = RegQueryValueExW(hkey, L"ServiceParams", NULL, &type, NULL, &sz);
456 if (r == ERROR_SUCCESS && type == REG_SZ && sz)
458 args[0] = HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY,sz);
459 num_args++;
460 RegQueryValueExW(hkey, L"ServiceParams", NULL, &type, (LPBYTE)args[0], &sz);
462 r = start_local_service(buf, num_args, (LPCWSTR *)args);
463 if (r != ERROR_SUCCESS)
464 hr = REGDB_E_CLASSNOTREG; /* FIXME: check retval */
465 HeapFree(GetProcessHeap(),0,args[0]);
467 else
469 WARN("No LocalService value\n");
470 hr = REGDB_E_CLASSNOTREG; /* FIXME: check retval */
472 RegCloseKey(hkey);
474 return hr;
477 static HRESULT create_server(REFCLSID rclsid, HANDLE *process)
479 static const WCHAR embeddingW[] = L" -Embedding";
480 HKEY key;
481 HRESULT hr;
482 WCHAR command[MAX_PATH + ARRAY_SIZE(embeddingW)];
483 DWORD size = (MAX_PATH+1) * sizeof(WCHAR);
484 STARTUPINFOW sinfo;
485 PROCESS_INFORMATION pinfo;
486 LONG ret;
488 hr = open_key_for_clsid(rclsid, L"LocalServer32", KEY_READ, &key);
489 if (FAILED(hr))
491 ERR("class %s not registered\n", debugstr_guid(rclsid));
492 return hr;
495 ret = RegQueryValueExW(key, NULL, NULL, NULL, (LPBYTE)command, &size);
496 RegCloseKey(key);
497 if (ret)
499 WARN("No default value for LocalServer32 key\n");
500 return REGDB_E_CLASSNOTREG; /* FIXME: check retval */
503 memset(&sinfo, 0, sizeof(sinfo));
504 sinfo.cb = sizeof(sinfo);
506 /* EXE servers are started with the -Embedding switch. */
508 lstrcatW(command, embeddingW);
510 TRACE("activating local server %s for %s\n", debugstr_w(command), debugstr_guid(rclsid));
512 /* FIXME: Win2003 supports a ServerExecutable value that is passed into
513 * CreateProcess */
514 if (!CreateProcessW(NULL, command, NULL, NULL, FALSE, DETACHED_PROCESS, NULL, NULL, &sinfo, &pinfo))
516 WARN("failed to run local server %s\n", debugstr_w(command));
517 return HRESULT_FROM_WIN32(GetLastError());
519 *process = pinfo.hProcess;
520 CloseHandle(pinfo.hThread);
522 return S_OK;
525 HRESULT rpc_get_local_class_object(REFCLSID rclsid, REFIID riid, void **obj)
527 PMInterfacePointer objref = NULL;
528 IServiceProvider *local_server;
529 IStream *stream = NULL;
530 ULARGE_INTEGER newpos;
531 LARGE_INTEGER seekto;
532 int tries = 0;
533 ULONG length;
534 HRESULT hr;
535 static const int MAXTRIES = 30; /* 30 seconds */
537 TRACE("clsid %s, riid %s\n", debugstr_guid(rclsid), debugstr_guid(riid));
539 while (tries++ < MAXTRIES)
541 DWORD index, start_ticks;
542 HANDLE process = 0;
544 if (SUCCEEDED(hr = rpcss_get_class_object(rclsid, &objref)))
545 break;
547 if (tries == 1)
549 if ((hr = create_local_service(rclsid)) && (hr = create_server(rclsid, &process)) )
550 return hr;
553 /* Wait for one second, even if messages arrive. */
554 start_ticks = GetTickCount();
557 if (SUCCEEDED(CoWaitForMultipleHandles(0, 1000, (process != 0), &process, &index)) && process && !index)
559 WARN("Server for %s failed to start.\n", debugstr_guid(rclsid));
560 CloseHandle(process);
561 return E_NOINTERFACE;
563 } while (GetTickCount() - start_ticks < 1000);
565 if (process) CloseHandle(process);
568 if (!objref || tries >= MAXTRIES)
569 return E_NOINTERFACE;
571 if (SUCCEEDED(hr = CreateStreamOnHGlobal(0, TRUE, &stream)))
572 hr = IStream_Write(stream, objref->abData, objref->ulCntData, &length);
574 MIDL_user_free(objref);
576 if (SUCCEEDED(hr))
578 seekto.QuadPart = 0;
579 IStream_Seek(stream, seekto, STREAM_SEEK_SET, &newpos);
581 TRACE("Unmarshalling local server.\n");
582 hr = CoUnmarshalInterface(stream, &IID_IServiceProvider, (void **)&local_server);
583 if (SUCCEEDED(hr))
585 hr = IServiceProvider_QueryService(local_server, rclsid, riid, obj);
586 IServiceProvider_Release(local_server);
590 if (stream)
591 IStream_Release(stream);
593 return hr;
596 HRESULT rpc_register_local_server(REFCLSID clsid, IStream *stream, DWORD flags, unsigned int *cookie)
598 MInterfacePointer *obj;
599 const void *ptr;
600 HGLOBAL hmem;
601 SIZE_T size;
602 HRESULT hr;
604 TRACE("%s, %#x\n", debugstr_guid(clsid), flags);
606 hr = GetHGlobalFromStream(stream, &hmem);
607 if (FAILED(hr)) return hr;
609 size = GlobalSize(hmem);
610 if (!(obj = heap_alloc(FIELD_OFFSET(MInterfacePointer, abData[size]))))
611 return E_OUTOFMEMORY;
612 obj->ulCntData = size;
613 ptr = GlobalLock(hmem);
614 memcpy(obj->abData, ptr, size);
615 GlobalUnlock(hmem);
617 hr = rpcss_server_register(clsid, flags, obj, cookie);
619 heap_free(obj);
621 return hr;
624 static HRESULT unmarshal_ORPCTHAT(RPC_MESSAGE *msg, ORPCTHAT *orpcthat, ORPC_EXTENT_ARRAY *orpc_ext_array,
625 WIRE_ORPC_EXTENT **first_wire_orpc_extent);
627 /* Channel Hook Functions */
629 static ULONG ChannelHooks_ClientGetSize(SChannelHookCallInfo *info, struct channel_hook_buffer_data **data,
630 unsigned int *hook_count, ULONG *extension_count)
632 struct channel_hook_entry *entry;
633 ULONG total_size = 0;
634 unsigned int hook_index = 0;
636 *hook_count = 0;
637 *extension_count = 0;
639 EnterCriticalSection(&csChannelHook);
641 LIST_FOR_EACH_ENTRY(entry, &channel_hooks, struct channel_hook_entry, entry)
642 (*hook_count)++;
644 if (*hook_count)
645 *data = HeapAlloc(GetProcessHeap(), 0, *hook_count * sizeof(struct channel_hook_buffer_data));
646 else
647 *data = NULL;
649 LIST_FOR_EACH_ENTRY(entry, &channel_hooks, struct channel_hook_entry, entry)
651 ULONG extension_size = 0;
653 IChannelHook_ClientGetSize(entry->hook, &entry->id, &info->iid, &extension_size);
655 TRACE("%s: extension_size = %u\n", debugstr_guid(&entry->id), extension_size);
657 extension_size = (extension_size+7)&~7;
658 (*data)[hook_index].id = entry->id;
659 (*data)[hook_index].extension_size = extension_size;
661 /* an extension is only put onto the wire if it has data to write */
662 if (extension_size)
664 total_size += FIELD_OFFSET(WIRE_ORPC_EXTENT, data[extension_size]);
665 (*extension_count)++;
668 hook_index++;
671 LeaveCriticalSection(&csChannelHook);
673 return total_size;
676 static unsigned char * ChannelHooks_ClientFillBuffer(SChannelHookCallInfo *info,
677 unsigned char *buffer, struct channel_hook_buffer_data *data,
678 unsigned int hook_count)
680 struct channel_hook_entry *entry;
682 EnterCriticalSection(&csChannelHook);
684 LIST_FOR_EACH_ENTRY(entry, &channel_hooks, struct channel_hook_entry, entry)
686 unsigned int i;
687 ULONG extension_size = 0;
688 WIRE_ORPC_EXTENT *wire_orpc_extent = (WIRE_ORPC_EXTENT *)buffer;
690 for (i = 0; i < hook_count; i++)
691 if (IsEqualGUID(&entry->id, &data[i].id))
692 extension_size = data[i].extension_size;
694 /* an extension is only put onto the wire if it has data to write */
695 if (!extension_size)
696 continue;
698 IChannelHook_ClientFillBuffer(entry->hook, &entry->id, &info->iid,
699 &extension_size, buffer + FIELD_OFFSET(WIRE_ORPC_EXTENT, data[0]));
701 TRACE("%s: extension_size = %u\n", debugstr_guid(&entry->id), extension_size);
703 /* FIXME: set unused portion of wire_orpc_extent->data to 0? */
705 wire_orpc_extent->conformance = (extension_size+7)&~7;
706 wire_orpc_extent->size = extension_size;
707 wire_orpc_extent->id = entry->id;
708 buffer += FIELD_OFFSET(WIRE_ORPC_EXTENT, data[wire_orpc_extent->conformance]);
711 LeaveCriticalSection(&csChannelHook);
713 return buffer;
716 static void ChannelHooks_ServerNotify(SChannelHookCallInfo *info,
717 DWORD lDataRep, WIRE_ORPC_EXTENT *first_wire_orpc_extent,
718 ULONG extension_count)
720 struct channel_hook_entry *entry;
721 ULONG i;
723 EnterCriticalSection(&csChannelHook);
725 LIST_FOR_EACH_ENTRY(entry, &channel_hooks, struct channel_hook_entry, entry)
727 WIRE_ORPC_EXTENT *wire_orpc_extent;
728 for (i = 0, wire_orpc_extent = first_wire_orpc_extent;
729 i < extension_count;
730 i++, wire_orpc_extent = (WIRE_ORPC_EXTENT *)&wire_orpc_extent->data[wire_orpc_extent->conformance])
732 if (IsEqualGUID(&entry->id, &wire_orpc_extent->id))
733 break;
735 if (i == extension_count) wire_orpc_extent = NULL;
737 IChannelHook_ServerNotify(entry->hook, &entry->id, &info->iid,
738 wire_orpc_extent ? wire_orpc_extent->size : 0,
739 wire_orpc_extent ? wire_orpc_extent->data : NULL,
740 lDataRep);
743 LeaveCriticalSection(&csChannelHook);
746 static ULONG ChannelHooks_ServerGetSize(SChannelHookCallInfo *info,
747 struct channel_hook_buffer_data **data, unsigned int *hook_count,
748 ULONG *extension_count)
750 struct channel_hook_entry *entry;
751 ULONG total_size = 0;
752 unsigned int hook_index = 0;
754 *hook_count = 0;
755 *extension_count = 0;
757 EnterCriticalSection(&csChannelHook);
759 LIST_FOR_EACH_ENTRY(entry, &channel_hooks, struct channel_hook_entry, entry)
760 (*hook_count)++;
762 if (*hook_count)
763 *data = HeapAlloc(GetProcessHeap(), 0, *hook_count * sizeof(struct channel_hook_buffer_data));
764 else
765 *data = NULL;
767 LIST_FOR_EACH_ENTRY(entry, &channel_hooks, struct channel_hook_entry, entry)
769 ULONG extension_size = 0;
771 IChannelHook_ServerGetSize(entry->hook, &entry->id, &info->iid, S_OK,
772 &extension_size);
774 TRACE("%s: extension_size = %u\n", debugstr_guid(&entry->id), extension_size);
776 extension_size = (extension_size+7)&~7;
777 (*data)[hook_index].id = entry->id;
778 (*data)[hook_index].extension_size = extension_size;
780 /* an extension is only put onto the wire if it has data to write */
781 if (extension_size)
783 total_size += FIELD_OFFSET(WIRE_ORPC_EXTENT, data[extension_size]);
784 (*extension_count)++;
787 hook_index++;
790 LeaveCriticalSection(&csChannelHook);
792 return total_size;
795 static unsigned char * ChannelHooks_ServerFillBuffer(SChannelHookCallInfo *info,
796 unsigned char *buffer, struct channel_hook_buffer_data *data,
797 unsigned int hook_count)
799 struct channel_hook_entry *entry;
801 EnterCriticalSection(&csChannelHook);
803 LIST_FOR_EACH_ENTRY(entry, &channel_hooks, struct channel_hook_entry, entry)
805 unsigned int i;
806 ULONG extension_size = 0;
807 WIRE_ORPC_EXTENT *wire_orpc_extent = (WIRE_ORPC_EXTENT *)buffer;
809 for (i = 0; i < hook_count; i++)
810 if (IsEqualGUID(&entry->id, &data[i].id))
811 extension_size = data[i].extension_size;
813 /* an extension is only put onto the wire if it has data to write */
814 if (!extension_size)
815 continue;
817 IChannelHook_ServerFillBuffer(entry->hook, &entry->id, &info->iid,
818 &extension_size, buffer + FIELD_OFFSET(WIRE_ORPC_EXTENT, data[0]),
819 S_OK);
821 TRACE("%s: extension_size = %u\n", debugstr_guid(&entry->id), extension_size);
823 /* FIXME: set unused portion of wire_orpc_extent->data to 0? */
825 wire_orpc_extent->conformance = (extension_size+7)&~7;
826 wire_orpc_extent->size = extension_size;
827 wire_orpc_extent->id = entry->id;
828 buffer += FIELD_OFFSET(WIRE_ORPC_EXTENT, data[wire_orpc_extent->conformance]);
831 LeaveCriticalSection(&csChannelHook);
833 return buffer;
836 static void ChannelHooks_ClientNotify(SChannelHookCallInfo *info,
837 DWORD lDataRep, WIRE_ORPC_EXTENT *first_wire_orpc_extent,
838 ULONG extension_count, HRESULT hrFault)
840 struct channel_hook_entry *entry;
841 ULONG i;
843 EnterCriticalSection(&csChannelHook);
845 LIST_FOR_EACH_ENTRY(entry, &channel_hooks, struct channel_hook_entry, entry)
847 WIRE_ORPC_EXTENT *wire_orpc_extent;
848 for (i = 0, wire_orpc_extent = first_wire_orpc_extent;
849 i < extension_count;
850 i++, wire_orpc_extent = (WIRE_ORPC_EXTENT *)&wire_orpc_extent->data[wire_orpc_extent->conformance])
852 if (IsEqualGUID(&entry->id, &wire_orpc_extent->id))
853 break;
855 if (i == extension_count) wire_orpc_extent = NULL;
857 IChannelHook_ClientNotify(entry->hook, &entry->id, &info->iid,
858 wire_orpc_extent ? wire_orpc_extent->size : 0,
859 wire_orpc_extent ? wire_orpc_extent->data : NULL,
860 lDataRep, hrFault);
863 LeaveCriticalSection(&csChannelHook);
866 HRESULT rpc_register_channel_hook(REFGUID rguid, IChannelHook *hook)
868 struct channel_hook_entry *entry;
870 entry = HeapAlloc(GetProcessHeap(), 0, sizeof(*entry));
871 if (!entry)
872 return E_OUTOFMEMORY;
874 entry->id = *rguid;
875 entry->hook = hook;
876 IChannelHook_AddRef(hook);
878 EnterCriticalSection(&csChannelHook);
879 list_add_tail(&channel_hooks, &entry->entry);
880 LeaveCriticalSection(&csChannelHook);
882 return S_OK;
885 void rpc_unregister_channel_hooks(void)
887 struct channel_hook_entry *cursor;
888 struct channel_hook_entry *cursor2;
890 EnterCriticalSection(&csChannelHook);
891 LIST_FOR_EACH_ENTRY_SAFE(cursor, cursor2, &channel_hooks, struct channel_hook_entry, entry)
892 HeapFree(GetProcessHeap(), 0, cursor);
893 LeaveCriticalSection(&csChannelHook);
894 DeleteCriticalSection(&csChannelHook);
895 DeleteCriticalSection(&csRegIf);
898 /* RPC Channel Buffer Functions */
900 static HRESULT WINAPI RpcChannelBuffer_QueryInterface(IRpcChannelBuffer *iface, REFIID riid, LPVOID *ppv)
902 *ppv = NULL;
903 if (IsEqualIID(riid,&IID_IRpcChannelBuffer) || IsEqualIID(riid,&IID_IUnknown))
905 *ppv = iface;
906 IRpcChannelBuffer_AddRef(iface);
907 return S_OK;
909 return E_NOINTERFACE;
912 static ULONG WINAPI RpcChannelBuffer_AddRef(LPRPCCHANNELBUFFER iface)
914 RpcChannelBuffer *This = (RpcChannelBuffer *)iface;
915 return InterlockedIncrement(&This->refs);
918 static ULONG WINAPI ServerRpcChannelBuffer_Release(LPRPCCHANNELBUFFER iface)
920 RpcChannelBuffer *This = (RpcChannelBuffer *)iface;
921 ULONG ref;
923 ref = InterlockedDecrement(&This->refs);
924 if (ref)
925 return ref;
927 HeapFree(GetProcessHeap(), 0, This);
928 return 0;
931 static ULONG WINAPI ClientRpcChannelBuffer_Release(LPRPCCHANNELBUFFER iface)
933 ClientRpcChannelBuffer *This = (ClientRpcChannelBuffer *)iface;
934 ULONG ref;
936 ref = InterlockedDecrement(&This->super.refs);
937 if (ref)
938 return ref;
940 if (This->event) CloseHandle(This->event);
941 RpcBindingFree(&This->bind);
942 HeapFree(GetProcessHeap(), 0, This);
943 return 0;
946 static HRESULT WINAPI ServerRpcChannelBuffer_GetBuffer(LPRPCCHANNELBUFFER iface, RPCOLEMESSAGE* olemsg, REFIID riid)
948 RpcChannelBuffer *This = (RpcChannelBuffer *)iface;
949 RPC_MESSAGE *msg = (RPC_MESSAGE *)olemsg;
950 RPC_STATUS status;
951 ORPCTHAT *orpcthat;
952 struct message_state *message_state;
953 ULONG extensions_size;
954 struct channel_hook_buffer_data *channel_hook_data;
955 unsigned int channel_hook_count;
956 ULONG extension_count;
958 TRACE("(%p)->(%p,%s)\n", This, olemsg, debugstr_guid(riid));
960 message_state = msg->Handle;
961 /* restore the binding handle and the real start of data */
962 msg->Handle = message_state->binding_handle;
963 msg->Buffer = (char *)msg->Buffer - message_state->prefix_data_len;
965 extensions_size = ChannelHooks_ServerGetSize(&message_state->channel_hook_info,
966 &channel_hook_data, &channel_hook_count, &extension_count);
968 msg->BufferLength += FIELD_OFFSET(WIRE_ORPCTHAT, extensions) + sizeof(DWORD);
969 if (extensions_size)
971 msg->BufferLength += FIELD_OFFSET(WIRE_ORPC_EXTENT_ARRAY, extent[2*sizeof(DWORD) + extensions_size]);
972 if (extension_count & 1)
973 msg->BufferLength += FIELD_OFFSET(WIRE_ORPC_EXTENT, data[0]);
976 if (message_state->bypass_rpcrt)
978 msg->Buffer = HeapAlloc(GetProcessHeap(), 0, msg->BufferLength);
979 if (msg->Buffer)
980 status = RPC_S_OK;
981 else
983 HeapFree(GetProcessHeap(), 0, channel_hook_data);
984 return E_OUTOFMEMORY;
987 else
988 status = I_RpcGetBuffer(msg);
990 orpcthat = msg->Buffer;
991 msg->Buffer = (char *)msg->Buffer + FIELD_OFFSET(WIRE_ORPCTHAT, extensions);
993 orpcthat->flags = ORPCF_NULL /* FIXME? */;
995 /* NDR representation of orpcthat->extensions */
996 *(DWORD *)msg->Buffer = extensions_size ? 1 : 0;
997 msg->Buffer = (char *)msg->Buffer + sizeof(DWORD);
999 if (extensions_size)
1001 WIRE_ORPC_EXTENT_ARRAY *orpc_extent_array = msg->Buffer;
1002 orpc_extent_array->size = extension_count;
1003 orpc_extent_array->reserved = 0;
1004 msg->Buffer = (char *)msg->Buffer + FIELD_OFFSET(WIRE_ORPC_EXTENT_ARRAY, extent);
1005 /* NDR representation of orpc_extent_array->extent */
1006 *(DWORD *)msg->Buffer = 1;
1007 msg->Buffer = (char *)msg->Buffer + sizeof(DWORD);
1008 /* NDR representation of [size_is] attribute of orpc_extent_array->extent */
1009 *(DWORD *)msg->Buffer = (extension_count + 1) & ~1;
1010 msg->Buffer = (char *)msg->Buffer + sizeof(DWORD);
1012 msg->Buffer = ChannelHooks_ServerFillBuffer(&message_state->channel_hook_info,
1013 msg->Buffer, channel_hook_data, channel_hook_count);
1015 /* we must add a dummy extension if there is an odd extension
1016 * count to meet the contract specified by the size_is attribute */
1017 if (extension_count & 1)
1019 WIRE_ORPC_EXTENT *wire_orpc_extent = msg->Buffer;
1020 wire_orpc_extent->conformance = 0;
1021 wire_orpc_extent->id = GUID_NULL;
1022 wire_orpc_extent->size = 0;
1023 msg->Buffer = (char *)msg->Buffer + FIELD_OFFSET(WIRE_ORPC_EXTENT, data[0]);
1027 HeapFree(GetProcessHeap(), 0, channel_hook_data);
1029 /* store the prefixed data length so that we can restore the real buffer
1030 * later */
1031 message_state->prefix_data_len = (char *)msg->Buffer - (char *)orpcthat;
1032 msg->BufferLength -= message_state->prefix_data_len;
1033 /* save away the message state again */
1034 msg->Handle = message_state;
1036 TRACE("-- %d\n", status);
1038 return HRESULT_FROM_WIN32(status);
1041 static HANDLE ClientRpcChannelBuffer_GetEventHandle(ClientRpcChannelBuffer *This)
1043 HANDLE event = InterlockedExchangePointer(&This->event, NULL);
1045 /* Note: must be auto-reset event so we can reuse it without a call
1046 * to ResetEvent */
1047 if (!event) event = CreateEventW(NULL, FALSE, FALSE, NULL);
1049 return event;
1052 static void ClientRpcChannelBuffer_ReleaseEventHandle(ClientRpcChannelBuffer *This, HANDLE event)
1054 if (InterlockedCompareExchangePointer(&This->event, event, NULL))
1055 /* already a handle cached in This */
1056 CloseHandle(event);
1059 static HRESULT WINAPI ClientRpcChannelBuffer_GetBuffer(LPRPCCHANNELBUFFER iface, RPCOLEMESSAGE* olemsg, REFIID riid)
1061 ClientRpcChannelBuffer *This = (ClientRpcChannelBuffer *)iface;
1062 RPC_MESSAGE *msg = (RPC_MESSAGE *)olemsg;
1063 RPC_CLIENT_INTERFACE *cif;
1064 RPC_STATUS status;
1065 ORPCTHIS *orpcthis;
1066 struct message_state *message_state;
1067 ULONG extensions_size;
1068 struct channel_hook_buffer_data *channel_hook_data;
1069 unsigned int channel_hook_count;
1070 ULONG extension_count;
1071 IPID ipid;
1072 HRESULT hr;
1073 struct apartment *apt = NULL;
1075 TRACE("(%p)->(%p,%s)\n", This, olemsg, debugstr_guid(riid));
1077 cif = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(RPC_CLIENT_INTERFACE));
1078 if (!cif)
1079 return E_OUTOFMEMORY;
1081 message_state = HeapAlloc(GetProcessHeap(), 0, sizeof(*message_state));
1082 if (!message_state)
1084 HeapFree(GetProcessHeap(), 0, cif);
1085 return E_OUTOFMEMORY;
1088 cif->Length = sizeof(RPC_CLIENT_INTERFACE);
1089 /* RPC interface ID = COM interface ID */
1090 cif->InterfaceId.SyntaxGUID = This->iid;
1091 /* COM objects always have a version of 0.0 */
1092 cif->InterfaceId.SyntaxVersion.MajorVersion = 0;
1093 cif->InterfaceId.SyntaxVersion.MinorVersion = 0;
1094 msg->Handle = This->bind;
1095 msg->RpcInterfaceInformation = cif;
1097 message_state->prefix_data_len = 0;
1098 message_state->binding_handle = This->bind;
1100 message_state->channel_hook_info.iid = *riid;
1101 message_state->channel_hook_info.cbSize = sizeof(message_state->channel_hook_info);
1102 CoGetCurrentLogicalThreadId(&message_state->channel_hook_info.uCausality);
1103 message_state->channel_hook_info.dwServerPid = This->server_pid;
1104 message_state->channel_hook_info.iMethod = msg->ProcNum & ~RPC_FLAGS_VALID_BIT;
1105 message_state->channel_hook_info.pObject = NULL; /* only present on server-side */
1106 message_state->target_hwnd = NULL;
1107 message_state->target_tid = 0;
1108 memset(&message_state->params, 0, sizeof(message_state->params));
1110 extensions_size = ChannelHooks_ClientGetSize(&message_state->channel_hook_info,
1111 &channel_hook_data, &channel_hook_count, &extension_count);
1113 msg->BufferLength += FIELD_OFFSET(WIRE_ORPCTHIS, extensions) + sizeof(DWORD);
1114 if (extensions_size)
1116 msg->BufferLength += FIELD_OFFSET(WIRE_ORPC_EXTENT_ARRAY, extent[2*sizeof(DWORD) + extensions_size]);
1117 if (extension_count & 1)
1118 msg->BufferLength += FIELD_OFFSET(WIRE_ORPC_EXTENT, data[0]);
1121 RpcBindingInqObject(message_state->binding_handle, &ipid);
1122 hr = ipid_get_dispatch_params(&ipid, &apt, NULL, &message_state->params.stub,
1123 &message_state->params.chan,
1124 &message_state->params.iid,
1125 &message_state->params.iface);
1126 if (hr == S_OK)
1128 /* stub, chan, iface and iid are unneeded in multi-threaded case as we go
1129 * via the RPC runtime */
1130 if (apt->multi_threaded)
1132 IRpcStubBuffer_Release(message_state->params.stub);
1133 message_state->params.stub = NULL;
1134 IRpcChannelBuffer_Release(message_state->params.chan);
1135 message_state->params.chan = NULL;
1136 message_state->params.iface = NULL;
1138 else
1140 message_state->params.bypass_rpcrt = TRUE;
1141 message_state->target_hwnd = apartment_getwindow(apt);
1142 message_state->target_tid = apt->tid;
1143 /* we assume later on that this being non-NULL is the indicator that
1144 * means call directly instead of going through RPC runtime */
1145 if (!message_state->target_hwnd)
1146 ERR("window for apartment %s is NULL\n", wine_dbgstr_longlong(apt->oxid));
1149 if (apt) apartment_release(apt);
1150 message_state->params.handle = ClientRpcChannelBuffer_GetEventHandle(This);
1151 /* Note: message_state->params.msg is initialised in
1152 * ClientRpcChannelBuffer_SendReceive */
1154 /* shortcut the RPC runtime */
1155 if (message_state->target_hwnd)
1157 msg->Buffer = HeapAlloc(GetProcessHeap(), 0, msg->BufferLength);
1158 if (msg->Buffer)
1159 status = RPC_S_OK;
1160 else
1161 status = ERROR_OUTOFMEMORY;
1163 else
1164 status = I_RpcGetBuffer(msg);
1166 msg->Handle = message_state;
1168 if (status == RPC_S_OK)
1170 orpcthis = msg->Buffer;
1171 msg->Buffer = (char *)msg->Buffer + FIELD_OFFSET(WIRE_ORPCTHIS, extensions);
1173 orpcthis->version.MajorVersion = COM_MAJOR_VERSION;
1174 orpcthis->version.MinorVersion = COM_MINOR_VERSION;
1175 orpcthis->flags = message_state->channel_hook_info.dwServerPid ? ORPCF_LOCAL : ORPCF_NULL;
1176 orpcthis->reserved1 = 0;
1177 orpcthis->cid = message_state->channel_hook_info.uCausality;
1179 /* NDR representation of orpcthis->extensions */
1180 *(DWORD *)msg->Buffer = extensions_size ? 1 : 0;
1181 msg->Buffer = (char *)msg->Buffer + sizeof(DWORD);
1183 if (extensions_size)
1185 ORPC_EXTENT_ARRAY *orpc_extent_array = msg->Buffer;
1186 orpc_extent_array->size = extension_count;
1187 orpc_extent_array->reserved = 0;
1188 msg->Buffer = (char *)msg->Buffer + FIELD_OFFSET(WIRE_ORPC_EXTENT_ARRAY, extent);
1189 /* NDR representation of orpc_extent_array->extent */
1190 *(DWORD *)msg->Buffer = 1;
1191 msg->Buffer = (char *)msg->Buffer + sizeof(DWORD);
1192 /* NDR representation of [size_is] attribute of orpc_extent_array->extent */
1193 *(DWORD *)msg->Buffer = (extension_count + 1) & ~1;
1194 msg->Buffer = (char *)msg->Buffer + sizeof(DWORD);
1196 msg->Buffer = ChannelHooks_ClientFillBuffer(&message_state->channel_hook_info,
1197 msg->Buffer, channel_hook_data, channel_hook_count);
1199 /* we must add a dummy extension if there is an odd extension
1200 * count to meet the contract specified by the size_is attribute */
1201 if (extension_count & 1)
1203 WIRE_ORPC_EXTENT *wire_orpc_extent = msg->Buffer;
1204 wire_orpc_extent->conformance = 0;
1205 wire_orpc_extent->id = GUID_NULL;
1206 wire_orpc_extent->size = 0;
1207 msg->Buffer = (char *)msg->Buffer + FIELD_OFFSET(WIRE_ORPC_EXTENT, data[0]);
1211 /* store the prefixed data length so that we can restore the real buffer
1212 * pointer in ClientRpcChannelBuffer_SendReceive. */
1213 message_state->prefix_data_len = (char *)msg->Buffer - (char *)orpcthis;
1214 msg->BufferLength -= message_state->prefix_data_len;
1217 HeapFree(GetProcessHeap(), 0, channel_hook_data);
1219 TRACE("-- %d\n", status);
1221 return HRESULT_FROM_WIN32(status);
1224 static HRESULT WINAPI ServerRpcChannelBuffer_SendReceive(LPRPCCHANNELBUFFER iface, RPCOLEMESSAGE *olemsg, ULONG *pstatus)
1226 FIXME("stub\n");
1227 return E_NOTIMPL;
1230 /* this thread runs an outgoing RPC */
1231 static DWORD WINAPI rpc_sendreceive_thread(LPVOID param)
1233 struct dispatch_params *data = param;
1235 /* Note: I_RpcSendReceive doesn't raise exceptions like the higher-level
1236 * RPC functions do */
1237 data->status = I_RpcSendReceive((RPC_MESSAGE *)data->msg);
1239 TRACE("completed with status 0x%x\n", data->status);
1241 SetEvent(data->handle);
1243 return 0;
1246 static inline HRESULT ClientRpcChannelBuffer_IsCorrectApartment(ClientRpcChannelBuffer *This, const struct apartment *apt)
1248 if (!apt)
1249 return S_FALSE;
1250 if (This->oxid != apartment_getoxid(apt))
1251 return S_FALSE;
1252 return S_OK;
1255 static HRESULT WINAPI ClientRpcChannelBuffer_SendReceive(LPRPCCHANNELBUFFER iface, RPCOLEMESSAGE *olemsg, ULONG *pstatus)
1257 ClientRpcChannelBuffer *This = (ClientRpcChannelBuffer *)iface;
1258 HRESULT hr;
1259 RPC_MESSAGE *msg = (RPC_MESSAGE *)olemsg;
1260 RPC_STATUS status;
1261 DWORD index;
1262 struct message_state *message_state;
1263 ORPCTHAT orpcthat;
1264 ORPC_EXTENT_ARRAY orpc_ext_array;
1265 WIRE_ORPC_EXTENT *first_wire_orpc_extent = NULL;
1266 HRESULT hrFault = S_OK;
1267 struct apartment *apt = apartment_get_current_or_mta();
1268 struct tlsdata *tlsdata;
1270 TRACE("(%p) iMethod=%d\n", olemsg, olemsg->iMethod);
1272 hr = ClientRpcChannelBuffer_IsCorrectApartment(This, apt);
1273 if (hr != S_OK)
1275 ERR("called from wrong apartment, should have been 0x%s\n",
1276 wine_dbgstr_longlong(This->oxid));
1277 if (apt) apartment_release(apt);
1278 return RPC_E_WRONG_THREAD;
1281 if (FAILED(hr = com_get_tlsdata(&tlsdata)))
1282 return hr;
1284 /* This situation should be impossible in multi-threaded apartments,
1285 * because the calling thread isn't re-enterable.
1286 * Note: doing a COM call during the processing of a sent message is
1287 * only disallowed if a client call is already being waited for
1288 * completion */
1289 if (!apt->multi_threaded &&
1290 tlsdata->pending_call_count_client &&
1291 InSendMessage())
1293 ERR("can't make an outgoing COM call in response to a sent message\n");
1294 apartment_release(apt);
1295 return RPC_E_CANTCALLOUT_ININPUTSYNCCALL;
1298 message_state = msg->Handle;
1299 /* restore the binding handle and the real start of data */
1300 msg->Handle = message_state->binding_handle;
1301 msg->Buffer = (char *)msg->Buffer - message_state->prefix_data_len;
1302 msg->BufferLength += message_state->prefix_data_len;
1304 /* Note: this is an optimization in the Microsoft OLE runtime that we need
1305 * to copy, as shown by the test_no_couninitialize_client test. without
1306 * short-circuiting the RPC runtime in the case below, the test will
1307 * deadlock on the loader lock due to the RPC runtime needing to create
1308 * a thread to process the RPC when this function is called indirectly
1309 * from DllMain */
1311 message_state->params.msg = olemsg;
1312 if (message_state->params.bypass_rpcrt)
1314 TRACE("Calling apartment thread 0x%08x...\n", message_state->target_tid);
1316 msg->ProcNum &= ~RPC_FLAGS_VALID_BIT;
1318 if (!PostMessageW(message_state->target_hwnd, DM_EXECUTERPC, 0,
1319 (LPARAM)&message_state->params))
1321 ERR("PostMessage failed with error %u\n", GetLastError());
1323 /* Note: message_state->params.iface doesn't have a reference and
1324 * so doesn't need to be released */
1326 hr = HRESULT_FROM_WIN32(GetLastError());
1329 else
1331 /* we use a separate thread here because we need to be able to
1332 * pump the message loop in the application thread: if we do not,
1333 * any windows created by this thread will hang and RPCs that try
1334 * and re-enter this STA from an incoming server thread will
1335 * deadlock. InstallShield is an example of that.
1337 if (!QueueUserWorkItem(rpc_sendreceive_thread, &message_state->params, WT_EXECUTEDEFAULT))
1339 ERR("QueueUserWorkItem failed with error %u\n", GetLastError());
1340 hr = E_UNEXPECTED;
1342 else
1343 hr = S_OK;
1346 if (hr == S_OK)
1348 if (WaitForSingleObject(message_state->params.handle, 0))
1350 tlsdata->pending_call_count_client++;
1351 hr = CoWaitForMultipleHandles(0, INFINITE, 1, &message_state->params.handle, &index);
1352 tlsdata->pending_call_count_client--;
1355 ClientRpcChannelBuffer_ReleaseEventHandle(This, message_state->params.handle);
1357 /* for WM shortcut, faults are returned in params->hr */
1358 if (hr == S_OK)
1359 hrFault = message_state->params.hr;
1361 status = message_state->params.status;
1363 orpcthat.flags = ORPCF_NULL;
1364 orpcthat.extensions = NULL;
1366 TRACE("RPC call status: 0x%x\n", status);
1367 if (status != RPC_S_OK)
1368 hr = HRESULT_FROM_WIN32(status);
1370 TRACE("hrFault = 0x%08x\n", hrFault);
1372 /* FIXME: this condition should be
1373 * "hr == S_OK && (!hrFault || msg->BufferLength > FIELD_OFFSET(ORPCTHAT, extensions) + 4)"
1374 * but we don't currently reset the message length for PostMessage
1375 * dispatched calls */
1376 if (hr == S_OK && hrFault == S_OK)
1378 HRESULT hr2;
1379 char *original_buffer = msg->Buffer;
1381 /* handle ORPCTHAT and client extensions */
1383 hr2 = unmarshal_ORPCTHAT(msg, &orpcthat, &orpc_ext_array, &first_wire_orpc_extent);
1384 if (FAILED(hr2))
1385 hr = hr2;
1387 message_state->prefix_data_len = (char *)msg->Buffer - original_buffer;
1388 msg->BufferLength -= message_state->prefix_data_len;
1390 else
1391 message_state->prefix_data_len = 0;
1393 if (hr == S_OK)
1395 ChannelHooks_ClientNotify(&message_state->channel_hook_info,
1396 msg->DataRepresentation,
1397 first_wire_orpc_extent,
1398 orpcthat.extensions && first_wire_orpc_extent ? orpcthat.extensions->size : 0,
1399 hrFault);
1402 /* save away the message state again */
1403 msg->Handle = message_state;
1405 if (pstatus) *pstatus = status;
1407 if (hr == S_OK)
1408 hr = hrFault;
1410 TRACE("-- 0x%08x\n", hr);
1412 apartment_release(apt);
1413 return hr;
1416 static HRESULT WINAPI ServerRpcChannelBuffer_FreeBuffer(LPRPCCHANNELBUFFER iface, RPCOLEMESSAGE* olemsg)
1418 RPC_MESSAGE *msg = (RPC_MESSAGE *)olemsg;
1419 RPC_STATUS status;
1420 struct message_state *message_state;
1422 TRACE("(%p)\n", msg);
1424 message_state = msg->Handle;
1425 /* restore the binding handle and the real start of data */
1426 msg->Handle = message_state->binding_handle;
1427 msg->Buffer = (char *)msg->Buffer - message_state->prefix_data_len;
1428 msg->BufferLength += message_state->prefix_data_len;
1429 message_state->prefix_data_len = 0;
1431 if (message_state->bypass_rpcrt)
1433 HeapFree(GetProcessHeap(), 0, msg->Buffer);
1434 status = RPC_S_OK;
1436 else
1437 status = I_RpcFreeBuffer(msg);
1439 msg->Handle = message_state;
1441 TRACE("-- %d\n", status);
1443 return HRESULT_FROM_WIN32(status);
1446 static HRESULT WINAPI ClientRpcChannelBuffer_FreeBuffer(LPRPCCHANNELBUFFER iface, RPCOLEMESSAGE* olemsg)
1448 RPC_MESSAGE *msg = (RPC_MESSAGE *)olemsg;
1449 RPC_STATUS status;
1450 struct message_state *message_state;
1452 TRACE("(%p)\n", msg);
1454 message_state = msg->Handle;
1455 /* restore the binding handle and the real start of data */
1456 msg->Handle = message_state->binding_handle;
1457 msg->Buffer = (char *)msg->Buffer - message_state->prefix_data_len;
1458 msg->BufferLength += message_state->prefix_data_len;
1460 if (message_state->params.bypass_rpcrt)
1462 HeapFree(GetProcessHeap(), 0, msg->Buffer);
1463 status = RPC_S_OK;
1465 else
1466 status = I_RpcFreeBuffer(msg);
1468 HeapFree(GetProcessHeap(), 0, msg->RpcInterfaceInformation);
1469 msg->RpcInterfaceInformation = NULL;
1471 if (message_state->params.stub)
1472 IRpcStubBuffer_Release(message_state->params.stub);
1473 if (message_state->params.chan)
1474 IRpcChannelBuffer_Release(message_state->params.chan);
1475 HeapFree(GetProcessHeap(), 0, message_state);
1477 TRACE("-- %d\n", status);
1479 return HRESULT_FROM_WIN32(status);
1482 static HRESULT WINAPI ClientRpcChannelBuffer_GetDestCtx(LPRPCCHANNELBUFFER iface, DWORD* pdwDestContext, void** ppvDestContext)
1484 ClientRpcChannelBuffer *This = (ClientRpcChannelBuffer *)iface;
1486 TRACE("(%p,%p)\n", pdwDestContext, ppvDestContext);
1488 *pdwDestContext = This->super.dest_context;
1489 *ppvDestContext = This->super.dest_context_data;
1491 return S_OK;
1494 static HRESULT WINAPI ServerRpcChannelBuffer_GetDestCtx(LPRPCCHANNELBUFFER iface, DWORD* dest_context, void** dest_context_data)
1496 RpcChannelBuffer *This = (RpcChannelBuffer *)iface;
1498 TRACE("(%p,%p)\n", dest_context, dest_context_data);
1500 *dest_context = This->dest_context;
1501 *dest_context_data = This->dest_context_data;
1502 return S_OK;
1505 static HRESULT WINAPI RpcChannelBuffer_IsConnected(LPRPCCHANNELBUFFER iface)
1507 TRACE("()\n");
1508 /* native does nothing too */
1509 return S_OK;
1512 static const IRpcChannelBufferVtbl ClientRpcChannelBufferVtbl =
1514 RpcChannelBuffer_QueryInterface,
1515 RpcChannelBuffer_AddRef,
1516 ClientRpcChannelBuffer_Release,
1517 ClientRpcChannelBuffer_GetBuffer,
1518 ClientRpcChannelBuffer_SendReceive,
1519 ClientRpcChannelBuffer_FreeBuffer,
1520 ClientRpcChannelBuffer_GetDestCtx,
1521 RpcChannelBuffer_IsConnected
1524 static const IRpcChannelBufferVtbl ServerRpcChannelBufferVtbl =
1526 RpcChannelBuffer_QueryInterface,
1527 RpcChannelBuffer_AddRef,
1528 ServerRpcChannelBuffer_Release,
1529 ServerRpcChannelBuffer_GetBuffer,
1530 ServerRpcChannelBuffer_SendReceive,
1531 ServerRpcChannelBuffer_FreeBuffer,
1532 ServerRpcChannelBuffer_GetDestCtx,
1533 RpcChannelBuffer_IsConnected
1536 /* returns a channel buffer for proxies */
1537 HRESULT rpc_create_clientchannel(const OXID *oxid, const IPID *ipid,
1538 const OXID_INFO *oxid_info, const IID *iid,
1539 DWORD dest_context, void *dest_context_data,
1540 IRpcChannelBuffer **chan, struct apartment *apt)
1542 ClientRpcChannelBuffer *This;
1543 WCHAR endpoint[200];
1544 RPC_BINDING_HANDLE bind;
1545 RPC_STATUS status;
1546 LPWSTR string_binding;
1548 /* FIXME: get the endpoint from oxid_info->psa instead */
1549 get_rpc_endpoint(endpoint, oxid);
1551 TRACE("proxy pipe: connecting to endpoint: %s\n", debugstr_w(endpoint));
1553 status = RpcStringBindingComposeW(
1554 NULL,
1555 rpctransportW,
1556 NULL,
1557 endpoint,
1558 NULL,
1559 &string_binding);
1561 if (status == RPC_S_OK)
1563 status = RpcBindingFromStringBindingW(string_binding, &bind);
1565 if (status == RPC_S_OK)
1567 IPID ipid2 = *ipid; /* why can't RpcBindingSetObject take a const? */
1568 status = RpcBindingSetObject(bind, &ipid2);
1569 if (status != RPC_S_OK)
1570 RpcBindingFree(&bind);
1573 RpcStringFreeW(&string_binding);
1576 if (status != RPC_S_OK)
1578 ERR("Couldn't get binding for endpoint %s, status = %d\n", debugstr_w(endpoint), status);
1579 return HRESULT_FROM_WIN32(status);
1582 This = HeapAlloc(GetProcessHeap(), 0, sizeof(*This));
1583 if (!This)
1585 RpcBindingFree(&bind);
1586 return E_OUTOFMEMORY;
1589 This->super.IRpcChannelBuffer_iface.lpVtbl = &ClientRpcChannelBufferVtbl;
1590 This->super.refs = 1;
1591 This->super.dest_context = dest_context;
1592 This->super.dest_context_data = dest_context_data;
1593 This->bind = bind;
1594 This->oxid = apartment_getoxid(apt);
1595 This->server_pid = oxid_info->dwPid;
1596 This->event = NULL;
1597 This->iid = *iid;
1599 *chan = &This->super.IRpcChannelBuffer_iface;
1601 return S_OK;
1604 HRESULT rpc_create_serverchannel(DWORD dest_context, void *dest_context_data, IRpcChannelBuffer **chan)
1606 RpcChannelBuffer *This = HeapAlloc(GetProcessHeap(), 0, sizeof(*This));
1607 if (!This)
1608 return E_OUTOFMEMORY;
1610 This->IRpcChannelBuffer_iface.lpVtbl = &ServerRpcChannelBufferVtbl;
1611 This->refs = 1;
1612 This->dest_context = dest_context;
1613 This->dest_context_data = dest_context_data;
1615 *chan = &This->IRpcChannelBuffer_iface;
1617 return S_OK;
1620 /* unmarshals ORPC_EXTENT_ARRAY according to NDR rules, but doesn't allocate
1621 * any memory */
1622 static HRESULT unmarshal_ORPC_EXTENT_ARRAY(RPC_MESSAGE *msg, const char *end,
1623 ORPC_EXTENT_ARRAY *extensions,
1624 WIRE_ORPC_EXTENT **first_wire_orpc_extent)
1626 DWORD pointer_id;
1627 DWORD i;
1629 memcpy(extensions, msg->Buffer, FIELD_OFFSET(WIRE_ORPC_EXTENT_ARRAY, extent));
1630 msg->Buffer = (char *)msg->Buffer + FIELD_OFFSET(WIRE_ORPC_EXTENT_ARRAY, extent);
1632 if ((const char *)msg->Buffer + 2 * sizeof(DWORD) > end)
1633 return RPC_E_INVALID_HEADER;
1635 pointer_id = *(DWORD *)msg->Buffer;
1636 msg->Buffer = (char *)msg->Buffer + sizeof(DWORD);
1637 extensions->extent = NULL;
1639 if (pointer_id)
1641 WIRE_ORPC_EXTENT *wire_orpc_extent;
1643 /* conformance */
1644 if (*(DWORD *)msg->Buffer != ((extensions->size+1)&~1))
1645 return RPC_S_INVALID_BOUND;
1647 msg->Buffer = (char *)msg->Buffer + sizeof(DWORD);
1649 /* arbitrary limit for security (don't know what native does) */
1650 if (extensions->size > 256)
1652 ERR("too many extensions: %d\n", extensions->size);
1653 return RPC_S_INVALID_BOUND;
1656 *first_wire_orpc_extent = wire_orpc_extent = msg->Buffer;
1657 for (i = 0; i < ((extensions->size+1)&~1); i++)
1659 if ((const char *)&wire_orpc_extent->data[0] > end)
1660 return RPC_S_INVALID_BOUND;
1661 if (wire_orpc_extent->conformance != ((wire_orpc_extent->size+7)&~7))
1662 return RPC_S_INVALID_BOUND;
1663 if ((const char *)&wire_orpc_extent->data[wire_orpc_extent->conformance] > end)
1664 return RPC_S_INVALID_BOUND;
1665 TRACE("size %u, guid %s\n", wire_orpc_extent->size, debugstr_guid(&wire_orpc_extent->id));
1666 wire_orpc_extent = (WIRE_ORPC_EXTENT *)&wire_orpc_extent->data[wire_orpc_extent->conformance];
1668 msg->Buffer = wire_orpc_extent;
1671 return S_OK;
1674 /* unmarshals ORPCTHIS according to NDR rules, but doesn't allocate any memory */
1675 static HRESULT unmarshal_ORPCTHIS(RPC_MESSAGE *msg, ORPCTHIS *orpcthis,
1676 ORPC_EXTENT_ARRAY *orpc_ext_array, WIRE_ORPC_EXTENT **first_wire_orpc_extent)
1678 const char *end = (char *)msg->Buffer + msg->BufferLength;
1680 *first_wire_orpc_extent = NULL;
1682 if (msg->BufferLength < FIELD_OFFSET(WIRE_ORPCTHIS, extensions) + sizeof(DWORD))
1684 ERR("invalid buffer length\n");
1685 return RPC_E_INVALID_HEADER;
1688 memcpy(orpcthis, msg->Buffer, FIELD_OFFSET(WIRE_ORPCTHIS, extensions));
1689 msg->Buffer = (char *)msg->Buffer + FIELD_OFFSET(WIRE_ORPCTHIS, extensions);
1691 if ((const char *)msg->Buffer + sizeof(DWORD) > end)
1692 return RPC_E_INVALID_HEADER;
1694 if (*(DWORD *)msg->Buffer)
1695 orpcthis->extensions = orpc_ext_array;
1696 else
1697 orpcthis->extensions = NULL;
1699 msg->Buffer = (char *)msg->Buffer + sizeof(DWORD);
1701 if (orpcthis->extensions)
1703 HRESULT hr = unmarshal_ORPC_EXTENT_ARRAY(msg, end, orpc_ext_array,
1704 first_wire_orpc_extent);
1705 if (FAILED(hr))
1706 return hr;
1709 if ((orpcthis->version.MajorVersion != COM_MAJOR_VERSION) ||
1710 (orpcthis->version.MinorVersion > COM_MINOR_VERSION))
1712 ERR("COM version {%d, %d} not supported\n",
1713 orpcthis->version.MajorVersion, orpcthis->version.MinorVersion);
1714 return RPC_E_VERSION_MISMATCH;
1717 if (orpcthis->flags & ~(ORPCF_LOCAL|ORPCF_RESERVED1|ORPCF_RESERVED2|ORPCF_RESERVED3|ORPCF_RESERVED4))
1719 ERR("invalid flags 0x%x\n", orpcthis->flags & ~(ORPCF_LOCAL|ORPCF_RESERVED1|ORPCF_RESERVED2|ORPCF_RESERVED3|ORPCF_RESERVED4));
1720 return RPC_E_INVALID_HEADER;
1723 return S_OK;
1726 static HRESULT unmarshal_ORPCTHAT(RPC_MESSAGE *msg, ORPCTHAT *orpcthat,
1727 ORPC_EXTENT_ARRAY *orpc_ext_array, WIRE_ORPC_EXTENT **first_wire_orpc_extent)
1729 const char *end = (char *)msg->Buffer + msg->BufferLength;
1731 *first_wire_orpc_extent = NULL;
1733 if (msg->BufferLength < FIELD_OFFSET(WIRE_ORPCTHAT, extensions) + sizeof(DWORD))
1735 ERR("invalid buffer length\n");
1736 return RPC_E_INVALID_HEADER;
1739 memcpy(orpcthat, msg->Buffer, FIELD_OFFSET(WIRE_ORPCTHAT, extensions));
1740 msg->Buffer = (char *)msg->Buffer + FIELD_OFFSET(WIRE_ORPCTHAT, extensions);
1742 if ((const char *)msg->Buffer + sizeof(DWORD) > end)
1743 return RPC_E_INVALID_HEADER;
1745 if (*(DWORD *)msg->Buffer)
1746 orpcthat->extensions = orpc_ext_array;
1747 else
1748 orpcthat->extensions = NULL;
1750 msg->Buffer = (char *)msg->Buffer + sizeof(DWORD);
1752 if (orpcthat->extensions)
1754 HRESULT hr = unmarshal_ORPC_EXTENT_ARRAY(msg, end, orpc_ext_array,
1755 first_wire_orpc_extent);
1756 if (FAILED(hr))
1757 return hr;
1760 if (orpcthat->flags & ~(ORPCF_LOCAL|ORPCF_RESERVED1|ORPCF_RESERVED2|ORPCF_RESERVED3|ORPCF_RESERVED4))
1762 ERR("invalid flags 0x%x\n", orpcthat->flags & ~(ORPCF_LOCAL|ORPCF_RESERVED1|ORPCF_RESERVED2|ORPCF_RESERVED3|ORPCF_RESERVED4));
1763 return RPC_E_INVALID_HEADER;
1766 return S_OK;
1769 void rpc_execute_call(struct dispatch_params *params)
1771 struct message_state *message_state = NULL;
1772 RPC_MESSAGE *msg = (RPC_MESSAGE *)params->msg;
1773 char *original_buffer = msg->Buffer;
1774 ORPCTHIS orpcthis;
1775 ORPC_EXTENT_ARRAY orpc_ext_array;
1776 WIRE_ORPC_EXTENT *first_wire_orpc_extent;
1777 GUID old_causality_id;
1778 struct tlsdata *tlsdata;
1779 struct apartment *apt;
1781 if (FAILED(com_get_tlsdata(&tlsdata)))
1782 return;
1784 apt = com_get_current_apt();
1786 /* handle ORPCTHIS and server extensions */
1788 params->hr = unmarshal_ORPCTHIS(msg, &orpcthis, &orpc_ext_array, &first_wire_orpc_extent);
1789 if (params->hr != S_OK)
1791 msg->Buffer = original_buffer;
1792 goto exit;
1795 message_state = HeapAlloc(GetProcessHeap(), 0, sizeof(*message_state));
1796 if (!message_state)
1798 params->hr = E_OUTOFMEMORY;
1799 msg->Buffer = original_buffer;
1800 goto exit;
1803 message_state->prefix_data_len = (char *)msg->Buffer - original_buffer;
1804 message_state->binding_handle = msg->Handle;
1805 message_state->bypass_rpcrt = params->bypass_rpcrt;
1807 message_state->channel_hook_info.iid = params->iid;
1808 message_state->channel_hook_info.cbSize = sizeof(message_state->channel_hook_info);
1809 message_state->channel_hook_info.uCausality = orpcthis.cid;
1810 message_state->channel_hook_info.dwServerPid = GetCurrentProcessId();
1811 message_state->channel_hook_info.iMethod = msg->ProcNum;
1812 message_state->channel_hook_info.pObject = params->iface;
1814 if (orpcthis.extensions && first_wire_orpc_extent &&
1815 orpcthis.extensions->size)
1816 ChannelHooks_ServerNotify(&message_state->channel_hook_info, msg->DataRepresentation, first_wire_orpc_extent, orpcthis.extensions->size);
1818 msg->Handle = message_state;
1819 msg->BufferLength -= message_state->prefix_data_len;
1821 /* call message filter */
1823 if (apt->filter)
1825 DWORD handlecall;
1826 INTERFACEINFO interface_info;
1827 CALLTYPE calltype;
1829 interface_info.pUnk = params->iface;
1830 interface_info.iid = params->iid;
1831 interface_info.wMethod = msg->ProcNum;
1833 if (IsEqualGUID(&orpcthis.cid, &tlsdata->causality_id))
1834 calltype = CALLTYPE_NESTED;
1835 else if (tlsdata->pending_call_count_server == 0)
1836 calltype = CALLTYPE_TOPLEVEL;
1837 else
1838 calltype = CALLTYPE_TOPLEVEL_CALLPENDING;
1840 handlecall = IMessageFilter_HandleInComingCall(apt->filter,
1841 calltype,
1842 UlongToHandle(GetCurrentProcessId()),
1843 0 /* FIXME */,
1844 &interface_info);
1845 TRACE("IMessageFilter_HandleInComingCall returned %d\n", handlecall);
1846 switch (handlecall)
1848 case SERVERCALL_REJECTED:
1849 params->hr = RPC_E_CALL_REJECTED;
1850 goto exit_reset_state;
1851 case SERVERCALL_RETRYLATER:
1852 #if 0 /* FIXME: handle retries on the client side before enabling this code */
1853 params->hr = RPC_E_RETRY;
1854 goto exit_reset_state;
1855 #else
1856 FIXME("retry call later not implemented\n");
1857 break;
1858 #endif
1859 case SERVERCALL_ISHANDLED:
1860 default:
1861 break;
1865 /* invoke the method */
1867 /* save the old causality ID - note: any calls executed while processing
1868 * messages received during the SendReceive will appear to originate from
1869 * this call - this should be checked with what Windows does */
1870 old_causality_id = tlsdata->causality_id;
1871 tlsdata->causality_id = orpcthis.cid;
1872 tlsdata->pending_call_count_server++;
1873 params->hr = IRpcStubBuffer_Invoke(params->stub, params->msg, params->chan);
1874 tlsdata->pending_call_count_server--;
1875 tlsdata->causality_id = old_causality_id;
1877 /* the invoke allocated a new buffer, so free the old one */
1878 if (message_state->bypass_rpcrt && original_buffer != msg->Buffer)
1879 HeapFree(GetProcessHeap(), 0, original_buffer);
1881 exit_reset_state:
1882 message_state = msg->Handle;
1883 msg->Handle = message_state->binding_handle;
1884 msg->Buffer = (char *)msg->Buffer - message_state->prefix_data_len;
1885 msg->BufferLength += message_state->prefix_data_len;
1887 exit:
1888 HeapFree(GetProcessHeap(), 0, message_state);
1889 if (params->handle) SetEvent(params->handle);
1892 static void __RPC_STUB dispatch_rpc(RPC_MESSAGE *msg)
1894 struct dispatch_params *params;
1895 struct stub_manager *stub_manager;
1896 struct apartment *apt;
1897 IPID ipid;
1898 HRESULT hr;
1900 RpcBindingInqObject(msg->Handle, &ipid);
1902 TRACE("ipid = %s, iMethod = %d\n", debugstr_guid(&ipid), msg->ProcNum);
1904 params = HeapAlloc(GetProcessHeap(), 0, sizeof(*params));
1905 if (!params)
1907 RpcRaiseException(E_OUTOFMEMORY);
1908 return;
1911 hr = ipid_get_dispatch_params(&ipid, &apt, &stub_manager, &params->stub, &params->chan,
1912 &params->iid, &params->iface);
1913 if (hr != S_OK)
1915 ERR("no apartment found for ipid %s\n", debugstr_guid(&ipid));
1916 HeapFree(GetProcessHeap(), 0, params);
1917 RpcRaiseException(hr);
1918 return;
1921 params->msg = (RPCOLEMESSAGE *)msg;
1922 params->status = RPC_S_OK;
1923 params->hr = S_OK;
1924 params->handle = NULL;
1925 params->bypass_rpcrt = FALSE;
1927 /* Note: this is the important difference between STAs and MTAs - we
1928 * always execute RPCs to STAs in the thread that originally created the
1929 * apartment (i.e. the one that pumps messages to the window) */
1930 if (!apt->multi_threaded)
1932 params->handle = CreateEventW(NULL, FALSE, FALSE, NULL);
1934 TRACE("Calling apartment thread 0x%08x...\n", apt->tid);
1936 if (PostMessageW(apartment_getwindow(apt), DM_EXECUTERPC, 0, (LPARAM)params))
1937 WaitForSingleObject(params->handle, INFINITE);
1938 else
1940 ERR("PostMessage failed with error %u\n", GetLastError());
1941 IRpcChannelBuffer_Release(params->chan);
1942 IRpcStubBuffer_Release(params->stub);
1944 CloseHandle(params->handle);
1946 else
1948 BOOL joined = FALSE;
1949 struct tlsdata *tlsdata;
1951 com_get_tlsdata(&tlsdata);
1953 if (!tlsdata->apt)
1955 enter_apartment(tlsdata, COINIT_MULTITHREADED);
1956 joined = TRUE;
1958 rpc_execute_call(params);
1959 if (joined)
1961 leave_apartment(tlsdata);
1965 hr = params->hr;
1966 if (params->chan)
1967 IRpcChannelBuffer_Release(params->chan);
1968 if (params->stub)
1969 IRpcStubBuffer_Release(params->stub);
1970 HeapFree(GetProcessHeap(), 0, params);
1972 stub_manager_int_release(stub_manager);
1973 apartment_release(apt);
1975 /* if IRpcStubBuffer_Invoke fails, we should raise an exception to tell
1976 * the RPC runtime that the call failed */
1977 if (hr != S_OK) RpcRaiseException(hr);
1980 /* stub registration */
1981 HRESULT rpc_register_interface(REFIID riid)
1983 struct registered_if *rif;
1984 BOOL found = FALSE;
1985 HRESULT hr = S_OK;
1987 TRACE("(%s)\n", debugstr_guid(riid));
1989 EnterCriticalSection(&csRegIf);
1990 LIST_FOR_EACH_ENTRY(rif, &registered_interfaces, struct registered_if, entry)
1992 if (IsEqualGUID(&rif->If.InterfaceId.SyntaxGUID, riid))
1994 rif->refs++;
1995 found = TRUE;
1996 break;
1999 if (!found)
2001 TRACE("Creating new interface\n");
2003 rif = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*rif));
2004 if (rif)
2006 RPC_STATUS status;
2008 rif->refs = 1;
2009 rif->If.Length = sizeof(RPC_SERVER_INTERFACE);
2010 /* RPC interface ID = COM interface ID */
2011 rif->If.InterfaceId.SyntaxGUID = *riid;
2012 rif->If.DispatchTable = &rpc_dispatch;
2013 /* all other fields are 0, including the version asCOM objects
2014 * always have a version of 0.0 */
2015 status = RpcServerRegisterIfEx(
2016 (RPC_IF_HANDLE)&rif->If,
2017 NULL, NULL,
2018 RPC_IF_OLE | RPC_IF_AUTOLISTEN,
2019 RPC_C_LISTEN_MAX_CALLS_DEFAULT,
2020 NULL);
2021 if (status == RPC_S_OK)
2022 list_add_tail(&registered_interfaces, &rif->entry);
2023 else
2025 ERR("RpcServerRegisterIfEx failed with error %d\n", status);
2026 HeapFree(GetProcessHeap(), 0, rif);
2027 hr = HRESULT_FROM_WIN32(status);
2030 else
2031 hr = E_OUTOFMEMORY;
2033 LeaveCriticalSection(&csRegIf);
2034 return hr;
2037 /* stub unregistration */
2038 void rpc_unregister_interface(REFIID riid, BOOL wait)
2040 struct registered_if *rif;
2041 EnterCriticalSection(&csRegIf);
2042 LIST_FOR_EACH_ENTRY(rif, &registered_interfaces, struct registered_if, entry)
2044 if (IsEqualGUID(&rif->If.InterfaceId.SyntaxGUID, riid))
2046 if (!--rif->refs)
2048 RpcServerUnregisterIf((RPC_IF_HANDLE)&rif->If, NULL, wait);
2049 list_remove(&rif->entry);
2050 HeapFree(GetProcessHeap(), 0, rif);
2052 break;
2055 LeaveCriticalSection(&csRegIf);
2058 /* get the info for an OXID, including the IPID for the rem unknown interface
2059 * and the string binding */
2060 HRESULT rpc_resolve_oxid(OXID oxid, OXID_INFO *oxid_info)
2062 TRACE("%s\n", wine_dbgstr_longlong(oxid));
2064 oxid_info->dwTid = 0;
2065 oxid_info->dwPid = 0;
2066 oxid_info->dwAuthnHint = RPC_C_AUTHN_LEVEL_NONE;
2067 /* FIXME: this is a hack around not having an OXID resolver yet -
2068 * this function should contact the machine's OXID resolver and then it
2069 * should give us the IPID of the IRemUnknown interface */
2070 oxid_info->ipidRemUnknown.Data1 = 0xffffffff;
2071 oxid_info->ipidRemUnknown.Data2 = 0xffff;
2072 oxid_info->ipidRemUnknown.Data3 = 0xffff;
2073 memcpy(oxid_info->ipidRemUnknown.Data4, &oxid, sizeof(OXID));
2074 oxid_info->psa = NULL /* FIXME */;
2076 return S_OK;
2079 /* make the apartment reachable by other threads and processes and create the
2080 * IRemUnknown object */
2081 void rpc_start_remoting(struct apartment *apt)
2083 if (!InterlockedExchange(&apt->remoting_started, TRUE))
2085 WCHAR endpoint[200];
2086 RPC_STATUS status;
2088 get_rpc_endpoint(endpoint, &apt->oxid);
2090 status = RpcServerUseProtseqEpW(
2091 rpctransportW,
2092 RPC_C_PROTSEQ_MAX_REQS_DEFAULT,
2093 endpoint,
2094 NULL);
2095 if (status != RPC_S_OK)
2096 ERR("Couldn't register endpoint %s\n", debugstr_w(endpoint));
2098 /* FIXME: move remote unknown exporting into this function */
2100 start_apartment_remote_unknown(apt);
2103 /******************************************************************************
2104 * DllDebugObjectRPCHook (combase.@)
2106 BOOL WINAPI DllDebugObjectRPCHook(BOOL trace, /* ORPC_INIT_ARGS * */ void *args)
2108 FIXME("%d, %p: stub\n", trace, args);
2110 return TRUE;