Intercept functions for 16-bit relay debugging by patching the
[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, { 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     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_STATUS status;
216     DWORD index;
217     struct dispatch_params *params;
218     DWORD tid;
219     
220     TRACE("(%p) iMethod=%ld\n", olemsg, olemsg->iMethod);
221
222     params = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*params));
223     if (!params) return E_OUTOFMEMORY;
224     
225     params->msg = olemsg;
226     params->status = RPC_S_OK;
227
228     /* we use a separate thread here because we need to be able to
229      * pump the message loop in the application thread: if we do not,
230      * any windows created by this thread will hang and RPCs that try
231      * and re-enter this STA from an incoming server thread will
232      * deadlock. InstallShield is an example of that.
233      */
234     params->handle = CreateThread(NULL, 0, rpc_sendreceive_thread, params, 0, &tid);
235     if (!params->handle)
236     {
237         ERR("Could not create RpcSendReceive thread, error %lx\n", GetLastError());
238         hr = E_UNEXPECTED;
239     }
240
241     if (hr == S_OK)
242         hr = CoWaitForMultipleHandles(0, INFINITE, 1, &params->handle, &index);
243     CloseHandle(params->handle);
244
245     status = params->status;
246     HeapFree(GetProcessHeap(), 0, params);
247     params = NULL;
248
249     if (hr) return hr;
250     
251     if (pstatus) *pstatus = status;
252
253     TRACE("RPC call status: 0x%lx\n", status);
254     if (status == RPC_S_OK)
255         hr = S_OK;
256     else if (status == RPC_S_CALL_FAILED)
257         hr = *(HRESULT *)olemsg->Buffer;
258     else
259         hr = HRESULT_FROM_WIN32(status);
260
261     TRACE("-- 0x%08lx\n", hr);
262
263     return hr;
264 }
265
266 static HRESULT WINAPI ServerRpcChannelBuffer_FreeBuffer(LPRPCCHANNELBUFFER iface, RPCOLEMESSAGE* olemsg)
267 {
268     RPC_MESSAGE *msg = (RPC_MESSAGE *)olemsg;
269     RPC_STATUS status;
270
271     TRACE("(%p)\n", msg);
272
273     status = I_RpcFreeBuffer(msg);
274
275     TRACE("-- %ld\n", status);
276
277     return HRESULT_FROM_WIN32(status);
278 }
279
280 static HRESULT WINAPI ClientRpcChannelBuffer_FreeBuffer(LPRPCCHANNELBUFFER iface, RPCOLEMESSAGE* olemsg)
281 {
282     RPC_MESSAGE *msg = (RPC_MESSAGE *)olemsg;
283     RPC_STATUS status;
284
285     TRACE("(%p)\n", msg);
286
287     status = I_RpcFreeBuffer(msg);
288
289     HeapFree(GetProcessHeap(), 0, msg->RpcInterfaceInformation);
290     msg->RpcInterfaceInformation = NULL;
291
292     TRACE("-- %ld\n", status);
293
294     return HRESULT_FROM_WIN32(status);
295 }
296
297 static HRESULT WINAPI RpcChannelBuffer_GetDestCtx(LPRPCCHANNELBUFFER iface, DWORD* pdwDestContext, void** ppvDestContext)
298 {
299     FIXME("(%p,%p), stub!\n", pdwDestContext, ppvDestContext);
300     return E_FAIL;
301 }
302
303 static HRESULT WINAPI RpcChannelBuffer_IsConnected(LPRPCCHANNELBUFFER iface)
304 {
305     TRACE("()\n");
306     /* native does nothing too */
307     return S_OK;
308 }
309
310 static const IRpcChannelBufferVtbl ClientRpcChannelBufferVtbl =
311 {
312     RpcChannelBuffer_QueryInterface,
313     RpcChannelBuffer_AddRef,
314     ClientRpcChannelBuffer_Release,
315     ClientRpcChannelBuffer_GetBuffer,
316     RpcChannelBuffer_SendReceive,
317     ClientRpcChannelBuffer_FreeBuffer,
318     RpcChannelBuffer_GetDestCtx,
319     RpcChannelBuffer_IsConnected
320 };
321
322 static const IRpcChannelBufferVtbl ServerRpcChannelBufferVtbl =
323 {
324     RpcChannelBuffer_QueryInterface,
325     RpcChannelBuffer_AddRef,
326     ServerRpcChannelBuffer_Release,
327     ServerRpcChannelBuffer_GetBuffer,
328     RpcChannelBuffer_SendReceive,
329     ServerRpcChannelBuffer_FreeBuffer,
330     RpcChannelBuffer_GetDestCtx,
331     RpcChannelBuffer_IsConnected
332 };
333
334 /* returns a channel buffer for proxies */
335 HRESULT RPC_CreateClientChannel(const OXID *oxid, const IPID *ipid, IRpcChannelBuffer **chan)
336 {
337     ClientRpcChannelBuffer *This;
338     WCHAR                   endpoint[200];
339     RPC_BINDING_HANDLE      bind;
340     RPC_STATUS              status;
341     LPWSTR                  string_binding;
342
343     /* connect to the apartment listener thread */
344     get_rpc_endpoint(endpoint, oxid);
345
346     TRACE("proxy pipe: connecting to endpoint: %s\n", debugstr_w(endpoint));
347
348     status = RpcStringBindingComposeW(
349         NULL,
350         wszPipeTransport,
351         NULL,
352         endpoint,
353         NULL,
354         &string_binding);
355         
356     if (status == RPC_S_OK)
357     {
358         status = RpcBindingFromStringBindingW(string_binding, &bind);
359
360         if (status == RPC_S_OK)
361         {
362             IPID ipid2 = *ipid; /* why can't RpcBindingSetObject take a const? */
363             status = RpcBindingSetObject(bind, &ipid2);
364             if (status != RPC_S_OK)
365                 RpcBindingFree(&bind);
366         }
367
368         RpcStringFreeW(&string_binding);
369     }
370
371     if (status != RPC_S_OK)
372     {
373         ERR("Couldn't get binding for endpoint %s, status = %ld\n", debugstr_w(endpoint), status);
374         return HRESULT_FROM_WIN32(status);
375     }
376
377     This = HeapAlloc(GetProcessHeap(), 0, sizeof(*This));
378     if (!This)
379     {
380         RpcBindingFree(&bind);
381         return E_OUTOFMEMORY;
382     }
383
384     This->super.lpVtbl = &ClientRpcChannelBufferVtbl;
385     This->super.refs = 1;
386     This->bind = bind;
387
388     *chan = (IRpcChannelBuffer*)This;
389
390     return S_OK;
391 }
392
393 HRESULT RPC_CreateServerChannel(IRpcChannelBuffer **chan)
394 {
395     RpcChannelBuffer *This = HeapAlloc(GetProcessHeap(), 0, sizeof(*This));
396     if (!This)
397         return E_OUTOFMEMORY;
398
399     This->lpVtbl = &ServerRpcChannelBufferVtbl;
400     This->refs = 1;
401     
402     *chan = (IRpcChannelBuffer*)This;
403
404     return S_OK;
405 }
406
407
408 HRESULT RPC_ExecuteCall(struct dispatch_params *params)
409 {
410     HRESULT hr = IRpcStubBuffer_Invoke(params->stub, params->msg, params->chan);
411     IRpcStubBuffer_Release(params->stub);
412     if (params->handle) SetEvent(params->handle);
413     return hr;
414 }
415
416 static void __RPC_STUB dispatch_rpc(RPC_MESSAGE *msg)
417 {
418     struct dispatch_params *params;
419     IRpcStubBuffer     *stub;
420     APARTMENT          *apt;
421     IPID                ipid;
422
423     RpcBindingInqObject(msg->Handle, &ipid);
424
425     TRACE("ipid = %s, iMethod = %d\n", debugstr_guid(&ipid), msg->ProcNum);
426
427     params = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*params));
428     if (!params) return RpcRaiseException(E_OUTOFMEMORY);
429
430     stub = ipid_to_apt_and_stubbuffer(&ipid, &apt);
431     if (!apt || !stub)
432     {
433         if (apt) apartment_release(apt);
434         /* ipid_to_apt_and_stubbuffer will already have logged the error */
435         return RpcRaiseException(RPC_E_DISCONNECTED);
436     }
437
438     params->msg = (RPCOLEMESSAGE *)msg;
439     params->stub = stub;
440     params->chan = NULL; /* FIXME: pass server channel */
441     params->status = RPC_S_OK;
442
443     /* Note: this is the important difference between STAs and MTAs - we
444      * always execute RPCs to STAs in the thread that originally created the
445      * apartment (i.e. the one that pumps messages to the window) */
446     if (apt->model & COINIT_APARTMENTTHREADED)
447     {
448         params->handle = CreateEventW(NULL, FALSE, FALSE, NULL);
449
450         TRACE("Calling apartment thread 0x%08lx...\n", apt->tid);
451
452         PostMessageW(apt->win, DM_EXECUTERPC, 0, (LPARAM)params);
453         WaitForSingleObject(params->handle, INFINITE);
454         CloseHandle(params->handle);
455     }
456     else
457         RPC_ExecuteCall(params);
458
459     HeapFree(GetProcessHeap(), 0, params);
460
461     apartment_release(apt);
462 }
463
464 /* stub registration */
465 HRESULT RPC_RegisterInterface(REFIID riid)
466 {
467     struct registered_if *rif;
468     BOOL found = FALSE;
469     HRESULT hr = S_OK;
470     
471     TRACE("(%s)\n", debugstr_guid(riid));
472
473     EnterCriticalSection(&csRegIf);
474     LIST_FOR_EACH_ENTRY(rif, &registered_interfaces, struct registered_if, entry)
475     {
476         if (IsEqualGUID(&rif->If.InterfaceId.SyntaxGUID, riid))
477         {
478             rif->refs++;
479             found = TRUE;
480             break;
481         }
482     }
483     if (!found)
484     {
485         TRACE("Creating new interface\n");
486
487         rif = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*rif));
488         if (rif)
489         {
490             RPC_STATUS status;
491
492             rif->refs = 1;
493             rif->If.Length = sizeof(RPC_SERVER_INTERFACE);
494             /* RPC interface ID = COM interface ID */
495             rif->If.InterfaceId.SyntaxGUID = *riid;
496             rif->If.DispatchTable = &rpc_dispatch;
497             /* all other fields are 0, including the version asCOM objects
498              * always have a version of 0.0 */
499             status = RpcServerRegisterIfEx(
500                 (RPC_IF_HANDLE)&rif->If,
501                 NULL, NULL,
502                 RPC_IF_OLE | RPC_IF_AUTOLISTEN,
503                 RPC_C_LISTEN_MAX_CALLS_DEFAULT,
504                 NULL);
505             if (status == RPC_S_OK)
506                 list_add_tail(&registered_interfaces, &rif->entry);
507             else
508             {
509                 ERR("RpcServerRegisterIfEx failed with error %ld\n", status);
510                 HeapFree(GetProcessHeap(), 0, rif);
511                 hr = HRESULT_FROM_WIN32(status);
512             }
513         }
514         else
515             hr = E_OUTOFMEMORY;
516     }
517     LeaveCriticalSection(&csRegIf);
518     return hr;
519 }
520
521 /* stub unregistration */
522 void RPC_UnregisterInterface(REFIID riid)
523 {
524     struct registered_if *rif;
525     EnterCriticalSection(&csRegIf);
526     LIST_FOR_EACH_ENTRY(rif, &registered_interfaces, struct registered_if, entry)
527     {
528         if (IsEqualGUID(&rif->If.InterfaceId.SyntaxGUID, riid))
529         {
530             if (!--rif->refs)
531             {
532 #if 0 /* this is a stub in builtin and spams the console with FIXME's */
533                 IID iid = *riid; /* RpcServerUnregisterIf doesn't take const IID */
534                 RpcServerUnregisterIf((RPC_IF_HANDLE)&rif->If, &iid, 0);
535                 list_remove(&rif->entry);
536                 HeapFree(GetProcessHeap(), 0, rif);
537 #endif
538             }
539             break;
540         }
541     }
542     LeaveCriticalSection(&csRegIf);
543 }
544
545 /* make the apartment reachable by other threads and processes and create the
546  * IRemUnknown object */
547 void RPC_StartRemoting(struct apartment *apt)
548 {
549     if (!InterlockedExchange(&apt->remoting_started, TRUE))
550     {
551         WCHAR endpoint[200];
552         RPC_STATUS status;
553
554         get_rpc_endpoint(endpoint, &apt->oxid);
555     
556         status = RpcServerUseProtseqEpW(
557             wszPipeTransport,
558             RPC_C_PROTSEQ_MAX_REQS_DEFAULT,
559             endpoint,
560             NULL);
561         if (status != RPC_S_OK)
562             ERR("Couldn't register endpoint %s\n", debugstr_w(endpoint));
563
564         /* FIXME: move remote unknown exporting into this function */
565     }
566     start_apartment_remote_unknown();
567 }
568
569
570 static HRESULT create_server(REFCLSID rclsid)
571 {
572     static const WCHAR  wszLocalServer32[] = { 'L','o','c','a','l','S','e','r','v','e','r','3','2',0 };
573     static const WCHAR  embedding[] = { ' ', '-','E','m','b','e','d','d','i','n','g',0 };
574     HKEY                hkeyclsid;
575     HKEY                key;
576     HRESULT             hres = E_UNEXPECTED;
577     WCHAR               exe[MAX_PATH+1];
578     DWORD               exelen = sizeof(exe);
579     WCHAR               command[MAX_PATH+sizeof(embedding)/sizeof(WCHAR)];
580     STARTUPINFOW        sinfo;
581     PROCESS_INFORMATION pinfo;
582
583     hres = HRESULT_FROM_WIN32(COM_OpenKeyForCLSID(rclsid, KEY_READ, &hkeyclsid));
584     if (hres != S_OK) {
585         ERR("class %s not registered\n", debugstr_guid(rclsid));
586         return REGDB_E_READREGDB;
587     }
588
589     hres = RegOpenKeyExW(hkeyclsid, wszLocalServer32, 0, KEY_READ, &key);
590
591     if (hres != ERROR_SUCCESS) {
592         WARN("class %s not registered as LocalServer32\n", debugstr_guid(rclsid));
593         return REGDB_E_READREGDB; /* Probably */
594     }
595
596     memset(exe,0,sizeof(exe));
597     hres= RegQueryValueExW(key, NULL, NULL, NULL, (LPBYTE)exe, &exelen);
598     RegCloseKey(key);
599     if (hres) {
600         WARN("No default value for LocalServer32 key\n");
601         return REGDB_E_CLASSNOTREG; /* FIXME: check retval */
602     }
603
604     memset(&sinfo,0,sizeof(sinfo));
605     sinfo.cb = sizeof(sinfo);
606
607     /* EXE servers are started with the -Embedding switch. MSDN also claims /Embedding is used,
608      * 9x does -Embedding, perhaps an 9x/NT difference?
609      */
610
611     strcpyW(command, exe);
612     strcatW(command, embedding);
613
614     TRACE("activating local server %s for %s\n", debugstr_w(command), debugstr_guid(rclsid));
615
616     if (!CreateProcessW(exe, command, NULL, NULL, FALSE, 0, NULL, NULL, &sinfo, &pinfo)) {
617         WARN("failed to run local server %s\n", debugstr_w(exe));
618         return HRESULT_FROM_WIN32(GetLastError());
619     }
620     CloseHandle(pinfo.hProcess);
621     CloseHandle(pinfo.hThread);
622
623     return S_OK;
624 }
625
626 /*
627  * start_local_service()  - start a service given its name and parameters
628  */
629 static DWORD start_local_service(LPCWSTR name, DWORD num, LPWSTR *params)
630 {
631     SC_HANDLE handle, hsvc;
632     DWORD     r = ERROR_FUNCTION_FAILED;
633
634     TRACE("Starting service %s %ld params\n", debugstr_w(name), num);
635
636     handle = OpenSCManagerW(NULL, NULL, SC_MANAGER_ALL_ACCESS);
637     if (!handle)
638         return r;
639     hsvc = OpenServiceW(handle, name, SC_MANAGER_ALL_ACCESS);
640     if (hsvc)
641     {
642         if(StartServiceW(hsvc, num, (LPCWSTR*)params))
643             r = ERROR_SUCCESS;
644         else
645             r = GetLastError();
646         if (r == ERROR_SERVICE_ALREADY_RUNNING)
647             r = ERROR_SUCCESS;
648         CloseServiceHandle(hsvc);
649     }
650     CloseServiceHandle(handle);
651
652     TRACE("StartService returned error %ld (%s)\n", r, r?"ok":"failed");
653
654     return r;
655 }
656
657 /*
658  * create_local_service()  - start a COM server in a service
659  *
660  *   To start a Local Service, we read the AppID value under
661  * the class's CLSID key, then open the HKCR\\AppId key specified
662  * there and check for a LocalService value.
663  *
664  * Note:  Local Services are not supported under Windows 9x
665  */
666 static HRESULT create_local_service(REFCLSID rclsid)
667 {
668     HRESULT hres = REGDB_E_READREGDB;
669     WCHAR buf[CHARS_IN_GUID], keyname[50];
670     static const WCHAR szAppId[] = { 'A','p','p','I','d',0 };
671     static const WCHAR szAppIdKey[] = { 'A','p','p','I','d','\\',0 };
672     static const WCHAR szLocalService[] = { 'L','o','c','a','l','S','e','r','v','i','c','e',0 };
673     static const WCHAR szServiceParams[] = {'S','e','r','v','i','c','e','P','a','r','a','m','s',0};
674     HKEY hkey;
675     LONG r;
676     DWORD type, sz;
677
678     TRACE("Attempting to start Local service for %s\n", debugstr_guid(rclsid));
679
680     /* read the AppID value under the class's key */
681     r = COM_OpenKeyForCLSID(rclsid, KEY_READ, &hkey);
682     if (r!=ERROR_SUCCESS)
683         return hres;
684     sz = sizeof buf;
685     r = RegQueryValueExW(hkey, szAppId, NULL, &type, (LPBYTE)buf, &sz);
686     RegCloseKey(hkey);
687     if (r!=ERROR_SUCCESS || type!=REG_SZ)
688         return hres;
689
690     /* read the LocalService and ServiceParameters values from the AppID key */
691     strcpyW(keyname, szAppIdKey);
692     strcatW(keyname, buf);
693     r = RegOpenKeyExW(HKEY_CLASSES_ROOT, keyname, 0, KEY_READ, &hkey);
694     if (r!=ERROR_SUCCESS)
695         return hres;
696     sz = sizeof buf;
697     r = RegQueryValueExW(hkey, szLocalService, NULL, &type, (LPBYTE)buf, &sz);
698     if (r==ERROR_SUCCESS && type==REG_SZ)
699     {
700         DWORD num_args = 0;
701         LPWSTR args[1] = { NULL };
702
703         /*
704          * FIXME: I'm not really sure how to deal with the service parameters.
705          *        I suspect that the string returned from RegQueryValueExW
706          *        should be split into a number of arguments by spaces.
707          *        It would make more sense if ServiceParams contained a
708          *        REG_MULTI_SZ here, but it's a REG_SZ for the services
709          *        that I'm interested in for the moment.
710          */
711         r = RegQueryValueExW(hkey, szServiceParams, NULL, &type, NULL, &sz);
712         if (r == ERROR_SUCCESS && type == REG_SZ && sz)
713         {
714             args[0] = HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY,sz);
715             num_args++;
716             RegQueryValueExW(hkey, szServiceParams, NULL, &type, (LPBYTE)args[0], &sz);
717         }
718         r = start_local_service(buf, num_args, args);
719         if (r==ERROR_SUCCESS)
720             hres = S_OK;
721         HeapFree(GetProcessHeap(),0,args[0]);
722     }
723     RegCloseKey(hkey);
724         
725     return hres;
726 }
727
728
729 static void get_localserver_pipe_name(WCHAR *pipefn, REFCLSID rclsid)
730 {
731     static const WCHAR wszPipeRef[] = {'\\','\\','.','\\','p','i','p','e','\\',0};
732     strcpyW(pipefn, wszPipeRef);
733     StringFromGUID2(rclsid, pipefn + sizeof(wszPipeRef)/sizeof(wszPipeRef[0]) - 1, CHARS_IN_GUID);
734 }
735
736 /* FIXME: should call to rpcss instead */
737 HRESULT RPC_GetLocalClassObject(REFCLSID rclsid, REFIID iid, LPVOID *ppv)
738 {
739     HRESULT        hres;
740     HANDLE         hPipe;
741     WCHAR          pipefn[100];
742     DWORD          res, bufferlen;
743     char           marshalbuffer[200];
744     IStream       *pStm;
745     LARGE_INTEGER  seekto;
746     ULARGE_INTEGER newpos;
747     int            tries = 0;
748
749     static const int MAXTRIES = 30; /* 30 seconds */
750
751     TRACE("rclsid=%s, iid=%s\n", debugstr_guid(rclsid), debugstr_guid(iid));
752
753     get_localserver_pipe_name(pipefn, rclsid);
754
755     while (tries++ < MAXTRIES) {
756         TRACE("waiting for %s\n", debugstr_w(pipefn));
757       
758         WaitNamedPipeW( pipefn, NMPWAIT_WAIT_FOREVER );
759         hPipe = CreateFileW(pipefn, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, 0);
760         if (hPipe == INVALID_HANDLE_VALUE) {
761             if (tries == 1) {
762                 if ( (hres = create_server(rclsid)) &&
763                      (hres = create_local_service(rclsid)) )
764                     return hres;
765                 Sleep(1000);
766             } else {
767                 WARN("Connecting to %s, no response yet, retrying: le is %lx\n", debugstr_w(pipefn), GetLastError());
768                 Sleep(1000);
769             }
770             continue;
771         }
772         bufferlen = 0;
773         if (!ReadFile(hPipe,marshalbuffer,sizeof(marshalbuffer),&bufferlen,NULL)) {
774             FIXME("Failed to read marshal id from classfactory of %s.\n",debugstr_guid(rclsid));
775             Sleep(1000);
776             continue;
777         }
778         TRACE("read marshal id from pipe\n");
779         CloseHandle(hPipe);
780         break;
781     }
782     
783     if (tries >= MAXTRIES)
784         return E_NOINTERFACE;
785     
786     hres = CreateStreamOnHGlobal(0,TRUE,&pStm);
787     if (hres) return hres;
788     hres = IStream_Write(pStm,marshalbuffer,bufferlen,&res);
789     if (hres) goto out;
790     seekto.u.LowPart = 0;seekto.u.HighPart = 0;
791     hres = IStream_Seek(pStm,seekto,SEEK_SET,&newpos);
792     
793     TRACE("unmarshalling classfactory\n");
794     hres = CoUnmarshalInterface(pStm,&IID_IClassFactory,ppv);
795 out:
796     IStream_Release(pStm);
797     return hres;
798 }
799
800
801 struct local_server_params
802 {
803     CLSID clsid;
804     IStream *stream;
805 };
806
807 /* FIXME: should call to rpcss instead */
808 static DWORD WINAPI local_server_thread(LPVOID param)
809 {
810     struct local_server_params * lsp = (struct local_server_params *)param;
811     HANDLE              hPipe;
812     WCHAR               pipefn[100];
813     HRESULT             hres;
814     IStream             *pStm = lsp->stream;
815     STATSTG             ststg;
816     unsigned char       *buffer;
817     int                 buflen;
818     LARGE_INTEGER       seekto;
819     ULARGE_INTEGER      newpos;
820     ULONG               res;
821
822     TRACE("Starting threader for %s.\n",debugstr_guid(&lsp->clsid));
823
824     get_localserver_pipe_name(pipefn, &lsp->clsid);
825
826     HeapFree(GetProcessHeap(), 0, lsp);
827
828     hPipe = CreateNamedPipeW( pipefn, PIPE_ACCESS_DUPLEX,
829                               PIPE_TYPE_BYTE|PIPE_WAIT, PIPE_UNLIMITED_INSTANCES,
830                               4096, 4096, 500 /* 0.5 second timeout */, NULL );
831     
832     if (hPipe == INVALID_HANDLE_VALUE)
833     {
834         FIXME("pipe creation failed for %s, le is %ld\n", debugstr_w(pipefn), GetLastError());
835         return 1;
836     }
837     
838     while (1) {
839         if (!ConnectNamedPipe(hPipe,NULL)) {
840             ERR("Failure during ConnectNamedPipe %ld, ABORT!\n",GetLastError());
841             break;
842         }
843
844         TRACE("marshalling IClassFactory to client\n");
845         
846         hres = IStream_Stat(pStm,&ststg,0);
847         if (hres) return hres;
848
849         buflen = ststg.cbSize.u.LowPart;
850         buffer = HeapAlloc(GetProcessHeap(),0,buflen);
851         seekto.u.LowPart = 0;
852         seekto.u.HighPart = 0;
853         hres = IStream_Seek(pStm,seekto,SEEK_SET,&newpos);
854         if (hres) {
855             FIXME("IStream_Seek failed, %lx\n",hres);
856             return hres;
857         }
858         
859         hres = IStream_Read(pStm,buffer,buflen,&res);
860         if (hres) {
861             FIXME("Stream Read failed, %lx\n",hres);
862             return hres;
863         }
864         
865         WriteFile(hPipe,buffer,buflen,&res,NULL);
866         FlushFileBuffers(hPipe);
867         DisconnectNamedPipe(hPipe);
868
869         TRACE("done marshalling IClassFactory\n");
870     }
871     CloseHandle(hPipe);
872     IStream_Release(pStm);
873     return 0;
874 }
875
876 void RPC_StartLocalServer(REFCLSID clsid, IStream *stream)
877 {
878     DWORD tid;
879     HANDLE thread;
880     struct local_server_params *lsp = HeapAlloc(GetProcessHeap(), 0, sizeof(*lsp));
881
882     lsp->clsid = *clsid;
883     lsp->stream = stream;
884
885     thread = CreateThread(NULL, 0, local_server_thread, lsp, 0, &tid);
886     CloseHandle(thread);
887     /* FIXME: failure handling */
888 }