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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
32 #define NONAMELESSUNION
33 #define NONAMELESSSTRUCT
46 #include "wine/unicode.h"
47 #include "wine/exception.h"
49 #include "compobj_private.h"
51 #include "wine/debug.h"
53 WINE_DEFAULT_DEBUG_CHANNEL(ole);
55 static void __RPC_STUB dispatch_rpc(RPC_MESSAGE *msg);
57 /* we only use one function to dispatch calls for all methods - we use the
58 * RPC_IF_OLE flag to tell the RPC runtime that this is the case */
59 static RPC_DISPATCH_FUNCTION rpc_dispatch_table[1] = { dispatch_rpc }; /* (RO) */
60 static RPC_DISPATCH_TABLE rpc_dispatch = { 1, rpc_dispatch_table }; /* (RO) */
62 static struct list registered_interfaces = LIST_INIT(registered_interfaces); /* (CS csRegIf) */
63 static CRITICAL_SECTION csRegIf;
64 static CRITICAL_SECTION_DEBUG csRegIf_debug =
67 { &csRegIf_debug.ProcessLocksList, &csRegIf_debug.ProcessLocksList },
68 0, 0, { (DWORD_PTR)(__FILE__ ": dcom registered server interfaces") }
70 static CRITICAL_SECTION csRegIf = { &csRegIf_debug, -1, 0, 0, 0, 0 };
72 static WCHAR wszPipeTransport[] = {'n','c','a','c','n','_','n','p',0};
78 DWORD refs; /* ref count */
79 RPC_SERVER_INTERFACE If; /* interface registered with the RPC runtime */
82 /* get the pipe endpoint specified of the specified apartment */
83 static inline void get_rpc_endpoint(LPWSTR endpoint, const OXID *oxid)
85 /* FIXME: should get endpoint from rpcss */
86 static const WCHAR wszEndpointFormat[] = {'\\','p','i','p','e','\\','O','L','E','_','%','0','8','l','x','%','0','8','l','x',0};
87 wsprintfW(endpoint, wszEndpointFormat, (DWORD)(*oxid >> 32),(DWORD)*oxid);
92 const IRpcChannelBufferVtbl *lpVtbl;
98 RpcChannelBuffer super; /* superclass */
100 RPC_BINDING_HANDLE bind; /* handle to the remote server */
101 OXID oxid; /* apartment in which the channel is valid */
102 } ClientRpcChannelBuffer;
104 struct dispatch_params
106 RPCOLEMESSAGE *msg; /* message */
107 IRpcStubBuffer *stub; /* stub buffer, if applicable */
108 IRpcChannelBuffer *chan; /* server channel buffer, if applicable */
109 HANDLE handle; /* handle that will become signaled when call finishes */
110 RPC_STATUS status; /* status (out) */
111 HRESULT hr; /* hresult (out) */
114 static WINE_EXCEPTION_FILTER(ole_filter)
116 if (GetExceptionCode() == EXCEPTION_ACCESS_VIOLATION)
117 return EXCEPTION_CONTINUE_SEARCH;
118 return EXCEPTION_EXECUTE_HANDLER;
121 static HRESULT WINAPI RpcChannelBuffer_QueryInterface(LPRPCCHANNELBUFFER iface, REFIID riid, LPVOID *ppv)
124 if (IsEqualIID(riid,&IID_IRpcChannelBuffer) || IsEqualIID(riid,&IID_IUnknown))
126 *ppv = (LPVOID)iface;
127 IUnknown_AddRef(iface);
130 return E_NOINTERFACE;
133 static ULONG WINAPI RpcChannelBuffer_AddRef(LPRPCCHANNELBUFFER iface)
135 RpcChannelBuffer *This = (RpcChannelBuffer *)iface;
136 return InterlockedIncrement(&This->refs);
139 static ULONG WINAPI ServerRpcChannelBuffer_Release(LPRPCCHANNELBUFFER iface)
141 RpcChannelBuffer *This = (RpcChannelBuffer *)iface;
144 ref = InterlockedDecrement(&This->refs);
148 HeapFree(GetProcessHeap(), 0, This);
152 static ULONG WINAPI ClientRpcChannelBuffer_Release(LPRPCCHANNELBUFFER iface)
154 ClientRpcChannelBuffer *This = (ClientRpcChannelBuffer *)iface;
157 ref = InterlockedDecrement(&This->super.refs);
161 RpcBindingFree(&This->bind);
162 HeapFree(GetProcessHeap(), 0, This);
166 static HRESULT WINAPI ServerRpcChannelBuffer_GetBuffer(LPRPCCHANNELBUFFER iface, RPCOLEMESSAGE* olemsg, REFIID riid)
168 RpcChannelBuffer *This = (RpcChannelBuffer *)iface;
169 RPC_MESSAGE *msg = (RPC_MESSAGE *)olemsg;
172 TRACE("(%p)->(%p,%s)\n", This, olemsg, debugstr_guid(riid));
174 status = I_RpcGetBuffer(msg);
176 TRACE("-- %ld\n", status);
178 return HRESULT_FROM_WIN32(status);
181 static HRESULT WINAPI ClientRpcChannelBuffer_GetBuffer(LPRPCCHANNELBUFFER iface, RPCOLEMESSAGE* olemsg, REFIID riid)
183 ClientRpcChannelBuffer *This = (ClientRpcChannelBuffer *)iface;
184 RPC_MESSAGE *msg = (RPC_MESSAGE *)olemsg;
185 RPC_CLIENT_INTERFACE *cif;
188 TRACE("(%p)->(%p,%s)\n", This, olemsg, debugstr_guid(riid));
190 cif = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(RPC_CLIENT_INTERFACE));
192 return E_OUTOFMEMORY;
194 cif->Length = sizeof(RPC_CLIENT_INTERFACE);
195 /* RPC interface ID = COM interface ID */
196 cif->InterfaceId.SyntaxGUID = *riid;
197 /* COM objects always have a version of 0.0 */
198 cif->InterfaceId.SyntaxVersion.MajorVersion = 0;
199 cif->InterfaceId.SyntaxVersion.MinorVersion = 0;
200 msg->RpcInterfaceInformation = cif;
201 msg->Handle = This->bind;
203 status = I_RpcGetBuffer(msg);
205 TRACE("-- %ld\n", status);
207 return HRESULT_FROM_WIN32(status);
210 static HRESULT WINAPI ServerRpcChannelBuffer_SendReceive(LPRPCCHANNELBUFFER iface, RPCOLEMESSAGE *olemsg, ULONG *pstatus)
216 /* this thread runs an outgoing RPC */
217 static DWORD WINAPI rpc_sendreceive_thread(LPVOID param)
219 struct dispatch_params *data = (struct dispatch_params *) param;
221 /* FIXME: trap and rethrow RPC exceptions in app thread */
222 data->status = I_RpcSendReceive((RPC_MESSAGE *)data->msg);
224 TRACE("completed with status 0x%lx\n", data->status);
229 static inline HRESULT ClientRpcChannelBuffer_IsCorrectApartment(ClientRpcChannelBuffer *This, APARTMENT *apt)
234 if (apartment_getoxid(apt, &oxid) != S_OK)
236 if (This->oxid != oxid)
241 static HRESULT WINAPI ClientRpcChannelBuffer_SendReceive(LPRPCCHANNELBUFFER iface, RPCOLEMESSAGE *olemsg, ULONG *pstatus)
243 ClientRpcChannelBuffer *This = (ClientRpcChannelBuffer *)iface;
245 RPC_MESSAGE *msg = (RPC_MESSAGE *)olemsg;
248 struct dispatch_params *params;
250 APARTMENT *apt = NULL;
253 TRACE("(%p) iMethod=%ld\n", olemsg, olemsg->iMethod);
255 hr = ClientRpcChannelBuffer_IsCorrectApartment(This, COM_CurrentApt());
258 ERR("called from wrong apartment, should have been 0x%s\n",
259 wine_dbgstr_longlong(This->oxid));
260 return RPC_E_WRONG_THREAD;
263 params = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*params));
264 if (!params) return E_OUTOFMEMORY;
266 params->msg = olemsg;
267 params->status = RPC_S_OK;
270 /* Note: this is an optimization in the Microsoft OLE runtime that we need
271 * to copy, as shown by the test_no_couninitialize_client test. without
272 * short-circuiting the RPC runtime in the case below, the test will
273 * deadlock on the loader lock due to the RPC runtime needing to create
274 * a thread to process the RPC when this function is called indirectly
277 RpcBindingInqObject(msg->Handle, &ipid);
278 hr = ipid_get_dispatch_params(&ipid, &apt, ¶ms->stub, ¶ms->chan);
279 if ((hr == S_OK) && (apt->model & COINIT_APARTMENTTHREADED))
281 params->handle = CreateEventW(NULL, FALSE, FALSE, NULL);
283 TRACE("Calling apartment thread 0x%08lx...\n", apt->tid);
285 if (!PostMessageW(apartment_getwindow(apt), DM_EXECUTERPC, 0, (LPARAM)params))
287 ERR("PostMessage failed with error %ld\n", GetLastError());
288 hr = HRESULT_FROM_WIN32(GetLastError());
295 /* otherwise, we go via RPC runtime so the stub and channel aren't
297 IRpcStubBuffer_Release(params->stub);
299 IRpcChannelBuffer_Release(params->chan);
303 /* we use a separate thread here because we need to be able to
304 * pump the message loop in the application thread: if we do not,
305 * any windows created by this thread will hang and RPCs that try
306 * and re-enter this STA from an incoming server thread will
307 * deadlock. InstallShield is an example of that.
309 params->handle = CreateThread(NULL, 0, rpc_sendreceive_thread, params, 0, &tid);
312 ERR("Could not create RpcSendReceive thread, error %lx\n", GetLastError());
318 if (apt) apartment_release(apt);
322 if (WaitForSingleObject(params->handle, 0))
323 hr = CoWaitForMultipleHandles(0, INFINITE, 1, ¶ms->handle, &index);
325 CloseHandle(params->handle);
327 if (hr == S_OK) hr = params->hr;
329 status = params->status;
330 HeapFree(GetProcessHeap(), 0, params);
335 if (pstatus) *pstatus = status;
337 TRACE("RPC call status: 0x%lx\n", status);
338 if (status == RPC_S_OK)
340 else if (status == RPC_S_CALL_FAILED)
341 hr = *(HRESULT *)olemsg->Buffer;
343 hr = HRESULT_FROM_WIN32(status);
345 TRACE("-- 0x%08lx\n", hr);
350 static HRESULT WINAPI ServerRpcChannelBuffer_FreeBuffer(LPRPCCHANNELBUFFER iface, RPCOLEMESSAGE* olemsg)
352 RPC_MESSAGE *msg = (RPC_MESSAGE *)olemsg;
355 TRACE("(%p)\n", msg);
357 status = I_RpcFreeBuffer(msg);
359 TRACE("-- %ld\n", status);
361 return HRESULT_FROM_WIN32(status);
364 static HRESULT WINAPI ClientRpcChannelBuffer_FreeBuffer(LPRPCCHANNELBUFFER iface, RPCOLEMESSAGE* olemsg)
366 RPC_MESSAGE *msg = (RPC_MESSAGE *)olemsg;
369 TRACE("(%p)\n", msg);
371 status = I_RpcFreeBuffer(msg);
373 HeapFree(GetProcessHeap(), 0, msg->RpcInterfaceInformation);
374 msg->RpcInterfaceInformation = NULL;
376 TRACE("-- %ld\n", status);
378 return HRESULT_FROM_WIN32(status);
381 static HRESULT WINAPI RpcChannelBuffer_GetDestCtx(LPRPCCHANNELBUFFER iface, DWORD* pdwDestContext, void** ppvDestContext)
383 FIXME("(%p,%p), stub!\n", pdwDestContext, ppvDestContext);
387 static HRESULT WINAPI RpcChannelBuffer_IsConnected(LPRPCCHANNELBUFFER iface)
390 /* native does nothing too */
394 static const IRpcChannelBufferVtbl ClientRpcChannelBufferVtbl =
396 RpcChannelBuffer_QueryInterface,
397 RpcChannelBuffer_AddRef,
398 ClientRpcChannelBuffer_Release,
399 ClientRpcChannelBuffer_GetBuffer,
400 ClientRpcChannelBuffer_SendReceive,
401 ClientRpcChannelBuffer_FreeBuffer,
402 RpcChannelBuffer_GetDestCtx,
403 RpcChannelBuffer_IsConnected
406 static const IRpcChannelBufferVtbl ServerRpcChannelBufferVtbl =
408 RpcChannelBuffer_QueryInterface,
409 RpcChannelBuffer_AddRef,
410 ServerRpcChannelBuffer_Release,
411 ServerRpcChannelBuffer_GetBuffer,
412 ServerRpcChannelBuffer_SendReceive,
413 ServerRpcChannelBuffer_FreeBuffer,
414 RpcChannelBuffer_GetDestCtx,
415 RpcChannelBuffer_IsConnected
418 /* returns a channel buffer for proxies */
419 HRESULT RPC_CreateClientChannel(const OXID *oxid, const IPID *ipid, IRpcChannelBuffer **chan)
421 ClientRpcChannelBuffer *This;
423 RPC_BINDING_HANDLE bind;
425 LPWSTR string_binding;
427 /* connect to the apartment listener thread */
428 get_rpc_endpoint(endpoint, oxid);
430 TRACE("proxy pipe: connecting to endpoint: %s\n", debugstr_w(endpoint));
432 status = RpcStringBindingComposeW(
440 if (status == RPC_S_OK)
442 status = RpcBindingFromStringBindingW(string_binding, &bind);
444 if (status == RPC_S_OK)
446 IPID ipid2 = *ipid; /* why can't RpcBindingSetObject take a const? */
447 status = RpcBindingSetObject(bind, &ipid2);
448 if (status != RPC_S_OK)
449 RpcBindingFree(&bind);
452 RpcStringFreeW(&string_binding);
455 if (status != RPC_S_OK)
457 ERR("Couldn't get binding for endpoint %s, status = %ld\n", debugstr_w(endpoint), status);
458 return HRESULT_FROM_WIN32(status);
461 This = HeapAlloc(GetProcessHeap(), 0, sizeof(*This));
464 RpcBindingFree(&bind);
465 return E_OUTOFMEMORY;
468 This->super.lpVtbl = &ClientRpcChannelBufferVtbl;
469 This->super.refs = 1;
471 apartment_getoxid(COM_CurrentApt(), &This->oxid);
473 *chan = (IRpcChannelBuffer*)This;
478 HRESULT RPC_CreateServerChannel(IRpcChannelBuffer **chan)
480 RpcChannelBuffer *This = HeapAlloc(GetProcessHeap(), 0, sizeof(*This));
482 return E_OUTOFMEMORY;
484 This->lpVtbl = &ServerRpcChannelBufferVtbl;
487 *chan = (IRpcChannelBuffer*)This;
493 void RPC_ExecuteCall(struct dispatch_params *params)
497 params->hr = IRpcStubBuffer_Invoke(params->stub, params->msg, params->chan);
501 params->hr = GetExceptionCode();
504 IRpcStubBuffer_Release(params->stub);
505 IRpcChannelBuffer_Release(params->chan);
506 if (params->handle) SetEvent(params->handle);
509 static void __RPC_STUB dispatch_rpc(RPC_MESSAGE *msg)
511 struct dispatch_params *params;
516 RpcBindingInqObject(msg->Handle, &ipid);
518 TRACE("ipid = %s, iMethod = %d\n", debugstr_guid(&ipid), msg->ProcNum);
520 params = HeapAlloc(GetProcessHeap(), 0, sizeof(*params));
521 if (!params) return RpcRaiseException(E_OUTOFMEMORY);
523 hr = ipid_get_dispatch_params(&ipid, &apt, ¶ms->stub, ¶ms->chan);
526 ERR("no apartment found for ipid %s\n", debugstr_guid(&ipid));
527 return RpcRaiseException(hr);
530 params->msg = (RPCOLEMESSAGE *)msg;
531 params->status = RPC_S_OK;
533 params->handle = NULL;
535 /* Note: this is the important difference between STAs and MTAs - we
536 * always execute RPCs to STAs in the thread that originally created the
537 * apartment (i.e. the one that pumps messages to the window) */
538 if (apt->model & COINIT_APARTMENTTHREADED)
540 params->handle = CreateEventW(NULL, FALSE, FALSE, NULL);
542 TRACE("Calling apartment thread 0x%08lx...\n", apt->tid);
544 if (PostMessageW(apartment_getwindow(apt), DM_EXECUTERPC, 0, (LPARAM)params))
545 WaitForSingleObject(params->handle, INFINITE);
548 ERR("PostMessage failed with error %ld\n", GetLastError());
549 IRpcChannelBuffer_Release(params->chan);
550 IRpcStubBuffer_Release(params->stub);
552 CloseHandle(params->handle);
557 if (!COM_CurrentInfo()->apt)
562 RPC_ExecuteCall(params);
565 apartment_release(COM_CurrentInfo()->apt);
566 COM_CurrentInfo()->apt = NULL;
570 HeapFree(GetProcessHeap(), 0, params);
572 apartment_release(apt);
575 /* stub registration */
576 HRESULT RPC_RegisterInterface(REFIID riid)
578 struct registered_if *rif;
582 TRACE("(%s)\n", debugstr_guid(riid));
584 EnterCriticalSection(&csRegIf);
585 LIST_FOR_EACH_ENTRY(rif, ®istered_interfaces, struct registered_if, entry)
587 if (IsEqualGUID(&rif->If.InterfaceId.SyntaxGUID, riid))
596 TRACE("Creating new interface\n");
598 rif = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*rif));
604 rif->If.Length = sizeof(RPC_SERVER_INTERFACE);
605 /* RPC interface ID = COM interface ID */
606 rif->If.InterfaceId.SyntaxGUID = *riid;
607 rif->If.DispatchTable = &rpc_dispatch;
608 /* all other fields are 0, including the version asCOM objects
609 * always have a version of 0.0 */
610 status = RpcServerRegisterIfEx(
611 (RPC_IF_HANDLE)&rif->If,
613 RPC_IF_OLE | RPC_IF_AUTOLISTEN,
614 RPC_C_LISTEN_MAX_CALLS_DEFAULT,
616 if (status == RPC_S_OK)
617 list_add_tail(®istered_interfaces, &rif->entry);
620 ERR("RpcServerRegisterIfEx failed with error %ld\n", status);
621 HeapFree(GetProcessHeap(), 0, rif);
622 hr = HRESULT_FROM_WIN32(status);
628 LeaveCriticalSection(&csRegIf);
632 /* stub unregistration */
633 void RPC_UnregisterInterface(REFIID riid)
635 struct registered_if *rif;
636 EnterCriticalSection(&csRegIf);
637 LIST_FOR_EACH_ENTRY(rif, ®istered_interfaces, struct registered_if, entry)
639 if (IsEqualGUID(&rif->If.InterfaceId.SyntaxGUID, riid))
643 #if 0 /* this is a stub in builtin and spams the console with FIXME's */
644 IID iid = *riid; /* RpcServerUnregisterIf doesn't take const IID */
645 RpcServerUnregisterIf((RPC_IF_HANDLE)&rif->If, &iid, 0);
646 list_remove(&rif->entry);
647 HeapFree(GetProcessHeap(), 0, rif);
653 LeaveCriticalSection(&csRegIf);
656 /* make the apartment reachable by other threads and processes and create the
657 * IRemUnknown object */
658 void RPC_StartRemoting(struct apartment *apt)
660 if (!InterlockedExchange(&apt->remoting_started, TRUE))
665 get_rpc_endpoint(endpoint, &apt->oxid);
667 status = RpcServerUseProtseqEpW(
669 RPC_C_PROTSEQ_MAX_REQS_DEFAULT,
672 if (status != RPC_S_OK)
673 ERR("Couldn't register endpoint %s\n", debugstr_w(endpoint));
675 /* FIXME: move remote unknown exporting into this function */
677 start_apartment_remote_unknown();
681 static HRESULT create_server(REFCLSID rclsid)
683 static const WCHAR wszLocalServer32[] = { 'L','o','c','a','l','S','e','r','v','e','r','3','2',0 };
684 static const WCHAR embedding[] = { ' ', '-','E','m','b','e','d','d','i','n','g',0 };
687 WCHAR command[MAX_PATH+sizeof(embedding)/sizeof(WCHAR)];
688 DWORD size = (MAX_PATH+1) * sizeof(WCHAR);
690 PROCESS_INFORMATION pinfo;
692 hres = COM_OpenKeyForCLSID(rclsid, wszLocalServer32, KEY_READ, &key);
694 ERR("class %s not registered\n", debugstr_guid(rclsid));
698 hres = RegQueryValueExW(key, NULL, NULL, NULL, (LPBYTE)command, &size);
701 WARN("No default value for LocalServer32 key\n");
702 return REGDB_E_CLASSNOTREG; /* FIXME: check retval */
705 memset(&sinfo,0,sizeof(sinfo));
706 sinfo.cb = sizeof(sinfo);
708 /* EXE servers are started with the -Embedding switch. */
710 strcatW(command, embedding);
712 TRACE("activating local server %s for %s\n", debugstr_w(command), debugstr_guid(rclsid));
714 /* FIXME: Win2003 supports a ServerExecutable value that is passed into
716 if (!CreateProcessW(NULL, command, NULL, NULL, FALSE, 0, NULL, NULL, &sinfo, &pinfo)) {
717 WARN("failed to run local server %s\n", debugstr_w(command));
718 return HRESULT_FROM_WIN32(GetLastError());
720 CloseHandle(pinfo.hProcess);
721 CloseHandle(pinfo.hThread);
727 * start_local_service() - start a service given its name and parameters
729 static DWORD start_local_service(LPCWSTR name, DWORD num, LPCWSTR *params)
731 SC_HANDLE handle, hsvc;
732 DWORD r = ERROR_FUNCTION_FAILED;
734 TRACE("Starting service %s %ld params\n", debugstr_w(name), num);
736 handle = OpenSCManagerW(NULL, NULL, SC_MANAGER_CONNECT);
739 hsvc = OpenServiceW(handle, name, SERVICE_START);
742 if(StartServiceW(hsvc, num, params))
746 if (r == ERROR_SERVICE_ALREADY_RUNNING)
748 CloseServiceHandle(hsvc);
752 CloseServiceHandle(handle);
754 TRACE("StartService returned error %ld (%s)\n", r, (r == ERROR_SUCCESS) ? "ok":"failed");
760 * create_local_service() - start a COM server in a service
762 * To start a Local Service, we read the AppID value under
763 * the class's CLSID key, then open the HKCR\\AppId key specified
764 * there and check for a LocalService value.
766 * Note: Local Services are not supported under Windows 9x
768 static HRESULT create_local_service(REFCLSID rclsid)
771 WCHAR buf[CHARS_IN_GUID], keyname[50];
772 static const WCHAR szAppId[] = { 'A','p','p','I','d',0 };
773 static const WCHAR szAppIdKey[] = { 'A','p','p','I','d','\\',0 };
774 static const WCHAR szLocalService[] = { 'L','o','c','a','l','S','e','r','v','i','c','e',0 };
775 static const WCHAR szServiceParams[] = {'S','e','r','v','i','c','e','P','a','r','a','m','s',0};
780 TRACE("Attempting to start Local service for %s\n", debugstr_guid(rclsid));
782 /* read the AppID value under the class's key */
783 hres = COM_OpenKeyForCLSID(rclsid, szAppId, KEY_READ, &hkey);
787 r = RegQueryValueExW(hkey, NULL, NULL, &type, (LPBYTE)buf, &sz);
789 if (r!=ERROR_SUCCESS || type!=REG_SZ)
792 /* read the LocalService and ServiceParameters values from the AppID key */
793 strcpyW(keyname, szAppIdKey);
794 strcatW(keyname, buf);
795 r = RegOpenKeyExW(HKEY_CLASSES_ROOT, keyname, 0, KEY_READ, &hkey);
796 if (r!=ERROR_SUCCESS)
799 r = RegQueryValueExW(hkey, szLocalService, NULL, &type, (LPBYTE)buf, &sz);
800 if (r==ERROR_SUCCESS && type==REG_SZ)
803 LPWSTR args[1] = { NULL };
806 * FIXME: I'm not really sure how to deal with the service parameters.
807 * I suspect that the string returned from RegQueryValueExW
808 * should be split into a number of arguments by spaces.
809 * It would make more sense if ServiceParams contained a
810 * REG_MULTI_SZ here, but it's a REG_SZ for the services
811 * that I'm interested in for the moment.
813 r = RegQueryValueExW(hkey, szServiceParams, NULL, &type, NULL, &sz);
814 if (r == ERROR_SUCCESS && type == REG_SZ && sz)
816 args[0] = HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY,sz);
818 RegQueryValueExW(hkey, szServiceParams, NULL, &type, (LPBYTE)args[0], &sz);
820 r = start_local_service(buf, num_args, (LPCWSTR *)args);
821 if (r==ERROR_SUCCESS)
823 HeapFree(GetProcessHeap(),0,args[0]);
831 static void get_localserver_pipe_name(WCHAR *pipefn, REFCLSID rclsid)
833 static const WCHAR wszPipeRef[] = {'\\','\\','.','\\','p','i','p','e','\\',0};
834 strcpyW(pipefn, wszPipeRef);
835 StringFromGUID2(rclsid, pipefn + sizeof(wszPipeRef)/sizeof(wszPipeRef[0]) - 1, CHARS_IN_GUID);
838 /* FIXME: should call to rpcss instead */
839 HRESULT RPC_GetLocalClassObject(REFCLSID rclsid, REFIID iid, LPVOID *ppv)
844 DWORD res, bufferlen;
845 char marshalbuffer[200];
847 LARGE_INTEGER seekto;
848 ULARGE_INTEGER newpos;
851 static const int MAXTRIES = 30; /* 30 seconds */
853 TRACE("rclsid=%s, iid=%s\n", debugstr_guid(rclsid), debugstr_guid(iid));
855 get_localserver_pipe_name(pipefn, rclsid);
857 while (tries++ < MAXTRIES) {
858 TRACE("waiting for %s\n", debugstr_w(pipefn));
860 WaitNamedPipeW( pipefn, NMPWAIT_WAIT_FOREVER );
861 hPipe = CreateFileW(pipefn, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, 0);
862 if (hPipe == INVALID_HANDLE_VALUE) {
864 if ( (hres = create_local_service(rclsid)) &&
865 (hres = create_server(rclsid)) )
869 WARN("Connecting to %s, no response yet, retrying: le is %lx\n", debugstr_w(pipefn), GetLastError());
875 if (!ReadFile(hPipe,marshalbuffer,sizeof(marshalbuffer),&bufferlen,NULL)) {
876 FIXME("Failed to read marshal id from classfactory of %s.\n",debugstr_guid(rclsid));
880 TRACE("read marshal id from pipe\n");
885 if (tries >= MAXTRIES)
886 return E_NOINTERFACE;
888 hres = CreateStreamOnHGlobal(0,TRUE,&pStm);
889 if (hres) return hres;
890 hres = IStream_Write(pStm,marshalbuffer,bufferlen,&res);
892 seekto.u.LowPart = 0;seekto.u.HighPart = 0;
893 hres = IStream_Seek(pStm,seekto,SEEK_SET,&newpos);
895 TRACE("unmarshalling classfactory\n");
896 hres = CoUnmarshalInterface(pStm,&IID_IClassFactory,ppv);
898 IStream_Release(pStm);
903 struct local_server_params
909 /* FIXME: should call to rpcss instead */
910 static DWORD WINAPI local_server_thread(LPVOID param)
912 struct local_server_params * lsp = (struct local_server_params *)param;
916 IStream *pStm = lsp->stream;
918 unsigned char *buffer;
920 LARGE_INTEGER seekto;
921 ULARGE_INTEGER newpos;
924 TRACE("Starting threader for %s.\n",debugstr_guid(&lsp->clsid));
926 get_localserver_pipe_name(pipefn, &lsp->clsid);
928 HeapFree(GetProcessHeap(), 0, lsp);
930 hPipe = CreateNamedPipeW( pipefn, PIPE_ACCESS_DUPLEX,
931 PIPE_TYPE_BYTE|PIPE_WAIT, PIPE_UNLIMITED_INSTANCES,
932 4096, 4096, 500 /* 0.5 second timeout */, NULL );
934 if (hPipe == INVALID_HANDLE_VALUE)
936 FIXME("pipe creation failed for %s, le is %ld\n", debugstr_w(pipefn), GetLastError());
941 if (!ConnectNamedPipe(hPipe,NULL)) {
942 ERR("Failure during ConnectNamedPipe %ld, ABORT!\n",GetLastError());
946 TRACE("marshalling IClassFactory to client\n");
948 hres = IStream_Stat(pStm,&ststg,0);
949 if (hres) return hres;
951 buflen = ststg.cbSize.u.LowPart;
952 buffer = HeapAlloc(GetProcessHeap(),0,buflen);
953 seekto.u.LowPart = 0;
954 seekto.u.HighPart = 0;
955 hres = IStream_Seek(pStm,seekto,SEEK_SET,&newpos);
957 FIXME("IStream_Seek failed, %lx\n",hres);
961 hres = IStream_Read(pStm,buffer,buflen,&res);
963 FIXME("Stream Read failed, %lx\n",hres);
967 WriteFile(hPipe,buffer,buflen,&res,NULL);
968 FlushFileBuffers(hPipe);
969 DisconnectNamedPipe(hPipe);
971 TRACE("done marshalling IClassFactory\n");
974 IStream_Release(pStm);
978 void RPC_StartLocalServer(REFCLSID clsid, IStream *stream)
982 struct local_server_params *lsp = HeapAlloc(GetProcessHeap(), 0, sizeof(*lsp));
985 lsp->stream = stream;
987 thread = CreateThread(NULL, 0, local_server_thread, lsp, 0, &tid);
989 /* FIXME: failure handling */