Release 0.9.14.
[wine/multimedia.git] / dlls / ole32 / rpc.c
blob3617e5074007ccc65471ca56ec9464e9433637b6
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., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
23 #include "config.h"
24 #include "wine/port.h"
26 #include <stdlib.h>
27 #include <stdarg.h>
28 #include <stdio.h>
29 #include <string.h>
30 #include <assert.h>
32 #define COBJMACROS
33 #define NONAMELESSUNION
34 #define NONAMELESSSTRUCT
36 #include "windef.h"
37 #include "winbase.h"
38 #include "winuser.h"
39 #include "winsvc.h"
40 #include "objbase.h"
41 #include "ole2.h"
42 #include "rpc.h"
43 #include "winerror.h"
44 #include "winreg.h"
45 #include "wtypes.h"
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 =
65 0, 0, &csRegIf,
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};
74 struct registered_if
76 struct list entry;
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);
89 typedef struct
91 const IRpcChannelBufferVtbl *lpVtbl;
92 LONG refs;
93 } RpcChannelBuffer;
95 typedef struct
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)
117 *ppv = NULL;
118 if (IsEqualIID(riid,&IID_IRpcChannelBuffer) || IsEqualIID(riid,&IID_IUnknown))
120 *ppv = (LPVOID)iface;
121 IUnknown_AddRef(iface);
122 return S_OK;
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;
136 ULONG ref;
138 ref = InterlockedDecrement(&This->refs);
139 if (ref)
140 return ref;
142 HeapFree(GetProcessHeap(), 0, This);
143 return 0;
146 static ULONG WINAPI ClientRpcChannelBuffer_Release(LPRPCCHANNELBUFFER iface)
148 ClientRpcChannelBuffer *This = (ClientRpcChannelBuffer *)iface;
149 ULONG ref;
151 ref = InterlockedDecrement(&This->super.refs);
152 if (ref)
153 return ref;
155 RpcBindingFree(&This->bind);
156 HeapFree(GetProcessHeap(), 0, This);
157 return 0;
160 static HRESULT WINAPI ServerRpcChannelBuffer_GetBuffer(LPRPCCHANNELBUFFER iface, RPCOLEMESSAGE* olemsg, REFIID riid)
162 RpcChannelBuffer *This = (RpcChannelBuffer *)iface;
163 RPC_MESSAGE *msg = (RPC_MESSAGE *)olemsg;
164 RPC_STATUS status;
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;
180 RPC_STATUS status;
182 TRACE("(%p)->(%p,%s)\n", This, olemsg, debugstr_guid(riid));
184 cif = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(RPC_CLIENT_INTERFACE));
185 if (!cif)
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)
206 FIXME("stub\n");
207 return E_NOTIMPL;
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);
222 return 0;
225 static inline HRESULT ClientRpcChannelBuffer_IsCorrectApartment(ClientRpcChannelBuffer *This, APARTMENT *apt)
227 OXID oxid;
228 if (!apt)
229 return S_FALSE;
230 if (apartment_getoxid(apt, &oxid) != S_OK)
231 return S_FALSE;
232 if (This->oxid != oxid)
233 return S_FALSE;
234 return S_OK;
237 static HRESULT WINAPI ClientRpcChannelBuffer_SendReceive(LPRPCCHANNELBUFFER iface, RPCOLEMESSAGE *olemsg, ULONG *pstatus)
239 ClientRpcChannelBuffer *This = (ClientRpcChannelBuffer *)iface;
240 HRESULT hr;
241 RPC_MESSAGE *msg = (RPC_MESSAGE *)olemsg;
242 RPC_STATUS status;
243 DWORD index;
244 struct dispatch_params *params;
245 APARTMENT *apt = NULL;
246 IPID ipid;
248 TRACE("(%p) iMethod=%ld\n", olemsg, olemsg->iMethod);
250 hr = ClientRpcChannelBuffer_IsCorrectApartment(This, COM_CurrentApt());
251 if (hr != S_OK)
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;
263 params->hr = 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
270 * from DllMain */
272 RpcBindingInqObject(msg->Handle, &ipid);
273 hr = ipid_get_dispatch_params(&ipid, &apt, &params->stub, &params->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());
285 else
287 if (hr == S_OK)
289 /* otherwise, we go via RPC runtime so the stub and channel aren't
290 * needed here */
291 IRpcStubBuffer_Release(params->stub);
292 params->stub = NULL;
293 IRpcChannelBuffer_Release(params->chan);
294 params->chan = NULL;
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());
306 hr = E_UNEXPECTED;
308 else
309 hr = S_OK;
311 if (apt) apartment_release(apt);
313 if (hr == S_OK)
315 if (WaitForSingleObject(params->handle, 0))
316 hr = CoWaitForMultipleHandles(0, INFINITE, 1, &params->handle, &index);
318 CloseHandle(params->handle);
320 if (hr == S_OK) hr = params->hr;
322 status = params->status;
323 HeapFree(GetProcessHeap(), 0, params);
324 params = NULL;
326 if (hr) return hr;
328 if (pstatus) *pstatus = status;
330 TRACE("RPC call status: 0x%lx\n", status);
331 if (status == RPC_S_OK)
332 hr = S_OK;
333 else if (status == RPC_S_CALL_FAILED)
334 hr = *(HRESULT *)olemsg->Buffer;
335 else
336 hr = HRESULT_FROM_WIN32(status);
338 TRACE("-- 0x%08lx\n", hr);
340 return hr;
343 static HRESULT WINAPI ServerRpcChannelBuffer_FreeBuffer(LPRPCCHANNELBUFFER iface, RPCOLEMESSAGE* olemsg)
345 RPC_MESSAGE *msg = (RPC_MESSAGE *)olemsg;
346 RPC_STATUS status;
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;
360 RPC_STATUS status;
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;
383 return S_OK;
386 static HRESULT WINAPI ServerRpcChannelBuffer_GetDestCtx(LPRPCCHANNELBUFFER iface, DWORD* pdwDestContext, void** ppvDestContext)
388 FIXME("(%p,%p), stub!\n", pdwDestContext, ppvDestContext);
389 return E_FAIL;
392 static HRESULT WINAPI RpcChannelBuffer_IsConnected(LPRPCCHANNELBUFFER iface)
394 TRACE("()\n");
395 /* native does nothing too */
396 return S_OK;
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;
429 WCHAR endpoint[200];
430 RPC_BINDING_HANDLE bind;
431 RPC_STATUS status;
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(
440 NULL,
441 wszRpcTransport,
442 NULL,
443 endpoint,
444 NULL,
445 &string_binding);
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));
469 if (!This)
471 RpcBindingFree(&bind);
472 return E_OUTOFMEMORY;
475 This->super.lpVtbl = &ClientRpcChannelBufferVtbl;
476 This->super.refs = 1;
477 This->bind = bind;
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;
484 return S_OK;
487 HRESULT RPC_CreateServerChannel(IRpcChannelBuffer **chan)
489 RpcChannelBuffer *This = HeapAlloc(GetProcessHeap(), 0, sizeof(*This));
490 if (!This)
491 return E_OUTOFMEMORY;
493 This->lpVtbl = &ServerRpcChannelBufferVtbl;
494 This->refs = 1;
496 *chan = (IRpcChannelBuffer*)This;
498 return S_OK;
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;
514 APARTMENT *apt;
515 IPID ipid;
516 HRESULT hr;
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, &params->stub, &params->chan);
526 if (hr != S_OK)
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;
534 params->hr = 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);
548 else
550 ERR("PostMessage failed with error %ld\n", GetLastError());
551 IRpcChannelBuffer_Release(params->chan);
552 IRpcStubBuffer_Release(params->stub);
554 CloseHandle(params->handle);
556 else
558 BOOL joined = FALSE;
559 if (!COM_CurrentInfo()->apt)
561 apartment_joinmta();
562 joined = TRUE;
564 RPC_ExecuteCall(params);
565 if (joined)
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;
581 BOOL found = FALSE;
582 HRESULT hr = S_OK;
584 TRACE("(%s)\n", debugstr_guid(riid));
586 EnterCriticalSection(&csRegIf);
587 LIST_FOR_EACH_ENTRY(rif, &registered_interfaces, struct registered_if, entry)
589 if (IsEqualGUID(&rif->If.InterfaceId.SyntaxGUID, riid))
591 rif->refs++;
592 found = TRUE;
593 break;
596 if (!found)
598 TRACE("Creating new interface\n");
600 rif = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*rif));
601 if (rif)
603 RPC_STATUS status;
605 rif->refs = 1;
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,
614 NULL, NULL,
615 RPC_IF_OLE | RPC_IF_AUTOLISTEN,
616 RPC_C_LISTEN_MAX_CALLS_DEFAULT,
617 NULL);
618 if (status == RPC_S_OK)
619 list_add_tail(&registered_interfaces, &rif->entry);
620 else
622 ERR("RpcServerRegisterIfEx failed with error %ld\n", status);
623 HeapFree(GetProcessHeap(), 0, rif);
624 hr = HRESULT_FROM_WIN32(status);
627 else
628 hr = E_OUTOFMEMORY;
630 LeaveCriticalSection(&csRegIf);
631 return hr;
634 /* stub unregistration */
635 void RPC_UnregisterInterface(REFIID riid)
637 struct registered_if *rif;
638 EnterCriticalSection(&csRegIf);
639 LIST_FOR_EACH_ENTRY(rif, &registered_interfaces, struct registered_if, entry)
641 if (IsEqualGUID(&rif->If.InterfaceId.SyntaxGUID, riid))
643 if (!--rif->refs)
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);
650 #endif
652 break;
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))
664 WCHAR endpoint[200];
665 RPC_STATUS status;
667 get_rpc_endpoint(endpoint, &apt->oxid);
669 status = RpcServerUseProtseqEpW(
670 wszRpcTransport,
671 RPC_C_PROTSEQ_MAX_REQS_DEFAULT,
672 endpoint,
673 NULL);
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 };
687 HKEY key;
688 HRESULT hres;
689 WCHAR command[MAX_PATH+sizeof(embedding)/sizeof(WCHAR)];
690 DWORD size = (MAX_PATH+1) * sizeof(WCHAR);
691 STARTUPINFOW sinfo;
692 PROCESS_INFORMATION pinfo;
694 hres = COM_OpenKeyForCLSID(rclsid, wszLocalServer32, KEY_READ, &key);
695 if (FAILED(hres)) {
696 ERR("class %s not registered\n", debugstr_guid(rclsid));
697 return hres;
700 hres = RegQueryValueExW(key, NULL, NULL, NULL, (LPBYTE)command, &size);
701 RegCloseKey(key);
702 if (hres) {
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
717 * CreateProcess */
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);
725 return S_OK;
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);
739 if (!handle)
740 return r;
741 hsvc = OpenServiceW(handle, name, SERVICE_START);
742 if (hsvc)
744 if(StartServiceW(hsvc, num, params))
745 r = ERROR_SUCCESS;
746 else
747 r = GetLastError();
748 if (r == ERROR_SERVICE_ALREADY_RUNNING)
749 r = ERROR_SUCCESS;
750 CloseServiceHandle(hsvc);
752 else
753 r = GetLastError();
754 CloseServiceHandle(handle);
756 TRACE("StartService returned error %ld (%s)\n", r, (r == ERROR_SUCCESS) ? "ok":"failed");
758 return r;
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)
772 HRESULT hres;
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};
778 HKEY hkey;
779 LONG r;
780 DWORD type, sz;
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);
786 if (FAILED(hres))
787 return hres;
788 sz = sizeof buf;
789 r = RegQueryValueExW(hkey, NULL, NULL, &type, (LPBYTE)buf, &sz);
790 RegCloseKey(hkey);
791 if (r!=ERROR_SUCCESS || type!=REG_SZ)
792 return hres;
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)
799 return hres;
800 sz = sizeof buf;
801 r = RegQueryValueExW(hkey, szLocalService, NULL, &type, (LPBYTE)buf, &sz);
802 if (r==ERROR_SUCCESS && type==REG_SZ)
804 DWORD num_args = 0;
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);
819 num_args++;
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)
824 hres = S_OK;
825 HeapFree(GetProcessHeap(),0,args[0]);
827 RegCloseKey(hkey);
829 return hres;
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)
843 HRESULT hres;
844 HANDLE hPipe;
845 WCHAR pipefn[100];
846 DWORD res, bufferlen;
847 char marshalbuffer[200];
848 IStream *pStm;
849 LARGE_INTEGER seekto;
850 ULARGE_INTEGER newpos;
851 int tries = 0;
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) {
865 if (tries == 1) {
866 if ( (hres = create_local_service(rclsid)) &&
867 (hres = create_server(rclsid)) )
868 return hres;
869 Sleep(1000);
870 } else {
871 WARN("Connecting to %s, no response yet, retrying: le is %lx\n", debugstr_w(pipefn), GetLastError());
872 Sleep(1000);
874 continue;
876 bufferlen = 0;
877 if (!ReadFile(hPipe,marshalbuffer,sizeof(marshalbuffer),&bufferlen,NULL)) {
878 FIXME("Failed to read marshal id from classfactory of %s.\n",debugstr_guid(rclsid));
879 Sleep(1000);
880 continue;
882 TRACE("read marshal id from pipe\n");
883 CloseHandle(hPipe);
884 break;
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);
893 if (hres) goto out;
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);
899 out:
900 IStream_Release(pStm);
901 return hres;
905 struct local_server_params
907 CLSID clsid;
908 IStream *stream;
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;
915 HANDLE hPipe;
916 WCHAR pipefn[100];
917 HRESULT hres;
918 IStream *pStm = lsp->stream;
919 STATSTG ststg;
920 unsigned char *buffer;
921 int buflen;
922 LARGE_INTEGER seekto;
923 ULARGE_INTEGER newpos;
924 ULONG res;
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());
939 return 1;
942 while (1) {
943 if (!ConnectNamedPipe(hPipe,NULL)) {
944 ERR("Failure during ConnectNamedPipe %ld, ABORT!\n",GetLastError());
945 break;
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);
958 if (hres) {
959 FIXME("IStream_Seek failed, %lx\n",hres);
960 return hres;
963 hres = IStream_Read(pStm,buffer,buflen,&res);
964 if (hres) {
965 FIXME("Stream Read failed, %lx\n",hres);
966 return hres;
969 WriteFile(hPipe,buffer,buflen,&res,NULL);
970 FlushFileBuffers(hPipe);
971 DisconnectNamedPipe(hPipe);
973 TRACE("done marshalling IClassFactory\n");
975 CloseHandle(hPipe);
976 IStream_Release(pStm);
977 return 0;
980 void RPC_StartLocalServer(REFCLSID clsid, IStream *stream)
982 DWORD tid;
983 HANDLE thread;
984 struct local_server_params *lsp = HeapAlloc(GetProcessHeap(), 0, sizeof(*lsp));
986 lsp->clsid = *clsid;
987 lsp->stream = stream;
989 thread = CreateThread(NULL, 0, local_server_thread, lsp, 0, &tid);
990 CloseHandle(thread);
991 /* FIXME: failure handling */