4 * Copyright 2001 Ove Kåven, TransGaming Technologies
5 * Copyright 2002 Marcus Meissner
6 * Copyright 2005 Mike Hearn, Rob Shearman for CodeWeavers
8 * This library is free software; you can redistribute it and/or
9 * modify it under the terms of the GNU Lesser General Public
10 * License as published by the Free Software Foundation; either
11 * version 2.1 of the License, or (at your option) any later version.
13 * This library is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 * Lesser General Public License for more details.
18 * You should have received a copy of the GNU Lesser General Public
19 * License along with this library; if not, write to the Free Software
20 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
24 #include "wine/port.h"
33 #define NONAMELESSUNION
34 #define NONAMELESSSTRUCT
46 #include "wine/unicode.h"
48 #include "compobj_private.h"
50 #include "wine/debug.h"
52 WINE_DEFAULT_DEBUG_CHANNEL(ole);
54 static void __RPC_STUB dispatch_rpc(RPC_MESSAGE *msg);
56 /* we only use one function to dispatch calls for all methods - we use the
57 * RPC_IF_OLE flag to tell the RPC runtime that this is the case */
58 static RPC_DISPATCH_FUNCTION rpc_dispatch_table[1] = { dispatch_rpc }; /* (RO) */
59 static RPC_DISPATCH_TABLE rpc_dispatch = { 1, rpc_dispatch_table }; /* (RO) */
61 static struct list registered_interfaces = LIST_INIT(registered_interfaces); /* (CS csRegIf) */
62 static CRITICAL_SECTION csRegIf;
63 static CRITICAL_SECTION_DEBUG csRegIf_debug =
66 { &csRegIf_debug.ProcessLocksList, &csRegIf_debug.ProcessLocksList },
67 0, 0, { (DWORD_PTR)(__FILE__ ": dcom registered server interfaces") }
69 static CRITICAL_SECTION csRegIf = { &csRegIf_debug, -1, 0, 0, 0, 0 };
71 static WCHAR wszRpcTransport[] = {'n','c','a','l','r','p','c',0};
77 DWORD refs; /* ref count */
78 RPC_SERVER_INTERFACE If; /* interface registered with the RPC runtime */
81 /* get the pipe endpoint specified of the specified apartment */
82 static inline void get_rpc_endpoint(LPWSTR endpoint, const OXID *oxid)
84 /* FIXME: should get endpoint from rpcss */
85 static const WCHAR wszEndpointFormat[] = {'\\','p','i','p','e','\\','O','L','E','_','%','0','8','l','x','%','0','8','l','x',0};
86 wsprintfW(endpoint, wszEndpointFormat, (DWORD)(*oxid >> 32),(DWORD)*oxid);
91 const IRpcChannelBufferVtbl *lpVtbl;
97 RpcChannelBuffer super; /* superclass */
99 RPC_BINDING_HANDLE bind; /* handle to the remote server */
100 OXID oxid; /* apartment in which the channel is valid */
101 DWORD dest_context; /* returned from GetDestCtx */
102 LPVOID dest_context_data; /* returned from GetDestCtx */
103 } ClientRpcChannelBuffer;
105 struct dispatch_params
107 RPCOLEMESSAGE *msg; /* message */
108 IRpcStubBuffer *stub; /* stub buffer, if applicable */
109 IRpcChannelBuffer *chan; /* server channel buffer, if applicable */
110 HANDLE handle; /* handle that will become signaled when call finishes */
111 RPC_STATUS status; /* status (out) */
112 HRESULT hr; /* hresult (out) */
115 static HRESULT WINAPI RpcChannelBuffer_QueryInterface(LPRPCCHANNELBUFFER iface, REFIID riid, LPVOID *ppv)
118 if (IsEqualIID(riid,&IID_IRpcChannelBuffer) || IsEqualIID(riid,&IID_IUnknown))
120 *ppv = (LPVOID)iface;
121 IUnknown_AddRef(iface);
124 return E_NOINTERFACE;
127 static ULONG WINAPI RpcChannelBuffer_AddRef(LPRPCCHANNELBUFFER iface)
129 RpcChannelBuffer *This = (RpcChannelBuffer *)iface;
130 return InterlockedIncrement(&This->refs);
133 static ULONG WINAPI ServerRpcChannelBuffer_Release(LPRPCCHANNELBUFFER iface)
135 RpcChannelBuffer *This = (RpcChannelBuffer *)iface;
138 ref = InterlockedDecrement(&This->refs);
142 HeapFree(GetProcessHeap(), 0, This);
146 static ULONG WINAPI ClientRpcChannelBuffer_Release(LPRPCCHANNELBUFFER iface)
148 ClientRpcChannelBuffer *This = (ClientRpcChannelBuffer *)iface;
151 ref = InterlockedDecrement(&This->super.refs);
155 RpcBindingFree(&This->bind);
156 HeapFree(GetProcessHeap(), 0, This);
160 static HRESULT WINAPI ServerRpcChannelBuffer_GetBuffer(LPRPCCHANNELBUFFER iface, RPCOLEMESSAGE* olemsg, REFIID riid)
162 RpcChannelBuffer *This = (RpcChannelBuffer *)iface;
163 RPC_MESSAGE *msg = (RPC_MESSAGE *)olemsg;
166 TRACE("(%p)->(%p,%s)\n", This, olemsg, debugstr_guid(riid));
168 status = I_RpcGetBuffer(msg);
170 TRACE("-- %ld\n", status);
172 return HRESULT_FROM_WIN32(status);
175 static HRESULT WINAPI ClientRpcChannelBuffer_GetBuffer(LPRPCCHANNELBUFFER iface, RPCOLEMESSAGE* olemsg, REFIID riid)
177 ClientRpcChannelBuffer *This = (ClientRpcChannelBuffer *)iface;
178 RPC_MESSAGE *msg = (RPC_MESSAGE *)olemsg;
179 RPC_CLIENT_INTERFACE *cif;
182 TRACE("(%p)->(%p,%s)\n", This, olemsg, debugstr_guid(riid));
184 cif = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(RPC_CLIENT_INTERFACE));
186 return E_OUTOFMEMORY;
188 cif->Length = sizeof(RPC_CLIENT_INTERFACE);
189 /* RPC interface ID = COM interface ID */
190 cif->InterfaceId.SyntaxGUID = *riid;
191 /* COM objects always have a version of 0.0 */
192 cif->InterfaceId.SyntaxVersion.MajorVersion = 0;
193 cif->InterfaceId.SyntaxVersion.MinorVersion = 0;
194 msg->RpcInterfaceInformation = cif;
195 msg->Handle = This->bind;
197 status = I_RpcGetBuffer(msg);
199 TRACE("-- %ld\n", status);
201 return HRESULT_FROM_WIN32(status);
204 static HRESULT WINAPI ServerRpcChannelBuffer_SendReceive(LPRPCCHANNELBUFFER iface, RPCOLEMESSAGE *olemsg, ULONG *pstatus)
210 /* this thread runs an outgoing RPC */
211 static DWORD WINAPI rpc_sendreceive_thread(LPVOID param)
213 struct dispatch_params *data = (struct dispatch_params *) param;
215 /* FIXME: trap and rethrow RPC exceptions in app thread */
216 data->status = I_RpcSendReceive((RPC_MESSAGE *)data->msg);
218 TRACE("completed with status 0x%lx\n", data->status);
220 SetEvent(data->handle);
225 static inline HRESULT ClientRpcChannelBuffer_IsCorrectApartment(ClientRpcChannelBuffer *This, APARTMENT *apt)
230 if (apartment_getoxid(apt, &oxid) != S_OK)
232 if (This->oxid != oxid)
237 static HRESULT WINAPI ClientRpcChannelBuffer_SendReceive(LPRPCCHANNELBUFFER iface, RPCOLEMESSAGE *olemsg, ULONG *pstatus)
239 ClientRpcChannelBuffer *This = (ClientRpcChannelBuffer *)iface;
241 RPC_MESSAGE *msg = (RPC_MESSAGE *)olemsg;
244 struct dispatch_params *params;
245 APARTMENT *apt = NULL;
248 TRACE("(%p) iMethod=%ld\n", olemsg, olemsg->iMethod);
250 hr = ClientRpcChannelBuffer_IsCorrectApartment(This, COM_CurrentApt());
253 ERR("called from wrong apartment, should have been 0x%s\n",
254 wine_dbgstr_longlong(This->oxid));
255 return RPC_E_WRONG_THREAD;
258 params = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*params));
259 if (!params) return E_OUTOFMEMORY;
261 params->msg = olemsg;
262 params->status = RPC_S_OK;
265 /* Note: this is an optimization in the Microsoft OLE runtime that we need
266 * to copy, as shown by the test_no_couninitialize_client test. without
267 * short-circuiting the RPC runtime in the case below, the test will
268 * deadlock on the loader lock due to the RPC runtime needing to create
269 * a thread to process the RPC when this function is called indirectly
272 RpcBindingInqObject(msg->Handle, &ipid);
273 hr = ipid_get_dispatch_params(&ipid, &apt, ¶ms->stub, ¶ms->chan);
274 params->handle = CreateEventW(NULL, FALSE, FALSE, NULL);
275 if ((hr == S_OK) && !apt->multi_threaded)
277 TRACE("Calling apartment thread 0x%08lx...\n", apt->tid);
279 if (!PostMessageW(apartment_getwindow(apt), DM_EXECUTERPC, 0, (LPARAM)params))
281 ERR("PostMessage failed with error %ld\n", GetLastError());
282 hr = HRESULT_FROM_WIN32(GetLastError());
289 /* otherwise, we go via RPC runtime so the stub and channel aren't
291 IRpcStubBuffer_Release(params->stub);
293 IRpcChannelBuffer_Release(params->chan);
297 /* we use a separate thread here because we need to be able to
298 * pump the message loop in the application thread: if we do not,
299 * any windows created by this thread will hang and RPCs that try
300 * and re-enter this STA from an incoming server thread will
301 * deadlock. InstallShield is an example of that.
303 if (!QueueUserWorkItem(rpc_sendreceive_thread, params, WT_EXECUTEDEFAULT))
305 ERR("QueueUserWorkItem failed with error %lx\n", GetLastError());
311 if (apt) apartment_release(apt);
315 if (WaitForSingleObject(params->handle, 0))
316 hr = CoWaitForMultipleHandles(0, INFINITE, 1, ¶ms->handle, &index);
318 CloseHandle(params->handle);
320 if (hr == S_OK) hr = params->hr;
322 status = params->status;
323 HeapFree(GetProcessHeap(), 0, params);
328 if (pstatus) *pstatus = status;
330 TRACE("RPC call status: 0x%lx\n", status);
331 if (status == RPC_S_OK)
333 else if (status == RPC_S_CALL_FAILED)
334 hr = *(HRESULT *)olemsg->Buffer;
336 hr = HRESULT_FROM_WIN32(status);
338 TRACE("-- 0x%08lx\n", hr);
343 static HRESULT WINAPI ServerRpcChannelBuffer_FreeBuffer(LPRPCCHANNELBUFFER iface, RPCOLEMESSAGE* olemsg)
345 RPC_MESSAGE *msg = (RPC_MESSAGE *)olemsg;
348 TRACE("(%p)\n", msg);
350 status = I_RpcFreeBuffer(msg);
352 TRACE("-- %ld\n", status);
354 return HRESULT_FROM_WIN32(status);
357 static HRESULT WINAPI ClientRpcChannelBuffer_FreeBuffer(LPRPCCHANNELBUFFER iface, RPCOLEMESSAGE* olemsg)
359 RPC_MESSAGE *msg = (RPC_MESSAGE *)olemsg;
362 TRACE("(%p)\n", msg);
364 status = I_RpcFreeBuffer(msg);
366 HeapFree(GetProcessHeap(), 0, msg->RpcInterfaceInformation);
367 msg->RpcInterfaceInformation = NULL;
369 TRACE("-- %ld\n", status);
371 return HRESULT_FROM_WIN32(status);
374 static HRESULT WINAPI ClientRpcChannelBuffer_GetDestCtx(LPRPCCHANNELBUFFER iface, DWORD* pdwDestContext, void** ppvDestContext)
376 ClientRpcChannelBuffer *This = (ClientRpcChannelBuffer *)iface;
378 TRACE("(%p,%p)\n", pdwDestContext, ppvDestContext);
380 *pdwDestContext = This->dest_context;
381 *ppvDestContext = This->dest_context_data;
386 static HRESULT WINAPI ServerRpcChannelBuffer_GetDestCtx(LPRPCCHANNELBUFFER iface, DWORD* pdwDestContext, void** ppvDestContext)
388 FIXME("(%p,%p), stub!\n", pdwDestContext, ppvDestContext);
392 static HRESULT WINAPI RpcChannelBuffer_IsConnected(LPRPCCHANNELBUFFER iface)
395 /* native does nothing too */
399 static const IRpcChannelBufferVtbl ClientRpcChannelBufferVtbl =
401 RpcChannelBuffer_QueryInterface,
402 RpcChannelBuffer_AddRef,
403 ClientRpcChannelBuffer_Release,
404 ClientRpcChannelBuffer_GetBuffer,
405 ClientRpcChannelBuffer_SendReceive,
406 ClientRpcChannelBuffer_FreeBuffer,
407 ClientRpcChannelBuffer_GetDestCtx,
408 RpcChannelBuffer_IsConnected
411 static const IRpcChannelBufferVtbl ServerRpcChannelBufferVtbl =
413 RpcChannelBuffer_QueryInterface,
414 RpcChannelBuffer_AddRef,
415 ServerRpcChannelBuffer_Release,
416 ServerRpcChannelBuffer_GetBuffer,
417 ServerRpcChannelBuffer_SendReceive,
418 ServerRpcChannelBuffer_FreeBuffer,
419 ServerRpcChannelBuffer_GetDestCtx,
420 RpcChannelBuffer_IsConnected
423 /* returns a channel buffer for proxies */
424 HRESULT RPC_CreateClientChannel(const OXID *oxid, const IPID *ipid,
425 DWORD dest_context, void *dest_context_data,
426 IRpcChannelBuffer **chan)
428 ClientRpcChannelBuffer *This;
430 RPC_BINDING_HANDLE bind;
432 LPWSTR string_binding;
434 /* connect to the apartment listener thread */
435 get_rpc_endpoint(endpoint, oxid);
437 TRACE("proxy pipe: connecting to endpoint: %s\n", debugstr_w(endpoint));
439 status = RpcStringBindingComposeW(
447 if (status == RPC_S_OK)
449 status = RpcBindingFromStringBindingW(string_binding, &bind);
451 if (status == RPC_S_OK)
453 IPID ipid2 = *ipid; /* why can't RpcBindingSetObject take a const? */
454 status = RpcBindingSetObject(bind, &ipid2);
455 if (status != RPC_S_OK)
456 RpcBindingFree(&bind);
459 RpcStringFreeW(&string_binding);
462 if (status != RPC_S_OK)
464 ERR("Couldn't get binding for endpoint %s, status = %ld\n", debugstr_w(endpoint), status);
465 return HRESULT_FROM_WIN32(status);
468 This = HeapAlloc(GetProcessHeap(), 0, sizeof(*This));
471 RpcBindingFree(&bind);
472 return E_OUTOFMEMORY;
475 This->super.lpVtbl = &ClientRpcChannelBufferVtbl;
476 This->super.refs = 1;
478 apartment_getoxid(COM_CurrentApt(), &This->oxid);
479 This->dest_context = dest_context;
480 This->dest_context_data = dest_context_data;
482 *chan = (IRpcChannelBuffer*)This;
487 HRESULT RPC_CreateServerChannel(IRpcChannelBuffer **chan)
489 RpcChannelBuffer *This = HeapAlloc(GetProcessHeap(), 0, sizeof(*This));
491 return E_OUTOFMEMORY;
493 This->lpVtbl = &ServerRpcChannelBufferVtbl;
496 *chan = (IRpcChannelBuffer*)This;
502 void RPC_ExecuteCall(struct dispatch_params *params)
504 params->hr = IRpcStubBuffer_Invoke(params->stub, params->msg, params->chan);
506 IRpcStubBuffer_Release(params->stub);
507 IRpcChannelBuffer_Release(params->chan);
508 if (params->handle) SetEvent(params->handle);
511 static void __RPC_STUB dispatch_rpc(RPC_MESSAGE *msg)
513 struct dispatch_params *params;
518 RpcBindingInqObject(msg->Handle, &ipid);
520 TRACE("ipid = %s, iMethod = %d\n", debugstr_guid(&ipid), msg->ProcNum);
522 params = HeapAlloc(GetProcessHeap(), 0, sizeof(*params));
523 if (!params) return RpcRaiseException(E_OUTOFMEMORY);
525 hr = ipid_get_dispatch_params(&ipid, &apt, ¶ms->stub, ¶ms->chan);
528 ERR("no apartment found for ipid %s\n", debugstr_guid(&ipid));
529 return RpcRaiseException(hr);
532 params->msg = (RPCOLEMESSAGE *)msg;
533 params->status = RPC_S_OK;
535 params->handle = NULL;
537 /* Note: this is the important difference between STAs and MTAs - we
538 * always execute RPCs to STAs in the thread that originally created the
539 * apartment (i.e. the one that pumps messages to the window) */
540 if (!apt->multi_threaded)
542 params->handle = CreateEventW(NULL, FALSE, FALSE, NULL);
544 TRACE("Calling apartment thread 0x%08lx...\n", apt->tid);
546 if (PostMessageW(apartment_getwindow(apt), DM_EXECUTERPC, 0, (LPARAM)params))
547 WaitForSingleObject(params->handle, INFINITE);
550 ERR("PostMessage failed with error %ld\n", GetLastError());
551 IRpcChannelBuffer_Release(params->chan);
552 IRpcStubBuffer_Release(params->stub);
554 CloseHandle(params->handle);
559 if (!COM_CurrentInfo()->apt)
564 RPC_ExecuteCall(params);
567 apartment_release(COM_CurrentInfo()->apt);
568 COM_CurrentInfo()->apt = NULL;
572 HeapFree(GetProcessHeap(), 0, params);
574 apartment_release(apt);
577 /* stub registration */
578 HRESULT RPC_RegisterInterface(REFIID riid)
580 struct registered_if *rif;
584 TRACE("(%s)\n", debugstr_guid(riid));
586 EnterCriticalSection(&csRegIf);
587 LIST_FOR_EACH_ENTRY(rif, ®istered_interfaces, struct registered_if, entry)
589 if (IsEqualGUID(&rif->If.InterfaceId.SyntaxGUID, riid))
598 TRACE("Creating new interface\n");
600 rif = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*rif));
606 rif->If.Length = sizeof(RPC_SERVER_INTERFACE);
607 /* RPC interface ID = COM interface ID */
608 rif->If.InterfaceId.SyntaxGUID = *riid;
609 rif->If.DispatchTable = &rpc_dispatch;
610 /* all other fields are 0, including the version asCOM objects
611 * always have a version of 0.0 */
612 status = RpcServerRegisterIfEx(
613 (RPC_IF_HANDLE)&rif->If,
615 RPC_IF_OLE | RPC_IF_AUTOLISTEN,
616 RPC_C_LISTEN_MAX_CALLS_DEFAULT,
618 if (status == RPC_S_OK)
619 list_add_tail(®istered_interfaces, &rif->entry);
622 ERR("RpcServerRegisterIfEx failed with error %ld\n", status);
623 HeapFree(GetProcessHeap(), 0, rif);
624 hr = HRESULT_FROM_WIN32(status);
630 LeaveCriticalSection(&csRegIf);
634 /* stub unregistration */
635 void RPC_UnregisterInterface(REFIID riid)
637 struct registered_if *rif;
638 EnterCriticalSection(&csRegIf);
639 LIST_FOR_EACH_ENTRY(rif, ®istered_interfaces, struct registered_if, entry)
641 if (IsEqualGUID(&rif->If.InterfaceId.SyntaxGUID, riid))
645 #if 0 /* this is a stub in builtin and spams the console with FIXME's */
646 IID iid = *riid; /* RpcServerUnregisterIf doesn't take const IID */
647 RpcServerUnregisterIf((RPC_IF_HANDLE)&rif->If, &iid, 0);
648 list_remove(&rif->entry);
649 HeapFree(GetProcessHeap(), 0, rif);
655 LeaveCriticalSection(&csRegIf);
658 /* make the apartment reachable by other threads and processes and create the
659 * IRemUnknown object */
660 void RPC_StartRemoting(struct apartment *apt)
662 if (!InterlockedExchange(&apt->remoting_started, TRUE))
667 get_rpc_endpoint(endpoint, &apt->oxid);
669 status = RpcServerUseProtseqEpW(
671 RPC_C_PROTSEQ_MAX_REQS_DEFAULT,
674 if (status != RPC_S_OK)
675 ERR("Couldn't register endpoint %s\n", debugstr_w(endpoint));
677 /* FIXME: move remote unknown exporting into this function */
679 start_apartment_remote_unknown();
683 static HRESULT create_server(REFCLSID rclsid)
685 static const WCHAR wszLocalServer32[] = { 'L','o','c','a','l','S','e','r','v','e','r','3','2',0 };
686 static const WCHAR embedding[] = { ' ', '-','E','m','b','e','d','d','i','n','g',0 };
689 WCHAR command[MAX_PATH+sizeof(embedding)/sizeof(WCHAR)];
690 DWORD size = (MAX_PATH+1) * sizeof(WCHAR);
692 PROCESS_INFORMATION pinfo;
694 hres = COM_OpenKeyForCLSID(rclsid, wszLocalServer32, KEY_READ, &key);
696 ERR("class %s not registered\n", debugstr_guid(rclsid));
700 hres = RegQueryValueExW(key, NULL, NULL, NULL, (LPBYTE)command, &size);
703 WARN("No default value for LocalServer32 key\n");
704 return REGDB_E_CLASSNOTREG; /* FIXME: check retval */
707 memset(&sinfo,0,sizeof(sinfo));
708 sinfo.cb = sizeof(sinfo);
710 /* EXE servers are started with the -Embedding switch. */
712 strcatW(command, embedding);
714 TRACE("activating local server %s for %s\n", debugstr_w(command), debugstr_guid(rclsid));
716 /* FIXME: Win2003 supports a ServerExecutable value that is passed into
718 if (!CreateProcessW(NULL, command, NULL, NULL, FALSE, 0, NULL, NULL, &sinfo, &pinfo)) {
719 WARN("failed to run local server %s\n", debugstr_w(command));
720 return HRESULT_FROM_WIN32(GetLastError());
722 CloseHandle(pinfo.hProcess);
723 CloseHandle(pinfo.hThread);
729 * start_local_service() - start a service given its name and parameters
731 static DWORD start_local_service(LPCWSTR name, DWORD num, LPCWSTR *params)
733 SC_HANDLE handle, hsvc;
734 DWORD r = ERROR_FUNCTION_FAILED;
736 TRACE("Starting service %s %ld params\n", debugstr_w(name), num);
738 handle = OpenSCManagerW(NULL, NULL, SC_MANAGER_CONNECT);
741 hsvc = OpenServiceW(handle, name, SERVICE_START);
744 if(StartServiceW(hsvc, num, params))
748 if (r == ERROR_SERVICE_ALREADY_RUNNING)
750 CloseServiceHandle(hsvc);
754 CloseServiceHandle(handle);
756 TRACE("StartService returned error %ld (%s)\n", r, (r == ERROR_SUCCESS) ? "ok":"failed");
762 * create_local_service() - start a COM server in a service
764 * To start a Local Service, we read the AppID value under
765 * the class's CLSID key, then open the HKCR\\AppId key specified
766 * there and check for a LocalService value.
768 * Note: Local Services are not supported under Windows 9x
770 static HRESULT create_local_service(REFCLSID rclsid)
773 WCHAR buf[CHARS_IN_GUID], keyname[50];
774 static const WCHAR szAppId[] = { 'A','p','p','I','d',0 };
775 static const WCHAR szAppIdKey[] = { 'A','p','p','I','d','\\',0 };
776 static const WCHAR szLocalService[] = { 'L','o','c','a','l','S','e','r','v','i','c','e',0 };
777 static const WCHAR szServiceParams[] = {'S','e','r','v','i','c','e','P','a','r','a','m','s',0};
782 TRACE("Attempting to start Local service for %s\n", debugstr_guid(rclsid));
784 /* read the AppID value under the class's key */
785 hres = COM_OpenKeyForCLSID(rclsid, szAppId, KEY_READ, &hkey);
789 r = RegQueryValueExW(hkey, NULL, NULL, &type, (LPBYTE)buf, &sz);
791 if (r!=ERROR_SUCCESS || type!=REG_SZ)
794 /* read the LocalService and ServiceParameters values from the AppID key */
795 strcpyW(keyname, szAppIdKey);
796 strcatW(keyname, buf);
797 r = RegOpenKeyExW(HKEY_CLASSES_ROOT, keyname, 0, KEY_READ, &hkey);
798 if (r!=ERROR_SUCCESS)
801 r = RegQueryValueExW(hkey, szLocalService, NULL, &type, (LPBYTE)buf, &sz);
802 if (r==ERROR_SUCCESS && type==REG_SZ)
805 LPWSTR args[1] = { NULL };
808 * FIXME: I'm not really sure how to deal with the service parameters.
809 * I suspect that the string returned from RegQueryValueExW
810 * should be split into a number of arguments by spaces.
811 * It would make more sense if ServiceParams contained a
812 * REG_MULTI_SZ here, but it's a REG_SZ for the services
813 * that I'm interested in for the moment.
815 r = RegQueryValueExW(hkey, szServiceParams, NULL, &type, NULL, &sz);
816 if (r == ERROR_SUCCESS && type == REG_SZ && sz)
818 args[0] = HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY,sz);
820 RegQueryValueExW(hkey, szServiceParams, NULL, &type, (LPBYTE)args[0], &sz);
822 r = start_local_service(buf, num_args, (LPCWSTR *)args);
823 if (r==ERROR_SUCCESS)
825 HeapFree(GetProcessHeap(),0,args[0]);
833 static void get_localserver_pipe_name(WCHAR *pipefn, REFCLSID rclsid)
835 static const WCHAR wszPipeRef[] = {'\\','\\','.','\\','p','i','p','e','\\',0};
836 strcpyW(pipefn, wszPipeRef);
837 StringFromGUID2(rclsid, pipefn + sizeof(wszPipeRef)/sizeof(wszPipeRef[0]) - 1, CHARS_IN_GUID);
840 /* FIXME: should call to rpcss instead */
841 HRESULT RPC_GetLocalClassObject(REFCLSID rclsid, REFIID iid, LPVOID *ppv)
846 DWORD res, bufferlen;
847 char marshalbuffer[200];
849 LARGE_INTEGER seekto;
850 ULARGE_INTEGER newpos;
853 static const int MAXTRIES = 30; /* 30 seconds */
855 TRACE("rclsid=%s, iid=%s\n", debugstr_guid(rclsid), debugstr_guid(iid));
857 get_localserver_pipe_name(pipefn, rclsid);
859 while (tries++ < MAXTRIES) {
860 TRACE("waiting for %s\n", debugstr_w(pipefn));
862 WaitNamedPipeW( pipefn, NMPWAIT_WAIT_FOREVER );
863 hPipe = CreateFileW(pipefn, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, 0);
864 if (hPipe == INVALID_HANDLE_VALUE) {
866 if ( (hres = create_local_service(rclsid)) &&
867 (hres = create_server(rclsid)) )
871 WARN("Connecting to %s, no response yet, retrying: le is %lx\n", debugstr_w(pipefn), GetLastError());
877 if (!ReadFile(hPipe,marshalbuffer,sizeof(marshalbuffer),&bufferlen,NULL)) {
878 FIXME("Failed to read marshal id from classfactory of %s.\n",debugstr_guid(rclsid));
882 TRACE("read marshal id from pipe\n");
887 if (tries >= MAXTRIES)
888 return E_NOINTERFACE;
890 hres = CreateStreamOnHGlobal(0,TRUE,&pStm);
891 if (hres) return hres;
892 hres = IStream_Write(pStm,marshalbuffer,bufferlen,&res);
894 seekto.u.LowPart = 0;seekto.u.HighPart = 0;
895 hres = IStream_Seek(pStm,seekto,SEEK_SET,&newpos);
897 TRACE("unmarshalling classfactory\n");
898 hres = CoUnmarshalInterface(pStm,&IID_IClassFactory,ppv);
900 IStream_Release(pStm);
905 struct local_server_params
911 /* FIXME: should call to rpcss instead */
912 static DWORD WINAPI local_server_thread(LPVOID param)
914 struct local_server_params * lsp = (struct local_server_params *)param;
918 IStream *pStm = lsp->stream;
920 unsigned char *buffer;
922 LARGE_INTEGER seekto;
923 ULARGE_INTEGER newpos;
926 TRACE("Starting threader for %s.\n",debugstr_guid(&lsp->clsid));
928 get_localserver_pipe_name(pipefn, &lsp->clsid);
930 HeapFree(GetProcessHeap(), 0, lsp);
932 hPipe = CreateNamedPipeW( pipefn, PIPE_ACCESS_DUPLEX,
933 PIPE_TYPE_BYTE|PIPE_WAIT, PIPE_UNLIMITED_INSTANCES,
934 4096, 4096, 500 /* 0.5 second timeout */, NULL );
936 if (hPipe == INVALID_HANDLE_VALUE)
938 FIXME("pipe creation failed for %s, le is %ld\n", debugstr_w(pipefn), GetLastError());
943 if (!ConnectNamedPipe(hPipe,NULL)) {
944 ERR("Failure during ConnectNamedPipe %ld, ABORT!\n",GetLastError());
948 TRACE("marshalling IClassFactory to client\n");
950 hres = IStream_Stat(pStm,&ststg,0);
951 if (hres) return hres;
953 buflen = ststg.cbSize.u.LowPart;
954 buffer = HeapAlloc(GetProcessHeap(),0,buflen);
955 seekto.u.LowPart = 0;
956 seekto.u.HighPart = 0;
957 hres = IStream_Seek(pStm,seekto,SEEK_SET,&newpos);
959 FIXME("IStream_Seek failed, %lx\n",hres);
963 hres = IStream_Read(pStm,buffer,buflen,&res);
965 FIXME("Stream Read failed, %lx\n",hres);
969 WriteFile(hPipe,buffer,buflen,&res,NULL);
970 FlushFileBuffers(hPipe);
971 DisconnectNamedPipe(hPipe);
973 TRACE("done marshalling IClassFactory\n");
976 IStream_Release(pStm);
980 void RPC_StartLocalServer(REFCLSID clsid, IStream *stream)
984 struct local_server_params *lsp = HeapAlloc(GetProcessHeap(), 0, sizeof(*lsp));
987 lsp->stream = stream;
989 thread = CreateThread(NULL, 0, local_server_thread, lsp, 0, &tid);
991 /* FIXME: failure handling */