ole32: Register the CLSID_Picture_Metafile and CLSID_Picture_Dib ProgIDs.
[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=%ld\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%08lx...\n", apt->tid);
298
299         if (!PostMessageW(apartment_getwindow(apt), DM_EXECUTERPC, 0, (LPARAM)params))
300         {
301             ERR("PostMessage failed with error %ld\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 %lx\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%08lx\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         return RpcRaiseException(hr);
551     }
552
553     params->msg = (RPCOLEMESSAGE *)msg;
554     params->status = RPC_S_OK;
555     params->hr = S_OK;
556     params->handle = NULL;
557
558     /* Note: this is the important difference between STAs and MTAs - we
559      * always execute RPCs to STAs in the thread that originally created the
560      * apartment (i.e. the one that pumps messages to the window) */
561     if (!apt->multi_threaded)
562     {
563         params->handle = CreateEventW(NULL, FALSE, FALSE, NULL);
564
565         TRACE("Calling apartment thread 0x%08lx...\n", apt->tid);
566
567         if (PostMessageW(apartment_getwindow(apt), DM_EXECUTERPC, 0, (LPARAM)params))
568             WaitForSingleObject(params->handle, INFINITE);
569         else
570         {
571             ERR("PostMessage failed with error %ld\n", GetLastError());
572             IRpcChannelBuffer_Release(params->chan);
573             IRpcStubBuffer_Release(params->stub);
574         }
575         CloseHandle(params->handle);
576     }
577     else
578     {
579         BOOL joined = FALSE;
580         if (!COM_CurrentInfo()->apt)
581         {
582             apartment_joinmta();
583             joined = TRUE;
584         }
585         RPC_ExecuteCall(params);
586         if (joined)
587         {
588             apartment_release(COM_CurrentInfo()->apt);
589             COM_CurrentInfo()->apt = NULL;
590         }
591     }
592
593     hr = params->hr;
594     HeapFree(GetProcessHeap(), 0, params);
595
596     apartment_release(apt);
597
598     /* if IRpcStubBuffer_Invoke fails, we should raise an exception to tell
599      * the RPC runtime that the call failed */
600     if (hr) RpcRaiseException(hr);
601 }
602
603 /* stub registration */
604 HRESULT RPC_RegisterInterface(REFIID riid)
605 {
606     struct registered_if *rif;
607     BOOL found = FALSE;
608     HRESULT hr = S_OK;
609     
610     TRACE("(%s)\n", debugstr_guid(riid));
611
612     EnterCriticalSection(&csRegIf);
613     LIST_FOR_EACH_ENTRY(rif, &registered_interfaces, struct registered_if, entry)
614     {
615         if (IsEqualGUID(&rif->If.InterfaceId.SyntaxGUID, riid))
616         {
617             rif->refs++;
618             found = TRUE;
619             break;
620         }
621     }
622     if (!found)
623     {
624         TRACE("Creating new interface\n");
625
626         rif = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*rif));
627         if (rif)
628         {
629             RPC_STATUS status;
630
631             rif->refs = 1;
632             rif->If.Length = sizeof(RPC_SERVER_INTERFACE);
633             /* RPC interface ID = COM interface ID */
634             rif->If.InterfaceId.SyntaxGUID = *riid;
635             rif->If.DispatchTable = &rpc_dispatch;
636             /* all other fields are 0, including the version asCOM objects
637              * always have a version of 0.0 */
638             status = RpcServerRegisterIfEx(
639                 (RPC_IF_HANDLE)&rif->If,
640                 NULL, NULL,
641                 RPC_IF_OLE | RPC_IF_AUTOLISTEN,
642                 RPC_C_LISTEN_MAX_CALLS_DEFAULT,
643                 NULL);
644             if (status == RPC_S_OK)
645                 list_add_tail(&registered_interfaces, &rif->entry);
646             else
647             {
648                 ERR("RpcServerRegisterIfEx failed with error %ld\n", status);
649                 HeapFree(GetProcessHeap(), 0, rif);
650                 hr = HRESULT_FROM_WIN32(status);
651             }
652         }
653         else
654             hr = E_OUTOFMEMORY;
655     }
656     LeaveCriticalSection(&csRegIf);
657     return hr;
658 }
659
660 /* stub unregistration */
661 void RPC_UnregisterInterface(REFIID riid)
662 {
663     struct registered_if *rif;
664     EnterCriticalSection(&csRegIf);
665     LIST_FOR_EACH_ENTRY(rif, &registered_interfaces, struct registered_if, entry)
666     {
667         if (IsEqualGUID(&rif->If.InterfaceId.SyntaxGUID, riid))
668         {
669             if (!--rif->refs)
670             {
671 #if 0 /* this is a stub in builtin and spams the console with FIXME's */
672                 IID iid = *riid; /* RpcServerUnregisterIf doesn't take const IID */
673                 RpcServerUnregisterIf((RPC_IF_HANDLE)&rif->If, &iid, 0);
674                 list_remove(&rif->entry);
675                 HeapFree(GetProcessHeap(), 0, rif);
676 #endif
677             }
678             break;
679         }
680     }
681     LeaveCriticalSection(&csRegIf);
682 }
683
684 /* make the apartment reachable by other threads and processes and create the
685  * IRemUnknown object */
686 void RPC_StartRemoting(struct apartment *apt)
687 {
688     if (!InterlockedExchange(&apt->remoting_started, TRUE))
689     {
690         WCHAR endpoint[200];
691         RPC_STATUS status;
692
693         get_rpc_endpoint(endpoint, &apt->oxid);
694     
695         status = RpcServerUseProtseqEpW(
696             wszRpcTransport,
697             RPC_C_PROTSEQ_MAX_REQS_DEFAULT,
698             endpoint,
699             NULL);
700         if (status != RPC_S_OK)
701             ERR("Couldn't register endpoint %s\n", debugstr_w(endpoint));
702
703         /* FIXME: move remote unknown exporting into this function */
704     }
705     start_apartment_remote_unknown();
706 }
707
708
709 static HRESULT create_server(REFCLSID rclsid)
710 {
711     static const WCHAR  wszLocalServer32[] = { 'L','o','c','a','l','S','e','r','v','e','r','3','2',0 };
712     static const WCHAR  embedding[] = { ' ', '-','E','m','b','e','d','d','i','n','g',0 };
713     HKEY                key;
714     HRESULT             hres;
715     WCHAR               command[MAX_PATH+sizeof(embedding)/sizeof(WCHAR)];
716     DWORD               size = (MAX_PATH+1) * sizeof(WCHAR);
717     STARTUPINFOW        sinfo;
718     PROCESS_INFORMATION pinfo;
719
720     hres = COM_OpenKeyForCLSID(rclsid, wszLocalServer32, KEY_READ, &key);
721     if (FAILED(hres)) {
722         ERR("class %s not registered\n", debugstr_guid(rclsid));
723         return hres;
724     }
725
726     hres = RegQueryValueExW(key, NULL, NULL, NULL, (LPBYTE)command, &size);
727     RegCloseKey(key);
728     if (hres) {
729         WARN("No default value for LocalServer32 key\n");
730         return REGDB_E_CLASSNOTREG; /* FIXME: check retval */
731     }
732
733     memset(&sinfo,0,sizeof(sinfo));
734     sinfo.cb = sizeof(sinfo);
735
736     /* EXE servers are started with the -Embedding switch. */
737
738     strcatW(command, embedding);
739
740     TRACE("activating local server %s for %s\n", debugstr_w(command), debugstr_guid(rclsid));
741
742     /* FIXME: Win2003 supports a ServerExecutable value that is passed into
743      * CreateProcess */
744     if (!CreateProcessW(NULL, command, NULL, NULL, FALSE, 0, NULL, NULL, &sinfo, &pinfo)) {
745         WARN("failed to run local server %s\n", debugstr_w(command));
746         return HRESULT_FROM_WIN32(GetLastError());
747     }
748     CloseHandle(pinfo.hProcess);
749     CloseHandle(pinfo.hThread);
750
751     return S_OK;
752 }
753
754 /*
755  * start_local_service()  - start a service given its name and parameters
756  */
757 static DWORD start_local_service(LPCWSTR name, DWORD num, LPCWSTR *params)
758 {
759     SC_HANDLE handle, hsvc;
760     DWORD     r = ERROR_FUNCTION_FAILED;
761
762     TRACE("Starting service %s %ld params\n", debugstr_w(name), num);
763
764     handle = OpenSCManagerW(NULL, NULL, SC_MANAGER_CONNECT);
765     if (!handle)
766         return r;
767     hsvc = OpenServiceW(handle, name, SERVICE_START);
768     if (hsvc)
769     {
770         if(StartServiceW(hsvc, num, params))
771             r = ERROR_SUCCESS;
772         else
773             r = GetLastError();
774         if (r == ERROR_SERVICE_ALREADY_RUNNING)
775             r = ERROR_SUCCESS;
776         CloseServiceHandle(hsvc);
777     }
778     else
779         r = GetLastError();
780     CloseServiceHandle(handle);
781
782     TRACE("StartService returned error %ld (%s)\n", r, (r == ERROR_SUCCESS) ? "ok":"failed");
783
784     return r;
785 }
786
787 /*
788  * create_local_service()  - start a COM server in a service
789  *
790  *   To start a Local Service, we read the AppID value under
791  * the class's CLSID key, then open the HKCR\\AppId key specified
792  * there and check for a LocalService value.
793  *
794  * Note:  Local Services are not supported under Windows 9x
795  */
796 static HRESULT create_local_service(REFCLSID rclsid)
797 {
798     HRESULT hres;
799     WCHAR buf[CHARS_IN_GUID], keyname[50];
800     static const WCHAR szAppId[] = { 'A','p','p','I','d',0 };
801     static const WCHAR szAppIdKey[] = { 'A','p','p','I','d','\\',0 };
802     static const WCHAR szLocalService[] = { 'L','o','c','a','l','S','e','r','v','i','c','e',0 };
803     static const WCHAR szServiceParams[] = {'S','e','r','v','i','c','e','P','a','r','a','m','s',0};
804     HKEY hkey;
805     LONG r;
806     DWORD type, sz;
807
808     TRACE("Attempting to start Local service for %s\n", debugstr_guid(rclsid));
809
810     /* read the AppID value under the class's key */
811     hres = COM_OpenKeyForCLSID(rclsid, szAppId, KEY_READ, &hkey);
812     if (FAILED(hres))
813         return hres;
814     sz = sizeof buf;
815     r = RegQueryValueExW(hkey, NULL, NULL, &type, (LPBYTE)buf, &sz);
816     RegCloseKey(hkey);
817     if (r!=ERROR_SUCCESS || type!=REG_SZ)
818         return hres;
819
820     /* read the LocalService and ServiceParameters values from the AppID key */
821     strcpyW(keyname, szAppIdKey);
822     strcatW(keyname, buf);
823     r = RegOpenKeyExW(HKEY_CLASSES_ROOT, keyname, 0, KEY_READ, &hkey);
824     if (r!=ERROR_SUCCESS)
825         return hres;
826     sz = sizeof buf;
827     r = RegQueryValueExW(hkey, szLocalService, NULL, &type, (LPBYTE)buf, &sz);
828     if (r==ERROR_SUCCESS && type==REG_SZ)
829     {
830         DWORD num_args = 0;
831         LPWSTR args[1] = { NULL };
832
833         /*
834          * FIXME: I'm not really sure how to deal with the service parameters.
835          *        I suspect that the string returned from RegQueryValueExW
836          *        should be split into a number of arguments by spaces.
837          *        It would make more sense if ServiceParams contained a
838          *        REG_MULTI_SZ here, but it's a REG_SZ for the services
839          *        that I'm interested in for the moment.
840          */
841         r = RegQueryValueExW(hkey, szServiceParams, NULL, &type, NULL, &sz);
842         if (r == ERROR_SUCCESS && type == REG_SZ && sz)
843         {
844             args[0] = HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY,sz);
845             num_args++;
846             RegQueryValueExW(hkey, szServiceParams, NULL, &type, (LPBYTE)args[0], &sz);
847         }
848         r = start_local_service(buf, num_args, (LPCWSTR *)args);
849         if (r==ERROR_SUCCESS)
850             hres = S_OK;
851         HeapFree(GetProcessHeap(),0,args[0]);
852     }
853     RegCloseKey(hkey);
854         
855     return hres;
856 }
857
858
859 static void get_localserver_pipe_name(WCHAR *pipefn, REFCLSID rclsid)
860 {
861     static const WCHAR wszPipeRef[] = {'\\','\\','.','\\','p','i','p','e','\\',0};
862     strcpyW(pipefn, wszPipeRef);
863     StringFromGUID2(rclsid, pipefn + sizeof(wszPipeRef)/sizeof(wszPipeRef[0]) - 1, CHARS_IN_GUID);
864 }
865
866 /* FIXME: should call to rpcss instead */
867 HRESULT RPC_GetLocalClassObject(REFCLSID rclsid, REFIID iid, LPVOID *ppv)
868 {
869     HRESULT        hres;
870     HANDLE         hPipe;
871     WCHAR          pipefn[100];
872     DWORD          res, bufferlen;
873     char           marshalbuffer[200];
874     IStream       *pStm;
875     LARGE_INTEGER  seekto;
876     ULARGE_INTEGER newpos;
877     int            tries = 0;
878
879     static const int MAXTRIES = 30; /* 30 seconds */
880
881     TRACE("rclsid=%s, iid=%s\n", debugstr_guid(rclsid), debugstr_guid(iid));
882
883     get_localserver_pipe_name(pipefn, rclsid);
884
885     while (tries++ < MAXTRIES) {
886         TRACE("waiting for %s\n", debugstr_w(pipefn));
887       
888         WaitNamedPipeW( pipefn, NMPWAIT_WAIT_FOREVER );
889         hPipe = CreateFileW(pipefn, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, 0);
890         if (hPipe == INVALID_HANDLE_VALUE) {
891             if (tries == 1) {
892                 if ( (hres = create_local_service(rclsid)) &&
893                      (hres = create_server(rclsid)) )
894                     return hres;
895                 Sleep(1000);
896             } else {
897                 WARN("Connecting to %s, no response yet, retrying: le is %lx\n", debugstr_w(pipefn), GetLastError());
898                 Sleep(1000);
899             }
900             continue;
901         }
902         bufferlen = 0;
903         if (!ReadFile(hPipe,marshalbuffer,sizeof(marshalbuffer),&bufferlen,NULL)) {
904             FIXME("Failed to read marshal id from classfactory of %s.\n",debugstr_guid(rclsid));
905             Sleep(1000);
906             continue;
907         }
908         TRACE("read marshal id from pipe\n");
909         CloseHandle(hPipe);
910         break;
911     }
912     
913     if (tries >= MAXTRIES)
914         return E_NOINTERFACE;
915     
916     hres = CreateStreamOnHGlobal(0,TRUE,&pStm);
917     if (hres) return hres;
918     hres = IStream_Write(pStm,marshalbuffer,bufferlen,&res);
919     if (hres) goto out;
920     seekto.u.LowPart = 0;seekto.u.HighPart = 0;
921     hres = IStream_Seek(pStm,seekto,SEEK_SET,&newpos);
922     
923     TRACE("unmarshalling classfactory\n");
924     hres = CoUnmarshalInterface(pStm,&IID_IClassFactory,ppv);
925 out:
926     IStream_Release(pStm);
927     return hres;
928 }
929
930
931 struct local_server_params
932 {
933     CLSID clsid;
934     IStream *stream;
935 };
936
937 /* FIXME: should call to rpcss instead */
938 static DWORD WINAPI local_server_thread(LPVOID param)
939 {
940     struct local_server_params * lsp = (struct local_server_params *)param;
941     HANDLE              hPipe;
942     WCHAR               pipefn[100];
943     HRESULT             hres;
944     IStream             *pStm = lsp->stream;
945     STATSTG             ststg;
946     unsigned char       *buffer;
947     int                 buflen;
948     LARGE_INTEGER       seekto;
949     ULARGE_INTEGER      newpos;
950     ULONG               res;
951
952     TRACE("Starting threader for %s.\n",debugstr_guid(&lsp->clsid));
953
954     get_localserver_pipe_name(pipefn, &lsp->clsid);
955
956     HeapFree(GetProcessHeap(), 0, lsp);
957
958     hPipe = CreateNamedPipeW( pipefn, PIPE_ACCESS_DUPLEX,
959                               PIPE_TYPE_BYTE|PIPE_WAIT, PIPE_UNLIMITED_INSTANCES,
960                               4096, 4096, 500 /* 0.5 second timeout */, NULL );
961     
962     if (hPipe == INVALID_HANDLE_VALUE)
963     {
964         FIXME("pipe creation failed for %s, le is %ld\n", debugstr_w(pipefn), GetLastError());
965         return 1;
966     }
967     
968     while (1) {
969         if (!ConnectNamedPipe(hPipe,NULL)) {
970             ERR("Failure during ConnectNamedPipe %ld, ABORT!\n",GetLastError());
971             break;
972         }
973
974         TRACE("marshalling IClassFactory to client\n");
975         
976         hres = IStream_Stat(pStm,&ststg,0);
977         if (hres) return hres;
978
979         seekto.u.LowPart = 0;
980         seekto.u.HighPart = 0;
981         hres = IStream_Seek(pStm,seekto,SEEK_SET,&newpos);
982         if (hres) {
983             FIXME("IStream_Seek failed, %lx\n",hres);
984             return hres;
985         }
986
987         buflen = ststg.cbSize.u.LowPart;
988         buffer = HeapAlloc(GetProcessHeap(),0,buflen);
989         
990         hres = IStream_Read(pStm,buffer,buflen,&res);
991         if (hres) {
992             FIXME("Stream Read failed, %lx\n",hres);
993             HeapFree(GetProcessHeap(),0,buffer);
994             return hres;
995         }
996         
997         WriteFile(hPipe,buffer,buflen,&res,NULL);
998         HeapFree(GetProcessHeap(),0,buffer);
999
1000         FlushFileBuffers(hPipe);
1001         DisconnectNamedPipe(hPipe);
1002
1003         TRACE("done marshalling IClassFactory\n");
1004     }
1005     CloseHandle(hPipe);
1006     IStream_Release(pStm);
1007     return 0;
1008 }
1009
1010 void RPC_StartLocalServer(REFCLSID clsid, IStream *stream)
1011 {
1012     DWORD tid;
1013     HANDLE thread;
1014     struct local_server_params *lsp = HeapAlloc(GetProcessHeap(), 0, sizeof(*lsp));
1015
1016     lsp->clsid = *clsid;
1017     lsp->stream = stream;
1018
1019     thread = CreateThread(NULL, 0, local_server_thread, lsp, 0, &tid);
1020     CloseHandle(thread);
1021     /* FIXME: failure handling */
1022 }