By-pass the RPC runtime if possible when calling an STA by posting a
[wine.git] / dlls / ole32 / rpc.c
bloba67d75d9cd8f806583e107dd17dc601a1274d9c5
1 /*
2 * RPC Manager
4 * Copyright 2001 Ove Kåven, TransGaming Technologies
5 * Copyright 2002 Marcus Meissner
6 * Copyright 2005 Mike Hearn, Rob Shearman for CodeWeavers
8 * This library is free software; you can redistribute it and/or
9 * modify it under the terms of the GNU Lesser General Public
10 * License as published by the Free Software Foundation; either
11 * version 2.1 of the License, or (at your option) any later version.
13 * This library is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 * Lesser General Public License for more details.
18 * You should have received a copy of the GNU Lesser General Public
19 * License along with this library; if not, write to the Free Software
20 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
23 #include "config.h"
25 #include <stdlib.h>
26 #include <stdarg.h>
27 #include <stdio.h>
28 #include <string.h>
29 #include <assert.h>
31 #define COBJMACROS
32 #define NONAMELESSUNION
33 #define NONAMELESSSTRUCT
35 #include "windef.h"
36 #include "winbase.h"
37 #include "winuser.h"
38 #include "winsvc.h"
39 #include "objbase.h"
40 #include "ole2.h"
41 #include "rpc.h"
42 #include "winerror.h"
43 #include "winreg.h"
44 #include "wtypes.h"
45 #include "wine/unicode.h"
47 #include "compobj_private.h"
49 #include "wine/debug.h"
51 WINE_DEFAULT_DEBUG_CHANNEL(ole);
53 static void __RPC_STUB dispatch_rpc(RPC_MESSAGE *msg);
55 /* we only use one function to dispatch calls for all methods - we use the
56 * RPC_IF_OLE flag to tell the RPC runtime that this is the case */
57 static RPC_DISPATCH_FUNCTION rpc_dispatch_table[1] = { dispatch_rpc }; /* (RO) */
58 static RPC_DISPATCH_TABLE rpc_dispatch = { 1, rpc_dispatch_table }; /* (RO) */
60 static struct list registered_interfaces = LIST_INIT(registered_interfaces); /* (CS csRegIf) */
61 static CRITICAL_SECTION csRegIf;
62 static CRITICAL_SECTION_DEBUG csRegIf_debug =
64 0, 0, &csRegIf,
65 { &csRegIf_debug.ProcessLocksList, &csRegIf_debug.ProcessLocksList },
66 0, 0, { 0, (DWORD)(__FILE__ ": dcom registered server interfaces") }
68 static CRITICAL_SECTION csRegIf = { &csRegIf_debug, -1, 0, 0, 0, 0 };
70 static WCHAR wszPipeTransport[] = {'n','c','a','c','n','_','n','p',0};
73 struct registered_if
75 struct list entry;
76 DWORD refs; /* ref count */
77 RPC_SERVER_INTERFACE If; /* interface registered with the RPC runtime */
80 /* get the pipe endpoint specified of the specified apartment */
81 static inline void get_rpc_endpoint(LPWSTR endpoint, const OXID *oxid)
83 /* FIXME: should get endpoint from rpcss */
84 static const WCHAR wszEndpointFormat[] = {'\\','p','i','p','e','\\','O','L','E','_','%','0','8','l','x','%','0','8','l','x',0};
85 wsprintfW(endpoint, wszEndpointFormat, (DWORD)(*oxid >> 32),(DWORD)*oxid);
88 typedef struct
90 const IRpcChannelBufferVtbl *lpVtbl;
91 LONG refs;
92 } RpcChannelBuffer;
94 typedef struct
96 RpcChannelBuffer super; /* superclass */
98 RPC_BINDING_HANDLE bind; /* handle to the remote server */
99 } ClientRpcChannelBuffer;
101 struct dispatch_params
103 RPCOLEMESSAGE *msg; /* message */
104 IRpcStubBuffer *stub; /* stub buffer, if applicable */
105 IRpcChannelBuffer *chan; /* server channel buffer, if applicable */
106 HANDLE handle; /* handle that will become signaled when call finishes */
107 RPC_STATUS status; /* status (out) */
110 static HRESULT WINAPI RpcChannelBuffer_QueryInterface(LPRPCCHANNELBUFFER iface, REFIID riid, LPVOID *ppv)
112 *ppv = NULL;
113 if (IsEqualIID(riid,&IID_IRpcChannelBuffer) || IsEqualIID(riid,&IID_IUnknown))
115 *ppv = (LPVOID)iface;
116 IUnknown_AddRef(iface);
117 return S_OK;
119 return E_NOINTERFACE;
122 static ULONG WINAPI RpcChannelBuffer_AddRef(LPRPCCHANNELBUFFER iface)
124 RpcChannelBuffer *This = (RpcChannelBuffer *)iface;
125 return InterlockedIncrement(&This->refs);
128 static ULONG WINAPI ServerRpcChannelBuffer_Release(LPRPCCHANNELBUFFER iface)
130 RpcChannelBuffer *This = (RpcChannelBuffer *)iface;
131 ULONG ref;
133 ref = InterlockedDecrement(&This->refs);
134 if (ref)
135 return ref;
137 HeapFree(GetProcessHeap(), 0, This);
138 return 0;
141 static ULONG WINAPI ClientRpcChannelBuffer_Release(LPRPCCHANNELBUFFER iface)
143 ClientRpcChannelBuffer *This = (ClientRpcChannelBuffer *)iface;
144 ULONG ref;
146 ref = InterlockedDecrement(&This->super.refs);
147 if (ref)
148 return ref;
150 RpcBindingFree(&This->bind);
151 HeapFree(GetProcessHeap(), 0, This);
152 return 0;
155 static HRESULT WINAPI ServerRpcChannelBuffer_GetBuffer(LPRPCCHANNELBUFFER iface, RPCOLEMESSAGE* olemsg, REFIID riid)
157 RpcChannelBuffer *This = (RpcChannelBuffer *)iface;
158 RPC_MESSAGE *msg = (RPC_MESSAGE *)olemsg;
159 RPC_STATUS status;
161 TRACE("(%p)->(%p,%s)\n", This, olemsg, debugstr_guid(riid));
163 status = I_RpcGetBuffer(msg);
165 TRACE("-- %ld\n", status);
167 return HRESULT_FROM_WIN32(status);
170 static HRESULT WINAPI ClientRpcChannelBuffer_GetBuffer(LPRPCCHANNELBUFFER iface, RPCOLEMESSAGE* olemsg, REFIID riid)
172 ClientRpcChannelBuffer *This = (ClientRpcChannelBuffer *)iface;
173 RPC_MESSAGE *msg = (RPC_MESSAGE *)olemsg;
174 RPC_CLIENT_INTERFACE *cif;
175 RPC_STATUS status;
177 TRACE("(%p)->(%p,%s)\n", This, olemsg, debugstr_guid(riid));
179 cif = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(RPC_CLIENT_INTERFACE));
180 if (!cif)
181 return E_OUTOFMEMORY;
183 cif->Length = sizeof(RPC_CLIENT_INTERFACE);
184 /* RPC interface ID = COM interface ID */
185 cif->InterfaceId.SyntaxGUID = *riid;
186 /* COM objects always have a version of 0.0 */
187 cif->InterfaceId.SyntaxVersion.MajorVersion = 0;
188 cif->InterfaceId.SyntaxVersion.MinorVersion = 0;
189 msg->RpcInterfaceInformation = cif;
190 msg->Handle = This->bind;
192 status = I_RpcGetBuffer(msg);
194 TRACE("-- %ld\n", status);
196 return HRESULT_FROM_WIN32(status);
199 /* this thread runs an outgoing RPC */
200 static DWORD WINAPI rpc_sendreceive_thread(LPVOID param)
202 struct dispatch_params *data = (struct dispatch_params *) param;
204 /* FIXME: trap and rethrow RPC exceptions in app thread */
205 data->status = I_RpcSendReceive((RPC_MESSAGE *)data->msg);
207 TRACE("completed with status 0x%lx\n", data->status);
209 return 0;
212 static HRESULT WINAPI RpcChannelBuffer_SendReceive(LPRPCCHANNELBUFFER iface, RPCOLEMESSAGE *olemsg, ULONG *pstatus)
214 HRESULT hr = S_OK;
215 RPC_MESSAGE *msg = (RPC_MESSAGE *)olemsg;
216 RPC_STATUS status;
217 DWORD index;
218 struct dispatch_params *params;
219 DWORD tid;
220 IRpcStubBuffer *stub;
221 APARTMENT *apt;
222 IPID ipid;
224 TRACE("(%p) iMethod=%ld\n", olemsg, olemsg->iMethod);
226 params = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*params));
227 if (!params) return E_OUTOFMEMORY;
229 params->msg = olemsg;
230 params->status = RPC_S_OK;
232 /* Note: this is an optimization in the Microsoft OLE runtime that we need
233 * to copy, as shown by the test_no_couninitialize_client test. without
234 * short-circuiting the RPC runtime in the case below, the test will
235 * deadlock on the loader lock due to the RPC runtime needing to create
236 * a thread to process the RPC when this function is called indirectly
237 * from DllMain */
239 RpcBindingInqObject(msg->Handle, &ipid);
240 stub = ipid_to_apt_and_stubbuffer(&ipid, &apt);
241 if (apt && (apt->model & COINIT_APARTMENTTHREADED))
243 params->stub = stub;
244 params->chan = NULL; /* FIXME: pass server channel */
245 params->handle = CreateEventW(NULL, FALSE, FALSE, NULL);
247 TRACE("Calling apartment thread 0x%08lx...\n", apt->tid);
249 PostMessageW(apt->win, DM_EXECUTERPC, 0, (LPARAM)params);
251 else
253 if (stub) IRpcStubBuffer_Release(stub);
255 /* we use a separate thread here because we need to be able to
256 * pump the message loop in the application thread: if we do not,
257 * any windows created by this thread will hang and RPCs that try
258 * and re-enter this STA from an incoming server thread will
259 * deadlock. InstallShield is an example of that.
261 params->handle = CreateThread(NULL, 0, rpc_sendreceive_thread, params, 0, &tid);
262 if (!params->handle)
264 ERR("Could not create RpcSendReceive thread, error %lx\n", GetLastError());
265 hr = E_UNEXPECTED;
268 if (apt) apartment_release(apt);
270 if (hr == S_OK)
271 hr = CoWaitForMultipleHandles(0, INFINITE, 1, &params->handle, &index);
272 CloseHandle(params->handle);
274 status = params->status;
275 HeapFree(GetProcessHeap(), 0, params);
276 params = NULL;
278 if (hr) return hr;
280 if (pstatus) *pstatus = status;
282 TRACE("RPC call status: 0x%lx\n", status);
283 if (status == RPC_S_OK)
284 hr = S_OK;
285 else if (status == RPC_S_CALL_FAILED)
286 hr = *(HRESULT *)olemsg->Buffer;
287 else
288 hr = HRESULT_FROM_WIN32(status);
290 TRACE("-- 0x%08lx\n", hr);
292 return hr;
295 static HRESULT WINAPI ServerRpcChannelBuffer_FreeBuffer(LPRPCCHANNELBUFFER iface, RPCOLEMESSAGE* olemsg)
297 RPC_MESSAGE *msg = (RPC_MESSAGE *)olemsg;
298 RPC_STATUS status;
300 TRACE("(%p)\n", msg);
302 status = I_RpcFreeBuffer(msg);
304 TRACE("-- %ld\n", status);
306 return HRESULT_FROM_WIN32(status);
309 static HRESULT WINAPI ClientRpcChannelBuffer_FreeBuffer(LPRPCCHANNELBUFFER iface, RPCOLEMESSAGE* olemsg)
311 RPC_MESSAGE *msg = (RPC_MESSAGE *)olemsg;
312 RPC_STATUS status;
314 TRACE("(%p)\n", msg);
316 status = I_RpcFreeBuffer(msg);
318 HeapFree(GetProcessHeap(), 0, msg->RpcInterfaceInformation);
319 msg->RpcInterfaceInformation = NULL;
321 TRACE("-- %ld\n", status);
323 return HRESULT_FROM_WIN32(status);
326 static HRESULT WINAPI RpcChannelBuffer_GetDestCtx(LPRPCCHANNELBUFFER iface, DWORD* pdwDestContext, void** ppvDestContext)
328 FIXME("(%p,%p), stub!\n", pdwDestContext, ppvDestContext);
329 return E_FAIL;
332 static HRESULT WINAPI RpcChannelBuffer_IsConnected(LPRPCCHANNELBUFFER iface)
334 TRACE("()\n");
335 /* native does nothing too */
336 return S_OK;
339 static const IRpcChannelBufferVtbl ClientRpcChannelBufferVtbl =
341 RpcChannelBuffer_QueryInterface,
342 RpcChannelBuffer_AddRef,
343 ClientRpcChannelBuffer_Release,
344 ClientRpcChannelBuffer_GetBuffer,
345 RpcChannelBuffer_SendReceive,
346 ClientRpcChannelBuffer_FreeBuffer,
347 RpcChannelBuffer_GetDestCtx,
348 RpcChannelBuffer_IsConnected
351 static const IRpcChannelBufferVtbl ServerRpcChannelBufferVtbl =
353 RpcChannelBuffer_QueryInterface,
354 RpcChannelBuffer_AddRef,
355 ServerRpcChannelBuffer_Release,
356 ServerRpcChannelBuffer_GetBuffer,
357 RpcChannelBuffer_SendReceive,
358 ServerRpcChannelBuffer_FreeBuffer,
359 RpcChannelBuffer_GetDestCtx,
360 RpcChannelBuffer_IsConnected
363 /* returns a channel buffer for proxies */
364 HRESULT RPC_CreateClientChannel(const OXID *oxid, const IPID *ipid, IRpcChannelBuffer **chan)
366 ClientRpcChannelBuffer *This;
367 WCHAR endpoint[200];
368 RPC_BINDING_HANDLE bind;
369 RPC_STATUS status;
370 LPWSTR string_binding;
372 /* connect to the apartment listener thread */
373 get_rpc_endpoint(endpoint, oxid);
375 TRACE("proxy pipe: connecting to endpoint: %s\n", debugstr_w(endpoint));
377 status = RpcStringBindingComposeW(
378 NULL,
379 wszPipeTransport,
380 NULL,
381 endpoint,
382 NULL,
383 &string_binding);
385 if (status == RPC_S_OK)
387 status = RpcBindingFromStringBindingW(string_binding, &bind);
389 if (status == RPC_S_OK)
391 IPID ipid2 = *ipid; /* why can't RpcBindingSetObject take a const? */
392 status = RpcBindingSetObject(bind, &ipid2);
393 if (status != RPC_S_OK)
394 RpcBindingFree(&bind);
397 RpcStringFreeW(&string_binding);
400 if (status != RPC_S_OK)
402 ERR("Couldn't get binding for endpoint %s, status = %ld\n", debugstr_w(endpoint), status);
403 return HRESULT_FROM_WIN32(status);
406 This = HeapAlloc(GetProcessHeap(), 0, sizeof(*This));
407 if (!This)
409 RpcBindingFree(&bind);
410 return E_OUTOFMEMORY;
413 This->super.lpVtbl = &ClientRpcChannelBufferVtbl;
414 This->super.refs = 1;
415 This->bind = bind;
417 *chan = (IRpcChannelBuffer*)This;
419 return S_OK;
422 HRESULT RPC_CreateServerChannel(IRpcChannelBuffer **chan)
424 RpcChannelBuffer *This = HeapAlloc(GetProcessHeap(), 0, sizeof(*This));
425 if (!This)
426 return E_OUTOFMEMORY;
428 This->lpVtbl = &ServerRpcChannelBufferVtbl;
429 This->refs = 1;
431 *chan = (IRpcChannelBuffer*)This;
433 return S_OK;
437 HRESULT RPC_ExecuteCall(struct dispatch_params *params)
439 HRESULT hr = IRpcStubBuffer_Invoke(params->stub, params->msg, params->chan);
440 IRpcStubBuffer_Release(params->stub);
441 if (params->handle) SetEvent(params->handle);
442 return hr;
445 static void __RPC_STUB dispatch_rpc(RPC_MESSAGE *msg)
447 struct dispatch_params *params;
448 IRpcStubBuffer *stub;
449 APARTMENT *apt;
450 IPID ipid;
452 RpcBindingInqObject(msg->Handle, &ipid);
454 TRACE("ipid = %s, iMethod = %d\n", debugstr_guid(&ipid), msg->ProcNum);
456 params = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*params));
457 if (!params) return RpcRaiseException(E_OUTOFMEMORY);
459 stub = ipid_to_apt_and_stubbuffer(&ipid, &apt);
460 if (!apt || !stub)
462 if (apt) apartment_release(apt);
463 /* ipid_to_apt_and_stubbuffer will already have logged the error */
464 return RpcRaiseException(RPC_E_DISCONNECTED);
467 params->msg = (RPCOLEMESSAGE *)msg;
468 params->stub = stub;
469 params->chan = NULL; /* FIXME: pass server channel */
470 params->status = RPC_S_OK;
472 /* Note: this is the important difference between STAs and MTAs - we
473 * always execute RPCs to STAs in the thread that originally created the
474 * apartment (i.e. the one that pumps messages to the window) */
475 if (apt->model & COINIT_APARTMENTTHREADED)
477 params->handle = CreateEventW(NULL, FALSE, FALSE, NULL);
479 TRACE("Calling apartment thread 0x%08lx...\n", apt->tid);
481 PostMessageW(apt->win, DM_EXECUTERPC, 0, (LPARAM)params);
482 WaitForSingleObject(params->handle, INFINITE);
483 CloseHandle(params->handle);
485 else
486 RPC_ExecuteCall(params);
488 HeapFree(GetProcessHeap(), 0, params);
490 apartment_release(apt);
493 /* stub registration */
494 HRESULT RPC_RegisterInterface(REFIID riid)
496 struct registered_if *rif;
497 BOOL found = FALSE;
498 HRESULT hr = S_OK;
500 TRACE("(%s)\n", debugstr_guid(riid));
502 EnterCriticalSection(&csRegIf);
503 LIST_FOR_EACH_ENTRY(rif, &registered_interfaces, struct registered_if, entry)
505 if (IsEqualGUID(&rif->If.InterfaceId.SyntaxGUID, riid))
507 rif->refs++;
508 found = TRUE;
509 break;
512 if (!found)
514 TRACE("Creating new interface\n");
516 rif = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*rif));
517 if (rif)
519 RPC_STATUS status;
521 rif->refs = 1;
522 rif->If.Length = sizeof(RPC_SERVER_INTERFACE);
523 /* RPC interface ID = COM interface ID */
524 rif->If.InterfaceId.SyntaxGUID = *riid;
525 rif->If.DispatchTable = &rpc_dispatch;
526 /* all other fields are 0, including the version asCOM objects
527 * always have a version of 0.0 */
528 status = RpcServerRegisterIfEx(
529 (RPC_IF_HANDLE)&rif->If,
530 NULL, NULL,
531 RPC_IF_OLE | RPC_IF_AUTOLISTEN,
532 RPC_C_LISTEN_MAX_CALLS_DEFAULT,
533 NULL);
534 if (status == RPC_S_OK)
535 list_add_tail(&registered_interfaces, &rif->entry);
536 else
538 ERR("RpcServerRegisterIfEx failed with error %ld\n", status);
539 HeapFree(GetProcessHeap(), 0, rif);
540 hr = HRESULT_FROM_WIN32(status);
543 else
544 hr = E_OUTOFMEMORY;
546 LeaveCriticalSection(&csRegIf);
547 return hr;
550 /* stub unregistration */
551 void RPC_UnregisterInterface(REFIID riid)
553 struct registered_if *rif;
554 EnterCriticalSection(&csRegIf);
555 LIST_FOR_EACH_ENTRY(rif, &registered_interfaces, struct registered_if, entry)
557 if (IsEqualGUID(&rif->If.InterfaceId.SyntaxGUID, riid))
559 if (!--rif->refs)
561 #if 0 /* this is a stub in builtin and spams the console with FIXME's */
562 IID iid = *riid; /* RpcServerUnregisterIf doesn't take const IID */
563 RpcServerUnregisterIf((RPC_IF_HANDLE)&rif->If, &iid, 0);
564 list_remove(&rif->entry);
565 HeapFree(GetProcessHeap(), 0, rif);
566 #endif
568 break;
571 LeaveCriticalSection(&csRegIf);
574 /* make the apartment reachable by other threads and processes and create the
575 * IRemUnknown object */
576 void RPC_StartRemoting(struct apartment *apt)
578 if (!InterlockedExchange(&apt->remoting_started, TRUE))
580 WCHAR endpoint[200];
581 RPC_STATUS status;
583 get_rpc_endpoint(endpoint, &apt->oxid);
585 status = RpcServerUseProtseqEpW(
586 wszPipeTransport,
587 RPC_C_PROTSEQ_MAX_REQS_DEFAULT,
588 endpoint,
589 NULL);
590 if (status != RPC_S_OK)
591 ERR("Couldn't register endpoint %s\n", debugstr_w(endpoint));
593 /* FIXME: move remote unknown exporting into this function */
595 start_apartment_remote_unknown();
599 static HRESULT create_server(REFCLSID rclsid)
601 static const WCHAR wszLocalServer32[] = { 'L','o','c','a','l','S','e','r','v','e','r','3','2',0 };
602 static const WCHAR embedding[] = { ' ', '-','E','m','b','e','d','d','i','n','g',0 };
603 HKEY hkeyclsid;
604 HKEY key;
605 HRESULT hres = E_UNEXPECTED;
606 WCHAR exe[MAX_PATH+1];
607 DWORD exelen = sizeof(exe);
608 WCHAR command[MAX_PATH+sizeof(embedding)/sizeof(WCHAR)];
609 STARTUPINFOW sinfo;
610 PROCESS_INFORMATION pinfo;
612 hres = HRESULT_FROM_WIN32(COM_OpenKeyForCLSID(rclsid, KEY_READ, &hkeyclsid));
613 if (hres != S_OK) {
614 ERR("class %s not registered\n", debugstr_guid(rclsid));
615 return REGDB_E_READREGDB;
618 hres = RegOpenKeyExW(hkeyclsid, wszLocalServer32, 0, KEY_READ, &key);
620 if (hres != ERROR_SUCCESS) {
621 WARN("class %s not registered as LocalServer32\n", debugstr_guid(rclsid));
622 return REGDB_E_READREGDB; /* Probably */
625 memset(exe,0,sizeof(exe));
626 hres= RegQueryValueExW(key, NULL, NULL, NULL, (LPBYTE)exe, &exelen);
627 RegCloseKey(key);
628 if (hres) {
629 WARN("No default value for LocalServer32 key\n");
630 return REGDB_E_CLASSNOTREG; /* FIXME: check retval */
633 memset(&sinfo,0,sizeof(sinfo));
634 sinfo.cb = sizeof(sinfo);
636 /* EXE servers are started with the -Embedding switch. MSDN also claims /Embedding is used,
637 * 9x does -Embedding, perhaps an 9x/NT difference?
640 strcpyW(command, exe);
641 strcatW(command, embedding);
643 TRACE("activating local server %s for %s\n", debugstr_w(command), debugstr_guid(rclsid));
645 if (!CreateProcessW(exe, command, NULL, NULL, FALSE, 0, NULL, NULL, &sinfo, &pinfo)) {
646 WARN("failed to run local server %s\n", debugstr_w(exe));
647 return HRESULT_FROM_WIN32(GetLastError());
649 CloseHandle(pinfo.hProcess);
650 CloseHandle(pinfo.hThread);
652 return S_OK;
656 * start_local_service() - start a service given its name and parameters
658 static DWORD start_local_service(LPCWSTR name, DWORD num, LPWSTR *params)
660 SC_HANDLE handle, hsvc;
661 DWORD r = ERROR_FUNCTION_FAILED;
663 TRACE("Starting service %s %ld params\n", debugstr_w(name), num);
665 handle = OpenSCManagerW(NULL, NULL, SC_MANAGER_ALL_ACCESS);
666 if (!handle)
667 return r;
668 hsvc = OpenServiceW(handle, name, SC_MANAGER_ALL_ACCESS);
669 if (hsvc)
671 if(StartServiceW(hsvc, num, (LPCWSTR*)params))
672 r = ERROR_SUCCESS;
673 else
674 r = GetLastError();
675 if (r == ERROR_SERVICE_ALREADY_RUNNING)
676 r = ERROR_SUCCESS;
677 CloseServiceHandle(hsvc);
679 CloseServiceHandle(handle);
681 TRACE("StartService returned error %ld (%s)\n", r, r?"ok":"failed");
683 return r;
687 * create_local_service() - start a COM server in a service
689 * To start a Local Service, we read the AppID value under
690 * the class's CLSID key, then open the HKCR\\AppId key specified
691 * there and check for a LocalService value.
693 * Note: Local Services are not supported under Windows 9x
695 static HRESULT create_local_service(REFCLSID rclsid)
697 HRESULT hres = REGDB_E_READREGDB;
698 WCHAR buf[CHARS_IN_GUID], keyname[50];
699 static const WCHAR szAppId[] = { 'A','p','p','I','d',0 };
700 static const WCHAR szAppIdKey[] = { 'A','p','p','I','d','\\',0 };
701 static const WCHAR szLocalService[] = { 'L','o','c','a','l','S','e','r','v','i','c','e',0 };
702 static const WCHAR szServiceParams[] = {'S','e','r','v','i','c','e','P','a','r','a','m','s',0};
703 HKEY hkey;
704 LONG r;
705 DWORD type, sz;
707 TRACE("Attempting to start Local service for %s\n", debugstr_guid(rclsid));
709 /* read the AppID value under the class's key */
710 r = COM_OpenKeyForCLSID(rclsid, KEY_READ, &hkey);
711 if (r!=ERROR_SUCCESS)
712 return hres;
713 sz = sizeof buf;
714 r = RegQueryValueExW(hkey, szAppId, NULL, &type, (LPBYTE)buf, &sz);
715 RegCloseKey(hkey);
716 if (r!=ERROR_SUCCESS || type!=REG_SZ)
717 return hres;
719 /* read the LocalService and ServiceParameters values from the AppID key */
720 strcpyW(keyname, szAppIdKey);
721 strcatW(keyname, buf);
722 r = RegOpenKeyExW(HKEY_CLASSES_ROOT, keyname, 0, KEY_READ, &hkey);
723 if (r!=ERROR_SUCCESS)
724 return hres;
725 sz = sizeof buf;
726 r = RegQueryValueExW(hkey, szLocalService, NULL, &type, (LPBYTE)buf, &sz);
727 if (r==ERROR_SUCCESS && type==REG_SZ)
729 DWORD num_args = 0;
730 LPWSTR args[1] = { NULL };
733 * FIXME: I'm not really sure how to deal with the service parameters.
734 * I suspect that the string returned from RegQueryValueExW
735 * should be split into a number of arguments by spaces.
736 * It would make more sense if ServiceParams contained a
737 * REG_MULTI_SZ here, but it's a REG_SZ for the services
738 * that I'm interested in for the moment.
740 r = RegQueryValueExW(hkey, szServiceParams, NULL, &type, NULL, &sz);
741 if (r == ERROR_SUCCESS && type == REG_SZ && sz)
743 args[0] = HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY,sz);
744 num_args++;
745 RegQueryValueExW(hkey, szServiceParams, NULL, &type, (LPBYTE)args[0], &sz);
747 r = start_local_service(buf, num_args, args);
748 if (r==ERROR_SUCCESS)
749 hres = S_OK;
750 HeapFree(GetProcessHeap(),0,args[0]);
752 RegCloseKey(hkey);
754 return hres;
758 static void get_localserver_pipe_name(WCHAR *pipefn, REFCLSID rclsid)
760 static const WCHAR wszPipeRef[] = {'\\','\\','.','\\','p','i','p','e','\\',0};
761 strcpyW(pipefn, wszPipeRef);
762 StringFromGUID2(rclsid, pipefn + sizeof(wszPipeRef)/sizeof(wszPipeRef[0]) - 1, CHARS_IN_GUID);
765 /* FIXME: should call to rpcss instead */
766 HRESULT RPC_GetLocalClassObject(REFCLSID rclsid, REFIID iid, LPVOID *ppv)
768 HRESULT hres;
769 HANDLE hPipe;
770 WCHAR pipefn[100];
771 DWORD res, bufferlen;
772 char marshalbuffer[200];
773 IStream *pStm;
774 LARGE_INTEGER seekto;
775 ULARGE_INTEGER newpos;
776 int tries = 0;
778 static const int MAXTRIES = 30; /* 30 seconds */
780 TRACE("rclsid=%s, iid=%s\n", debugstr_guid(rclsid), debugstr_guid(iid));
782 get_localserver_pipe_name(pipefn, rclsid);
784 while (tries++ < MAXTRIES) {
785 TRACE("waiting for %s\n", debugstr_w(pipefn));
787 WaitNamedPipeW( pipefn, NMPWAIT_WAIT_FOREVER );
788 hPipe = CreateFileW(pipefn, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, 0);
789 if (hPipe == INVALID_HANDLE_VALUE) {
790 if (tries == 1) {
791 if ( (hres = create_server(rclsid)) &&
792 (hres = create_local_service(rclsid)) )
793 return hres;
794 Sleep(1000);
795 } else {
796 WARN("Connecting to %s, no response yet, retrying: le is %lx\n", debugstr_w(pipefn), GetLastError());
797 Sleep(1000);
799 continue;
801 bufferlen = 0;
802 if (!ReadFile(hPipe,marshalbuffer,sizeof(marshalbuffer),&bufferlen,NULL)) {
803 FIXME("Failed to read marshal id from classfactory of %s.\n",debugstr_guid(rclsid));
804 Sleep(1000);
805 continue;
807 TRACE("read marshal id from pipe\n");
808 CloseHandle(hPipe);
809 break;
812 if (tries >= MAXTRIES)
813 return E_NOINTERFACE;
815 hres = CreateStreamOnHGlobal(0,TRUE,&pStm);
816 if (hres) return hres;
817 hres = IStream_Write(pStm,marshalbuffer,bufferlen,&res);
818 if (hres) goto out;
819 seekto.u.LowPart = 0;seekto.u.HighPart = 0;
820 hres = IStream_Seek(pStm,seekto,SEEK_SET,&newpos);
822 TRACE("unmarshalling classfactory\n");
823 hres = CoUnmarshalInterface(pStm,&IID_IClassFactory,ppv);
824 out:
825 IStream_Release(pStm);
826 return hres;
830 struct local_server_params
832 CLSID clsid;
833 IStream *stream;
836 /* FIXME: should call to rpcss instead */
837 static DWORD WINAPI local_server_thread(LPVOID param)
839 struct local_server_params * lsp = (struct local_server_params *)param;
840 HANDLE hPipe;
841 WCHAR pipefn[100];
842 HRESULT hres;
843 IStream *pStm = lsp->stream;
844 STATSTG ststg;
845 unsigned char *buffer;
846 int buflen;
847 LARGE_INTEGER seekto;
848 ULARGE_INTEGER newpos;
849 ULONG res;
851 TRACE("Starting threader for %s.\n",debugstr_guid(&lsp->clsid));
853 get_localserver_pipe_name(pipefn, &lsp->clsid);
855 HeapFree(GetProcessHeap(), 0, lsp);
857 hPipe = CreateNamedPipeW( pipefn, PIPE_ACCESS_DUPLEX,
858 PIPE_TYPE_BYTE|PIPE_WAIT, PIPE_UNLIMITED_INSTANCES,
859 4096, 4096, 500 /* 0.5 second timeout */, NULL );
861 if (hPipe == INVALID_HANDLE_VALUE)
863 FIXME("pipe creation failed for %s, le is %ld\n", debugstr_w(pipefn), GetLastError());
864 return 1;
867 while (1) {
868 if (!ConnectNamedPipe(hPipe,NULL)) {
869 ERR("Failure during ConnectNamedPipe %ld, ABORT!\n",GetLastError());
870 break;
873 TRACE("marshalling IClassFactory to client\n");
875 hres = IStream_Stat(pStm,&ststg,0);
876 if (hres) return hres;
878 buflen = ststg.cbSize.u.LowPart;
879 buffer = HeapAlloc(GetProcessHeap(),0,buflen);
880 seekto.u.LowPart = 0;
881 seekto.u.HighPart = 0;
882 hres = IStream_Seek(pStm,seekto,SEEK_SET,&newpos);
883 if (hres) {
884 FIXME("IStream_Seek failed, %lx\n",hres);
885 return hres;
888 hres = IStream_Read(pStm,buffer,buflen,&res);
889 if (hres) {
890 FIXME("Stream Read failed, %lx\n",hres);
891 return hres;
894 WriteFile(hPipe,buffer,buflen,&res,NULL);
895 FlushFileBuffers(hPipe);
896 DisconnectNamedPipe(hPipe);
898 TRACE("done marshalling IClassFactory\n");
900 CloseHandle(hPipe);
901 IStream_Release(pStm);
902 return 0;
905 void RPC_StartLocalServer(REFCLSID clsid, IStream *stream)
907 DWORD tid;
908 HANDLE thread;
909 struct local_server_params *lsp = HeapAlloc(GetProcessHeap(), 0, sizeof(*lsp));
911 lsp->clsid = *clsid;
912 lsp->stream = stream;
914 thread = CreateThread(NULL, 0, local_server_thread, lsp, 0, &tid);
915 CloseHandle(thread);
916 /* FIXME: failure handling */