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