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