Implements OleLoadPicturePath.
[wine] / dlls / ole32 / rpc.c
1 /*
2  *      (Local) RPC Stuff
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, { 0, (DWORD)(__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     DWORD                  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 static HRESULT WINAPI RpcChannelBuffer_QueryInterface(LPRPCCHANNELBUFFER iface, REFIID riid, LPVOID *ppv)
102 {
103     *ppv = NULL;
104     if (IsEqualIID(riid,&IID_IRpcChannelBuffer) || IsEqualIID(riid,&IID_IUnknown))
105     {
106         *ppv = (LPVOID)iface;
107         IUnknown_AddRef(iface);
108         return S_OK;
109     }
110     return E_NOINTERFACE;
111 }
112
113 static ULONG WINAPI RpcChannelBuffer_AddRef(LPRPCCHANNELBUFFER iface)
114 {
115     RpcChannelBuffer *This = (RpcChannelBuffer *)iface;
116     return InterlockedIncrement(&This->refs);
117 }
118
119 static ULONG WINAPI ServerRpcChannelBuffer_Release(LPRPCCHANNELBUFFER iface)
120 {
121     RpcChannelBuffer *This = (RpcChannelBuffer *)iface;
122     ULONG ref;
123
124     ref = InterlockedDecrement(&This->refs);
125     if (ref)
126         return ref;
127
128     HeapFree(GetProcessHeap(), 0, This);
129     return 0;
130 }
131
132 static ULONG WINAPI ClientRpcChannelBuffer_Release(LPRPCCHANNELBUFFER iface)
133 {
134     ClientRpcChannelBuffer *This = (ClientRpcChannelBuffer *)iface;
135     ULONG ref;
136
137     ref = InterlockedDecrement(&This->super.refs);
138     if (ref)
139         return ref;
140
141     RpcBindingFree(&This->bind);
142     HeapFree(GetProcessHeap(), 0, This);
143     return 0;
144 }
145
146 static HRESULT WINAPI ServerRpcChannelBuffer_GetBuffer(LPRPCCHANNELBUFFER iface, RPCOLEMESSAGE* olemsg, REFIID riid)
147 {
148     RpcChannelBuffer *This = (RpcChannelBuffer *)iface;
149     RPC_MESSAGE *msg = (RPC_MESSAGE *)olemsg;
150     RPC_STATUS status;
151
152     TRACE("(%p)->(%p,%p)\n", This, olemsg, riid);
153
154     status = I_RpcGetBuffer(msg);
155
156     TRACE("-- %ld\n", status);
157
158     return HRESULT_FROM_WIN32(status);
159 }
160
161 static HRESULT WINAPI ClientRpcChannelBuffer_GetBuffer(LPRPCCHANNELBUFFER iface, RPCOLEMESSAGE* olemsg, REFIID riid)
162 {
163     ClientRpcChannelBuffer *This = (ClientRpcChannelBuffer *)iface;
164     RPC_MESSAGE *msg = (RPC_MESSAGE *)olemsg;
165     RPC_CLIENT_INTERFACE *cif;
166     RPC_STATUS status;
167
168     TRACE("(%p)->(%p,%p)\n", This, olemsg, riid);
169
170     cif = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(RPC_CLIENT_INTERFACE));
171     if (!cif)
172         return E_OUTOFMEMORY;
173
174     cif->Length = sizeof(RPC_CLIENT_INTERFACE);
175     /* RPC interface ID = COM interface ID */
176     cif->InterfaceId.SyntaxGUID = *riid;
177     /* COM objects always have a version of 0.0 */
178     cif->InterfaceId.SyntaxVersion.MajorVersion = 0;
179     cif->InterfaceId.SyntaxVersion.MinorVersion = 0;
180     msg->RpcInterfaceInformation = cif;
181     msg->Handle = This->bind;
182     
183     status = I_RpcGetBuffer(msg);
184
185     TRACE("-- %ld\n", status);
186
187     return HRESULT_FROM_WIN32(status);
188 }
189
190 static HRESULT WINAPI RpcChannelBuffer_SendReceive(LPRPCCHANNELBUFFER iface, RPCOLEMESSAGE *olemsg, ULONG *pstatus)
191 {
192     RPC_MESSAGE *msg = (RPC_MESSAGE *)olemsg;
193     RPC_STATUS status;
194     HRESULT hr;
195
196     TRACE("(%p)\n", msg);
197
198     status = I_RpcSendReceive(msg);
199
200     if (pstatus) *pstatus = status;
201
202     if (status == RPC_S_OK)
203         hr = S_OK;
204     else if (status == RPC_S_CALL_FAILED)
205         hr = *(HRESULT *)msg->Buffer;
206     else
207         hr = HRESULT_FROM_WIN32(status);
208
209     TRACE("-- 0x%08lx\n", hr);
210
211     return hr;
212 }
213
214 static HRESULT WINAPI ServerRpcChannelBuffer_FreeBuffer(LPRPCCHANNELBUFFER iface, RPCOLEMESSAGE* olemsg)
215 {
216     RPC_MESSAGE *msg = (RPC_MESSAGE *)olemsg;
217     RPC_STATUS status;
218
219     TRACE("(%p)\n", msg);
220
221     status = I_RpcFreeBuffer(msg);
222
223     TRACE("-- %ld\n", status);
224
225     return HRESULT_FROM_WIN32(status);
226 }
227
228 static HRESULT WINAPI ClientRpcChannelBuffer_FreeBuffer(LPRPCCHANNELBUFFER iface, RPCOLEMESSAGE* olemsg)
229 {
230     RPC_MESSAGE *msg = (RPC_MESSAGE *)olemsg;
231     RPC_STATUS status;
232
233     TRACE("(%p)\n", msg);
234
235     status = I_RpcFreeBuffer(msg);
236
237     HeapFree(GetProcessHeap(), 0, msg->RpcInterfaceInformation);
238     msg->RpcInterfaceInformation = NULL;
239
240     TRACE("-- %ld\n", status);
241
242     return HRESULT_FROM_WIN32(status);
243 }
244
245 static HRESULT WINAPI RpcChannelBuffer_GetDestCtx(LPRPCCHANNELBUFFER iface, DWORD* pdwDestContext, void** ppvDestContext)
246 {
247     FIXME("(%p,%p), stub!\n", pdwDestContext, ppvDestContext);
248     return E_FAIL;
249 }
250
251 static HRESULT WINAPI RpcChannelBuffer_IsConnected(LPRPCCHANNELBUFFER iface)
252 {
253     TRACE("()\n");
254     /* native does nothing too */
255     return S_OK;
256 }
257
258 static const IRpcChannelBufferVtbl ClientRpcChannelBufferVtbl =
259 {
260     RpcChannelBuffer_QueryInterface,
261     RpcChannelBuffer_AddRef,
262     ClientRpcChannelBuffer_Release,
263     ClientRpcChannelBuffer_GetBuffer,
264     RpcChannelBuffer_SendReceive,
265     ClientRpcChannelBuffer_FreeBuffer,
266     RpcChannelBuffer_GetDestCtx,
267     RpcChannelBuffer_IsConnected
268 };
269
270 static const IRpcChannelBufferVtbl ServerRpcChannelBufferVtbl =
271 {
272     RpcChannelBuffer_QueryInterface,
273     RpcChannelBuffer_AddRef,
274     ServerRpcChannelBuffer_Release,
275     ServerRpcChannelBuffer_GetBuffer,
276     RpcChannelBuffer_SendReceive,
277     ServerRpcChannelBuffer_FreeBuffer,
278     RpcChannelBuffer_GetDestCtx,
279     RpcChannelBuffer_IsConnected
280 };
281
282 /* returns a channel buffer for proxies */
283 HRESULT RPC_CreateClientChannel(const OXID *oxid, const IPID *ipid, IRpcChannelBuffer **chan)
284 {
285     ClientRpcChannelBuffer *This;
286     WCHAR                   endpoint[200];
287     RPC_BINDING_HANDLE      bind;
288     RPC_STATUS              status;
289     LPWSTR                  string_binding;
290
291     /* connect to the apartment listener thread */
292     get_rpc_endpoint(endpoint, oxid);
293
294     TRACE("proxy pipe: connecting to endpoint: %s\n", debugstr_w(endpoint));
295
296     status = RpcStringBindingComposeW(
297         NULL,
298         wszPipeTransport,
299         NULL,
300         endpoint,
301         NULL,
302         &string_binding);
303         
304     if (status == RPC_S_OK)
305     {
306         status = RpcBindingFromStringBindingW(string_binding, &bind);
307
308         if (status == RPC_S_OK)
309         {
310             IPID ipid2 = *ipid; /* why can't RpcBindingSetObject take a const? */
311             status = RpcBindingSetObject(bind, &ipid2);
312             if (status != RPC_S_OK)
313                 RpcBindingFree(&bind);
314         }
315
316         RpcStringFreeW(&string_binding);
317     }
318
319     if (status != RPC_S_OK)
320     {
321         ERR("Couldn't get binding for endpoint %s, status = %ld\n", debugstr_w(endpoint), status);
322         return HRESULT_FROM_WIN32(status);
323     }
324
325     This = HeapAlloc(GetProcessHeap(), 0, sizeof(*This));
326     if (!This)
327     {
328         RpcBindingFree(&bind);
329         return E_OUTOFMEMORY;
330     }
331
332     This->super.lpVtbl = &ClientRpcChannelBufferVtbl;
333     This->super.refs = 1;
334     This->bind = bind;
335
336     *chan = (IRpcChannelBuffer*)This;
337
338     return S_OK;
339 }
340
341 HRESULT RPC_CreateServerChannel(IRpcChannelBuffer **chan)
342 {
343     RpcChannelBuffer *This = HeapAlloc(GetProcessHeap(), 0, sizeof(*This));
344     if (!This)
345         return E_OUTOFMEMORY;
346
347     This->lpVtbl = &ServerRpcChannelBufferVtbl;
348     This->refs = 1;
349     
350     *chan = (IRpcChannelBuffer*)This;
351
352     return S_OK;
353 }
354
355
356 HRESULT RPC_ExecuteCall(RPCOLEMESSAGE *msg, IRpcStubBuffer *stub)
357 {
358     /* FIXME: pass server channel buffer, but don't create it every time */
359     return IRpcStubBuffer_Invoke(stub, msg, NULL);
360 }
361
362 static void __RPC_STUB dispatch_rpc(RPC_MESSAGE *msg)
363 {
364     IRpcStubBuffer     *stub;
365     APARTMENT          *apt;
366     IPID                ipid;
367
368     RpcBindingInqObject(msg->Handle, &ipid);
369
370     stub = ipid_to_apt_and_stubbuffer(&ipid, &apt);
371     if (!apt || !stub)
372     {
373         if (apt) COM_ApartmentRelease(apt);
374         /* ipid_to_apt_and_stubbuffer will already have logged the error */
375         return RpcRaiseException(RPC_E_DISCONNECTED);
376     }
377
378     /* Note: this is the important difference between STAs and MTAs - we
379      * always execute RPCs to STAs in the thread that originally created the
380      * apartment (i.e. the one that pumps messages to the window) */
381     if (apt->model & COINIT_APARTMENTTHREADED)
382         SendMessageW(apt->win, DM_EXECUTERPC, (WPARAM)msg, (LPARAM)stub);
383     else
384         RPC_ExecuteCall((RPCOLEMESSAGE *)msg, stub);
385
386     COM_ApartmentRelease(apt);
387     IRpcStubBuffer_Release(stub);
388 }
389
390 /* stub registration */
391 HRESULT RPC_RegisterInterface(REFIID riid)
392 {
393     struct registered_if *rif;
394     BOOL found = FALSE;
395     HRESULT hr = S_OK;
396     
397     TRACE("(%s)\n", debugstr_guid(riid));
398
399     EnterCriticalSection(&csRegIf);
400     LIST_FOR_EACH_ENTRY(rif, &registered_interfaces, struct registered_if, entry)
401     {
402         if (IsEqualGUID(&rif->If.InterfaceId.SyntaxGUID, riid))
403         {
404             rif->refs++;
405             found = TRUE;
406             break;
407         }
408     }
409     if (!found)
410     {
411         TRACE("Creating new interface\n");
412
413         rif = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*rif));
414         if (rif)
415         {
416             RPC_STATUS status;
417
418             rif->refs = 1;
419             rif->If.Length = sizeof(RPC_SERVER_INTERFACE);
420             /* RPC interface ID = COM interface ID */
421             rif->If.InterfaceId.SyntaxGUID = *riid;
422             rif->If.DispatchTable = &rpc_dispatch;
423             /* all other fields are 0, including the version asCOM objects
424              * always have a version of 0.0 */
425             status = RpcServerRegisterIfEx(
426                 (RPC_IF_HANDLE)&rif->If,
427                 NULL, NULL,
428                 RPC_IF_OLE | RPC_IF_AUTOLISTEN,
429                 RPC_C_LISTEN_MAX_CALLS_DEFAULT,
430                 NULL);
431             if (status == RPC_S_OK)
432                 list_add_tail(&registered_interfaces, &rif->entry);
433             else
434             {
435                 ERR("RpcServerRegisterIfEx failed with error %ld\n", status);
436                 HeapFree(GetProcessHeap(), 0, rif);
437                 hr = HRESULT_FROM_WIN32(status);
438             }
439         }
440         else
441             hr = E_OUTOFMEMORY;
442     }
443     LeaveCriticalSection(&csRegIf);
444     return hr;
445 }
446
447 /* stub unregistration */
448 void RPC_UnregisterInterface(REFIID riid)
449 {
450     struct registered_if *rif;
451     EnterCriticalSection(&csRegIf);
452     LIST_FOR_EACH_ENTRY(rif, &registered_interfaces, struct registered_if, entry)
453     {
454         if (IsEqualGUID(&rif->If.InterfaceId.SyntaxGUID, riid))
455         {
456             if (!--rif->refs)
457             {
458 #if 0 /* this is a stub in builtin and spams the console with FIXME's */
459                 IID iid = *riid; /* RpcServerUnregisterIf doesn't take const IID */
460                 RpcServerUnregisterIf((RPC_IF_HANDLE)&rif->If, &iid, 0);
461                 list_remove(&rif->entry);
462                 HeapFree(GetProcessHeap(), 0, rif);
463 #endif
464             }
465             break;
466         }
467     }
468     LeaveCriticalSection(&csRegIf);
469 }
470
471 /* make the apartment reachable by other threads and processes and create the
472  * IRemUnknown object */
473 void RPC_StartRemoting(struct apartment *apt)
474 {
475     if (!InterlockedExchange(&apt->remoting_started, TRUE))
476     {
477         WCHAR endpoint[200];
478         RPC_STATUS status;
479
480         get_rpc_endpoint(endpoint, &apt->oxid);
481     
482         status = RpcServerUseProtseqEpW(
483             wszPipeTransport,
484             RPC_C_PROTSEQ_MAX_REQS_DEFAULT,
485             endpoint,
486             NULL);
487         if (status != RPC_S_OK)
488             ERR("Couldn't register endpoint %s\n", debugstr_w(endpoint));
489
490         /* FIXME: move remote unknown exporting into this function */
491     }
492     start_apartment_remote_unknown();
493 }
494
495
496 static HRESULT create_server(REFCLSID rclsid)
497 {
498     static const WCHAR  embedding[] = { ' ', '-','E','m','b','e','d','d','i','n','g',0 };
499     HKEY                key;
500     char                buf[200];
501     HRESULT             hres = E_UNEXPECTED;
502     char                xclsid[80];
503     WCHAR               exe[MAX_PATH+1];
504     DWORD               exelen = sizeof(exe);
505     WCHAR               command[MAX_PATH+sizeof(embedding)/sizeof(WCHAR)];
506     STARTUPINFOW        sinfo;
507     PROCESS_INFORMATION pinfo;
508
509     WINE_StringFromCLSID((LPCLSID)rclsid,xclsid);
510
511     sprintf(buf,"CLSID\\%s\\LocalServer32",xclsid);
512     hres = RegOpenKeyExA(HKEY_CLASSES_ROOT, buf, 0, KEY_READ, &key);
513
514     if (hres != ERROR_SUCCESS) {
515         WARN("CLSID %s not registered as LocalServer32\n", xclsid);
516         return REGDB_E_READREGDB; /* Probably */
517     }
518
519     memset(exe,0,sizeof(exe));
520     hres= RegQueryValueExW(key, NULL, NULL, NULL, (LPBYTE)exe, &exelen);
521     RegCloseKey(key);
522     if (hres) {
523         WARN("No default value for LocalServer32 key\n");
524         return REGDB_E_CLASSNOTREG; /* FIXME: check retval */
525     }
526
527     memset(&sinfo,0,sizeof(sinfo));
528     sinfo.cb = sizeof(sinfo);
529
530     /* EXE servers are started with the -Embedding switch. MSDN also claims /Embedding is used,
531      * 9x does -Embedding, perhaps an 9x/NT difference?
532      */
533
534     strcpyW(command, exe);
535     strcatW(command, embedding);
536
537     TRACE("activating local server '%s' for %s\n", debugstr_w(command), xclsid);
538
539     if (!CreateProcessW(exe, command, NULL, NULL, FALSE, 0, NULL, NULL, &sinfo, &pinfo)) {
540         WARN("failed to run local server %s\n", debugstr_w(exe));
541         return HRESULT_FROM_WIN32(GetLastError());
542     }
543     CloseHandle(pinfo.hProcess);
544     CloseHandle(pinfo.hThread);
545
546     return S_OK;
547 }
548
549 /*
550  * start_local_service()  - start a service given its name and parameters
551  */
552 static DWORD start_local_service(LPCWSTR name, DWORD num, LPWSTR *params)
553 {
554     SC_HANDLE handle, hsvc;
555     DWORD     r = ERROR_FUNCTION_FAILED;
556
557     TRACE("Starting service %s %ld params\n", debugstr_w(name), num);
558
559     handle = OpenSCManagerW(NULL, NULL, SC_MANAGER_ALL_ACCESS);
560     if (!handle)
561         return r;
562     hsvc = OpenServiceW(handle, name, SC_MANAGER_ALL_ACCESS);
563     if (hsvc)
564     {
565         if(StartServiceW(hsvc, num, (LPCWSTR*)params))
566             r = ERROR_SUCCESS;
567         else
568             r = GetLastError();
569         if (r == ERROR_SERVICE_ALREADY_RUNNING)
570             r = ERROR_SUCCESS;
571         CloseServiceHandle(hsvc);
572     }
573     CloseServiceHandle(handle);
574
575     TRACE("StartService returned error %ld (%s)\n", r, r?"ok":"failed");
576
577     return r;
578 }
579
580 /*
581  * create_local_service()  - start a COM server in a service
582  *
583  *   To start a Local Service, we read the AppID value under
584  * the class's CLSID key, then open the HKCR\\AppId key specified
585  * there and check for a LocalService value.
586  *
587  * Note:  Local Services are not supported under Windows 9x
588  */
589 static HRESULT create_local_service(REFCLSID rclsid)
590 {
591     HRESULT hres = REGDB_E_READREGDB;
592     WCHAR buf[40], keyname[50];
593     static const WCHAR szClsId[] = { 'C','L','S','I','D','\\',0 };
594     static const WCHAR szAppId[] = { 'A','p','p','I','d',0 };
595     static const WCHAR szAppIdKey[] = { 'A','p','p','I','d','\\',0 };
596     static const WCHAR szLocalService[] = { 'L','o','c','a','l','S','e','r','v','i','c','e',0 };
597     static const WCHAR szServiceParams[] = {'S','e','r','v','i','c','e','P','a','r','a','m','s',0};
598     HKEY hkey;
599     LONG r;
600     DWORD type, sz;
601
602     TRACE("Attempting to start Local service for %s\n", debugstr_guid(rclsid));
603
604     /* read the AppID value under the class's key */
605     strcpyW(keyname,szClsId);
606     StringFromGUID2(rclsid,&keyname[6],39);
607     r = RegOpenKeyExW(HKEY_CLASSES_ROOT, keyname, 0, KEY_READ, &hkey);
608     if (r!=ERROR_SUCCESS)
609         return hres;
610     sz = sizeof buf;
611     r = RegQueryValueExW(hkey, szAppId, NULL, &type, (LPBYTE)buf, &sz);
612     RegCloseKey(hkey);
613     if (r!=ERROR_SUCCESS || type!=REG_SZ)
614         return hres;
615
616     /* read the LocalService and ServiceParameters values from the AppID key */
617     strcpyW(keyname, szAppIdKey);
618     strcatW(keyname, buf);
619     r = RegOpenKeyExW(HKEY_CLASSES_ROOT, keyname, 0, KEY_READ, &hkey);
620     if (r!=ERROR_SUCCESS)
621         return hres;
622     sz = sizeof buf;
623     r = RegQueryValueExW(hkey, szLocalService, NULL, &type, (LPBYTE)buf, &sz);
624     if (r==ERROR_SUCCESS && type==REG_SZ)
625     {
626         DWORD num_args = 0;
627         LPWSTR args[1] = { NULL };
628
629         /*
630          * FIXME: I'm not really sure how to deal with the service parameters.
631          *        I suspect that the string returned from RegQueryValueExW
632          *        should be split into a number of arguments by spaces.
633          *        It would make more sense if ServiceParams contained a
634          *        REG_MULTI_SZ here, but it's a REG_SZ for the services
635          *        that I'm interested in for the moment.
636          */
637         r = RegQueryValueExW(hkey, szServiceParams, NULL, &type, NULL, &sz);
638         if (r == ERROR_SUCCESS && type == REG_SZ && sz)
639         {
640             args[0] = HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY,sz);
641             num_args++;
642             RegQueryValueExW(hkey, szServiceParams, NULL, &type, (LPBYTE)args[0], &sz);
643         }
644         r = start_local_service(buf, num_args, args);
645         if (r==ERROR_SUCCESS)
646             hres = S_OK;
647         HeapFree(GetProcessHeap(),0,args[0]);
648     }
649     RegCloseKey(hkey);
650         
651     return hres;
652 }
653
654 #define PIPEPREF "\\\\.\\pipe\\"
655
656 /* FIXME: should call to rpcss instead */
657 HRESULT RPC_GetLocalClassObject(REFCLSID rclsid, REFIID iid, LPVOID *ppv)
658 {
659     HRESULT        hres;
660     HANDLE         hPipe;
661     char           pipefn[200];
662     DWORD          res, bufferlen;
663     char           marshalbuffer[200];
664     IStream       *pStm;
665     LARGE_INTEGER  seekto;
666     ULARGE_INTEGER newpos;
667     int            tries = 0;
668
669     static const int MAXTRIES = 30; /* 30 seconds */
670
671     TRACE("rclsid=%s, iid=%s\n", debugstr_guid(rclsid), debugstr_guid(iid));
672
673     strcpy(pipefn,PIPEPREF);
674     WINE_StringFromCLSID(rclsid,pipefn+strlen(PIPEPREF));
675
676     while (tries++ < MAXTRIES) {
677         TRACE("waiting for %s\n", pipefn);
678       
679         WaitNamedPipeA( pipefn, NMPWAIT_WAIT_FOREVER );
680         hPipe = CreateFileA(pipefn, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, 0);
681         if (hPipe == INVALID_HANDLE_VALUE) {
682             if (tries == 1) {
683                 if ( (hres = create_server(rclsid)) &&
684                      (hres = create_local_service(rclsid)) )
685                     return hres;
686                 Sleep(1000);
687             } else {
688                 WARN("Connecting to %s, no response yet, retrying: le is %lx\n",pipefn,GetLastError());
689                 Sleep(1000);
690             }
691             continue;
692         }
693         bufferlen = 0;
694         if (!ReadFile(hPipe,marshalbuffer,sizeof(marshalbuffer),&bufferlen,NULL)) {
695             FIXME("Failed to read marshal id from classfactory of %s.\n",debugstr_guid(rclsid));
696             Sleep(1000);
697             continue;
698         }
699         TRACE("read marshal id from pipe\n");
700         CloseHandle(hPipe);
701         break;
702     }
703     
704     if (tries >= MAXTRIES)
705         return E_NOINTERFACE;
706     
707     hres = CreateStreamOnHGlobal(0,TRUE,&pStm);
708     if (hres) return hres;
709     hres = IStream_Write(pStm,marshalbuffer,bufferlen,&res);
710     if (hres) goto out;
711     seekto.u.LowPart = 0;seekto.u.HighPart = 0;
712     hres = IStream_Seek(pStm,seekto,SEEK_SET,&newpos);
713     
714     TRACE("unmarshalling classfactory\n");
715     hres = CoUnmarshalInterface(pStm,&IID_IClassFactory,ppv);
716 out:
717     IStream_Release(pStm);
718     return hres;
719 }
720
721
722 struct local_server_params
723 {
724     CLSID clsid;
725     IStream *stream;
726 };
727
728 /* FIXME: should call to rpcss instead */
729 static DWORD WINAPI local_server_thread(LPVOID param)
730 {
731     struct local_server_params * lsp = (struct local_server_params *)param;
732     HANDLE              hPipe;
733     char                pipefn[200];
734     HRESULT             hres;
735     IStream             *pStm = lsp->stream;
736     STATSTG             ststg;
737     unsigned char       *buffer;
738     int                 buflen;
739     LARGE_INTEGER       seekto;
740     ULARGE_INTEGER      newpos;
741     ULONG               res;
742
743     TRACE("Starting threader for %s.\n",debugstr_guid(&lsp->clsid));
744
745     strcpy(pipefn,PIPEPREF);
746     WINE_StringFromCLSID(&lsp->clsid,pipefn+strlen(PIPEPREF));
747
748     HeapFree(GetProcessHeap(), 0, lsp);
749
750     hPipe = CreateNamedPipeA( pipefn, PIPE_ACCESS_DUPLEX,
751                               PIPE_TYPE_BYTE|PIPE_WAIT, PIPE_UNLIMITED_INSTANCES,
752                               4096, 4096, 500 /* 0.5 second timeout */, NULL );
753     
754     if (hPipe == INVALID_HANDLE_VALUE)
755     {
756         FIXME("pipe creation failed for %s, le is %ld\n",pipefn,GetLastError());
757         return 1;
758     }
759     
760     while (1) {
761         if (!ConnectNamedPipe(hPipe,NULL)) {
762             ERR("Failure during ConnectNamedPipe %ld, ABORT!\n",GetLastError());
763             break;
764         }
765
766         TRACE("marshalling IClassFactory to client\n");
767         
768         hres = IStream_Stat(pStm,&ststg,0);
769         if (hres) return hres;
770
771         buflen = ststg.cbSize.u.LowPart;
772         buffer = HeapAlloc(GetProcessHeap(),0,buflen);
773         seekto.u.LowPart = 0;
774         seekto.u.HighPart = 0;
775         hres = IStream_Seek(pStm,seekto,SEEK_SET,&newpos);
776         if (hres) {
777             FIXME("IStream_Seek failed, %lx\n",hres);
778             return hres;
779         }
780         
781         hres = IStream_Read(pStm,buffer,buflen,&res);
782         if (hres) {
783             FIXME("Stream Read failed, %lx\n",hres);
784             return hres;
785         }
786         
787         WriteFile(hPipe,buffer,buflen,&res,NULL);
788         FlushFileBuffers(hPipe);
789         DisconnectNamedPipe(hPipe);
790
791         TRACE("done marshalling IClassFactory\n");
792     }
793     CloseHandle(hPipe);
794     IStream_Release(pStm);
795     return 0;
796 }
797
798 void RPC_StartLocalServer(REFCLSID clsid, IStream *stream)
799 {
800     DWORD tid;
801     HANDLE thread;
802     struct local_server_params *lsp = HeapAlloc(GetProcessHeap(), 0, sizeof(*lsp));
803
804     lsp->clsid = *clsid;
805     lsp->stream = stream;
806
807     thread = CreateThread(NULL, 0, local_server_thread, lsp, 0, &tid);
808     CloseHandle(thread);
809     /* FIXME: failure handling */
810 }