Fixed some traces to use the right printf format and avoid typecasts.
[wine] / dlls / ole32 / rpc.c
1 /*
2  *      RPC Manager
3  *
4  * Copyright 2001  Ove Kåven, TransGaming Technologies
5  * Copyright 2002  Marcus Meissner
6  * Copyright 2005  Mike Hearn, Rob Shearman for CodeWeavers
7  *
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.
12  *
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.
17  *
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
21  */
22
23 #include "config.h"
24
25 #include <stdlib.h>
26 #include <stdarg.h>
27 #include <stdio.h>
28 #include <string.h>
29 #include <assert.h>
30
31 #define COBJMACROS
32 #define NONAMELESSUNION
33 #define NONAMELESSSTRUCT
34
35 #include "windef.h"
36 #include "winbase.h"
37 #include "winuser.h"
38 #include "winsvc.h"
39 #include "objbase.h"
40 #include "ole2.h"
41 #include "rpc.h"
42 #include "winerror.h"
43 #include "winreg.h"
44 #include "wtypes.h"
45 #include "wine/unicode.h"
46
47 #include "compobj_private.h"
48
49 #include "wine/debug.h"
50
51 WINE_DEFAULT_DEBUG_CHANNEL(ole);
52
53 static void __RPC_STUB dispatch_rpc(RPC_MESSAGE *msg);
54
55 /* we only use one function to dispatch calls for all methods - we use the
56  * RPC_IF_OLE flag to tell the RPC runtime that this is the case */
57 static RPC_DISPATCH_FUNCTION rpc_dispatch_table[1] = { dispatch_rpc }; /* (RO) */
58 static RPC_DISPATCH_TABLE rpc_dispatch = { 1, rpc_dispatch_table }; /* (RO) */
59
60 static struct list registered_interfaces = LIST_INIT(registered_interfaces); /* (CS csRegIf) */
61 static CRITICAL_SECTION csRegIf;
62 static CRITICAL_SECTION_DEBUG csRegIf_debug =
63 {
64     0, 0, &csRegIf,
65     { &csRegIf_debug.ProcessLocksList, &csRegIf_debug.ProcessLocksList },
66       0, 0, { (DWORD_PTR)(__FILE__ ": dcom registered server interfaces") }
67 };
68 static CRITICAL_SECTION csRegIf = { &csRegIf_debug, -1, 0, 0, 0, 0 };
69
70 static WCHAR wszPipeTransport[] = {'n','c','a','c','n','_','n','p',0};
71
72
73 struct registered_if
74 {
75     struct list entry;
76     DWORD refs; /* ref count */
77     RPC_SERVER_INTERFACE If; /* interface registered with the RPC runtime */
78 };
79
80 /* get the pipe endpoint specified of the specified apartment */
81 static inline void get_rpc_endpoint(LPWSTR endpoint, const OXID *oxid)
82 {
83     /* FIXME: should get endpoint from rpcss */
84     static const WCHAR wszEndpointFormat[] = {'\\','p','i','p','e','\\','O','L','E','_','%','0','8','l','x','%','0','8','l','x',0};
85     wsprintfW(endpoint, wszEndpointFormat, (DWORD)(*oxid >> 32),(DWORD)*oxid);
86 }
87
88 typedef struct
89 {
90     const IRpcChannelBufferVtbl *lpVtbl;
91     LONG                  refs;
92 } RpcChannelBuffer;
93
94 typedef struct
95 {
96     RpcChannelBuffer       super; /* superclass */
97
98     RPC_BINDING_HANDLE     bind; /* handle to the remote server */
99 } ClientRpcChannelBuffer;
100
101 struct dispatch_params
102 {
103     RPCOLEMESSAGE     *msg; /* message */
104     IRpcStubBuffer    *stub; /* stub buffer, if applicable */
105     IRpcChannelBuffer *chan; /* server channel buffer, if applicable */
106     HANDLE             handle; /* handle that will become signaled when call finishes */
107     RPC_STATUS         status; /* status (out) */
108 };
109
110 static HRESULT WINAPI RpcChannelBuffer_QueryInterface(LPRPCCHANNELBUFFER iface, REFIID riid, LPVOID *ppv)
111 {
112     *ppv = NULL;
113     if (IsEqualIID(riid,&IID_IRpcChannelBuffer) || IsEqualIID(riid,&IID_IUnknown))
114     {
115         *ppv = (LPVOID)iface;
116         IUnknown_AddRef(iface);
117         return S_OK;
118     }
119     return E_NOINTERFACE;
120 }
121
122 static ULONG WINAPI RpcChannelBuffer_AddRef(LPRPCCHANNELBUFFER iface)
123 {
124     RpcChannelBuffer *This = (RpcChannelBuffer *)iface;
125     return InterlockedIncrement(&This->refs);
126 }
127
128 static ULONG WINAPI ServerRpcChannelBuffer_Release(LPRPCCHANNELBUFFER iface)
129 {
130     RpcChannelBuffer *This = (RpcChannelBuffer *)iface;
131     ULONG ref;
132
133     ref = InterlockedDecrement(&This->refs);
134     if (ref)
135         return ref;
136
137     HeapFree(GetProcessHeap(), 0, This);
138     return 0;
139 }
140
141 static ULONG WINAPI ClientRpcChannelBuffer_Release(LPRPCCHANNELBUFFER iface)
142 {
143     ClientRpcChannelBuffer *This = (ClientRpcChannelBuffer *)iface;
144     ULONG ref;
145
146     ref = InterlockedDecrement(&This->super.refs);
147     if (ref)
148         return ref;
149
150     RpcBindingFree(&This->bind);
151     HeapFree(GetProcessHeap(), 0, This);
152     return 0;
153 }
154
155 static HRESULT WINAPI ServerRpcChannelBuffer_GetBuffer(LPRPCCHANNELBUFFER iface, RPCOLEMESSAGE* olemsg, REFIID riid)
156 {
157     RpcChannelBuffer *This = (RpcChannelBuffer *)iface;
158     RPC_MESSAGE *msg = (RPC_MESSAGE *)olemsg;
159     RPC_STATUS status;
160
161     TRACE("(%p)->(%p,%s)\n", This, olemsg, debugstr_guid(riid));
162
163     status = I_RpcGetBuffer(msg);
164
165     TRACE("-- %ld\n", status);
166
167     return HRESULT_FROM_WIN32(status);
168 }
169
170 static HRESULT WINAPI ClientRpcChannelBuffer_GetBuffer(LPRPCCHANNELBUFFER iface, RPCOLEMESSAGE* olemsg, REFIID riid)
171 {
172     ClientRpcChannelBuffer *This = (ClientRpcChannelBuffer *)iface;
173     RPC_MESSAGE *msg = (RPC_MESSAGE *)olemsg;
174     RPC_CLIENT_INTERFACE *cif;
175     RPC_STATUS status;
176
177     TRACE("(%p)->(%p,%s)\n", This, olemsg, debugstr_guid(riid));
178
179     cif = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(RPC_CLIENT_INTERFACE));
180     if (!cif)
181         return E_OUTOFMEMORY;
182
183     cif->Length = sizeof(RPC_CLIENT_INTERFACE);
184     /* RPC interface ID = COM interface ID */
185     cif->InterfaceId.SyntaxGUID = *riid;
186     /* COM objects always have a version of 0.0 */
187     cif->InterfaceId.SyntaxVersion.MajorVersion = 0;
188     cif->InterfaceId.SyntaxVersion.MinorVersion = 0;
189     msg->RpcInterfaceInformation = cif;
190     msg->Handle = This->bind;
191     
192     status = I_RpcGetBuffer(msg);
193
194     TRACE("-- %ld\n", status);
195
196     return HRESULT_FROM_WIN32(status);
197 }
198
199 /* this thread runs an outgoing RPC */
200 static DWORD WINAPI rpc_sendreceive_thread(LPVOID param)
201 {
202     struct dispatch_params *data = (struct dispatch_params *) param;
203     
204     /* FIXME: trap and rethrow RPC exceptions in app thread */
205     data->status = I_RpcSendReceive((RPC_MESSAGE *)data->msg);
206
207     TRACE("completed with status 0x%lx\n", data->status);
208     
209     return 0;
210 }
211
212 static HRESULT WINAPI RpcChannelBuffer_SendReceive(LPRPCCHANNELBUFFER iface, RPCOLEMESSAGE *olemsg, ULONG *pstatus)
213 {
214     HRESULT hr = S_OK;
215     RPC_MESSAGE *msg = (RPC_MESSAGE *)olemsg;
216     RPC_STATUS status;
217     DWORD index;
218     struct dispatch_params *params;
219     DWORD tid;
220     IRpcStubBuffer *stub;
221     APARTMENT *apt;
222     IPID ipid;
223
224     TRACE("(%p) iMethod=%ld\n", olemsg, olemsg->iMethod);
225
226     params = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*params));
227     if (!params) return E_OUTOFMEMORY;
228     
229     params->msg = olemsg;
230     params->status = RPC_S_OK;
231
232     /* Note: this is an optimization in the Microsoft OLE runtime that we need
233      * to copy, as shown by the test_no_couninitialize_client test. without
234      * short-circuiting the RPC runtime in the case below, the test will
235      * deadlock on the loader lock due to the RPC runtime needing to create
236      * a thread to process the RPC when this function is called indirectly
237      * from DllMain */
238
239     RpcBindingInqObject(msg->Handle, &ipid);
240     stub = ipid_to_apt_and_stubbuffer(&ipid, &apt);
241     if (apt && (apt->model & COINIT_APARTMENTTHREADED))
242     {
243         params->stub = stub;
244         params->chan = NULL; /* FIXME: pass server channel */
245         params->handle = CreateEventW(NULL, FALSE, FALSE, NULL);
246
247         TRACE("Calling apartment thread 0x%08lx...\n", apt->tid);
248
249         PostMessageW(apt->win, DM_EXECUTERPC, 0, (LPARAM)params);
250     }
251     else
252     {
253         if (stub) IRpcStubBuffer_Release(stub);
254
255         /* we use a separate thread here because we need to be able to
256          * pump the message loop in the application thread: if we do not,
257          * any windows created by this thread will hang and RPCs that try
258          * and re-enter this STA from an incoming server thread will
259          * deadlock. InstallShield is an example of that.
260          */
261         params->handle = CreateThread(NULL, 0, rpc_sendreceive_thread, params, 0, &tid);
262         if (!params->handle)
263         {
264             ERR("Could not create RpcSendReceive thread, error %lx\n", GetLastError());
265             hr = E_UNEXPECTED;
266         }
267     }
268     if (apt) apartment_release(apt);
269
270     if (hr == S_OK)
271         hr = CoWaitForMultipleHandles(0, INFINITE, 1, &params->handle, &index);
272     CloseHandle(params->handle);
273
274     status = params->status;
275     HeapFree(GetProcessHeap(), 0, params);
276     params = NULL;
277
278     if (hr) return hr;
279     
280     if (pstatus) *pstatus = status;
281
282     TRACE("RPC call status: 0x%lx\n", status);
283     if (status == RPC_S_OK)
284         hr = S_OK;
285     else if (status == RPC_S_CALL_FAILED)
286         hr = *(HRESULT *)olemsg->Buffer;
287     else
288         hr = HRESULT_FROM_WIN32(status);
289
290     TRACE("-- 0x%08lx\n", hr);
291
292     return hr;
293 }
294
295 static HRESULT WINAPI ServerRpcChannelBuffer_FreeBuffer(LPRPCCHANNELBUFFER iface, RPCOLEMESSAGE* olemsg)
296 {
297     RPC_MESSAGE *msg = (RPC_MESSAGE *)olemsg;
298     RPC_STATUS status;
299
300     TRACE("(%p)\n", msg);
301
302     status = I_RpcFreeBuffer(msg);
303
304     TRACE("-- %ld\n", status);
305
306     return HRESULT_FROM_WIN32(status);
307 }
308
309 static HRESULT WINAPI ClientRpcChannelBuffer_FreeBuffer(LPRPCCHANNELBUFFER iface, RPCOLEMESSAGE* olemsg)
310 {
311     RPC_MESSAGE *msg = (RPC_MESSAGE *)olemsg;
312     RPC_STATUS status;
313
314     TRACE("(%p)\n", msg);
315
316     status = I_RpcFreeBuffer(msg);
317
318     HeapFree(GetProcessHeap(), 0, msg->RpcInterfaceInformation);
319     msg->RpcInterfaceInformation = NULL;
320
321     TRACE("-- %ld\n", status);
322
323     return HRESULT_FROM_WIN32(status);
324 }
325
326 static HRESULT WINAPI RpcChannelBuffer_GetDestCtx(LPRPCCHANNELBUFFER iface, DWORD* pdwDestContext, void** ppvDestContext)
327 {
328     FIXME("(%p,%p), stub!\n", pdwDestContext, ppvDestContext);
329     return E_FAIL;
330 }
331
332 static HRESULT WINAPI RpcChannelBuffer_IsConnected(LPRPCCHANNELBUFFER iface)
333 {
334     TRACE("()\n");
335     /* native does nothing too */
336     return S_OK;
337 }
338
339 static const IRpcChannelBufferVtbl ClientRpcChannelBufferVtbl =
340 {
341     RpcChannelBuffer_QueryInterface,
342     RpcChannelBuffer_AddRef,
343     ClientRpcChannelBuffer_Release,
344     ClientRpcChannelBuffer_GetBuffer,
345     RpcChannelBuffer_SendReceive,
346     ClientRpcChannelBuffer_FreeBuffer,
347     RpcChannelBuffer_GetDestCtx,
348     RpcChannelBuffer_IsConnected
349 };
350
351 static const IRpcChannelBufferVtbl ServerRpcChannelBufferVtbl =
352 {
353     RpcChannelBuffer_QueryInterface,
354     RpcChannelBuffer_AddRef,
355     ServerRpcChannelBuffer_Release,
356     ServerRpcChannelBuffer_GetBuffer,
357     RpcChannelBuffer_SendReceive,
358     ServerRpcChannelBuffer_FreeBuffer,
359     RpcChannelBuffer_GetDestCtx,
360     RpcChannelBuffer_IsConnected
361 };
362
363 /* returns a channel buffer for proxies */
364 HRESULT RPC_CreateClientChannel(const OXID *oxid, const IPID *ipid, IRpcChannelBuffer **chan)
365 {
366     ClientRpcChannelBuffer *This;
367     WCHAR                   endpoint[200];
368     RPC_BINDING_HANDLE      bind;
369     RPC_STATUS              status;
370     LPWSTR                  string_binding;
371
372     /* connect to the apartment listener thread */
373     get_rpc_endpoint(endpoint, oxid);
374
375     TRACE("proxy pipe: connecting to endpoint: %s\n", debugstr_w(endpoint));
376
377     status = RpcStringBindingComposeW(
378         NULL,
379         wszPipeTransport,
380         NULL,
381         endpoint,
382         NULL,
383         &string_binding);
384         
385     if (status == RPC_S_OK)
386     {
387         status = RpcBindingFromStringBindingW(string_binding, &bind);
388
389         if (status == RPC_S_OK)
390         {
391             IPID ipid2 = *ipid; /* why can't RpcBindingSetObject take a const? */
392             status = RpcBindingSetObject(bind, &ipid2);
393             if (status != RPC_S_OK)
394                 RpcBindingFree(&bind);
395         }
396
397         RpcStringFreeW(&string_binding);
398     }
399
400     if (status != RPC_S_OK)
401     {
402         ERR("Couldn't get binding for endpoint %s, status = %ld\n", debugstr_w(endpoint), status);
403         return HRESULT_FROM_WIN32(status);
404     }
405
406     This = HeapAlloc(GetProcessHeap(), 0, sizeof(*This));
407     if (!This)
408     {
409         RpcBindingFree(&bind);
410         return E_OUTOFMEMORY;
411     }
412
413     This->super.lpVtbl = &ClientRpcChannelBufferVtbl;
414     This->super.refs = 1;
415     This->bind = bind;
416
417     *chan = (IRpcChannelBuffer*)This;
418
419     return S_OK;
420 }
421
422 HRESULT RPC_CreateServerChannel(IRpcChannelBuffer **chan)
423 {
424     RpcChannelBuffer *This = HeapAlloc(GetProcessHeap(), 0, sizeof(*This));
425     if (!This)
426         return E_OUTOFMEMORY;
427
428     This->lpVtbl = &ServerRpcChannelBufferVtbl;
429     This->refs = 1;
430     
431     *chan = (IRpcChannelBuffer*)This;
432
433     return S_OK;
434 }
435
436
437 HRESULT RPC_ExecuteCall(struct dispatch_params *params)
438 {
439     HRESULT hr = IRpcStubBuffer_Invoke(params->stub, params->msg, params->chan);
440     IRpcStubBuffer_Release(params->stub);
441     if (params->handle) SetEvent(params->handle);
442     return hr;
443 }
444
445 static void __RPC_STUB dispatch_rpc(RPC_MESSAGE *msg)
446 {
447     struct dispatch_params *params;
448     IRpcStubBuffer     *stub;
449     APARTMENT          *apt;
450     IPID                ipid;
451
452     RpcBindingInqObject(msg->Handle, &ipid);
453
454     TRACE("ipid = %s, iMethod = %d\n", debugstr_guid(&ipid), msg->ProcNum);
455
456     params = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*params));
457     if (!params) return RpcRaiseException(E_OUTOFMEMORY);
458
459     stub = ipid_to_apt_and_stubbuffer(&ipid, &apt);
460     if (!apt || !stub)
461     {
462         if (apt) apartment_release(apt);
463         ERR("no apartment found for ipid %s\n", debugstr_guid(&ipid));
464         return RpcRaiseException(RPC_E_DISCONNECTED);
465     }
466
467     params->msg = (RPCOLEMESSAGE *)msg;
468     params->stub = stub;
469     params->chan = NULL; /* FIXME: pass server channel */
470     params->status = RPC_S_OK;
471
472     /* Note: this is the important difference between STAs and MTAs - we
473      * always execute RPCs to STAs in the thread that originally created the
474      * apartment (i.e. the one that pumps messages to the window) */
475     if (apt->model & COINIT_APARTMENTTHREADED)
476     {
477         params->handle = CreateEventW(NULL, FALSE, FALSE, NULL);
478
479         TRACE("Calling apartment thread 0x%08lx...\n", apt->tid);
480
481         PostMessageW(apt->win, DM_EXECUTERPC, 0, (LPARAM)params);
482         WaitForSingleObject(params->handle, INFINITE);
483         CloseHandle(params->handle);
484     }
485     else
486         RPC_ExecuteCall(params);
487
488     HeapFree(GetProcessHeap(), 0, params);
489
490     apartment_release(apt);
491 }
492
493 /* stub registration */
494 HRESULT RPC_RegisterInterface(REFIID riid)
495 {
496     struct registered_if *rif;
497     BOOL found = FALSE;
498     HRESULT hr = S_OK;
499     
500     TRACE("(%s)\n", debugstr_guid(riid));
501
502     EnterCriticalSection(&csRegIf);
503     LIST_FOR_EACH_ENTRY(rif, &registered_interfaces, struct registered_if, entry)
504     {
505         if (IsEqualGUID(&rif->If.InterfaceId.SyntaxGUID, riid))
506         {
507             rif->refs++;
508             found = TRUE;
509             break;
510         }
511     }
512     if (!found)
513     {
514         TRACE("Creating new interface\n");
515
516         rif = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*rif));
517         if (rif)
518         {
519             RPC_STATUS status;
520
521             rif->refs = 1;
522             rif->If.Length = sizeof(RPC_SERVER_INTERFACE);
523             /* RPC interface ID = COM interface ID */
524             rif->If.InterfaceId.SyntaxGUID = *riid;
525             rif->If.DispatchTable = &rpc_dispatch;
526             /* all other fields are 0, including the version asCOM objects
527              * always have a version of 0.0 */
528             status = RpcServerRegisterIfEx(
529                 (RPC_IF_HANDLE)&rif->If,
530                 NULL, NULL,
531                 RPC_IF_OLE | RPC_IF_AUTOLISTEN,
532                 RPC_C_LISTEN_MAX_CALLS_DEFAULT,
533                 NULL);
534             if (status == RPC_S_OK)
535                 list_add_tail(&registered_interfaces, &rif->entry);
536             else
537             {
538                 ERR("RpcServerRegisterIfEx failed with error %ld\n", status);
539                 HeapFree(GetProcessHeap(), 0, rif);
540                 hr = HRESULT_FROM_WIN32(status);
541             }
542         }
543         else
544             hr = E_OUTOFMEMORY;
545     }
546     LeaveCriticalSection(&csRegIf);
547     return hr;
548 }
549
550 /* stub unregistration */
551 void RPC_UnregisterInterface(REFIID riid)
552 {
553     struct registered_if *rif;
554     EnterCriticalSection(&csRegIf);
555     LIST_FOR_EACH_ENTRY(rif, &registered_interfaces, struct registered_if, entry)
556     {
557         if (IsEqualGUID(&rif->If.InterfaceId.SyntaxGUID, riid))
558         {
559             if (!--rif->refs)
560             {
561 #if 0 /* this is a stub in builtin and spams the console with FIXME's */
562                 IID iid = *riid; /* RpcServerUnregisterIf doesn't take const IID */
563                 RpcServerUnregisterIf((RPC_IF_HANDLE)&rif->If, &iid, 0);
564                 list_remove(&rif->entry);
565                 HeapFree(GetProcessHeap(), 0, rif);
566 #endif
567             }
568             break;
569         }
570     }
571     LeaveCriticalSection(&csRegIf);
572 }
573
574 /* make the apartment reachable by other threads and processes and create the
575  * IRemUnknown object */
576 void RPC_StartRemoting(struct apartment *apt)
577 {
578     if (!InterlockedExchange(&apt->remoting_started, TRUE))
579     {
580         WCHAR endpoint[200];
581         RPC_STATUS status;
582
583         get_rpc_endpoint(endpoint, &apt->oxid);
584     
585         status = RpcServerUseProtseqEpW(
586             wszPipeTransport,
587             RPC_C_PROTSEQ_MAX_REQS_DEFAULT,
588             endpoint,
589             NULL);
590         if (status != RPC_S_OK)
591             ERR("Couldn't register endpoint %s\n", debugstr_w(endpoint));
592
593         /* FIXME: move remote unknown exporting into this function */
594     }
595     start_apartment_remote_unknown();
596 }
597
598
599 static HRESULT create_server(REFCLSID rclsid)
600 {
601     static const WCHAR  wszLocalServer32[] = { 'L','o','c','a','l','S','e','r','v','e','r','3','2',0 };
602     static const WCHAR  embedding[] = { ' ', '-','E','m','b','e','d','d','i','n','g',0 };
603     HKEY                hkeyclsid;
604     HKEY                key;
605     HRESULT             hres = E_UNEXPECTED;
606     WCHAR               exe[MAX_PATH+1];
607     DWORD               exelen = sizeof(exe);
608     WCHAR               command[MAX_PATH+sizeof(embedding)/sizeof(WCHAR)];
609     STARTUPINFOW        sinfo;
610     PROCESS_INFORMATION pinfo;
611
612     hres = HRESULT_FROM_WIN32(COM_OpenKeyForCLSID(rclsid, KEY_READ, &hkeyclsid));
613     if (hres != S_OK) {
614         ERR("class %s not registered\n", debugstr_guid(rclsid));
615         return REGDB_E_READREGDB;
616     }
617
618     hres = RegOpenKeyExW(hkeyclsid, wszLocalServer32, 0, KEY_READ, &key);
619
620     if (hres != ERROR_SUCCESS) {
621         WARN("class %s not registered as LocalServer32\n", debugstr_guid(rclsid));
622         return REGDB_E_READREGDB; /* Probably */
623     }
624
625     memset(exe,0,sizeof(exe));
626     hres= RegQueryValueExW(key, NULL, NULL, NULL, (LPBYTE)exe, &exelen);
627     RegCloseKey(key);
628     if (hres) {
629         WARN("No default value for LocalServer32 key\n");
630         return REGDB_E_CLASSNOTREG; /* FIXME: check retval */
631     }
632
633     memset(&sinfo,0,sizeof(sinfo));
634     sinfo.cb = sizeof(sinfo);
635
636     /* EXE servers are started with the -Embedding switch. MSDN also claims /Embedding is used,
637      * 9x does -Embedding, perhaps an 9x/NT difference?
638      */
639
640     strcpyW(command, exe);
641     strcatW(command, embedding);
642
643     TRACE("activating local server %s for %s\n", debugstr_w(command), debugstr_guid(rclsid));
644
645     if (!CreateProcessW(exe, command, NULL, NULL, FALSE, 0, NULL, NULL, &sinfo, &pinfo)) {
646         WARN("failed to run local server %s\n", debugstr_w(exe));
647         return HRESULT_FROM_WIN32(GetLastError());
648     }
649     CloseHandle(pinfo.hProcess);
650     CloseHandle(pinfo.hThread);
651
652     return S_OK;
653 }
654
655 /*
656  * start_local_service()  - start a service given its name and parameters
657  */
658 static DWORD start_local_service(LPCWSTR name, DWORD num, LPWSTR *params)
659 {
660     SC_HANDLE handle, hsvc;
661     DWORD     r = ERROR_FUNCTION_FAILED;
662
663     TRACE("Starting service %s %ld params\n", debugstr_w(name), num);
664
665     handle = OpenSCManagerW(NULL, NULL, SC_MANAGER_ALL_ACCESS);
666     if (!handle)
667         return r;
668     hsvc = OpenServiceW(handle, name, SC_MANAGER_ALL_ACCESS);
669     if (hsvc)
670     {
671         if(StartServiceW(hsvc, num, (LPCWSTR*)params))
672             r = ERROR_SUCCESS;
673         else
674             r = GetLastError();
675         if (r == ERROR_SERVICE_ALREADY_RUNNING)
676             r = ERROR_SUCCESS;
677         CloseServiceHandle(hsvc);
678     }
679     CloseServiceHandle(handle);
680
681     TRACE("StartService returned error %ld (%s)\n", r, r?"ok":"failed");
682
683     return r;
684 }
685
686 /*
687  * create_local_service()  - start a COM server in a service
688  *
689  *   To start a Local Service, we read the AppID value under
690  * the class's CLSID key, then open the HKCR\\AppId key specified
691  * there and check for a LocalService value.
692  *
693  * Note:  Local Services are not supported under Windows 9x
694  */
695 static HRESULT create_local_service(REFCLSID rclsid)
696 {
697     HRESULT hres = REGDB_E_READREGDB;
698     WCHAR buf[CHARS_IN_GUID], keyname[50];
699     static const WCHAR szAppId[] = { 'A','p','p','I','d',0 };
700     static const WCHAR szAppIdKey[] = { 'A','p','p','I','d','\\',0 };
701     static const WCHAR szLocalService[] = { 'L','o','c','a','l','S','e','r','v','i','c','e',0 };
702     static const WCHAR szServiceParams[] = {'S','e','r','v','i','c','e','P','a','r','a','m','s',0};
703     HKEY hkey;
704     LONG r;
705     DWORD type, sz;
706
707     TRACE("Attempting to start Local service for %s\n", debugstr_guid(rclsid));
708
709     /* read the AppID value under the class's key */
710     r = COM_OpenKeyForCLSID(rclsid, KEY_READ, &hkey);
711     if (r!=ERROR_SUCCESS)
712         return hres;
713     sz = sizeof buf;
714     r = RegQueryValueExW(hkey, szAppId, NULL, &type, (LPBYTE)buf, &sz);
715     RegCloseKey(hkey);
716     if (r!=ERROR_SUCCESS || type!=REG_SZ)
717         return hres;
718
719     /* read the LocalService and ServiceParameters values from the AppID key */
720     strcpyW(keyname, szAppIdKey);
721     strcatW(keyname, buf);
722     r = RegOpenKeyExW(HKEY_CLASSES_ROOT, keyname, 0, KEY_READ, &hkey);
723     if (r!=ERROR_SUCCESS)
724         return hres;
725     sz = sizeof buf;
726     r = RegQueryValueExW(hkey, szLocalService, NULL, &type, (LPBYTE)buf, &sz);
727     if (r==ERROR_SUCCESS && type==REG_SZ)
728     {
729         DWORD num_args = 0;
730         LPWSTR args[1] = { NULL };
731
732         /*
733          * FIXME: I'm not really sure how to deal with the service parameters.
734          *        I suspect that the string returned from RegQueryValueExW
735          *        should be split into a number of arguments by spaces.
736          *        It would make more sense if ServiceParams contained a
737          *        REG_MULTI_SZ here, but it's a REG_SZ for the services
738          *        that I'm interested in for the moment.
739          */
740         r = RegQueryValueExW(hkey, szServiceParams, NULL, &type, NULL, &sz);
741         if (r == ERROR_SUCCESS && type == REG_SZ && sz)
742         {
743             args[0] = HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY,sz);
744             num_args++;
745             RegQueryValueExW(hkey, szServiceParams, NULL, &type, (LPBYTE)args[0], &sz);
746         }
747         r = start_local_service(buf, num_args, args);
748         if (r==ERROR_SUCCESS)
749             hres = S_OK;
750         HeapFree(GetProcessHeap(),0,args[0]);
751     }
752     RegCloseKey(hkey);
753         
754     return hres;
755 }
756
757
758 static void get_localserver_pipe_name(WCHAR *pipefn, REFCLSID rclsid)
759 {
760     static const WCHAR wszPipeRef[] = {'\\','\\','.','\\','p','i','p','e','\\',0};
761     strcpyW(pipefn, wszPipeRef);
762     StringFromGUID2(rclsid, pipefn + sizeof(wszPipeRef)/sizeof(wszPipeRef[0]) - 1, CHARS_IN_GUID);
763 }
764
765 /* FIXME: should call to rpcss instead */
766 HRESULT RPC_GetLocalClassObject(REFCLSID rclsid, REFIID iid, LPVOID *ppv)
767 {
768     HRESULT        hres;
769     HANDLE         hPipe;
770     WCHAR          pipefn[100];
771     DWORD          res, bufferlen;
772     char           marshalbuffer[200];
773     IStream       *pStm;
774     LARGE_INTEGER  seekto;
775     ULARGE_INTEGER newpos;
776     int            tries = 0;
777
778     static const int MAXTRIES = 30; /* 30 seconds */
779
780     TRACE("rclsid=%s, iid=%s\n", debugstr_guid(rclsid), debugstr_guid(iid));
781
782     get_localserver_pipe_name(pipefn, rclsid);
783
784     while (tries++ < MAXTRIES) {
785         TRACE("waiting for %s\n", debugstr_w(pipefn));
786       
787         WaitNamedPipeW( pipefn, NMPWAIT_WAIT_FOREVER );
788         hPipe = CreateFileW(pipefn, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, 0);
789         if (hPipe == INVALID_HANDLE_VALUE) {
790             if (tries == 1) {
791                 if ( (hres = create_server(rclsid)) &&
792                      (hres = create_local_service(rclsid)) )
793                     return hres;
794                 Sleep(1000);
795             } else {
796                 WARN("Connecting to %s, no response yet, retrying: le is %lx\n", debugstr_w(pipefn), GetLastError());
797                 Sleep(1000);
798             }
799             continue;
800         }
801         bufferlen = 0;
802         if (!ReadFile(hPipe,marshalbuffer,sizeof(marshalbuffer),&bufferlen,NULL)) {
803             FIXME("Failed to read marshal id from classfactory of %s.\n",debugstr_guid(rclsid));
804             Sleep(1000);
805             continue;
806         }
807         TRACE("read marshal id from pipe\n");
808         CloseHandle(hPipe);
809         break;
810     }
811     
812     if (tries >= MAXTRIES)
813         return E_NOINTERFACE;
814     
815     hres = CreateStreamOnHGlobal(0,TRUE,&pStm);
816     if (hres) return hres;
817     hres = IStream_Write(pStm,marshalbuffer,bufferlen,&res);
818     if (hres) goto out;
819     seekto.u.LowPart = 0;seekto.u.HighPart = 0;
820     hres = IStream_Seek(pStm,seekto,SEEK_SET,&newpos);
821     
822     TRACE("unmarshalling classfactory\n");
823     hres = CoUnmarshalInterface(pStm,&IID_IClassFactory,ppv);
824 out:
825     IStream_Release(pStm);
826     return hres;
827 }
828
829
830 struct local_server_params
831 {
832     CLSID clsid;
833     IStream *stream;
834 };
835
836 /* FIXME: should call to rpcss instead */
837 static DWORD WINAPI local_server_thread(LPVOID param)
838 {
839     struct local_server_params * lsp = (struct local_server_params *)param;
840     HANDLE              hPipe;
841     WCHAR               pipefn[100];
842     HRESULT             hres;
843     IStream             *pStm = lsp->stream;
844     STATSTG             ststg;
845     unsigned char       *buffer;
846     int                 buflen;
847     LARGE_INTEGER       seekto;
848     ULARGE_INTEGER      newpos;
849     ULONG               res;
850
851     TRACE("Starting threader for %s.\n",debugstr_guid(&lsp->clsid));
852
853     get_localserver_pipe_name(pipefn, &lsp->clsid);
854
855     HeapFree(GetProcessHeap(), 0, lsp);
856
857     hPipe = CreateNamedPipeW( pipefn, PIPE_ACCESS_DUPLEX,
858                               PIPE_TYPE_BYTE|PIPE_WAIT, PIPE_UNLIMITED_INSTANCES,
859                               4096, 4096, 500 /* 0.5 second timeout */, NULL );
860     
861     if (hPipe == INVALID_HANDLE_VALUE)
862     {
863         FIXME("pipe creation failed for %s, le is %ld\n", debugstr_w(pipefn), GetLastError());
864         return 1;
865     }
866     
867     while (1) {
868         if (!ConnectNamedPipe(hPipe,NULL)) {
869             ERR("Failure during ConnectNamedPipe %ld, ABORT!\n",GetLastError());
870             break;
871         }
872
873         TRACE("marshalling IClassFactory to client\n");
874         
875         hres = IStream_Stat(pStm,&ststg,0);
876         if (hres) return hres;
877
878         buflen = ststg.cbSize.u.LowPart;
879         buffer = HeapAlloc(GetProcessHeap(),0,buflen);
880         seekto.u.LowPart = 0;
881         seekto.u.HighPart = 0;
882         hres = IStream_Seek(pStm,seekto,SEEK_SET,&newpos);
883         if (hres) {
884             FIXME("IStream_Seek failed, %lx\n",hres);
885             return hres;
886         }
887         
888         hres = IStream_Read(pStm,buffer,buflen,&res);
889         if (hres) {
890             FIXME("Stream Read failed, %lx\n",hres);
891             return hres;
892         }
893         
894         WriteFile(hPipe,buffer,buflen,&res,NULL);
895         FlushFileBuffers(hPipe);
896         DisconnectNamedPipe(hPipe);
897
898         TRACE("done marshalling IClassFactory\n");
899     }
900     CloseHandle(hPipe);
901     IStream_Release(pStm);
902     return 0;
903 }
904
905 void RPC_StartLocalServer(REFCLSID clsid, IStream *stream)
906 {
907     DWORD tid;
908     HANDLE thread;
909     struct local_server_params *lsp = HeapAlloc(GetProcessHeap(), 0, sizeof(*lsp));
910
911     lsp->clsid = *clsid;
912     lsp->stream = stream;
913
914     thread = CreateThread(NULL, 0, local_server_thread, lsp, 0, &tid);
915     CloseHandle(thread);
916     /* FIXME: failure handling */
917 }