ole32: Don't return from CoRegisterClassObject until we have created the named pipe.
[wine/multimedia.git] / dlls / ole32 / rpc.c
blob7646e1dbf81c3888146772fbd582ced47d2148ad
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 HANDLE event; /* cached event handle */
104 } ClientRpcChannelBuffer;
106 struct dispatch_params
108 RPCOLEMESSAGE *msg; /* message */
109 IRpcStubBuffer *stub; /* stub buffer, if applicable */
110 IRpcChannelBuffer *chan; /* server channel buffer, if applicable */
111 HANDLE handle; /* handle that will become signaled when call finishes */
112 RPC_STATUS status; /* status (out) */
113 HRESULT hr; /* hresult (out) */
116 static HRESULT WINAPI RpcChannelBuffer_QueryInterface(LPRPCCHANNELBUFFER iface, REFIID riid, LPVOID *ppv)
118 *ppv = NULL;
119 if (IsEqualIID(riid,&IID_IRpcChannelBuffer) || IsEqualIID(riid,&IID_IUnknown))
121 *ppv = (LPVOID)iface;
122 IUnknown_AddRef(iface);
123 return S_OK;
125 return E_NOINTERFACE;
128 static ULONG WINAPI RpcChannelBuffer_AddRef(LPRPCCHANNELBUFFER iface)
130 RpcChannelBuffer *This = (RpcChannelBuffer *)iface;
131 return InterlockedIncrement(&This->refs);
134 static ULONG WINAPI ServerRpcChannelBuffer_Release(LPRPCCHANNELBUFFER iface)
136 RpcChannelBuffer *This = (RpcChannelBuffer *)iface;
137 ULONG ref;
139 ref = InterlockedDecrement(&This->refs);
140 if (ref)
141 return ref;
143 HeapFree(GetProcessHeap(), 0, This);
144 return 0;
147 static ULONG WINAPI ClientRpcChannelBuffer_Release(LPRPCCHANNELBUFFER iface)
149 ClientRpcChannelBuffer *This = (ClientRpcChannelBuffer *)iface;
150 ULONG ref;
152 ref = InterlockedDecrement(&This->super.refs);
153 if (ref)
154 return ref;
156 if (This->event) CloseHandle(This->event);
157 RpcBindingFree(&This->bind);
158 HeapFree(GetProcessHeap(), 0, This);
159 return 0;
162 static HRESULT WINAPI ServerRpcChannelBuffer_GetBuffer(LPRPCCHANNELBUFFER iface, RPCOLEMESSAGE* olemsg, REFIID riid)
164 RpcChannelBuffer *This = (RpcChannelBuffer *)iface;
165 RPC_MESSAGE *msg = (RPC_MESSAGE *)olemsg;
166 RPC_STATUS status;
168 TRACE("(%p)->(%p,%s)\n", This, olemsg, debugstr_guid(riid));
170 status = I_RpcGetBuffer(msg);
172 TRACE("-- %ld\n", status);
174 return HRESULT_FROM_WIN32(status);
177 static HRESULT WINAPI ClientRpcChannelBuffer_GetBuffer(LPRPCCHANNELBUFFER iface, RPCOLEMESSAGE* olemsg, REFIID riid)
179 ClientRpcChannelBuffer *This = (ClientRpcChannelBuffer *)iface;
180 RPC_MESSAGE *msg = (RPC_MESSAGE *)olemsg;
181 RPC_CLIENT_INTERFACE *cif;
182 RPC_STATUS status;
184 TRACE("(%p)->(%p,%s)\n", This, olemsg, debugstr_guid(riid));
186 cif = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(RPC_CLIENT_INTERFACE));
187 if (!cif)
188 return E_OUTOFMEMORY;
190 cif->Length = sizeof(RPC_CLIENT_INTERFACE);
191 /* RPC interface ID = COM interface ID */
192 cif->InterfaceId.SyntaxGUID = *riid;
193 /* COM objects always have a version of 0.0 */
194 cif->InterfaceId.SyntaxVersion.MajorVersion = 0;
195 cif->InterfaceId.SyntaxVersion.MinorVersion = 0;
196 msg->RpcInterfaceInformation = cif;
197 msg->Handle = This->bind;
199 status = I_RpcGetBuffer(msg);
201 TRACE("-- %ld\n", status);
203 return HRESULT_FROM_WIN32(status);
206 static HRESULT WINAPI ServerRpcChannelBuffer_SendReceive(LPRPCCHANNELBUFFER iface, RPCOLEMESSAGE *olemsg, ULONG *pstatus)
208 FIXME("stub\n");
209 return E_NOTIMPL;
212 static HANDLE ClientRpcChannelBuffer_GetEventHandle(ClientRpcChannelBuffer *This)
214 HANDLE event = InterlockedExchangePointer(&This->event, NULL);
216 /* Note: must be auto-reset event so we can reuse it without a call
217 * to ResetEvent */
218 if (!event) event = CreateEventW(NULL, FALSE, FALSE, NULL);
220 return event;
223 static void ClientRpcChannelBuffer_ReleaseEventHandle(ClientRpcChannelBuffer *This, HANDLE event)
225 if (InterlockedCompareExchangePointer(&This->event, event, NULL))
226 /* already a handle cached in This */
227 CloseHandle(event);
230 /* this thread runs an outgoing RPC */
231 static DWORD WINAPI rpc_sendreceive_thread(LPVOID param)
233 struct dispatch_params *data = (struct dispatch_params *) param;
235 /* FIXME: trap and rethrow RPC exceptions in app thread */
236 data->status = I_RpcSendReceive((RPC_MESSAGE *)data->msg);
238 TRACE("completed with status 0x%lx\n", data->status);
240 SetEvent(data->handle);
242 return 0;
245 static inline HRESULT ClientRpcChannelBuffer_IsCorrectApartment(ClientRpcChannelBuffer *This, APARTMENT *apt)
247 OXID oxid;
248 if (!apt)
249 return S_FALSE;
250 if (apartment_getoxid(apt, &oxid) != S_OK)
251 return S_FALSE;
252 if (This->oxid != oxid)
253 return S_FALSE;
254 return S_OK;
257 static HRESULT WINAPI ClientRpcChannelBuffer_SendReceive(LPRPCCHANNELBUFFER iface, RPCOLEMESSAGE *olemsg, ULONG *pstatus)
259 ClientRpcChannelBuffer *This = (ClientRpcChannelBuffer *)iface;
260 HRESULT hr;
261 RPC_MESSAGE *msg = (RPC_MESSAGE *)olemsg;
262 RPC_STATUS status;
263 DWORD index;
264 struct dispatch_params *params;
265 APARTMENT *apt = NULL;
266 IPID ipid;
268 TRACE("(%p) iMethod=%ld\n", olemsg, olemsg->iMethod);
270 hr = ClientRpcChannelBuffer_IsCorrectApartment(This, COM_CurrentApt());
271 if (hr != S_OK)
273 ERR("called from wrong apartment, should have been 0x%s\n",
274 wine_dbgstr_longlong(This->oxid));
275 return RPC_E_WRONG_THREAD;
278 params = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*params));
279 if (!params) return E_OUTOFMEMORY;
281 params->msg = olemsg;
282 params->status = RPC_S_OK;
283 params->hr = S_OK;
285 /* Note: this is an optimization in the Microsoft OLE runtime that we need
286 * to copy, as shown by the test_no_couninitialize_client test. without
287 * short-circuiting the RPC runtime in the case below, the test will
288 * deadlock on the loader lock due to the RPC runtime needing to create
289 * a thread to process the RPC when this function is called indirectly
290 * from DllMain */
292 RpcBindingInqObject(msg->Handle, &ipid);
293 hr = ipid_get_dispatch_params(&ipid, &apt, &params->stub, &params->chan);
294 params->handle = ClientRpcChannelBuffer_GetEventHandle(This);
295 if ((hr == S_OK) && !apt->multi_threaded)
297 TRACE("Calling apartment thread 0x%08lx...\n", apt->tid);
299 if (!PostMessageW(apartment_getwindow(apt), DM_EXECUTERPC, 0, (LPARAM)params))
301 ERR("PostMessage failed with error %ld\n", GetLastError());
302 hr = HRESULT_FROM_WIN32(GetLastError());
305 else
307 if (hr == S_OK)
309 /* otherwise, we go via RPC runtime so the stub and channel aren't
310 * needed here */
311 IRpcStubBuffer_Release(params->stub);
312 params->stub = NULL;
313 IRpcChannelBuffer_Release(params->chan);
314 params->chan = NULL;
317 /* we use a separate thread here because we need to be able to
318 * pump the message loop in the application thread: if we do not,
319 * any windows created by this thread will hang and RPCs that try
320 * and re-enter this STA from an incoming server thread will
321 * deadlock. InstallShield is an example of that.
323 if (!QueueUserWorkItem(rpc_sendreceive_thread, params, WT_EXECUTEDEFAULT))
325 ERR("QueueUserWorkItem failed with error %lx\n", GetLastError());
326 hr = E_UNEXPECTED;
328 else
329 hr = S_OK;
331 if (apt) apartment_release(apt);
333 if (hr == S_OK)
335 if (WaitForSingleObject(params->handle, 0))
336 hr = CoWaitForMultipleHandles(0, INFINITE, 1, &params->handle, &index);
338 ClientRpcChannelBuffer_ReleaseEventHandle(This, params->handle);
340 if (hr == S_OK) hr = params->hr;
342 status = params->status;
343 HeapFree(GetProcessHeap(), 0, params);
344 params = NULL;
346 if (hr) return hr;
348 if (pstatus) *pstatus = status;
350 TRACE("RPC call status: 0x%lx\n", status);
351 if (status == RPC_S_OK)
352 hr = S_OK;
353 else if (status == RPC_S_CALL_FAILED)
354 hr = *(HRESULT *)olemsg->Buffer;
355 else
356 hr = HRESULT_FROM_WIN32(status);
358 TRACE("-- 0x%08lx\n", hr);
360 return hr;
363 static HRESULT WINAPI ServerRpcChannelBuffer_FreeBuffer(LPRPCCHANNELBUFFER iface, RPCOLEMESSAGE* olemsg)
365 RPC_MESSAGE *msg = (RPC_MESSAGE *)olemsg;
366 RPC_STATUS status;
368 TRACE("(%p)\n", msg);
370 status = I_RpcFreeBuffer(msg);
372 TRACE("-- %ld\n", status);
374 return HRESULT_FROM_WIN32(status);
377 static HRESULT WINAPI ClientRpcChannelBuffer_FreeBuffer(LPRPCCHANNELBUFFER iface, RPCOLEMESSAGE* olemsg)
379 RPC_MESSAGE *msg = (RPC_MESSAGE *)olemsg;
380 RPC_STATUS status;
382 TRACE("(%p)\n", msg);
384 status = I_RpcFreeBuffer(msg);
386 HeapFree(GetProcessHeap(), 0, msg->RpcInterfaceInformation);
387 msg->RpcInterfaceInformation = NULL;
389 TRACE("-- %ld\n", status);
391 return HRESULT_FROM_WIN32(status);
394 static HRESULT WINAPI ClientRpcChannelBuffer_GetDestCtx(LPRPCCHANNELBUFFER iface, DWORD* pdwDestContext, void** ppvDestContext)
396 ClientRpcChannelBuffer *This = (ClientRpcChannelBuffer *)iface;
398 TRACE("(%p,%p)\n", pdwDestContext, ppvDestContext);
400 *pdwDestContext = This->dest_context;
401 *ppvDestContext = This->dest_context_data;
403 return S_OK;
406 static HRESULT WINAPI ServerRpcChannelBuffer_GetDestCtx(LPRPCCHANNELBUFFER iface, DWORD* pdwDestContext, void** ppvDestContext)
408 FIXME("(%p,%p), stub!\n", pdwDestContext, ppvDestContext);
409 return E_FAIL;
412 static HRESULT WINAPI RpcChannelBuffer_IsConnected(LPRPCCHANNELBUFFER iface)
414 TRACE("()\n");
415 /* native does nothing too */
416 return S_OK;
419 static const IRpcChannelBufferVtbl ClientRpcChannelBufferVtbl =
421 RpcChannelBuffer_QueryInterface,
422 RpcChannelBuffer_AddRef,
423 ClientRpcChannelBuffer_Release,
424 ClientRpcChannelBuffer_GetBuffer,
425 ClientRpcChannelBuffer_SendReceive,
426 ClientRpcChannelBuffer_FreeBuffer,
427 ClientRpcChannelBuffer_GetDestCtx,
428 RpcChannelBuffer_IsConnected
431 static const IRpcChannelBufferVtbl ServerRpcChannelBufferVtbl =
433 RpcChannelBuffer_QueryInterface,
434 RpcChannelBuffer_AddRef,
435 ServerRpcChannelBuffer_Release,
436 ServerRpcChannelBuffer_GetBuffer,
437 ServerRpcChannelBuffer_SendReceive,
438 ServerRpcChannelBuffer_FreeBuffer,
439 ServerRpcChannelBuffer_GetDestCtx,
440 RpcChannelBuffer_IsConnected
443 /* returns a channel buffer for proxies */
444 HRESULT RPC_CreateClientChannel(const OXID *oxid, const IPID *ipid,
445 DWORD dest_context, void *dest_context_data,
446 IRpcChannelBuffer **chan)
448 ClientRpcChannelBuffer *This;
449 WCHAR endpoint[200];
450 RPC_BINDING_HANDLE bind;
451 RPC_STATUS status;
452 LPWSTR string_binding;
454 /* connect to the apartment listener thread */
455 get_rpc_endpoint(endpoint, oxid);
457 TRACE("proxy pipe: connecting to endpoint: %s\n", debugstr_w(endpoint));
459 status = RpcStringBindingComposeW(
460 NULL,
461 wszRpcTransport,
462 NULL,
463 endpoint,
464 NULL,
465 &string_binding);
467 if (status == RPC_S_OK)
469 status = RpcBindingFromStringBindingW(string_binding, &bind);
471 if (status == RPC_S_OK)
473 IPID ipid2 = *ipid; /* why can't RpcBindingSetObject take a const? */
474 status = RpcBindingSetObject(bind, &ipid2);
475 if (status != RPC_S_OK)
476 RpcBindingFree(&bind);
479 RpcStringFreeW(&string_binding);
482 if (status != RPC_S_OK)
484 ERR("Couldn't get binding for endpoint %s, status = %ld\n", debugstr_w(endpoint), status);
485 return HRESULT_FROM_WIN32(status);
488 This = HeapAlloc(GetProcessHeap(), 0, sizeof(*This));
489 if (!This)
491 RpcBindingFree(&bind);
492 return E_OUTOFMEMORY;
495 This->super.lpVtbl = &ClientRpcChannelBufferVtbl;
496 This->super.refs = 1;
497 This->bind = bind;
498 apartment_getoxid(COM_CurrentApt(), &This->oxid);
499 This->dest_context = dest_context;
500 This->dest_context_data = dest_context_data;
501 This->event = NULL;
503 *chan = (IRpcChannelBuffer*)This;
505 return S_OK;
508 HRESULT RPC_CreateServerChannel(IRpcChannelBuffer **chan)
510 RpcChannelBuffer *This = HeapAlloc(GetProcessHeap(), 0, sizeof(*This));
511 if (!This)
512 return E_OUTOFMEMORY;
514 This->lpVtbl = &ServerRpcChannelBufferVtbl;
515 This->refs = 1;
517 *chan = (IRpcChannelBuffer*)This;
519 return S_OK;
523 void RPC_ExecuteCall(struct dispatch_params *params)
525 params->hr = IRpcStubBuffer_Invoke(params->stub, params->msg, params->chan);
527 IRpcStubBuffer_Release(params->stub);
528 IRpcChannelBuffer_Release(params->chan);
529 if (params->handle) SetEvent(params->handle);
532 static void __RPC_STUB dispatch_rpc(RPC_MESSAGE *msg)
534 struct dispatch_params *params;
535 APARTMENT *apt;
536 IPID ipid;
537 HRESULT hr;
539 RpcBindingInqObject(msg->Handle, &ipid);
541 TRACE("ipid = %s, iMethod = %d\n", debugstr_guid(&ipid), msg->ProcNum);
543 params = HeapAlloc(GetProcessHeap(), 0, sizeof(*params));
544 if (!params) return RpcRaiseException(E_OUTOFMEMORY);
546 hr = ipid_get_dispatch_params(&ipid, &apt, &params->stub, &params->chan);
547 if (hr != S_OK)
549 ERR("no apartment found for ipid %s\n", debugstr_guid(&ipid));
550 return RpcRaiseException(hr);
553 params->msg = (RPCOLEMESSAGE *)msg;
554 params->status = RPC_S_OK;
555 params->hr = S_OK;
556 params->handle = NULL;
558 /* Note: this is the important difference between STAs and MTAs - we
559 * always execute RPCs to STAs in the thread that originally created the
560 * apartment (i.e. the one that pumps messages to the window) */
561 if (!apt->multi_threaded)
563 params->handle = CreateEventW(NULL, FALSE, FALSE, NULL);
565 TRACE("Calling apartment thread 0x%08lx...\n", apt->tid);
567 if (PostMessageW(apartment_getwindow(apt), DM_EXECUTERPC, 0, (LPARAM)params))
568 WaitForSingleObject(params->handle, INFINITE);
569 else
571 ERR("PostMessage failed with error %ld\n", GetLastError());
572 IRpcChannelBuffer_Release(params->chan);
573 IRpcStubBuffer_Release(params->stub);
575 CloseHandle(params->handle);
577 else
579 BOOL joined = FALSE;
580 if (!COM_CurrentInfo()->apt)
582 apartment_joinmta();
583 joined = TRUE;
585 RPC_ExecuteCall(params);
586 if (joined)
588 apartment_release(COM_CurrentInfo()->apt);
589 COM_CurrentInfo()->apt = NULL;
593 hr = params->hr;
594 HeapFree(GetProcessHeap(), 0, params);
596 apartment_release(apt);
598 /* if IRpcStubBuffer_Invoke fails, we should raise an exception to tell
599 * the RPC runtime that the call failed */
600 if (hr) RpcRaiseException(hr);
603 /* stub registration */
604 HRESULT RPC_RegisterInterface(REFIID riid)
606 struct registered_if *rif;
607 BOOL found = FALSE;
608 HRESULT hr = S_OK;
610 TRACE("(%s)\n", debugstr_guid(riid));
612 EnterCriticalSection(&csRegIf);
613 LIST_FOR_EACH_ENTRY(rif, &registered_interfaces, struct registered_if, entry)
615 if (IsEqualGUID(&rif->If.InterfaceId.SyntaxGUID, riid))
617 rif->refs++;
618 found = TRUE;
619 break;
622 if (!found)
624 TRACE("Creating new interface\n");
626 rif = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*rif));
627 if (rif)
629 RPC_STATUS status;
631 rif->refs = 1;
632 rif->If.Length = sizeof(RPC_SERVER_INTERFACE);
633 /* RPC interface ID = COM interface ID */
634 rif->If.InterfaceId.SyntaxGUID = *riid;
635 rif->If.DispatchTable = &rpc_dispatch;
636 /* all other fields are 0, including the version asCOM objects
637 * always have a version of 0.0 */
638 status = RpcServerRegisterIfEx(
639 (RPC_IF_HANDLE)&rif->If,
640 NULL, NULL,
641 RPC_IF_OLE | RPC_IF_AUTOLISTEN,
642 RPC_C_LISTEN_MAX_CALLS_DEFAULT,
643 NULL);
644 if (status == RPC_S_OK)
645 list_add_tail(&registered_interfaces, &rif->entry);
646 else
648 ERR("RpcServerRegisterIfEx failed with error %ld\n", status);
649 HeapFree(GetProcessHeap(), 0, rif);
650 hr = HRESULT_FROM_WIN32(status);
653 else
654 hr = E_OUTOFMEMORY;
656 LeaveCriticalSection(&csRegIf);
657 return hr;
660 /* stub unregistration */
661 void RPC_UnregisterInterface(REFIID riid)
663 struct registered_if *rif;
664 EnterCriticalSection(&csRegIf);
665 LIST_FOR_EACH_ENTRY(rif, &registered_interfaces, struct registered_if, entry)
667 if (IsEqualGUID(&rif->If.InterfaceId.SyntaxGUID, riid))
669 if (!--rif->refs)
671 #if 0 /* this is a stub in builtin and spams the console with FIXME's */
672 IID iid = *riid; /* RpcServerUnregisterIf doesn't take const IID */
673 RpcServerUnregisterIf((RPC_IF_HANDLE)&rif->If, &iid, 0);
674 list_remove(&rif->entry);
675 HeapFree(GetProcessHeap(), 0, rif);
676 #endif
678 break;
681 LeaveCriticalSection(&csRegIf);
684 /* make the apartment reachable by other threads and processes and create the
685 * IRemUnknown object */
686 void RPC_StartRemoting(struct apartment *apt)
688 if (!InterlockedExchange(&apt->remoting_started, TRUE))
690 WCHAR endpoint[200];
691 RPC_STATUS status;
693 get_rpc_endpoint(endpoint, &apt->oxid);
695 status = RpcServerUseProtseqEpW(
696 wszRpcTransport,
697 RPC_C_PROTSEQ_MAX_REQS_DEFAULT,
698 endpoint,
699 NULL);
700 if (status != RPC_S_OK)
701 ERR("Couldn't register endpoint %s\n", debugstr_w(endpoint));
703 /* FIXME: move remote unknown exporting into this function */
705 start_apartment_remote_unknown();
709 static HRESULT create_server(REFCLSID rclsid)
711 static const WCHAR wszLocalServer32[] = { 'L','o','c','a','l','S','e','r','v','e','r','3','2',0 };
712 static const WCHAR embedding[] = { ' ', '-','E','m','b','e','d','d','i','n','g',0 };
713 HKEY key;
714 HRESULT hres;
715 WCHAR command[MAX_PATH+sizeof(embedding)/sizeof(WCHAR)];
716 DWORD size = (MAX_PATH+1) * sizeof(WCHAR);
717 STARTUPINFOW sinfo;
718 PROCESS_INFORMATION pinfo;
720 hres = COM_OpenKeyForCLSID(rclsid, wszLocalServer32, KEY_READ, &key);
721 if (FAILED(hres)) {
722 ERR("class %s not registered\n", debugstr_guid(rclsid));
723 return hres;
726 hres = RegQueryValueExW(key, NULL, NULL, NULL, (LPBYTE)command, &size);
727 RegCloseKey(key);
728 if (hres) {
729 WARN("No default value for LocalServer32 key\n");
730 return REGDB_E_CLASSNOTREG; /* FIXME: check retval */
733 memset(&sinfo,0,sizeof(sinfo));
734 sinfo.cb = sizeof(sinfo);
736 /* EXE servers are started with the -Embedding switch. */
738 strcatW(command, embedding);
740 TRACE("activating local server %s for %s\n", debugstr_w(command), debugstr_guid(rclsid));
742 /* FIXME: Win2003 supports a ServerExecutable value that is passed into
743 * CreateProcess */
744 if (!CreateProcessW(NULL, command, NULL, NULL, FALSE, 0, NULL, NULL, &sinfo, &pinfo)) {
745 WARN("failed to run local server %s\n", debugstr_w(command));
746 return HRESULT_FROM_WIN32(GetLastError());
748 CloseHandle(pinfo.hProcess);
749 CloseHandle(pinfo.hThread);
751 return S_OK;
755 * start_local_service() - start a service given its name and parameters
757 static DWORD start_local_service(LPCWSTR name, DWORD num, LPCWSTR *params)
759 SC_HANDLE handle, hsvc;
760 DWORD r = ERROR_FUNCTION_FAILED;
762 TRACE("Starting service %s %ld params\n", debugstr_w(name), num);
764 handle = OpenSCManagerW(NULL, NULL, SC_MANAGER_CONNECT);
765 if (!handle)
766 return r;
767 hsvc = OpenServiceW(handle, name, SERVICE_START);
768 if (hsvc)
770 if(StartServiceW(hsvc, num, params))
771 r = ERROR_SUCCESS;
772 else
773 r = GetLastError();
774 if (r == ERROR_SERVICE_ALREADY_RUNNING)
775 r = ERROR_SUCCESS;
776 CloseServiceHandle(hsvc);
778 else
779 r = GetLastError();
780 CloseServiceHandle(handle);
782 TRACE("StartService returned error %ld (%s)\n", r, (r == ERROR_SUCCESS) ? "ok":"failed");
784 return r;
788 * create_local_service() - start a COM server in a service
790 * To start a Local Service, we read the AppID value under
791 * the class's CLSID key, then open the HKCR\\AppId key specified
792 * there and check for a LocalService value.
794 * Note: Local Services are not supported under Windows 9x
796 static HRESULT create_local_service(REFCLSID rclsid)
798 HRESULT hres;
799 WCHAR buf[CHARS_IN_GUID];
800 static const WCHAR szLocalService[] = { 'L','o','c','a','l','S','e','r','v','i','c','e',0 };
801 static const WCHAR szServiceParams[] = {'S','e','r','v','i','c','e','P','a','r','a','m','s',0};
802 HKEY hkey;
803 LONG r;
804 DWORD type, sz;
806 TRACE("Attempting to start Local service for %s\n", debugstr_guid(rclsid));
808 hres = COM_OpenKeyForAppIdFromCLSID(rclsid, KEY_READ, &hkey);
809 if (FAILED(hres))
810 return hres;
812 /* read the LocalService and ServiceParameters values from the AppID key */
813 sz = sizeof buf;
814 r = RegQueryValueExW(hkey, szLocalService, NULL, &type, (LPBYTE)buf, &sz);
815 if (r==ERROR_SUCCESS && type==REG_SZ)
817 DWORD num_args = 0;
818 LPWSTR args[1] = { NULL };
821 * FIXME: I'm not really sure how to deal with the service parameters.
822 * I suspect that the string returned from RegQueryValueExW
823 * should be split into a number of arguments by spaces.
824 * It would make more sense if ServiceParams contained a
825 * REG_MULTI_SZ here, but it's a REG_SZ for the services
826 * that I'm interested in for the moment.
828 r = RegQueryValueExW(hkey, szServiceParams, NULL, &type, NULL, &sz);
829 if (r == ERROR_SUCCESS && type == REG_SZ && sz)
831 args[0] = HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY,sz);
832 num_args++;
833 RegQueryValueExW(hkey, szServiceParams, NULL, &type, (LPBYTE)args[0], &sz);
835 r = start_local_service(buf, num_args, (LPCWSTR *)args);
836 if (r != ERROR_SUCCESS)
837 hres = REGDB_E_CLASSNOTREG; /* FIXME: check retval */
838 HeapFree(GetProcessHeap(),0,args[0]);
840 else
842 WARN("No LocalService value\n");
843 hres = REGDB_E_CLASSNOTREG; /* FIXME: check retval */
845 RegCloseKey(hkey);
847 return hres;
851 static void get_localserver_pipe_name(WCHAR *pipefn, REFCLSID rclsid)
853 static const WCHAR wszPipeRef[] = {'\\','\\','.','\\','p','i','p','e','\\',0};
854 strcpyW(pipefn, wszPipeRef);
855 StringFromGUID2(rclsid, pipefn + sizeof(wszPipeRef)/sizeof(wszPipeRef[0]) - 1, CHARS_IN_GUID);
858 /* FIXME: should call to rpcss instead */
859 HRESULT RPC_GetLocalClassObject(REFCLSID rclsid, REFIID iid, LPVOID *ppv)
861 HRESULT hres;
862 HANDLE hPipe;
863 WCHAR pipefn[100];
864 DWORD res, bufferlen;
865 char marshalbuffer[200];
866 IStream *pStm;
867 LARGE_INTEGER seekto;
868 ULARGE_INTEGER newpos;
869 int tries = 0;
871 static const int MAXTRIES = 30; /* 30 seconds */
873 TRACE("rclsid=%s, iid=%s\n", debugstr_guid(rclsid), debugstr_guid(iid));
875 get_localserver_pipe_name(pipefn, rclsid);
877 while (tries++ < MAXTRIES) {
878 TRACE("waiting for %s\n", debugstr_w(pipefn));
880 WaitNamedPipeW( pipefn, NMPWAIT_WAIT_FOREVER );
881 hPipe = CreateFileW(pipefn, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, 0);
882 if (hPipe == INVALID_HANDLE_VALUE) {
883 if (tries == 1) {
884 if ( (hres = create_local_service(rclsid)) &&
885 (hres = create_server(rclsid)) )
886 return hres;
887 Sleep(1000);
888 } else {
889 WARN("Connecting to %s, no response yet, retrying: le is %lx\n", debugstr_w(pipefn), GetLastError());
890 Sleep(1000);
892 continue;
894 bufferlen = 0;
895 if (!ReadFile(hPipe,marshalbuffer,sizeof(marshalbuffer),&bufferlen,NULL)) {
896 FIXME("Failed to read marshal id from classfactory of %s.\n",debugstr_guid(rclsid));
897 Sleep(1000);
898 continue;
900 TRACE("read marshal id from pipe\n");
901 CloseHandle(hPipe);
902 break;
905 if (tries >= MAXTRIES)
906 return E_NOINTERFACE;
908 hres = CreateStreamOnHGlobal(0,TRUE,&pStm);
909 if (hres) return hres;
910 hres = IStream_Write(pStm,marshalbuffer,bufferlen,&res);
911 if (hres) goto out;
912 seekto.u.LowPart = 0;seekto.u.HighPart = 0;
913 hres = IStream_Seek(pStm,seekto,SEEK_SET,&newpos);
915 TRACE("unmarshalling classfactory\n");
916 hres = CoUnmarshalInterface(pStm,&IID_IClassFactory,ppv);
917 out:
918 IStream_Release(pStm);
919 return hres;
923 struct local_server_params
925 CLSID clsid;
926 IStream *stream;
927 HANDLE ready_event;
930 /* FIXME: should call to rpcss instead */
931 static DWORD WINAPI local_server_thread(LPVOID param)
933 struct local_server_params * lsp = (struct local_server_params *)param;
934 HANDLE hPipe;
935 WCHAR pipefn[100];
936 HRESULT hres;
937 IStream *pStm = lsp->stream;
938 STATSTG ststg;
939 unsigned char *buffer;
940 int buflen;
941 LARGE_INTEGER seekto;
942 ULARGE_INTEGER newpos;
943 ULONG res;
945 TRACE("Starting threader for %s.\n",debugstr_guid(&lsp->clsid));
947 get_localserver_pipe_name(pipefn, &lsp->clsid);
949 hPipe = CreateNamedPipeW( pipefn, PIPE_ACCESS_DUPLEX,
950 PIPE_TYPE_BYTE|PIPE_WAIT, PIPE_UNLIMITED_INSTANCES,
951 4096, 4096, 500 /* 0.5 second timeout */, NULL );
953 SetEvent(lsp->ready_event);
955 HeapFree(GetProcessHeap(), 0, lsp);
957 if (hPipe == INVALID_HANDLE_VALUE)
959 FIXME("pipe creation failed for %s, le is %ld\n", debugstr_w(pipefn), GetLastError());
960 return 1;
963 while (1) {
964 if (!ConnectNamedPipe(hPipe,NULL) && GetLastError() != ERROR_PIPE_CONNECTED) {
965 ERR("Failure during ConnectNamedPipe %ld, ABORT!\n",GetLastError());
966 break;
969 TRACE("marshalling IClassFactory to client\n");
971 hres = IStream_Stat(pStm,&ststg,0);
972 if (hres) return hres;
974 seekto.u.LowPart = 0;
975 seekto.u.HighPart = 0;
976 hres = IStream_Seek(pStm,seekto,SEEK_SET,&newpos);
977 if (hres) {
978 FIXME("IStream_Seek failed, %lx\n",hres);
979 return hres;
982 buflen = ststg.cbSize.u.LowPart;
983 buffer = HeapAlloc(GetProcessHeap(),0,buflen);
985 hres = IStream_Read(pStm,buffer,buflen,&res);
986 if (hres) {
987 FIXME("Stream Read failed, %lx\n",hres);
988 HeapFree(GetProcessHeap(),0,buffer);
989 return hres;
992 WriteFile(hPipe,buffer,buflen,&res,NULL);
993 HeapFree(GetProcessHeap(),0,buffer);
995 FlushFileBuffers(hPipe);
996 DisconnectNamedPipe(hPipe);
998 TRACE("done marshalling IClassFactory\n");
1000 CloseHandle(hPipe);
1001 IStream_Release(pStm);
1002 return 0;
1005 void RPC_StartLocalServer(REFCLSID clsid, IStream *stream)
1007 DWORD tid;
1008 HANDLE thread, ready_event;
1009 struct local_server_params *lsp = HeapAlloc(GetProcessHeap(), 0, sizeof(*lsp));
1011 lsp->clsid = *clsid;
1012 lsp->stream = stream;
1013 IStream_AddRef(stream);
1014 lsp->ready_event = ready_event = CreateEventW(NULL, FALSE, FALSE, NULL);
1016 thread = CreateThread(NULL, 0, local_server_thread, lsp, 0, &tid);
1017 CloseHandle(thread);
1018 /* FIXME: failure handling */
1020 WaitForSingleObject(ready_event, INFINITE);
1021 CloseHandle(ready_event);