mshtml: Added wrapper of nsIURI interface.
[wine/wine-kai.git] / dlls / ole32 / rpc.c
blob05becb219e44bb2429107c1460d2159a3d974818
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"
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 "excpt.h"
47 #include "wine/unicode.h"
48 #include "wine/exception.h"
50 #include "compobj_private.h"
52 #include "wine/debug.h"
54 WINE_DEFAULT_DEBUG_CHANNEL(ole);
56 static void __RPC_STUB dispatch_rpc(RPC_MESSAGE *msg);
58 /* we only use one function to dispatch calls for all methods - we use the
59 * RPC_IF_OLE flag to tell the RPC runtime that this is the case */
60 static RPC_DISPATCH_FUNCTION rpc_dispatch_table[1] = { dispatch_rpc }; /* (RO) */
61 static RPC_DISPATCH_TABLE rpc_dispatch = { 1, rpc_dispatch_table }; /* (RO) */
63 static struct list registered_interfaces = LIST_INIT(registered_interfaces); /* (CS csRegIf) */
64 static CRITICAL_SECTION csRegIf;
65 static CRITICAL_SECTION_DEBUG csRegIf_debug =
67 0, 0, &csRegIf,
68 { &csRegIf_debug.ProcessLocksList, &csRegIf_debug.ProcessLocksList },
69 0, 0, { (DWORD_PTR)(__FILE__ ": dcom registered server interfaces") }
71 static CRITICAL_SECTION csRegIf = { &csRegIf_debug, -1, 0, 0, 0, 0 };
73 static WCHAR wszPipeTransport[] = {'n','c','a','c','n','_','n','p',0};
76 struct registered_if
78 struct list entry;
79 DWORD refs; /* ref count */
80 RPC_SERVER_INTERFACE If; /* interface registered with the RPC runtime */
83 /* get the pipe endpoint specified of the specified apartment */
84 static inline void get_rpc_endpoint(LPWSTR endpoint, const OXID *oxid)
86 /* FIXME: should get endpoint from rpcss */
87 static const WCHAR wszEndpointFormat[] = {'\\','p','i','p','e','\\','O','L','E','_','%','0','8','l','x','%','0','8','l','x',0};
88 wsprintfW(endpoint, wszEndpointFormat, (DWORD)(*oxid >> 32),(DWORD)*oxid);
91 typedef struct
93 const IRpcChannelBufferVtbl *lpVtbl;
94 LONG refs;
95 } RpcChannelBuffer;
97 typedef struct
99 RpcChannelBuffer super; /* superclass */
101 RPC_BINDING_HANDLE bind; /* handle to the remote server */
102 OXID oxid; /* apartment in which the channel is valid */
103 } 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 WINE_EXCEPTION_FILTER(ole_filter)
117 if (GetExceptionCode() == EXCEPTION_ACCESS_VIOLATION)
118 return EXCEPTION_CONTINUE_SEARCH;
119 return EXCEPTION_EXECUTE_HANDLER;
122 static HRESULT WINAPI RpcChannelBuffer_QueryInterface(LPRPCCHANNELBUFFER iface, REFIID riid, LPVOID *ppv)
124 *ppv = NULL;
125 if (IsEqualIID(riid,&IID_IRpcChannelBuffer) || IsEqualIID(riid,&IID_IUnknown))
127 *ppv = (LPVOID)iface;
128 IUnknown_AddRef(iface);
129 return S_OK;
131 return E_NOINTERFACE;
134 static ULONG WINAPI RpcChannelBuffer_AddRef(LPRPCCHANNELBUFFER iface)
136 RpcChannelBuffer *This = (RpcChannelBuffer *)iface;
137 return InterlockedIncrement(&This->refs);
140 static ULONG WINAPI ServerRpcChannelBuffer_Release(LPRPCCHANNELBUFFER iface)
142 RpcChannelBuffer *This = (RpcChannelBuffer *)iface;
143 ULONG ref;
145 ref = InterlockedDecrement(&This->refs);
146 if (ref)
147 return ref;
149 HeapFree(GetProcessHeap(), 0, This);
150 return 0;
153 static ULONG WINAPI ClientRpcChannelBuffer_Release(LPRPCCHANNELBUFFER iface)
155 ClientRpcChannelBuffer *This = (ClientRpcChannelBuffer *)iface;
156 ULONG ref;
158 ref = InterlockedDecrement(&This->super.refs);
159 if (ref)
160 return ref;
162 RpcBindingFree(&This->bind);
163 HeapFree(GetProcessHeap(), 0, This);
164 return 0;
167 static HRESULT WINAPI ServerRpcChannelBuffer_GetBuffer(LPRPCCHANNELBUFFER iface, RPCOLEMESSAGE* olemsg, REFIID riid)
169 RpcChannelBuffer *This = (RpcChannelBuffer *)iface;
170 RPC_MESSAGE *msg = (RPC_MESSAGE *)olemsg;
171 RPC_STATUS status;
173 TRACE("(%p)->(%p,%s)\n", This, olemsg, debugstr_guid(riid));
175 status = I_RpcGetBuffer(msg);
177 TRACE("-- %ld\n", status);
179 return HRESULT_FROM_WIN32(status);
182 static HRESULT WINAPI ClientRpcChannelBuffer_GetBuffer(LPRPCCHANNELBUFFER iface, RPCOLEMESSAGE* olemsg, REFIID riid)
184 ClientRpcChannelBuffer *This = (ClientRpcChannelBuffer *)iface;
185 RPC_MESSAGE *msg = (RPC_MESSAGE *)olemsg;
186 RPC_CLIENT_INTERFACE *cif;
187 RPC_STATUS status;
189 TRACE("(%p)->(%p,%s)\n", This, olemsg, debugstr_guid(riid));
191 cif = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(RPC_CLIENT_INTERFACE));
192 if (!cif)
193 return E_OUTOFMEMORY;
195 cif->Length = sizeof(RPC_CLIENT_INTERFACE);
196 /* RPC interface ID = COM interface ID */
197 cif->InterfaceId.SyntaxGUID = *riid;
198 /* COM objects always have a version of 0.0 */
199 cif->InterfaceId.SyntaxVersion.MajorVersion = 0;
200 cif->InterfaceId.SyntaxVersion.MinorVersion = 0;
201 msg->RpcInterfaceInformation = cif;
202 msg->Handle = This->bind;
204 status = I_RpcGetBuffer(msg);
206 TRACE("-- %ld\n", status);
208 return HRESULT_FROM_WIN32(status);
211 static HRESULT WINAPI ServerRpcChannelBuffer_SendReceive(LPRPCCHANNELBUFFER iface, RPCOLEMESSAGE *olemsg, ULONG *pstatus)
213 FIXME("stub\n");
214 return E_NOTIMPL;
217 /* this thread runs an outgoing RPC */
218 static DWORD WINAPI rpc_sendreceive_thread(LPVOID param)
220 struct dispatch_params *data = (struct dispatch_params *) param;
222 /* FIXME: trap and rethrow RPC exceptions in app thread */
223 data->status = I_RpcSendReceive((RPC_MESSAGE *)data->msg);
225 TRACE("completed with status 0x%lx\n", data->status);
227 return 0;
230 static inline HRESULT ClientRpcChannelBuffer_IsCorrectApartment(ClientRpcChannelBuffer *This, APARTMENT *apt)
232 OXID oxid;
233 if (!apt)
234 return S_FALSE;
235 if (apartment_getoxid(apt, &oxid) != S_OK)
236 return S_FALSE;
237 if (This->oxid != oxid)
238 return S_FALSE;
239 return S_OK;
242 static HRESULT WINAPI ClientRpcChannelBuffer_SendReceive(LPRPCCHANNELBUFFER iface, RPCOLEMESSAGE *olemsg, ULONG *pstatus)
244 ClientRpcChannelBuffer *This = (ClientRpcChannelBuffer *)iface;
245 HRESULT hr;
246 RPC_MESSAGE *msg = (RPC_MESSAGE *)olemsg;
247 RPC_STATUS status;
248 DWORD index;
249 struct dispatch_params *params;
250 DWORD tid;
251 APARTMENT *apt = NULL;
252 IPID ipid;
254 TRACE("(%p) iMethod=%ld\n", olemsg, olemsg->iMethod);
256 hr = ClientRpcChannelBuffer_IsCorrectApartment(This, COM_CurrentApt());
257 if (hr != S_OK)
259 ERR("called from wrong apartment, should have been 0x%s\n",
260 wine_dbgstr_longlong(This->oxid));
261 return RPC_E_WRONG_THREAD;
264 params = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*params));
265 if (!params) return E_OUTOFMEMORY;
267 params->msg = olemsg;
268 params->status = RPC_S_OK;
269 params->hr = S_OK;
271 /* Note: this is an optimization in the Microsoft OLE runtime that we need
272 * to copy, as shown by the test_no_couninitialize_client test. without
273 * short-circuiting the RPC runtime in the case below, the test will
274 * deadlock on the loader lock due to the RPC runtime needing to create
275 * a thread to process the RPC when this function is called indirectly
276 * from DllMain */
278 RpcBindingInqObject(msg->Handle, &ipid);
279 hr = ipid_get_dispatch_params(&ipid, &apt, &params->stub, &params->chan);
280 if ((hr == S_OK) && (apt->model & COINIT_APARTMENTTHREADED))
282 params->handle = CreateEventW(NULL, FALSE, FALSE, NULL);
284 TRACE("Calling apartment thread 0x%08lx...\n", apt->tid);
286 if (!PostMessageW(apartment_getwindow(apt), DM_EXECUTERPC, 0, (LPARAM)params))
288 ERR("PostMessage failed with error %ld\n", GetLastError());
289 hr = HRESULT_FROM_WIN32(GetLastError());
292 else
294 if (hr == S_OK)
296 /* otherwise, we go via RPC runtime so the stub and channel aren't
297 * needed here */
298 IRpcStubBuffer_Release(params->stub);
299 params->stub = NULL;
300 IRpcChannelBuffer_Release(params->chan);
301 params->chan = NULL;
304 /* we use a separate thread here because we need to be able to
305 * pump the message loop in the application thread: if we do not,
306 * any windows created by this thread will hang and RPCs that try
307 * and re-enter this STA from an incoming server thread will
308 * deadlock. InstallShield is an example of that.
310 params->handle = CreateThread(NULL, 0, rpc_sendreceive_thread, params, 0, &tid);
311 if (!params->handle)
313 ERR("Could not create RpcSendReceive thread, error %lx\n", GetLastError());
314 hr = E_UNEXPECTED;
316 else
317 hr = S_OK;
319 if (apt) apartment_release(apt);
321 if (hr == S_OK)
323 if (WaitForSingleObject(params->handle, 0))
324 hr = CoWaitForMultipleHandles(0, INFINITE, 1, &params->handle, &index);
326 CloseHandle(params->handle);
328 if (hr == S_OK) hr = params->hr;
330 status = params->status;
331 HeapFree(GetProcessHeap(), 0, params);
332 params = NULL;
334 if (hr) return hr;
336 if (pstatus) *pstatus = status;
338 TRACE("RPC call status: 0x%lx\n", status);
339 if (status == RPC_S_OK)
340 hr = S_OK;
341 else if (status == RPC_S_CALL_FAILED)
342 hr = *(HRESULT *)olemsg->Buffer;
343 else
344 hr = HRESULT_FROM_WIN32(status);
346 TRACE("-- 0x%08lx\n", hr);
348 return hr;
351 static HRESULT WINAPI ServerRpcChannelBuffer_FreeBuffer(LPRPCCHANNELBUFFER iface, RPCOLEMESSAGE* olemsg)
353 RPC_MESSAGE *msg = (RPC_MESSAGE *)olemsg;
354 RPC_STATUS status;
356 TRACE("(%p)\n", msg);
358 status = I_RpcFreeBuffer(msg);
360 TRACE("-- %ld\n", status);
362 return HRESULT_FROM_WIN32(status);
365 static HRESULT WINAPI ClientRpcChannelBuffer_FreeBuffer(LPRPCCHANNELBUFFER iface, RPCOLEMESSAGE* olemsg)
367 RPC_MESSAGE *msg = (RPC_MESSAGE *)olemsg;
368 RPC_STATUS status;
370 TRACE("(%p)\n", msg);
372 status = I_RpcFreeBuffer(msg);
374 HeapFree(GetProcessHeap(), 0, msg->RpcInterfaceInformation);
375 msg->RpcInterfaceInformation = NULL;
377 TRACE("-- %ld\n", status);
379 return HRESULT_FROM_WIN32(status);
382 static HRESULT WINAPI RpcChannelBuffer_GetDestCtx(LPRPCCHANNELBUFFER iface, DWORD* pdwDestContext, void** ppvDestContext)
384 FIXME("(%p,%p), stub!\n", pdwDestContext, ppvDestContext);
385 return E_FAIL;
388 static HRESULT WINAPI RpcChannelBuffer_IsConnected(LPRPCCHANNELBUFFER iface)
390 TRACE("()\n");
391 /* native does nothing too */
392 return S_OK;
395 static const IRpcChannelBufferVtbl ClientRpcChannelBufferVtbl =
397 RpcChannelBuffer_QueryInterface,
398 RpcChannelBuffer_AddRef,
399 ClientRpcChannelBuffer_Release,
400 ClientRpcChannelBuffer_GetBuffer,
401 ClientRpcChannelBuffer_SendReceive,
402 ClientRpcChannelBuffer_FreeBuffer,
403 RpcChannelBuffer_GetDestCtx,
404 RpcChannelBuffer_IsConnected
407 static const IRpcChannelBufferVtbl ServerRpcChannelBufferVtbl =
409 RpcChannelBuffer_QueryInterface,
410 RpcChannelBuffer_AddRef,
411 ServerRpcChannelBuffer_Release,
412 ServerRpcChannelBuffer_GetBuffer,
413 ServerRpcChannelBuffer_SendReceive,
414 ServerRpcChannelBuffer_FreeBuffer,
415 RpcChannelBuffer_GetDestCtx,
416 RpcChannelBuffer_IsConnected
419 /* returns a channel buffer for proxies */
420 HRESULT RPC_CreateClientChannel(const OXID *oxid, const IPID *ipid, IRpcChannelBuffer **chan)
422 ClientRpcChannelBuffer *This;
423 WCHAR endpoint[200];
424 RPC_BINDING_HANDLE bind;
425 RPC_STATUS status;
426 LPWSTR string_binding;
428 /* connect to the apartment listener thread */
429 get_rpc_endpoint(endpoint, oxid);
431 TRACE("proxy pipe: connecting to endpoint: %s\n", debugstr_w(endpoint));
433 status = RpcStringBindingComposeW(
434 NULL,
435 wszPipeTransport,
436 NULL,
437 endpoint,
438 NULL,
439 &string_binding);
441 if (status == RPC_S_OK)
443 status = RpcBindingFromStringBindingW(string_binding, &bind);
445 if (status == RPC_S_OK)
447 IPID ipid2 = *ipid; /* why can't RpcBindingSetObject take a const? */
448 status = RpcBindingSetObject(bind, &ipid2);
449 if (status != RPC_S_OK)
450 RpcBindingFree(&bind);
453 RpcStringFreeW(&string_binding);
456 if (status != RPC_S_OK)
458 ERR("Couldn't get binding for endpoint %s, status = %ld\n", debugstr_w(endpoint), status);
459 return HRESULT_FROM_WIN32(status);
462 This = HeapAlloc(GetProcessHeap(), 0, sizeof(*This));
463 if (!This)
465 RpcBindingFree(&bind);
466 return E_OUTOFMEMORY;
469 This->super.lpVtbl = &ClientRpcChannelBufferVtbl;
470 This->super.refs = 1;
471 This->bind = bind;
472 apartment_getoxid(COM_CurrentApt(), &This->oxid);
474 *chan = (IRpcChannelBuffer*)This;
476 return S_OK;
479 HRESULT RPC_CreateServerChannel(IRpcChannelBuffer **chan)
481 RpcChannelBuffer *This = HeapAlloc(GetProcessHeap(), 0, sizeof(*This));
482 if (!This)
483 return E_OUTOFMEMORY;
485 This->lpVtbl = &ServerRpcChannelBufferVtbl;
486 This->refs = 1;
488 *chan = (IRpcChannelBuffer*)This;
490 return S_OK;
494 void RPC_ExecuteCall(struct dispatch_params *params)
496 __TRY
498 params->hr = IRpcStubBuffer_Invoke(params->stub, params->msg, params->chan);
500 __EXCEPT(ole_filter)
502 params->hr = GetExceptionCode();
504 __ENDTRY
505 IRpcStubBuffer_Release(params->stub);
506 IRpcChannelBuffer_Release(params->chan);
507 if (params->handle) SetEvent(params->handle);
510 static void __RPC_STUB dispatch_rpc(RPC_MESSAGE *msg)
512 struct dispatch_params *params;
513 APARTMENT *apt;
514 IPID ipid;
515 HRESULT hr;
517 RpcBindingInqObject(msg->Handle, &ipid);
519 TRACE("ipid = %s, iMethod = %d\n", debugstr_guid(&ipid), msg->ProcNum);
521 params = HeapAlloc(GetProcessHeap(), 0, sizeof(*params));
522 if (!params) return RpcRaiseException(E_OUTOFMEMORY);
524 hr = ipid_get_dispatch_params(&ipid, &apt, &params->stub, &params->chan);
525 if (hr != S_OK)
527 ERR("no apartment found for ipid %s\n", debugstr_guid(&ipid));
528 return RpcRaiseException(hr);
531 params->msg = (RPCOLEMESSAGE *)msg;
532 params->status = RPC_S_OK;
533 params->hr = S_OK;
534 params->handle = NULL;
536 /* Note: this is the important difference between STAs and MTAs - we
537 * always execute RPCs to STAs in the thread that originally created the
538 * apartment (i.e. the one that pumps messages to the window) */
539 if (apt->model & COINIT_APARTMENTTHREADED)
541 params->handle = CreateEventW(NULL, FALSE, FALSE, NULL);
543 TRACE("Calling apartment thread 0x%08lx...\n", apt->tid);
545 if (PostMessageW(apartment_getwindow(apt), DM_EXECUTERPC, 0, (LPARAM)params))
546 WaitForSingleObject(params->handle, INFINITE);
547 else
549 ERR("PostMessage failed with error %ld\n", GetLastError());
550 IRpcChannelBuffer_Release(params->chan);
551 IRpcStubBuffer_Release(params->stub);
553 CloseHandle(params->handle);
555 else
557 BOOL joined = FALSE;
558 if (!COM_CurrentInfo()->apt)
560 apartment_joinmta();
561 joined = TRUE;
563 RPC_ExecuteCall(params);
564 if (joined)
566 apartment_release(COM_CurrentInfo()->apt);
567 COM_CurrentInfo()->apt = NULL;
571 HeapFree(GetProcessHeap(), 0, params);
573 apartment_release(apt);
576 /* stub registration */
577 HRESULT RPC_RegisterInterface(REFIID riid)
579 struct registered_if *rif;
580 BOOL found = FALSE;
581 HRESULT hr = S_OK;
583 TRACE("(%s)\n", debugstr_guid(riid));
585 EnterCriticalSection(&csRegIf);
586 LIST_FOR_EACH_ENTRY(rif, &registered_interfaces, struct registered_if, entry)
588 if (IsEqualGUID(&rif->If.InterfaceId.SyntaxGUID, riid))
590 rif->refs++;
591 found = TRUE;
592 break;
595 if (!found)
597 TRACE("Creating new interface\n");
599 rif = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*rif));
600 if (rif)
602 RPC_STATUS status;
604 rif->refs = 1;
605 rif->If.Length = sizeof(RPC_SERVER_INTERFACE);
606 /* RPC interface ID = COM interface ID */
607 rif->If.InterfaceId.SyntaxGUID = *riid;
608 rif->If.DispatchTable = &rpc_dispatch;
609 /* all other fields are 0, including the version asCOM objects
610 * always have a version of 0.0 */
611 status = RpcServerRegisterIfEx(
612 (RPC_IF_HANDLE)&rif->If,
613 NULL, NULL,
614 RPC_IF_OLE | RPC_IF_AUTOLISTEN,
615 RPC_C_LISTEN_MAX_CALLS_DEFAULT,
616 NULL);
617 if (status == RPC_S_OK)
618 list_add_tail(&registered_interfaces, &rif->entry);
619 else
621 ERR("RpcServerRegisterIfEx failed with error %ld\n", status);
622 HeapFree(GetProcessHeap(), 0, rif);
623 hr = HRESULT_FROM_WIN32(status);
626 else
627 hr = E_OUTOFMEMORY;
629 LeaveCriticalSection(&csRegIf);
630 return hr;
633 /* stub unregistration */
634 void RPC_UnregisterInterface(REFIID riid)
636 struct registered_if *rif;
637 EnterCriticalSection(&csRegIf);
638 LIST_FOR_EACH_ENTRY(rif, &registered_interfaces, struct registered_if, entry)
640 if (IsEqualGUID(&rif->If.InterfaceId.SyntaxGUID, riid))
642 if (!--rif->refs)
644 #if 0 /* this is a stub in builtin and spams the console with FIXME's */
645 IID iid = *riid; /* RpcServerUnregisterIf doesn't take const IID */
646 RpcServerUnregisterIf((RPC_IF_HANDLE)&rif->If, &iid, 0);
647 list_remove(&rif->entry);
648 HeapFree(GetProcessHeap(), 0, rif);
649 #endif
651 break;
654 LeaveCriticalSection(&csRegIf);
657 /* make the apartment reachable by other threads and processes and create the
658 * IRemUnknown object */
659 void RPC_StartRemoting(struct apartment *apt)
661 if (!InterlockedExchange(&apt->remoting_started, TRUE))
663 WCHAR endpoint[200];
664 RPC_STATUS status;
666 get_rpc_endpoint(endpoint, &apt->oxid);
668 status = RpcServerUseProtseqEpW(
669 wszPipeTransport,
670 RPC_C_PROTSEQ_MAX_REQS_DEFAULT,
671 endpoint,
672 NULL);
673 if (status != RPC_S_OK)
674 ERR("Couldn't register endpoint %s\n", debugstr_w(endpoint));
676 /* FIXME: move remote unknown exporting into this function */
678 start_apartment_remote_unknown();
682 static HRESULT create_server(REFCLSID rclsid)
684 static const WCHAR wszLocalServer32[] = { 'L','o','c','a','l','S','e','r','v','e','r','3','2',0 };
685 static const WCHAR embedding[] = { ' ', '-','E','m','b','e','d','d','i','n','g',0 };
686 HKEY key;
687 HRESULT hres;
688 WCHAR command[MAX_PATH+sizeof(embedding)/sizeof(WCHAR)];
689 DWORD size = (MAX_PATH+1) * sizeof(WCHAR);
690 STARTUPINFOW sinfo;
691 PROCESS_INFORMATION pinfo;
693 hres = COM_OpenKeyForCLSID(rclsid, wszLocalServer32, KEY_READ, &key);
694 if (FAILED(hres)) {
695 ERR("class %s not registered\n", debugstr_guid(rclsid));
696 return hres;
699 hres = RegQueryValueExW(key, NULL, NULL, NULL, (LPBYTE)command, &size);
700 RegCloseKey(key);
701 if (hres) {
702 WARN("No default value for LocalServer32 key\n");
703 return REGDB_E_CLASSNOTREG; /* FIXME: check retval */
706 memset(&sinfo,0,sizeof(sinfo));
707 sinfo.cb = sizeof(sinfo);
709 /* EXE servers are started with the -Embedding switch. */
711 strcatW(command, embedding);
713 TRACE("activating local server %s for %s\n", debugstr_w(command), debugstr_guid(rclsid));
715 /* FIXME: Win2003 supports a ServerExecutable value that is passed into
716 * CreateProcess */
717 if (!CreateProcessW(NULL, command, NULL, NULL, FALSE, 0, NULL, NULL, &sinfo, &pinfo)) {
718 WARN("failed to run local server %s\n", debugstr_w(command));
719 return HRESULT_FROM_WIN32(GetLastError());
721 CloseHandle(pinfo.hProcess);
722 CloseHandle(pinfo.hThread);
724 return S_OK;
728 * start_local_service() - start a service given its name and parameters
730 static DWORD start_local_service(LPCWSTR name, DWORD num, LPCWSTR *params)
732 SC_HANDLE handle, hsvc;
733 DWORD r = ERROR_FUNCTION_FAILED;
735 TRACE("Starting service %s %ld params\n", debugstr_w(name), num);
737 handle = OpenSCManagerW(NULL, NULL, SC_MANAGER_CONNECT);
738 if (!handle)
739 return r;
740 hsvc = OpenServiceW(handle, name, SERVICE_START);
741 if (hsvc)
743 if(StartServiceW(hsvc, num, params))
744 r = ERROR_SUCCESS;
745 else
746 r = GetLastError();
747 if (r == ERROR_SERVICE_ALREADY_RUNNING)
748 r = ERROR_SUCCESS;
749 CloseServiceHandle(hsvc);
751 else
752 r = GetLastError();
753 CloseServiceHandle(handle);
755 TRACE("StartService returned error %ld (%s)\n", r, (r == ERROR_SUCCESS) ? "ok":"failed");
757 return r;
761 * create_local_service() - start a COM server in a service
763 * To start a Local Service, we read the AppID value under
764 * the class's CLSID key, then open the HKCR\\AppId key specified
765 * there and check for a LocalService value.
767 * Note: Local Services are not supported under Windows 9x
769 static HRESULT create_local_service(REFCLSID rclsid)
771 HRESULT hres;
772 WCHAR buf[CHARS_IN_GUID], keyname[50];
773 static const WCHAR szAppId[] = { 'A','p','p','I','d',0 };
774 static const WCHAR szAppIdKey[] = { 'A','p','p','I','d','\\',0 };
775 static const WCHAR szLocalService[] = { 'L','o','c','a','l','S','e','r','v','i','c','e',0 };
776 static const WCHAR szServiceParams[] = {'S','e','r','v','i','c','e','P','a','r','a','m','s',0};
777 HKEY hkey;
778 LONG r;
779 DWORD type, sz;
781 TRACE("Attempting to start Local service for %s\n", debugstr_guid(rclsid));
783 /* read the AppID value under the class's key */
784 hres = COM_OpenKeyForCLSID(rclsid, szAppId, KEY_READ, &hkey);
785 if (FAILED(hres))
786 return hres;
787 sz = sizeof buf;
788 r = RegQueryValueExW(hkey, NULL, NULL, &type, (LPBYTE)buf, &sz);
789 RegCloseKey(hkey);
790 if (r!=ERROR_SUCCESS || type!=REG_SZ)
791 return hres;
793 /* read the LocalService and ServiceParameters values from the AppID key */
794 strcpyW(keyname, szAppIdKey);
795 strcatW(keyname, buf);
796 r = RegOpenKeyExW(HKEY_CLASSES_ROOT, keyname, 0, KEY_READ, &hkey);
797 if (r!=ERROR_SUCCESS)
798 return hres;
799 sz = sizeof buf;
800 r = RegQueryValueExW(hkey, szLocalService, NULL, &type, (LPBYTE)buf, &sz);
801 if (r==ERROR_SUCCESS && type==REG_SZ)
803 DWORD num_args = 0;
804 LPWSTR args[1] = { NULL };
807 * FIXME: I'm not really sure how to deal with the service parameters.
808 * I suspect that the string returned from RegQueryValueExW
809 * should be split into a number of arguments by spaces.
810 * It would make more sense if ServiceParams contained a
811 * REG_MULTI_SZ here, but it's a REG_SZ for the services
812 * that I'm interested in for the moment.
814 r = RegQueryValueExW(hkey, szServiceParams, NULL, &type, NULL, &sz);
815 if (r == ERROR_SUCCESS && type == REG_SZ && sz)
817 args[0] = HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY,sz);
818 num_args++;
819 RegQueryValueExW(hkey, szServiceParams, NULL, &type, (LPBYTE)args[0], &sz);
821 r = start_local_service(buf, num_args, (LPCWSTR *)args);
822 if (r==ERROR_SUCCESS)
823 hres = S_OK;
824 HeapFree(GetProcessHeap(),0,args[0]);
826 RegCloseKey(hkey);
828 return hres;
832 static void get_localserver_pipe_name(WCHAR *pipefn, REFCLSID rclsid)
834 static const WCHAR wszPipeRef[] = {'\\','\\','.','\\','p','i','p','e','\\',0};
835 strcpyW(pipefn, wszPipeRef);
836 StringFromGUID2(rclsid, pipefn + sizeof(wszPipeRef)/sizeof(wszPipeRef[0]) - 1, CHARS_IN_GUID);
839 /* FIXME: should call to rpcss instead */
840 HRESULT RPC_GetLocalClassObject(REFCLSID rclsid, REFIID iid, LPVOID *ppv)
842 HRESULT hres;
843 HANDLE hPipe;
844 WCHAR pipefn[100];
845 DWORD res, bufferlen;
846 char marshalbuffer[200];
847 IStream *pStm;
848 LARGE_INTEGER seekto;
849 ULARGE_INTEGER newpos;
850 int tries = 0;
852 static const int MAXTRIES = 30; /* 30 seconds */
854 TRACE("rclsid=%s, iid=%s\n", debugstr_guid(rclsid), debugstr_guid(iid));
856 get_localserver_pipe_name(pipefn, rclsid);
858 while (tries++ < MAXTRIES) {
859 TRACE("waiting for %s\n", debugstr_w(pipefn));
861 WaitNamedPipeW( pipefn, NMPWAIT_WAIT_FOREVER );
862 hPipe = CreateFileW(pipefn, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, 0);
863 if (hPipe == INVALID_HANDLE_VALUE) {
864 if (tries == 1) {
865 if ( (hres = create_local_service(rclsid)) &&
866 (hres = create_server(rclsid)) )
867 return hres;
868 Sleep(1000);
869 } else {
870 WARN("Connecting to %s, no response yet, retrying: le is %lx\n", debugstr_w(pipefn), GetLastError());
871 Sleep(1000);
873 continue;
875 bufferlen = 0;
876 if (!ReadFile(hPipe,marshalbuffer,sizeof(marshalbuffer),&bufferlen,NULL)) {
877 FIXME("Failed to read marshal id from classfactory of %s.\n",debugstr_guid(rclsid));
878 Sleep(1000);
879 continue;
881 TRACE("read marshal id from pipe\n");
882 CloseHandle(hPipe);
883 break;
886 if (tries >= MAXTRIES)
887 return E_NOINTERFACE;
889 hres = CreateStreamOnHGlobal(0,TRUE,&pStm);
890 if (hres) return hres;
891 hres = IStream_Write(pStm,marshalbuffer,bufferlen,&res);
892 if (hres) goto out;
893 seekto.u.LowPart = 0;seekto.u.HighPart = 0;
894 hres = IStream_Seek(pStm,seekto,SEEK_SET,&newpos);
896 TRACE("unmarshalling classfactory\n");
897 hres = CoUnmarshalInterface(pStm,&IID_IClassFactory,ppv);
898 out:
899 IStream_Release(pStm);
900 return hres;
904 struct local_server_params
906 CLSID clsid;
907 IStream *stream;
910 /* FIXME: should call to rpcss instead */
911 static DWORD WINAPI local_server_thread(LPVOID param)
913 struct local_server_params * lsp = (struct local_server_params *)param;
914 HANDLE hPipe;
915 WCHAR pipefn[100];
916 HRESULT hres;
917 IStream *pStm = lsp->stream;
918 STATSTG ststg;
919 unsigned char *buffer;
920 int buflen;
921 LARGE_INTEGER seekto;
922 ULARGE_INTEGER newpos;
923 ULONG res;
925 TRACE("Starting threader for %s.\n",debugstr_guid(&lsp->clsid));
927 get_localserver_pipe_name(pipefn, &lsp->clsid);
929 HeapFree(GetProcessHeap(), 0, lsp);
931 hPipe = CreateNamedPipeW( pipefn, PIPE_ACCESS_DUPLEX,
932 PIPE_TYPE_BYTE|PIPE_WAIT, PIPE_UNLIMITED_INSTANCES,
933 4096, 4096, 500 /* 0.5 second timeout */, NULL );
935 if (hPipe == INVALID_HANDLE_VALUE)
937 FIXME("pipe creation failed for %s, le is %ld\n", debugstr_w(pipefn), GetLastError());
938 return 1;
941 while (1) {
942 if (!ConnectNamedPipe(hPipe,NULL)) {
943 ERR("Failure during ConnectNamedPipe %ld, ABORT!\n",GetLastError());
944 break;
947 TRACE("marshalling IClassFactory to client\n");
949 hres = IStream_Stat(pStm,&ststg,0);
950 if (hres) return hres;
952 buflen = ststg.cbSize.u.LowPart;
953 buffer = HeapAlloc(GetProcessHeap(),0,buflen);
954 seekto.u.LowPart = 0;
955 seekto.u.HighPart = 0;
956 hres = IStream_Seek(pStm,seekto,SEEK_SET,&newpos);
957 if (hres) {
958 FIXME("IStream_Seek failed, %lx\n",hres);
959 return hres;
962 hres = IStream_Read(pStm,buffer,buflen,&res);
963 if (hres) {
964 FIXME("Stream Read failed, %lx\n",hres);
965 return hres;
968 WriteFile(hPipe,buffer,buflen,&res,NULL);
969 FlushFileBuffers(hPipe);
970 DisconnectNamedPipe(hPipe);
972 TRACE("done marshalling IClassFactory\n");
974 CloseHandle(hPipe);
975 IStream_Release(pStm);
976 return 0;
979 void RPC_StartLocalServer(REFCLSID clsid, IStream *stream)
981 DWORD tid;
982 HANDLE thread;
983 struct local_server_params *lsp = HeapAlloc(GetProcessHeap(), 0, sizeof(*lsp));
985 lsp->clsid = *clsid;
986 lsp->stream = stream;
988 thread = CreateThread(NULL, 0, local_server_thread, lsp, 0, &tid);
989 CloseHandle(thread);
990 /* FIXME: failure handling */