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