ntdll: Add a test for NtNotifyChangeDirectoryFile.
[wine/multimedia.git] / dlls / ole32 / rpc.c
blob06c24d3f0549d63cb9d27e76d635e4fbdbe20752
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 "excpt.h"
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 =
66 0, 0, &csRegIf,
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};
75 struct registered_if
77 struct list entry;
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);
90 typedef struct
92 const IRpcChannelBufferVtbl *lpVtbl;
93 LONG refs;
94 } RpcChannelBuffer;
96 typedef struct
98 RpcChannelBuffer super; /* superclass */
100 RPC_BINDING_HANDLE bind; /* handle to the remote server */
101 } ClientRpcChannelBuffer;
103 struct dispatch_params
105 RPCOLEMESSAGE *msg; /* message */
106 IRpcStubBuffer *stub; /* stub buffer, if applicable */
107 IRpcChannelBuffer *chan; /* server channel buffer, if applicable */
108 HANDLE handle; /* handle that will become signaled when call finishes */
109 RPC_STATUS status; /* status (out) */
110 HRESULT hr; /* hresult (out) */
113 static WINE_EXCEPTION_FILTER(ole_filter)
115 if (GetExceptionCode() == EXCEPTION_ACCESS_VIOLATION)
116 return EXCEPTION_CONTINUE_SEARCH;
117 return EXCEPTION_EXECUTE_HANDLER;
120 static HRESULT WINAPI RpcChannelBuffer_QueryInterface(LPRPCCHANNELBUFFER iface, REFIID riid, LPVOID *ppv)
122 *ppv = NULL;
123 if (IsEqualIID(riid,&IID_IRpcChannelBuffer) || IsEqualIID(riid,&IID_IUnknown))
125 *ppv = (LPVOID)iface;
126 IUnknown_AddRef(iface);
127 return S_OK;
129 return E_NOINTERFACE;
132 static ULONG WINAPI RpcChannelBuffer_AddRef(LPRPCCHANNELBUFFER iface)
134 RpcChannelBuffer *This = (RpcChannelBuffer *)iface;
135 return InterlockedIncrement(&This->refs);
138 static ULONG WINAPI ServerRpcChannelBuffer_Release(LPRPCCHANNELBUFFER iface)
140 RpcChannelBuffer *This = (RpcChannelBuffer *)iface;
141 ULONG ref;
143 ref = InterlockedDecrement(&This->refs);
144 if (ref)
145 return ref;
147 HeapFree(GetProcessHeap(), 0, This);
148 return 0;
151 static ULONG WINAPI ClientRpcChannelBuffer_Release(LPRPCCHANNELBUFFER iface)
153 ClientRpcChannelBuffer *This = (ClientRpcChannelBuffer *)iface;
154 ULONG ref;
156 ref = InterlockedDecrement(&This->super.refs);
157 if (ref)
158 return ref;
160 RpcBindingFree(&This->bind);
161 HeapFree(GetProcessHeap(), 0, This);
162 return 0;
165 static HRESULT WINAPI ServerRpcChannelBuffer_GetBuffer(LPRPCCHANNELBUFFER iface, RPCOLEMESSAGE* olemsg, REFIID riid)
167 RpcChannelBuffer *This = (RpcChannelBuffer *)iface;
168 RPC_MESSAGE *msg = (RPC_MESSAGE *)olemsg;
169 RPC_STATUS status;
171 TRACE("(%p)->(%p,%s)\n", This, olemsg, debugstr_guid(riid));
173 status = I_RpcGetBuffer(msg);
175 TRACE("-- %ld\n", status);
177 return HRESULT_FROM_WIN32(status);
180 static HRESULT WINAPI ClientRpcChannelBuffer_GetBuffer(LPRPCCHANNELBUFFER iface, RPCOLEMESSAGE* olemsg, REFIID riid)
182 ClientRpcChannelBuffer *This = (ClientRpcChannelBuffer *)iface;
183 RPC_MESSAGE *msg = (RPC_MESSAGE *)olemsg;
184 RPC_CLIENT_INTERFACE *cif;
185 RPC_STATUS status;
187 TRACE("(%p)->(%p,%s)\n", This, olemsg, debugstr_guid(riid));
189 cif = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(RPC_CLIENT_INTERFACE));
190 if (!cif)
191 return E_OUTOFMEMORY;
193 cif->Length = sizeof(RPC_CLIENT_INTERFACE);
194 /* RPC interface ID = COM interface ID */
195 cif->InterfaceId.SyntaxGUID = *riid;
196 /* COM objects always have a version of 0.0 */
197 cif->InterfaceId.SyntaxVersion.MajorVersion = 0;
198 cif->InterfaceId.SyntaxVersion.MinorVersion = 0;
199 msg->RpcInterfaceInformation = cif;
200 msg->Handle = This->bind;
202 status = I_RpcGetBuffer(msg);
204 TRACE("-- %ld\n", status);
206 return HRESULT_FROM_WIN32(status);
209 /* this thread runs an outgoing RPC */
210 static DWORD WINAPI rpc_sendreceive_thread(LPVOID param)
212 struct dispatch_params *data = (struct dispatch_params *) param;
214 /* FIXME: trap and rethrow RPC exceptions in app thread */
215 data->status = I_RpcSendReceive((RPC_MESSAGE *)data->msg);
217 TRACE("completed with status 0x%lx\n", data->status);
219 return 0;
222 static HRESULT WINAPI RpcChannelBuffer_SendReceive(LPRPCCHANNELBUFFER iface, RPCOLEMESSAGE *olemsg, ULONG *pstatus)
224 HRESULT hr = S_OK;
225 RPC_MESSAGE *msg = (RPC_MESSAGE *)olemsg;
226 RPC_STATUS status;
227 DWORD index;
228 struct dispatch_params *params;
229 DWORD tid;
230 APARTMENT *apt = NULL;
231 IPID ipid;
233 TRACE("(%p) iMethod=%ld\n", olemsg, olemsg->iMethod);
235 params = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*params));
236 if (!params) return E_OUTOFMEMORY;
238 params->msg = olemsg;
239 params->status = RPC_S_OK;
240 params->hr = S_OK;
242 /* Note: this is an optimization in the Microsoft OLE runtime that we need
243 * to copy, as shown by the test_no_couninitialize_client test. without
244 * short-circuiting the RPC runtime in the case below, the test will
245 * deadlock on the loader lock due to the RPC runtime needing to create
246 * a thread to process the RPC when this function is called indirectly
247 * from DllMain */
249 RpcBindingInqObject(msg->Handle, &ipid);
250 hr = ipid_get_dispatch_params(&ipid, &apt, &params->stub, &params->chan);
251 if ((hr == S_OK) && (apt->model & COINIT_APARTMENTTHREADED))
253 params->handle = CreateEventW(NULL, FALSE, FALSE, NULL);
255 TRACE("Calling apartment thread 0x%08lx...\n", apt->tid);
257 if (!PostMessageW(apartment_getwindow(apt), DM_EXECUTERPC, 0, (LPARAM)params))
259 ERR("PostMessage failed with error %ld\n", GetLastError());
260 hr = HRESULT_FROM_WIN32(GetLastError());
263 else
265 if (hr == S_OK)
267 /* otherwise, we go via RPC runtime so the stub and channel aren't
268 * needed here */
269 IRpcStubBuffer_Release(params->stub);
270 params->stub = NULL;
271 IRpcChannelBuffer_Release(params->chan);
272 params->chan = NULL;
275 /* we use a separate thread here because we need to be able to
276 * pump the message loop in the application thread: if we do not,
277 * any windows created by this thread will hang and RPCs that try
278 * and re-enter this STA from an incoming server thread will
279 * deadlock. InstallShield is an example of that.
281 params->handle = CreateThread(NULL, 0, rpc_sendreceive_thread, params, 0, &tid);
282 if (!params->handle)
284 ERR("Could not create RpcSendReceive thread, error %lx\n", GetLastError());
285 hr = E_UNEXPECTED;
287 else
288 hr = S_OK;
290 if (apt) apartment_release(apt);
292 if (hr == S_OK)
294 if (WaitForSingleObject(params->handle, 0))
295 hr = CoWaitForMultipleHandles(0, INFINITE, 1, &params->handle, &index);
297 CloseHandle(params->handle);
299 if (hr == S_OK) hr = params->hr;
301 status = params->status;
302 HeapFree(GetProcessHeap(), 0, params);
303 params = NULL;
305 if (hr) return hr;
307 if (pstatus) *pstatus = status;
309 TRACE("RPC call status: 0x%lx\n", status);
310 if (status == RPC_S_OK)
311 hr = S_OK;
312 else if (status == RPC_S_CALL_FAILED)
313 hr = *(HRESULT *)olemsg->Buffer;
314 else
315 hr = HRESULT_FROM_WIN32(status);
317 TRACE("-- 0x%08lx\n", hr);
319 return hr;
322 static HRESULT WINAPI ServerRpcChannelBuffer_FreeBuffer(LPRPCCHANNELBUFFER iface, RPCOLEMESSAGE* olemsg)
324 RPC_MESSAGE *msg = (RPC_MESSAGE *)olemsg;
325 RPC_STATUS status;
327 TRACE("(%p)\n", msg);
329 status = I_RpcFreeBuffer(msg);
331 TRACE("-- %ld\n", status);
333 return HRESULT_FROM_WIN32(status);
336 static HRESULT WINAPI ClientRpcChannelBuffer_FreeBuffer(LPRPCCHANNELBUFFER iface, RPCOLEMESSAGE* olemsg)
338 RPC_MESSAGE *msg = (RPC_MESSAGE *)olemsg;
339 RPC_STATUS status;
341 TRACE("(%p)\n", msg);
343 status = I_RpcFreeBuffer(msg);
345 HeapFree(GetProcessHeap(), 0, msg->RpcInterfaceInformation);
346 msg->RpcInterfaceInformation = NULL;
348 TRACE("-- %ld\n", status);
350 return HRESULT_FROM_WIN32(status);
353 static HRESULT WINAPI RpcChannelBuffer_GetDestCtx(LPRPCCHANNELBUFFER iface, DWORD* pdwDestContext, void** ppvDestContext)
355 FIXME("(%p,%p), stub!\n", pdwDestContext, ppvDestContext);
356 return E_FAIL;
359 static HRESULT WINAPI RpcChannelBuffer_IsConnected(LPRPCCHANNELBUFFER iface)
361 TRACE("()\n");
362 /* native does nothing too */
363 return S_OK;
366 static const IRpcChannelBufferVtbl ClientRpcChannelBufferVtbl =
368 RpcChannelBuffer_QueryInterface,
369 RpcChannelBuffer_AddRef,
370 ClientRpcChannelBuffer_Release,
371 ClientRpcChannelBuffer_GetBuffer,
372 RpcChannelBuffer_SendReceive,
373 ClientRpcChannelBuffer_FreeBuffer,
374 RpcChannelBuffer_GetDestCtx,
375 RpcChannelBuffer_IsConnected
378 static const IRpcChannelBufferVtbl ServerRpcChannelBufferVtbl =
380 RpcChannelBuffer_QueryInterface,
381 RpcChannelBuffer_AddRef,
382 ServerRpcChannelBuffer_Release,
383 ServerRpcChannelBuffer_GetBuffer,
384 RpcChannelBuffer_SendReceive,
385 ServerRpcChannelBuffer_FreeBuffer,
386 RpcChannelBuffer_GetDestCtx,
387 RpcChannelBuffer_IsConnected
390 /* returns a channel buffer for proxies */
391 HRESULT RPC_CreateClientChannel(const OXID *oxid, const IPID *ipid, IRpcChannelBuffer **chan)
393 ClientRpcChannelBuffer *This;
394 WCHAR endpoint[200];
395 RPC_BINDING_HANDLE bind;
396 RPC_STATUS status;
397 LPWSTR string_binding;
399 /* connect to the apartment listener thread */
400 get_rpc_endpoint(endpoint, oxid);
402 TRACE("proxy pipe: connecting to endpoint: %s\n", debugstr_w(endpoint));
404 status = RpcStringBindingComposeW(
405 NULL,
406 wszPipeTransport,
407 NULL,
408 endpoint,
409 NULL,
410 &string_binding);
412 if (status == RPC_S_OK)
414 status = RpcBindingFromStringBindingW(string_binding, &bind);
416 if (status == RPC_S_OK)
418 IPID ipid2 = *ipid; /* why can't RpcBindingSetObject take a const? */
419 status = RpcBindingSetObject(bind, &ipid2);
420 if (status != RPC_S_OK)
421 RpcBindingFree(&bind);
424 RpcStringFreeW(&string_binding);
427 if (status != RPC_S_OK)
429 ERR("Couldn't get binding for endpoint %s, status = %ld\n", debugstr_w(endpoint), status);
430 return HRESULT_FROM_WIN32(status);
433 This = HeapAlloc(GetProcessHeap(), 0, sizeof(*This));
434 if (!This)
436 RpcBindingFree(&bind);
437 return E_OUTOFMEMORY;
440 This->super.lpVtbl = &ClientRpcChannelBufferVtbl;
441 This->super.refs = 1;
442 This->bind = bind;
444 *chan = (IRpcChannelBuffer*)This;
446 return S_OK;
449 HRESULT RPC_CreateServerChannel(IRpcChannelBuffer **chan)
451 RpcChannelBuffer *This = HeapAlloc(GetProcessHeap(), 0, sizeof(*This));
452 if (!This)
453 return E_OUTOFMEMORY;
455 This->lpVtbl = &ServerRpcChannelBufferVtbl;
456 This->refs = 1;
458 *chan = (IRpcChannelBuffer*)This;
460 return S_OK;
464 void RPC_ExecuteCall(struct dispatch_params *params)
466 __TRY
468 params->hr = IRpcStubBuffer_Invoke(params->stub, params->msg, params->chan);
470 __EXCEPT(ole_filter)
472 params->hr = GetExceptionCode();
474 __ENDTRY
475 IRpcStubBuffer_Release(params->stub);
476 IRpcChannelBuffer_Release(params->chan);
477 if (params->handle) SetEvent(params->handle);
480 static void __RPC_STUB dispatch_rpc(RPC_MESSAGE *msg)
482 struct dispatch_params *params;
483 APARTMENT *apt;
484 IPID ipid;
485 HRESULT hr;
487 RpcBindingInqObject(msg->Handle, &ipid);
489 TRACE("ipid = %s, iMethod = %d\n", debugstr_guid(&ipid), msg->ProcNum);
491 params = HeapAlloc(GetProcessHeap(), 0, sizeof(*params));
492 if (!params) return RpcRaiseException(E_OUTOFMEMORY);
494 hr = ipid_get_dispatch_params(&ipid, &apt, &params->stub, &params->chan);
495 if (hr != S_OK)
497 ERR("no apartment found for ipid %s\n", debugstr_guid(&ipid));
498 return RpcRaiseException(hr);
501 params->msg = (RPCOLEMESSAGE *)msg;
502 params->status = RPC_S_OK;
503 params->hr = S_OK;
504 params->handle = NULL;
506 /* Note: this is the important difference between STAs and MTAs - we
507 * always execute RPCs to STAs in the thread that originally created the
508 * apartment (i.e. the one that pumps messages to the window) */
509 if (apt->model & COINIT_APARTMENTTHREADED)
511 params->handle = CreateEventW(NULL, FALSE, FALSE, NULL);
513 TRACE("Calling apartment thread 0x%08lx...\n", apt->tid);
515 if (PostMessageW(apartment_getwindow(apt), DM_EXECUTERPC, 0, (LPARAM)params))
516 WaitForSingleObject(params->handle, INFINITE);
517 else
519 ERR("PostMessage failed with error %ld\n", GetLastError());
520 IRpcChannelBuffer_Release(params->chan);
521 IRpcStubBuffer_Release(params->stub);
523 CloseHandle(params->handle);
525 else
527 BOOL joined = FALSE;
528 if (!COM_CurrentInfo()->apt)
530 apartment_joinmta();
531 joined = TRUE;
533 RPC_ExecuteCall(params);
534 if (joined)
536 apartment_release(COM_CurrentInfo()->apt);
537 COM_CurrentInfo()->apt = NULL;
541 HeapFree(GetProcessHeap(), 0, params);
543 apartment_release(apt);
546 /* stub registration */
547 HRESULT RPC_RegisterInterface(REFIID riid)
549 struct registered_if *rif;
550 BOOL found = FALSE;
551 HRESULT hr = S_OK;
553 TRACE("(%s)\n", debugstr_guid(riid));
555 EnterCriticalSection(&csRegIf);
556 LIST_FOR_EACH_ENTRY(rif, &registered_interfaces, struct registered_if, entry)
558 if (IsEqualGUID(&rif->If.InterfaceId.SyntaxGUID, riid))
560 rif->refs++;
561 found = TRUE;
562 break;
565 if (!found)
567 TRACE("Creating new interface\n");
569 rif = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*rif));
570 if (rif)
572 RPC_STATUS status;
574 rif->refs = 1;
575 rif->If.Length = sizeof(RPC_SERVER_INTERFACE);
576 /* RPC interface ID = COM interface ID */
577 rif->If.InterfaceId.SyntaxGUID = *riid;
578 rif->If.DispatchTable = &rpc_dispatch;
579 /* all other fields are 0, including the version asCOM objects
580 * always have a version of 0.0 */
581 status = RpcServerRegisterIfEx(
582 (RPC_IF_HANDLE)&rif->If,
583 NULL, NULL,
584 RPC_IF_OLE | RPC_IF_AUTOLISTEN,
585 RPC_C_LISTEN_MAX_CALLS_DEFAULT,
586 NULL);
587 if (status == RPC_S_OK)
588 list_add_tail(&registered_interfaces, &rif->entry);
589 else
591 ERR("RpcServerRegisterIfEx failed with error %ld\n", status);
592 HeapFree(GetProcessHeap(), 0, rif);
593 hr = HRESULT_FROM_WIN32(status);
596 else
597 hr = E_OUTOFMEMORY;
599 LeaveCriticalSection(&csRegIf);
600 return hr;
603 /* stub unregistration */
604 void RPC_UnregisterInterface(REFIID riid)
606 struct registered_if *rif;
607 EnterCriticalSection(&csRegIf);
608 LIST_FOR_EACH_ENTRY(rif, &registered_interfaces, struct registered_if, entry)
610 if (IsEqualGUID(&rif->If.InterfaceId.SyntaxGUID, riid))
612 if (!--rif->refs)
614 #if 0 /* this is a stub in builtin and spams the console with FIXME's */
615 IID iid = *riid; /* RpcServerUnregisterIf doesn't take const IID */
616 RpcServerUnregisterIf((RPC_IF_HANDLE)&rif->If, &iid, 0);
617 list_remove(&rif->entry);
618 HeapFree(GetProcessHeap(), 0, rif);
619 #endif
621 break;
624 LeaveCriticalSection(&csRegIf);
627 /* make the apartment reachable by other threads and processes and create the
628 * IRemUnknown object */
629 void RPC_StartRemoting(struct apartment *apt)
631 if (!InterlockedExchange(&apt->remoting_started, TRUE))
633 WCHAR endpoint[200];
634 RPC_STATUS status;
636 get_rpc_endpoint(endpoint, &apt->oxid);
638 status = RpcServerUseProtseqEpW(
639 wszPipeTransport,
640 RPC_C_PROTSEQ_MAX_REQS_DEFAULT,
641 endpoint,
642 NULL);
643 if (status != RPC_S_OK)
644 ERR("Couldn't register endpoint %s\n", debugstr_w(endpoint));
646 /* FIXME: move remote unknown exporting into this function */
648 start_apartment_remote_unknown();
652 static HRESULT create_server(REFCLSID rclsid)
654 static const WCHAR wszLocalServer32[] = { 'L','o','c','a','l','S','e','r','v','e','r','3','2',0 };
655 static const WCHAR embedding[] = { ' ', '-','E','m','b','e','d','d','i','n','g',0 };
656 HKEY key;
657 HRESULT hres;
658 WCHAR command[MAX_PATH+sizeof(embedding)/sizeof(WCHAR)];
659 DWORD size = (MAX_PATH+1) * sizeof(WCHAR);
660 STARTUPINFOW sinfo;
661 PROCESS_INFORMATION pinfo;
663 hres = COM_OpenKeyForCLSID(rclsid, wszLocalServer32, KEY_READ, &key);
664 if (FAILED(hres)) {
665 ERR("class %s not registered\n", debugstr_guid(rclsid));
666 return hres;
669 hres = RegQueryValueExW(key, NULL, NULL, NULL, (LPBYTE)command, &size);
670 RegCloseKey(key);
671 if (hres) {
672 WARN("No default value for LocalServer32 key\n");
673 return REGDB_E_CLASSNOTREG; /* FIXME: check retval */
676 memset(&sinfo,0,sizeof(sinfo));
677 sinfo.cb = sizeof(sinfo);
679 /* EXE servers are started with the -Embedding switch. */
681 strcatW(command, embedding);
683 TRACE("activating local server %s for %s\n", debugstr_w(command), debugstr_guid(rclsid));
685 /* FIXME: Win2003 supports a ServerExecutable value that is passed into
686 * CreateProcess */
687 if (!CreateProcessW(NULL, command, NULL, NULL, FALSE, 0, NULL, NULL, &sinfo, &pinfo)) {
688 WARN("failed to run local server %s\n", debugstr_w(command));
689 return HRESULT_FROM_WIN32(GetLastError());
691 CloseHandle(pinfo.hProcess);
692 CloseHandle(pinfo.hThread);
694 return S_OK;
698 * start_local_service() - start a service given its name and parameters
700 static DWORD start_local_service(LPCWSTR name, DWORD num, LPCWSTR *params)
702 SC_HANDLE handle, hsvc;
703 DWORD r = ERROR_FUNCTION_FAILED;
705 TRACE("Starting service %s %ld params\n", debugstr_w(name), num);
707 handle = OpenSCManagerW(NULL, NULL, SC_MANAGER_CONNECT);
708 if (!handle)
709 return r;
710 hsvc = OpenServiceW(handle, name, SERVICE_START);
711 if (hsvc)
713 if(StartServiceW(hsvc, num, params))
714 r = ERROR_SUCCESS;
715 else
716 r = GetLastError();
717 if (r == ERROR_SERVICE_ALREADY_RUNNING)
718 r = ERROR_SUCCESS;
719 CloseServiceHandle(hsvc);
721 else
722 r = GetLastError();
723 CloseServiceHandle(handle);
725 TRACE("StartService returned error %ld (%s)\n", r, (r == ERROR_SUCCESS) ? "ok":"failed");
727 return r;
731 * create_local_service() - start a COM server in a service
733 * To start a Local Service, we read the AppID value under
734 * the class's CLSID key, then open the HKCR\\AppId key specified
735 * there and check for a LocalService value.
737 * Note: Local Services are not supported under Windows 9x
739 static HRESULT create_local_service(REFCLSID rclsid)
741 HRESULT hres;
742 WCHAR buf[CHARS_IN_GUID], keyname[50];
743 static const WCHAR szAppId[] = { 'A','p','p','I','d',0 };
744 static const WCHAR szAppIdKey[] = { 'A','p','p','I','d','\\',0 };
745 static const WCHAR szLocalService[] = { 'L','o','c','a','l','S','e','r','v','i','c','e',0 };
746 static const WCHAR szServiceParams[] = {'S','e','r','v','i','c','e','P','a','r','a','m','s',0};
747 HKEY hkey;
748 LONG r;
749 DWORD type, sz;
751 TRACE("Attempting to start Local service for %s\n", debugstr_guid(rclsid));
753 /* read the AppID value under the class's key */
754 hres = COM_OpenKeyForCLSID(rclsid, szAppId, KEY_READ, &hkey);
755 if (FAILED(hres))
756 return hres;
757 sz = sizeof buf;
758 r = RegQueryValueExW(hkey, NULL, NULL, &type, (LPBYTE)buf, &sz);
759 RegCloseKey(hkey);
760 if (r!=ERROR_SUCCESS || type!=REG_SZ)
761 return hres;
763 /* read the LocalService and ServiceParameters values from the AppID key */
764 strcpyW(keyname, szAppIdKey);
765 strcatW(keyname, buf);
766 r = RegOpenKeyExW(HKEY_CLASSES_ROOT, keyname, 0, KEY_READ, &hkey);
767 if (r!=ERROR_SUCCESS)
768 return hres;
769 sz = sizeof buf;
770 r = RegQueryValueExW(hkey, szLocalService, NULL, &type, (LPBYTE)buf, &sz);
771 if (r==ERROR_SUCCESS && type==REG_SZ)
773 DWORD num_args = 0;
774 LPWSTR args[1] = { NULL };
777 * FIXME: I'm not really sure how to deal with the service parameters.
778 * I suspect that the string returned from RegQueryValueExW
779 * should be split into a number of arguments by spaces.
780 * It would make more sense if ServiceParams contained a
781 * REG_MULTI_SZ here, but it's a REG_SZ for the services
782 * that I'm interested in for the moment.
784 r = RegQueryValueExW(hkey, szServiceParams, NULL, &type, NULL, &sz);
785 if (r == ERROR_SUCCESS && type == REG_SZ && sz)
787 args[0] = HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY,sz);
788 num_args++;
789 RegQueryValueExW(hkey, szServiceParams, NULL, &type, (LPBYTE)args[0], &sz);
791 r = start_local_service(buf, num_args, (LPCWSTR *)args);
792 if (r==ERROR_SUCCESS)
793 hres = S_OK;
794 HeapFree(GetProcessHeap(),0,args[0]);
796 RegCloseKey(hkey);
798 return hres;
802 static void get_localserver_pipe_name(WCHAR *pipefn, REFCLSID rclsid)
804 static const WCHAR wszPipeRef[] = {'\\','\\','.','\\','p','i','p','e','\\',0};
805 strcpyW(pipefn, wszPipeRef);
806 StringFromGUID2(rclsid, pipefn + sizeof(wszPipeRef)/sizeof(wszPipeRef[0]) - 1, CHARS_IN_GUID);
809 /* FIXME: should call to rpcss instead */
810 HRESULT RPC_GetLocalClassObject(REFCLSID rclsid, REFIID iid, LPVOID *ppv)
812 HRESULT hres;
813 HANDLE hPipe;
814 WCHAR pipefn[100];
815 DWORD res, bufferlen;
816 char marshalbuffer[200];
817 IStream *pStm;
818 LARGE_INTEGER seekto;
819 ULARGE_INTEGER newpos;
820 int tries = 0;
822 static const int MAXTRIES = 30; /* 30 seconds */
824 TRACE("rclsid=%s, iid=%s\n", debugstr_guid(rclsid), debugstr_guid(iid));
826 get_localserver_pipe_name(pipefn, rclsid);
828 while (tries++ < MAXTRIES) {
829 TRACE("waiting for %s\n", debugstr_w(pipefn));
831 WaitNamedPipeW( pipefn, NMPWAIT_WAIT_FOREVER );
832 hPipe = CreateFileW(pipefn, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, 0);
833 if (hPipe == INVALID_HANDLE_VALUE) {
834 if (tries == 1) {
835 if ( (hres = create_local_service(rclsid)) &&
836 (hres = create_server(rclsid)) )
837 return hres;
838 Sleep(1000);
839 } else {
840 WARN("Connecting to %s, no response yet, retrying: le is %lx\n", debugstr_w(pipefn), GetLastError());
841 Sleep(1000);
843 continue;
845 bufferlen = 0;
846 if (!ReadFile(hPipe,marshalbuffer,sizeof(marshalbuffer),&bufferlen,NULL)) {
847 FIXME("Failed to read marshal id from classfactory of %s.\n",debugstr_guid(rclsid));
848 Sleep(1000);
849 continue;
851 TRACE("read marshal id from pipe\n");
852 CloseHandle(hPipe);
853 break;
856 if (tries >= MAXTRIES)
857 return E_NOINTERFACE;
859 hres = CreateStreamOnHGlobal(0,TRUE,&pStm);
860 if (hres) return hres;
861 hres = IStream_Write(pStm,marshalbuffer,bufferlen,&res);
862 if (hres) goto out;
863 seekto.u.LowPart = 0;seekto.u.HighPart = 0;
864 hres = IStream_Seek(pStm,seekto,SEEK_SET,&newpos);
866 TRACE("unmarshalling classfactory\n");
867 hres = CoUnmarshalInterface(pStm,&IID_IClassFactory,ppv);
868 out:
869 IStream_Release(pStm);
870 return hres;
874 struct local_server_params
876 CLSID clsid;
877 IStream *stream;
880 /* FIXME: should call to rpcss instead */
881 static DWORD WINAPI local_server_thread(LPVOID param)
883 struct local_server_params * lsp = (struct local_server_params *)param;
884 HANDLE hPipe;
885 WCHAR pipefn[100];
886 HRESULT hres;
887 IStream *pStm = lsp->stream;
888 STATSTG ststg;
889 unsigned char *buffer;
890 int buflen;
891 LARGE_INTEGER seekto;
892 ULARGE_INTEGER newpos;
893 ULONG res;
895 TRACE("Starting threader for %s.\n",debugstr_guid(&lsp->clsid));
897 get_localserver_pipe_name(pipefn, &lsp->clsid);
899 HeapFree(GetProcessHeap(), 0, lsp);
901 hPipe = CreateNamedPipeW( pipefn, PIPE_ACCESS_DUPLEX,
902 PIPE_TYPE_BYTE|PIPE_WAIT, PIPE_UNLIMITED_INSTANCES,
903 4096, 4096, 500 /* 0.5 second timeout */, NULL );
905 if (hPipe == INVALID_HANDLE_VALUE)
907 FIXME("pipe creation failed for %s, le is %ld\n", debugstr_w(pipefn), GetLastError());
908 return 1;
911 while (1) {
912 if (!ConnectNamedPipe(hPipe,NULL)) {
913 ERR("Failure during ConnectNamedPipe %ld, ABORT!\n",GetLastError());
914 break;
917 TRACE("marshalling IClassFactory to client\n");
919 hres = IStream_Stat(pStm,&ststg,0);
920 if (hres) return hres;
922 buflen = ststg.cbSize.u.LowPart;
923 buffer = HeapAlloc(GetProcessHeap(),0,buflen);
924 seekto.u.LowPart = 0;
925 seekto.u.HighPart = 0;
926 hres = IStream_Seek(pStm,seekto,SEEK_SET,&newpos);
927 if (hres) {
928 FIXME("IStream_Seek failed, %lx\n",hres);
929 return hres;
932 hres = IStream_Read(pStm,buffer,buflen,&res);
933 if (hres) {
934 FIXME("Stream Read failed, %lx\n",hres);
935 return hres;
938 WriteFile(hPipe,buffer,buflen,&res,NULL);
939 FlushFileBuffers(hPipe);
940 DisconnectNamedPipe(hPipe);
942 TRACE("done marshalling IClassFactory\n");
944 CloseHandle(hPipe);
945 IStream_Release(pStm);
946 return 0;
949 void RPC_StartLocalServer(REFCLSID clsid, IStream *stream)
951 DWORD tid;
952 HANDLE thread;
953 struct local_server_params *lsp = HeapAlloc(GetProcessHeap(), 0, sizeof(*lsp));
955 lsp->clsid = *clsid;
956 lsp->stream = stream;
958 thread = CreateThread(NULL, 0, local_server_thread, lsp, 0, &tid);
959 CloseHandle(thread);
960 /* FIXME: failure handling */