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