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