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
24 #include "wine/port.h"
33 #define NONAMELESSUNION
34 #define NONAMELESSSTRUCT
47 #include "wine/unicode.h"
48 #include "wine/exception.h"
50 #include "compobj_private.h"
52 #include "wine/debug.h"
54 WINE_DEFAULT_DEBUG_CHANNEL(ole);
56 static void __RPC_STUB dispatch_rpc(RPC_MESSAGE *msg);
58 /* we only use one function to dispatch calls for all methods - we use the
59 * RPC_IF_OLE flag to tell the RPC runtime that this is the case */
60 static RPC_DISPATCH_FUNCTION rpc_dispatch_table[1] = { dispatch_rpc }; /* (RO) */
61 static RPC_DISPATCH_TABLE rpc_dispatch = { 1, rpc_dispatch_table }; /* (RO) */
63 static struct list registered_interfaces = LIST_INIT(registered_interfaces); /* (CS csRegIf) */
64 static CRITICAL_SECTION csRegIf;
65 static CRITICAL_SECTION_DEBUG csRegIf_debug =
68 { &csRegIf_debug.ProcessLocksList, &csRegIf_debug.ProcessLocksList },
69 0, 0, { (DWORD_PTR)(__FILE__ ": dcom registered server interfaces") }
71 static CRITICAL_SECTION csRegIf = { &csRegIf_debug, -1, 0, 0, 0, 0 };
73 static WCHAR wszPipeTransport[] = {'n','c','a','c','n','_','n','p',0};
79 DWORD refs; /* ref count */
80 RPC_SERVER_INTERFACE If; /* interface registered with the RPC runtime */
83 /* get the pipe endpoint specified of the specified apartment */
84 static inline void get_rpc_endpoint(LPWSTR endpoint, const OXID *oxid)
86 /* FIXME: should get endpoint from rpcss */
87 static const WCHAR wszEndpointFormat[] = {'\\','p','i','p','e','\\','O','L','E','_','%','0','8','l','x','%','0','8','l','x',0};
88 wsprintfW(endpoint, wszEndpointFormat, (DWORD)(*oxid >> 32),(DWORD)*oxid);
93 const IRpcChannelBufferVtbl *lpVtbl;
99 RpcChannelBuffer super; /* superclass */
101 RPC_BINDING_HANDLE bind; /* handle to the remote server */
102 OXID oxid; /* apartment in which the channel is valid */
103 DWORD dest_context; /* returned from GetDestCtx */
104 LPVOID dest_context_data; /* returned from GetDestCtx */
105 } ClientRpcChannelBuffer;
107 struct dispatch_params
109 RPCOLEMESSAGE *msg; /* message */
110 IRpcStubBuffer *stub; /* stub buffer, if applicable */
111 IRpcChannelBuffer *chan; /* server channel buffer, if applicable */
112 HANDLE handle; /* handle that will become signaled when call finishes */
113 RPC_STATUS status; /* status (out) */
114 HRESULT hr; /* hresult (out) */
117 static WINE_EXCEPTION_FILTER(ole_filter)
119 if (GetExceptionCode() == EXCEPTION_ACCESS_VIOLATION)
120 return EXCEPTION_CONTINUE_SEARCH;
121 return EXCEPTION_EXECUTE_HANDLER;
124 static HRESULT WINAPI RpcChannelBuffer_QueryInterface(LPRPCCHANNELBUFFER iface, REFIID riid, LPVOID *ppv)
127 if (IsEqualIID(riid,&IID_IRpcChannelBuffer) || IsEqualIID(riid,&IID_IUnknown))
129 *ppv = (LPVOID)iface;
130 IUnknown_AddRef(iface);
133 return E_NOINTERFACE;
136 static ULONG WINAPI RpcChannelBuffer_AddRef(LPRPCCHANNELBUFFER iface)
138 RpcChannelBuffer *This = (RpcChannelBuffer *)iface;
139 return InterlockedIncrement(&This->refs);
142 static ULONG WINAPI ServerRpcChannelBuffer_Release(LPRPCCHANNELBUFFER iface)
144 RpcChannelBuffer *This = (RpcChannelBuffer *)iface;
147 ref = InterlockedDecrement(&This->refs);
151 HeapFree(GetProcessHeap(), 0, This);
155 static ULONG WINAPI ClientRpcChannelBuffer_Release(LPRPCCHANNELBUFFER iface)
157 ClientRpcChannelBuffer *This = (ClientRpcChannelBuffer *)iface;
160 ref = InterlockedDecrement(&This->super.refs);
164 RpcBindingFree(&This->bind);
165 HeapFree(GetProcessHeap(), 0, This);
169 static HRESULT WINAPI ServerRpcChannelBuffer_GetBuffer(LPRPCCHANNELBUFFER iface, RPCOLEMESSAGE* olemsg, REFIID riid)
171 RpcChannelBuffer *This = (RpcChannelBuffer *)iface;
172 RPC_MESSAGE *msg = (RPC_MESSAGE *)olemsg;
175 TRACE("(%p)->(%p,%s)\n", This, olemsg, debugstr_guid(riid));
177 status = I_RpcGetBuffer(msg);
179 TRACE("-- %ld\n", status);
181 return HRESULT_FROM_WIN32(status);
184 static HRESULT WINAPI ClientRpcChannelBuffer_GetBuffer(LPRPCCHANNELBUFFER iface, RPCOLEMESSAGE* olemsg, REFIID riid)
186 ClientRpcChannelBuffer *This = (ClientRpcChannelBuffer *)iface;
187 RPC_MESSAGE *msg = (RPC_MESSAGE *)olemsg;
188 RPC_CLIENT_INTERFACE *cif;
191 TRACE("(%p)->(%p,%s)\n", This, olemsg, debugstr_guid(riid));
193 cif = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(RPC_CLIENT_INTERFACE));
195 return E_OUTOFMEMORY;
197 cif->Length = sizeof(RPC_CLIENT_INTERFACE);
198 /* RPC interface ID = COM interface ID */
199 cif->InterfaceId.SyntaxGUID = *riid;
200 /* COM objects always have a version of 0.0 */
201 cif->InterfaceId.SyntaxVersion.MajorVersion = 0;
202 cif->InterfaceId.SyntaxVersion.MinorVersion = 0;
203 msg->RpcInterfaceInformation = cif;
204 msg->Handle = This->bind;
206 status = I_RpcGetBuffer(msg);
208 TRACE("-- %ld\n", status);
210 return HRESULT_FROM_WIN32(status);
213 static HRESULT WINAPI ServerRpcChannelBuffer_SendReceive(LPRPCCHANNELBUFFER iface, RPCOLEMESSAGE *olemsg, ULONG *pstatus)
219 /* this thread runs an outgoing RPC */
220 static DWORD WINAPI rpc_sendreceive_thread(LPVOID param)
222 struct dispatch_params *data = (struct dispatch_params *) param;
224 /* FIXME: trap and rethrow RPC exceptions in app thread */
225 data->status = I_RpcSendReceive((RPC_MESSAGE *)data->msg);
227 TRACE("completed with status 0x%lx\n", data->status);
229 SetEvent(data->handle);
234 static inline HRESULT ClientRpcChannelBuffer_IsCorrectApartment(ClientRpcChannelBuffer *This, APARTMENT *apt)
239 if (apartment_getoxid(apt, &oxid) != S_OK)
241 if (This->oxid != oxid)
246 static HRESULT WINAPI ClientRpcChannelBuffer_SendReceive(LPRPCCHANNELBUFFER iface, RPCOLEMESSAGE *olemsg, ULONG *pstatus)
248 ClientRpcChannelBuffer *This = (ClientRpcChannelBuffer *)iface;
250 RPC_MESSAGE *msg = (RPC_MESSAGE *)olemsg;
253 struct dispatch_params *params;
254 APARTMENT *apt = NULL;
257 TRACE("(%p) iMethod=%ld\n", olemsg, olemsg->iMethod);
259 hr = ClientRpcChannelBuffer_IsCorrectApartment(This, COM_CurrentApt());
262 ERR("called from wrong apartment, should have been 0x%s\n",
263 wine_dbgstr_longlong(This->oxid));
264 return RPC_E_WRONG_THREAD;
267 params = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*params));
268 if (!params) return E_OUTOFMEMORY;
270 params->msg = olemsg;
271 params->status = RPC_S_OK;
274 /* Note: this is an optimization in the Microsoft OLE runtime that we need
275 * to copy, as shown by the test_no_couninitialize_client test. without
276 * short-circuiting the RPC runtime in the case below, the test will
277 * deadlock on the loader lock due to the RPC runtime needing to create
278 * a thread to process the RPC when this function is called indirectly
281 RpcBindingInqObject(msg->Handle, &ipid);
282 hr = ipid_get_dispatch_params(&ipid, &apt, ¶ms->stub, ¶ms->chan);
283 params->handle = CreateEventW(NULL, FALSE, FALSE, NULL);
284 if ((hr == S_OK) && !apt->multi_threaded)
286 TRACE("Calling apartment thread 0x%08lx...\n", apt->tid);
288 if (!PostMessageW(apartment_getwindow(apt), DM_EXECUTERPC, 0, (LPARAM)params))
290 ERR("PostMessage failed with error %ld\n", GetLastError());
291 hr = HRESULT_FROM_WIN32(GetLastError());
298 /* otherwise, we go via RPC runtime so the stub and channel aren't
300 IRpcStubBuffer_Release(params->stub);
302 IRpcChannelBuffer_Release(params->chan);
306 /* we use a separate thread here because we need to be able to
307 * pump the message loop in the application thread: if we do not,
308 * any windows created by this thread will hang and RPCs that try
309 * and re-enter this STA from an incoming server thread will
310 * deadlock. InstallShield is an example of that.
312 if (!QueueUserWorkItem(rpc_sendreceive_thread, params, WT_EXECUTEDEFAULT))
314 ERR("QueueUserWorkItem failed with error %lx\n", GetLastError());
320 if (apt) apartment_release(apt);
324 if (WaitForSingleObject(params->handle, 0))
325 hr = CoWaitForMultipleHandles(0, INFINITE, 1, ¶ms->handle, &index);
327 CloseHandle(params->handle);
329 if (hr == S_OK) hr = params->hr;
331 status = params->status;
332 HeapFree(GetProcessHeap(), 0, params);
337 if (pstatus) *pstatus = status;
339 TRACE("RPC call status: 0x%lx\n", status);
340 if (status == RPC_S_OK)
342 else if (status == RPC_S_CALL_FAILED)
343 hr = *(HRESULT *)olemsg->Buffer;
345 hr = HRESULT_FROM_WIN32(status);
347 TRACE("-- 0x%08lx\n", hr);
352 static HRESULT WINAPI ServerRpcChannelBuffer_FreeBuffer(LPRPCCHANNELBUFFER iface, RPCOLEMESSAGE* olemsg)
354 RPC_MESSAGE *msg = (RPC_MESSAGE *)olemsg;
357 TRACE("(%p)\n", msg);
359 status = I_RpcFreeBuffer(msg);
361 TRACE("-- %ld\n", status);
363 return HRESULT_FROM_WIN32(status);
366 static HRESULT WINAPI ClientRpcChannelBuffer_FreeBuffer(LPRPCCHANNELBUFFER iface, RPCOLEMESSAGE* olemsg)
368 RPC_MESSAGE *msg = (RPC_MESSAGE *)olemsg;
371 TRACE("(%p)\n", msg);
373 status = I_RpcFreeBuffer(msg);
375 HeapFree(GetProcessHeap(), 0, msg->RpcInterfaceInformation);
376 msg->RpcInterfaceInformation = NULL;
378 TRACE("-- %ld\n", status);
380 return HRESULT_FROM_WIN32(status);
383 static HRESULT WINAPI ClientRpcChannelBuffer_GetDestCtx(LPRPCCHANNELBUFFER iface, DWORD* pdwDestContext, void** ppvDestContext)
385 ClientRpcChannelBuffer *This = (ClientRpcChannelBuffer *)iface;
387 TRACE("(%p,%p)\n", pdwDestContext, ppvDestContext);
389 *pdwDestContext = This->dest_context;
390 *ppvDestContext = This->dest_context_data;
395 static HRESULT WINAPI ServerRpcChannelBuffer_GetDestCtx(LPRPCCHANNELBUFFER iface, DWORD* pdwDestContext, void** ppvDestContext)
397 FIXME("(%p,%p), stub!\n", pdwDestContext, ppvDestContext);
401 static HRESULT WINAPI RpcChannelBuffer_IsConnected(LPRPCCHANNELBUFFER iface)
404 /* native does nothing too */
408 static const IRpcChannelBufferVtbl ClientRpcChannelBufferVtbl =
410 RpcChannelBuffer_QueryInterface,
411 RpcChannelBuffer_AddRef,
412 ClientRpcChannelBuffer_Release,
413 ClientRpcChannelBuffer_GetBuffer,
414 ClientRpcChannelBuffer_SendReceive,
415 ClientRpcChannelBuffer_FreeBuffer,
416 ClientRpcChannelBuffer_GetDestCtx,
417 RpcChannelBuffer_IsConnected
420 static const IRpcChannelBufferVtbl ServerRpcChannelBufferVtbl =
422 RpcChannelBuffer_QueryInterface,
423 RpcChannelBuffer_AddRef,
424 ServerRpcChannelBuffer_Release,
425 ServerRpcChannelBuffer_GetBuffer,
426 ServerRpcChannelBuffer_SendReceive,
427 ServerRpcChannelBuffer_FreeBuffer,
428 ServerRpcChannelBuffer_GetDestCtx,
429 RpcChannelBuffer_IsConnected
432 /* returns a channel buffer for proxies */
433 HRESULT RPC_CreateClientChannel(const OXID *oxid, const IPID *ipid,
434 DWORD dest_context, void *dest_context_data,
435 IRpcChannelBuffer **chan)
437 ClientRpcChannelBuffer *This;
439 RPC_BINDING_HANDLE bind;
441 LPWSTR string_binding;
443 /* connect to the apartment listener thread */
444 get_rpc_endpoint(endpoint, oxid);
446 TRACE("proxy pipe: connecting to endpoint: %s\n", debugstr_w(endpoint));
448 status = RpcStringBindingComposeW(
456 if (status == RPC_S_OK)
458 status = RpcBindingFromStringBindingW(string_binding, &bind);
460 if (status == RPC_S_OK)
462 IPID ipid2 = *ipid; /* why can't RpcBindingSetObject take a const? */
463 status = RpcBindingSetObject(bind, &ipid2);
464 if (status != RPC_S_OK)
465 RpcBindingFree(&bind);
468 RpcStringFreeW(&string_binding);
471 if (status != RPC_S_OK)
473 ERR("Couldn't get binding for endpoint %s, status = %ld\n", debugstr_w(endpoint), status);
474 return HRESULT_FROM_WIN32(status);
477 This = HeapAlloc(GetProcessHeap(), 0, sizeof(*This));
480 RpcBindingFree(&bind);
481 return E_OUTOFMEMORY;
484 This->super.lpVtbl = &ClientRpcChannelBufferVtbl;
485 This->super.refs = 1;
487 apartment_getoxid(COM_CurrentApt(), &This->oxid);
488 This->dest_context = dest_context;
489 This->dest_context_data = dest_context_data;
491 *chan = (IRpcChannelBuffer*)This;
496 HRESULT RPC_CreateServerChannel(IRpcChannelBuffer **chan)
498 RpcChannelBuffer *This = HeapAlloc(GetProcessHeap(), 0, sizeof(*This));
500 return E_OUTOFMEMORY;
502 This->lpVtbl = &ServerRpcChannelBufferVtbl;
505 *chan = (IRpcChannelBuffer*)This;
511 void RPC_ExecuteCall(struct dispatch_params *params)
515 params->hr = IRpcStubBuffer_Invoke(params->stub, params->msg, params->chan);
519 params->hr = GetExceptionCode();
522 IRpcStubBuffer_Release(params->stub);
523 IRpcChannelBuffer_Release(params->chan);
524 if (params->handle) SetEvent(params->handle);
527 static void __RPC_STUB dispatch_rpc(RPC_MESSAGE *msg)
529 struct dispatch_params *params;
534 RpcBindingInqObject(msg->Handle, &ipid);
536 TRACE("ipid = %s, iMethod = %d\n", debugstr_guid(&ipid), msg->ProcNum);
538 params = HeapAlloc(GetProcessHeap(), 0, sizeof(*params));
539 if (!params) return RpcRaiseException(E_OUTOFMEMORY);
541 hr = ipid_get_dispatch_params(&ipid, &apt, ¶ms->stub, ¶ms->chan);
544 ERR("no apartment found for ipid %s\n", debugstr_guid(&ipid));
545 return RpcRaiseException(hr);
548 params->msg = (RPCOLEMESSAGE *)msg;
549 params->status = RPC_S_OK;
551 params->handle = NULL;
553 /* Note: this is the important difference between STAs and MTAs - we
554 * always execute RPCs to STAs in the thread that originally created the
555 * apartment (i.e. the one that pumps messages to the window) */
556 if (!apt->multi_threaded)
558 params->handle = CreateEventW(NULL, FALSE, FALSE, NULL);
560 TRACE("Calling apartment thread 0x%08lx...\n", apt->tid);
562 if (PostMessageW(apartment_getwindow(apt), DM_EXECUTERPC, 0, (LPARAM)params))
563 WaitForSingleObject(params->handle, INFINITE);
566 ERR("PostMessage failed with error %ld\n", GetLastError());
567 IRpcChannelBuffer_Release(params->chan);
568 IRpcStubBuffer_Release(params->stub);
570 CloseHandle(params->handle);
575 if (!COM_CurrentInfo()->apt)
580 RPC_ExecuteCall(params);
583 apartment_release(COM_CurrentInfo()->apt);
584 COM_CurrentInfo()->apt = NULL;
588 HeapFree(GetProcessHeap(), 0, params);
590 apartment_release(apt);
593 /* stub registration */
594 HRESULT RPC_RegisterInterface(REFIID riid)
596 struct registered_if *rif;
600 TRACE("(%s)\n", debugstr_guid(riid));
602 EnterCriticalSection(&csRegIf);
603 LIST_FOR_EACH_ENTRY(rif, ®istered_interfaces, struct registered_if, entry)
605 if (IsEqualGUID(&rif->If.InterfaceId.SyntaxGUID, riid))
614 TRACE("Creating new interface\n");
616 rif = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*rif));
622 rif->If.Length = sizeof(RPC_SERVER_INTERFACE);
623 /* RPC interface ID = COM interface ID */
624 rif->If.InterfaceId.SyntaxGUID = *riid;
625 rif->If.DispatchTable = &rpc_dispatch;
626 /* all other fields are 0, including the version asCOM objects
627 * always have a version of 0.0 */
628 status = RpcServerRegisterIfEx(
629 (RPC_IF_HANDLE)&rif->If,
631 RPC_IF_OLE | RPC_IF_AUTOLISTEN,
632 RPC_C_LISTEN_MAX_CALLS_DEFAULT,
634 if (status == RPC_S_OK)
635 list_add_tail(®istered_interfaces, &rif->entry);
638 ERR("RpcServerRegisterIfEx failed with error %ld\n", status);
639 HeapFree(GetProcessHeap(), 0, rif);
640 hr = HRESULT_FROM_WIN32(status);
646 LeaveCriticalSection(&csRegIf);
650 /* stub unregistration */
651 void RPC_UnregisterInterface(REFIID riid)
653 struct registered_if *rif;
654 EnterCriticalSection(&csRegIf);
655 LIST_FOR_EACH_ENTRY(rif, ®istered_interfaces, struct registered_if, entry)
657 if (IsEqualGUID(&rif->If.InterfaceId.SyntaxGUID, riid))
661 #if 0 /* this is a stub in builtin and spams the console with FIXME's */
662 IID iid = *riid; /* RpcServerUnregisterIf doesn't take const IID */
663 RpcServerUnregisterIf((RPC_IF_HANDLE)&rif->If, &iid, 0);
664 list_remove(&rif->entry);
665 HeapFree(GetProcessHeap(), 0, rif);
671 LeaveCriticalSection(&csRegIf);
674 /* make the apartment reachable by other threads and processes and create the
675 * IRemUnknown object */
676 void RPC_StartRemoting(struct apartment *apt)
678 if (!InterlockedExchange(&apt->remoting_started, TRUE))
683 get_rpc_endpoint(endpoint, &apt->oxid);
685 status = RpcServerUseProtseqEpW(
687 RPC_C_PROTSEQ_MAX_REQS_DEFAULT,
690 if (status != RPC_S_OK)
691 ERR("Couldn't register endpoint %s\n", debugstr_w(endpoint));
693 /* FIXME: move remote unknown exporting into this function */
695 start_apartment_remote_unknown();
699 static HRESULT create_server(REFCLSID rclsid)
701 static const WCHAR wszLocalServer32[] = { 'L','o','c','a','l','S','e','r','v','e','r','3','2',0 };
702 static const WCHAR embedding[] = { ' ', '-','E','m','b','e','d','d','i','n','g',0 };
705 WCHAR command[MAX_PATH+sizeof(embedding)/sizeof(WCHAR)];
706 DWORD size = (MAX_PATH+1) * sizeof(WCHAR);
708 PROCESS_INFORMATION pinfo;
710 hres = COM_OpenKeyForCLSID(rclsid, wszLocalServer32, KEY_READ, &key);
712 ERR("class %s not registered\n", debugstr_guid(rclsid));
716 hres = RegQueryValueExW(key, NULL, NULL, NULL, (LPBYTE)command, &size);
719 WARN("No default value for LocalServer32 key\n");
720 return REGDB_E_CLASSNOTREG; /* FIXME: check retval */
723 memset(&sinfo,0,sizeof(sinfo));
724 sinfo.cb = sizeof(sinfo);
726 /* EXE servers are started with the -Embedding switch. */
728 strcatW(command, embedding);
730 TRACE("activating local server %s for %s\n", debugstr_w(command), debugstr_guid(rclsid));
732 /* FIXME: Win2003 supports a ServerExecutable value that is passed into
734 if (!CreateProcessW(NULL, command, NULL, NULL, FALSE, 0, NULL, NULL, &sinfo, &pinfo)) {
735 WARN("failed to run local server %s\n", debugstr_w(command));
736 return HRESULT_FROM_WIN32(GetLastError());
738 CloseHandle(pinfo.hProcess);
739 CloseHandle(pinfo.hThread);
745 * start_local_service() - start a service given its name and parameters
747 static DWORD start_local_service(LPCWSTR name, DWORD num, LPCWSTR *params)
749 SC_HANDLE handle, hsvc;
750 DWORD r = ERROR_FUNCTION_FAILED;
752 TRACE("Starting service %s %ld params\n", debugstr_w(name), num);
754 handle = OpenSCManagerW(NULL, NULL, SC_MANAGER_CONNECT);
757 hsvc = OpenServiceW(handle, name, SERVICE_START);
760 if(StartServiceW(hsvc, num, params))
764 if (r == ERROR_SERVICE_ALREADY_RUNNING)
766 CloseServiceHandle(hsvc);
770 CloseServiceHandle(handle);
772 TRACE("StartService returned error %ld (%s)\n", r, (r == ERROR_SUCCESS) ? "ok":"failed");
778 * create_local_service() - start a COM server in a service
780 * To start a Local Service, we read the AppID value under
781 * the class's CLSID key, then open the HKCR\\AppId key specified
782 * there and check for a LocalService value.
784 * Note: Local Services are not supported under Windows 9x
786 static HRESULT create_local_service(REFCLSID rclsid)
789 WCHAR buf[CHARS_IN_GUID], keyname[50];
790 static const WCHAR szAppId[] = { 'A','p','p','I','d',0 };
791 static const WCHAR szAppIdKey[] = { 'A','p','p','I','d','\\',0 };
792 static const WCHAR szLocalService[] = { 'L','o','c','a','l','S','e','r','v','i','c','e',0 };
793 static const WCHAR szServiceParams[] = {'S','e','r','v','i','c','e','P','a','r','a','m','s',0};
798 TRACE("Attempting to start Local service for %s\n", debugstr_guid(rclsid));
800 /* read the AppID value under the class's key */
801 hres = COM_OpenKeyForCLSID(rclsid, szAppId, KEY_READ, &hkey);
805 r = RegQueryValueExW(hkey, NULL, NULL, &type, (LPBYTE)buf, &sz);
807 if (r!=ERROR_SUCCESS || type!=REG_SZ)
810 /* read the LocalService and ServiceParameters values from the AppID key */
811 strcpyW(keyname, szAppIdKey);
812 strcatW(keyname, buf);
813 r = RegOpenKeyExW(HKEY_CLASSES_ROOT, keyname, 0, KEY_READ, &hkey);
814 if (r!=ERROR_SUCCESS)
817 r = RegQueryValueExW(hkey, szLocalService, NULL, &type, (LPBYTE)buf, &sz);
818 if (r==ERROR_SUCCESS && type==REG_SZ)
821 LPWSTR args[1] = { NULL };
824 * FIXME: I'm not really sure how to deal with the service parameters.
825 * I suspect that the string returned from RegQueryValueExW
826 * should be split into a number of arguments by spaces.
827 * It would make more sense if ServiceParams contained a
828 * REG_MULTI_SZ here, but it's a REG_SZ for the services
829 * that I'm interested in for the moment.
831 r = RegQueryValueExW(hkey, szServiceParams, NULL, &type, NULL, &sz);
832 if (r == ERROR_SUCCESS && type == REG_SZ && sz)
834 args[0] = HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY,sz);
836 RegQueryValueExW(hkey, szServiceParams, NULL, &type, (LPBYTE)args[0], &sz);
838 r = start_local_service(buf, num_args, (LPCWSTR *)args);
839 if (r==ERROR_SUCCESS)
841 HeapFree(GetProcessHeap(),0,args[0]);
849 static void get_localserver_pipe_name(WCHAR *pipefn, REFCLSID rclsid)
851 static const WCHAR wszPipeRef[] = {'\\','\\','.','\\','p','i','p','e','\\',0};
852 strcpyW(pipefn, wszPipeRef);
853 StringFromGUID2(rclsid, pipefn + sizeof(wszPipeRef)/sizeof(wszPipeRef[0]) - 1, CHARS_IN_GUID);
856 /* FIXME: should call to rpcss instead */
857 HRESULT RPC_GetLocalClassObject(REFCLSID rclsid, REFIID iid, LPVOID *ppv)
862 DWORD res, bufferlen;
863 char marshalbuffer[200];
865 LARGE_INTEGER seekto;
866 ULARGE_INTEGER newpos;
869 static const int MAXTRIES = 30; /* 30 seconds */
871 TRACE("rclsid=%s, iid=%s\n", debugstr_guid(rclsid), debugstr_guid(iid));
873 get_localserver_pipe_name(pipefn, rclsid);
875 while (tries++ < MAXTRIES) {
876 TRACE("waiting for %s\n", debugstr_w(pipefn));
878 WaitNamedPipeW( pipefn, NMPWAIT_WAIT_FOREVER );
879 hPipe = CreateFileW(pipefn, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, 0);
880 if (hPipe == INVALID_HANDLE_VALUE) {
882 if ( (hres = create_local_service(rclsid)) &&
883 (hres = create_server(rclsid)) )
887 WARN("Connecting to %s, no response yet, retrying: le is %lx\n", debugstr_w(pipefn), GetLastError());
893 if (!ReadFile(hPipe,marshalbuffer,sizeof(marshalbuffer),&bufferlen,NULL)) {
894 FIXME("Failed to read marshal id from classfactory of %s.\n",debugstr_guid(rclsid));
898 TRACE("read marshal id from pipe\n");
903 if (tries >= MAXTRIES)
904 return E_NOINTERFACE;
906 hres = CreateStreamOnHGlobal(0,TRUE,&pStm);
907 if (hres) return hres;
908 hres = IStream_Write(pStm,marshalbuffer,bufferlen,&res);
910 seekto.u.LowPart = 0;seekto.u.HighPart = 0;
911 hres = IStream_Seek(pStm,seekto,SEEK_SET,&newpos);
913 TRACE("unmarshalling classfactory\n");
914 hres = CoUnmarshalInterface(pStm,&IID_IClassFactory,ppv);
916 IStream_Release(pStm);
921 struct local_server_params
927 /* FIXME: should call to rpcss instead */
928 static DWORD WINAPI local_server_thread(LPVOID param)
930 struct local_server_params * lsp = (struct local_server_params *)param;
934 IStream *pStm = lsp->stream;
936 unsigned char *buffer;
938 LARGE_INTEGER seekto;
939 ULARGE_INTEGER newpos;
942 TRACE("Starting threader for %s.\n",debugstr_guid(&lsp->clsid));
944 get_localserver_pipe_name(pipefn, &lsp->clsid);
946 HeapFree(GetProcessHeap(), 0, lsp);
948 hPipe = CreateNamedPipeW( pipefn, PIPE_ACCESS_DUPLEX,
949 PIPE_TYPE_BYTE|PIPE_WAIT, PIPE_UNLIMITED_INSTANCES,
950 4096, 4096, 500 /* 0.5 second timeout */, NULL );
952 if (hPipe == INVALID_HANDLE_VALUE)
954 FIXME("pipe creation failed for %s, le is %ld\n", debugstr_w(pipefn), GetLastError());
959 if (!ConnectNamedPipe(hPipe,NULL)) {
960 ERR("Failure during ConnectNamedPipe %ld, ABORT!\n",GetLastError());
964 TRACE("marshalling IClassFactory to client\n");
966 hres = IStream_Stat(pStm,&ststg,0);
967 if (hres) return hres;
969 buflen = ststg.cbSize.u.LowPart;
970 buffer = HeapAlloc(GetProcessHeap(),0,buflen);
971 seekto.u.LowPart = 0;
972 seekto.u.HighPart = 0;
973 hres = IStream_Seek(pStm,seekto,SEEK_SET,&newpos);
975 FIXME("IStream_Seek failed, %lx\n",hres);
979 hres = IStream_Read(pStm,buffer,buflen,&res);
981 FIXME("Stream Read failed, %lx\n",hres);
985 WriteFile(hPipe,buffer,buflen,&res,NULL);
986 FlushFileBuffers(hPipe);
987 DisconnectNamedPipe(hPipe);
989 TRACE("done marshalling IClassFactory\n");
992 IStream_Release(pStm);
996 void RPC_StartLocalServer(REFCLSID clsid, IStream *stream)
1000 struct local_server_params *lsp = HeapAlloc(GetProcessHeap(), 0, sizeof(*lsp));
1002 lsp->clsid = *clsid;
1003 lsp->stream = stream;
1005 thread = CreateThread(NULL, 0, local_server_thread, lsp, 0, &tid);
1006 CloseHandle(thread);
1007 /* FIXME: failure handling */