* Sync up to trunk head (r60691).
[reactos.git] / dll / win32 / ole32 / rpc.c
1 /*
2 * RPC Manager
3 *
4 * Copyright 2001 Ove Kåven, TransGaming Technologies
5 * Copyright 2002 Marcus Meissner
6 * Copyright 2005 Mike Hearn, Rob Shearman for CodeWeavers
7 *
8 * This library is free software; you can redistribute it and/or
9 * modify it under the terms of the GNU Lesser General Public
10 * License as published by the Free Software Foundation; either
11 * version 2.1 of the License, or (at your option) any later version.
12 *
13 * This library is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 * Lesser General Public License for more details.
17 *
18 * You should have received a copy of the GNU Lesser General Public
19 * License along with this library; if not, write to the Free Software
20 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
21 */
22
23 #define WIN32_NO_STATUS
24 #define _INC_WINDOWS
25
26 #include <config.h>
27 //#include "wine/port.h"
28
29 #include <stdarg.h>
30 //#include <string.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 <servprov.h>
46 #include <wine/unicode.h>
47
48 #include "compobj_private.h"
49
50 #include <wine/debug.h>
51
52 WINE_DEFAULT_DEBUG_CHANNEL(ole);
53
54 static void __RPC_STUB dispatch_rpc(RPC_MESSAGE *msg);
55
56 /* we only use one function to dispatch calls for all methods - we use the
57 * RPC_IF_OLE flag to tell the RPC runtime that this is the case */
58 static RPC_DISPATCH_FUNCTION rpc_dispatch_table[1] = { dispatch_rpc }; /* (RO) */
59 static RPC_DISPATCH_TABLE rpc_dispatch = { 1, rpc_dispatch_table }; /* (RO) */
60
61 static struct list registered_interfaces = LIST_INIT(registered_interfaces); /* (CS csRegIf) */
62 static CRITICAL_SECTION csRegIf;
63 static CRITICAL_SECTION_DEBUG csRegIf_debug =
64 {
65 0, 0, &csRegIf,
66 { &csRegIf_debug.ProcessLocksList, &csRegIf_debug.ProcessLocksList },
67 0, 0, { (DWORD_PTR)(__FILE__ ": dcom registered server interfaces") }
68 };
69 static CRITICAL_SECTION csRegIf = { &csRegIf_debug, -1, 0, 0, 0, 0 };
70
71 static struct list channel_hooks = LIST_INIT(channel_hooks); /* (CS csChannelHook) */
72 static CRITICAL_SECTION csChannelHook;
73 static CRITICAL_SECTION_DEBUG csChannelHook_debug =
74 {
75 0, 0, &csChannelHook,
76 { &csChannelHook_debug.ProcessLocksList, &csChannelHook_debug.ProcessLocksList },
77 0, 0, { (DWORD_PTR)(__FILE__ ": channel hooks") }
78 };
79 static CRITICAL_SECTION csChannelHook = { &csChannelHook_debug, -1, 0, 0, 0, 0 };
80
81 static WCHAR wszRpcTransport[] = {'n','c','a','l','r','p','c',0};
82
83
84 struct registered_if
85 {
86 struct list entry;
87 DWORD refs; /* ref count */
88 RPC_SERVER_INTERFACE If; /* interface registered with the RPC runtime */
89 };
90
91 /* get the pipe endpoint specified of the specified apartment */
92 static inline void get_rpc_endpoint(LPWSTR endpoint, const OXID *oxid)
93 {
94 /* FIXME: should get endpoint from rpcss */
95 static const WCHAR wszEndpointFormat[] = {'\\','p','i','p','e','\\','O','L','E','_','%','0','8','l','x','%','0','8','l','x',0};
96 wsprintfW(endpoint, wszEndpointFormat, (DWORD)(*oxid >> 32),(DWORD)*oxid);
97 }
98
99 typedef struct
100 {
101 IRpcChannelBuffer IRpcChannelBuffer_iface;
102 LONG refs;
103
104 DWORD dest_context; /* returned from GetDestCtx */
105 void *dest_context_data; /* returned from GetDestCtx */
106 } RpcChannelBuffer;
107
108 typedef struct
109 {
110 RpcChannelBuffer super; /* superclass */
111
112 RPC_BINDING_HANDLE bind; /* handle to the remote server */
113 OXID oxid; /* apartment in which the channel is valid */
114 DWORD server_pid; /* id of server process */
115 HANDLE event; /* cached event handle */
116 } ClientRpcChannelBuffer;
117
118 struct dispatch_params
119 {
120 RPCOLEMESSAGE *msg; /* message */
121 IRpcStubBuffer *stub; /* stub buffer, if applicable */
122 IRpcChannelBuffer *chan; /* server channel buffer, if applicable */
123 IID iid; /* ID of interface being called */
124 IUnknown *iface; /* interface being called */
125 HANDLE handle; /* handle that will become signaled when call finishes */
126 BOOL bypass_rpcrt; /* bypass RPC runtime? */
127 RPC_STATUS status; /* status (out) */
128 HRESULT hr; /* hresult (out) */
129 };
130
131 struct message_state
132 {
133 RPC_BINDING_HANDLE binding_handle;
134 ULONG prefix_data_len;
135 SChannelHookCallInfo channel_hook_info;
136 BOOL bypass_rpcrt;
137
138 /* client only */
139 HWND target_hwnd;
140 DWORD target_tid;
141 struct dispatch_params params;
142 };
143
144 typedef struct
145 {
146 ULONG conformance; /* NDR */
147 GUID id;
148 ULONG size;
149 /* [size_is((size+7)&~7)] */ unsigned char data[1];
150 } WIRE_ORPC_EXTENT;
151
152 typedef struct
153 {
154 ULONG size;
155 ULONG reserved;
156 unsigned char extent[1];
157 } WIRE_ORPC_EXTENT_ARRAY;
158
159 typedef struct
160 {
161 ULONG version;
162 ULONG flags;
163 ULONG reserved1;
164 GUID cid;
165 unsigned char extensions[1];
166 } WIRE_ORPCTHIS;
167
168 typedef struct
169 {
170 ULONG flags;
171 unsigned char extensions[1];
172 } WIRE_ORPCTHAT;
173
174 struct channel_hook_entry
175 {
176 struct list entry;
177 GUID id;
178 IChannelHook *hook;
179 };
180
181 struct channel_hook_buffer_data
182 {
183 GUID id;
184 ULONG extension_size;
185 };
186
187
188 static HRESULT unmarshal_ORPCTHAT(RPC_MESSAGE *msg, ORPCTHAT *orpcthat,
189 ORPC_EXTENT_ARRAY *orpc_ext_array, WIRE_ORPC_EXTENT **first_wire_orpc_extent);
190
191 /* Channel Hook Functions */
192
193 static ULONG ChannelHooks_ClientGetSize(SChannelHookCallInfo *info,
194 struct channel_hook_buffer_data **data, unsigned int *hook_count,
195 ULONG *extension_count)
196 {
197 struct channel_hook_entry *entry;
198 ULONG total_size = 0;
199 unsigned int hook_index = 0;
200
201 *hook_count = 0;
202 *extension_count = 0;
203
204 EnterCriticalSection(&csChannelHook);
205
206 LIST_FOR_EACH_ENTRY(entry, &channel_hooks, struct channel_hook_entry, entry)
207 (*hook_count)++;
208
209 if (*hook_count)
210 *data = HeapAlloc(GetProcessHeap(), 0, *hook_count * sizeof(struct channel_hook_buffer_data));
211 else
212 *data = NULL;
213
214 LIST_FOR_EACH_ENTRY(entry, &channel_hooks, struct channel_hook_entry, entry)
215 {
216 ULONG extension_size = 0;
217
218 IChannelHook_ClientGetSize(entry->hook, &entry->id, &info->iid, &extension_size);
219
220 TRACE("%s: extension_size = %u\n", debugstr_guid(&entry->id), extension_size);
221
222 extension_size = (extension_size+7)&~7;
223 (*data)[hook_index].id = entry->id;
224 (*data)[hook_index].extension_size = extension_size;
225
226 /* an extension is only put onto the wire if it has data to write */
227 if (extension_size)
228 {
229 total_size += FIELD_OFFSET(WIRE_ORPC_EXTENT, data[extension_size]);
230 (*extension_count)++;
231 }
232
233 hook_index++;
234 }
235
236 LeaveCriticalSection(&csChannelHook);
237
238 return total_size;
239 }
240
241 static unsigned char * ChannelHooks_ClientFillBuffer(SChannelHookCallInfo *info,
242 unsigned char *buffer, struct channel_hook_buffer_data *data,
243 unsigned int hook_count)
244 {
245 struct channel_hook_entry *entry;
246
247 EnterCriticalSection(&csChannelHook);
248
249 LIST_FOR_EACH_ENTRY(entry, &channel_hooks, struct channel_hook_entry, entry)
250 {
251 unsigned int i;
252 ULONG extension_size = 0;
253 WIRE_ORPC_EXTENT *wire_orpc_extent = (WIRE_ORPC_EXTENT *)buffer;
254
255 for (i = 0; i < hook_count; i++)
256 if (IsEqualGUID(&entry->id, &data[i].id))
257 extension_size = data[i].extension_size;
258
259 /* an extension is only put onto the wire if it has data to write */
260 if (!extension_size)
261 continue;
262
263 IChannelHook_ClientFillBuffer(entry->hook, &entry->id, &info->iid,
264 &extension_size, buffer + FIELD_OFFSET(WIRE_ORPC_EXTENT, data[0]));
265
266 TRACE("%s: extension_size = %u\n", debugstr_guid(&entry->id), extension_size);
267
268 /* FIXME: set unused portion of wire_orpc_extent->data to 0? */
269
270 wire_orpc_extent->conformance = (extension_size+7)&~7;
271 wire_orpc_extent->size = extension_size;
272 wire_orpc_extent->id = entry->id;
273 buffer += FIELD_OFFSET(WIRE_ORPC_EXTENT, data[wire_orpc_extent->conformance]);
274 }
275
276 LeaveCriticalSection(&csChannelHook);
277
278 return buffer;
279 }
280
281 static void ChannelHooks_ServerNotify(SChannelHookCallInfo *info,
282 DWORD lDataRep, WIRE_ORPC_EXTENT *first_wire_orpc_extent,
283 ULONG extension_count)
284 {
285 struct channel_hook_entry *entry;
286 ULONG i;
287
288 EnterCriticalSection(&csChannelHook);
289
290 LIST_FOR_EACH_ENTRY(entry, &channel_hooks, struct channel_hook_entry, entry)
291 {
292 WIRE_ORPC_EXTENT *wire_orpc_extent;
293 for (i = 0, wire_orpc_extent = first_wire_orpc_extent;
294 i < extension_count;
295 i++, wire_orpc_extent = (WIRE_ORPC_EXTENT *)&wire_orpc_extent->data[wire_orpc_extent->conformance])
296 {
297 if (IsEqualGUID(&entry->id, &wire_orpc_extent->id))
298 break;
299 }
300 if (i == extension_count) wire_orpc_extent = NULL;
301
302 IChannelHook_ServerNotify(entry->hook, &entry->id, &info->iid,
303 wire_orpc_extent ? wire_orpc_extent->size : 0,
304 wire_orpc_extent ? wire_orpc_extent->data : NULL,
305 lDataRep);
306 }
307
308 LeaveCriticalSection(&csChannelHook);
309 }
310
311 static ULONG ChannelHooks_ServerGetSize(SChannelHookCallInfo *info,
312 struct channel_hook_buffer_data **data, unsigned int *hook_count,
313 ULONG *extension_count)
314 {
315 struct channel_hook_entry *entry;
316 ULONG total_size = 0;
317 unsigned int hook_index = 0;
318
319 *hook_count = 0;
320 *extension_count = 0;
321
322 EnterCriticalSection(&csChannelHook);
323
324 LIST_FOR_EACH_ENTRY(entry, &channel_hooks, struct channel_hook_entry, entry)
325 (*hook_count)++;
326
327 if (*hook_count)
328 *data = HeapAlloc(GetProcessHeap(), 0, *hook_count * sizeof(struct channel_hook_buffer_data));
329 else
330 *data = NULL;
331
332 LIST_FOR_EACH_ENTRY(entry, &channel_hooks, struct channel_hook_entry, entry)
333 {
334 ULONG extension_size = 0;
335
336 IChannelHook_ServerGetSize(entry->hook, &entry->id, &info->iid, S_OK,
337 &extension_size);
338
339 TRACE("%s: extension_size = %u\n", debugstr_guid(&entry->id), extension_size);
340
341 extension_size = (extension_size+7)&~7;
342 (*data)[hook_index].id = entry->id;
343 (*data)[hook_index].extension_size = extension_size;
344
345 /* an extension is only put onto the wire if it has data to write */
346 if (extension_size)
347 {
348 total_size += FIELD_OFFSET(WIRE_ORPC_EXTENT, data[extension_size]);
349 (*extension_count)++;
350 }
351
352 hook_index++;
353 }
354
355 LeaveCriticalSection(&csChannelHook);
356
357 return total_size;
358 }
359
360 static unsigned char * ChannelHooks_ServerFillBuffer(SChannelHookCallInfo *info,
361 unsigned char *buffer, struct channel_hook_buffer_data *data,
362 unsigned int hook_count)
363 {
364 struct channel_hook_entry *entry;
365
366 EnterCriticalSection(&csChannelHook);
367
368 LIST_FOR_EACH_ENTRY(entry, &channel_hooks, struct channel_hook_entry, entry)
369 {
370 unsigned int i;
371 ULONG extension_size = 0;
372 WIRE_ORPC_EXTENT *wire_orpc_extent = (WIRE_ORPC_EXTENT *)buffer;
373
374 for (i = 0; i < hook_count; i++)
375 if (IsEqualGUID(&entry->id, &data[i].id))
376 extension_size = data[i].extension_size;
377
378 /* an extension is only put onto the wire if it has data to write */
379 if (!extension_size)
380 continue;
381
382 IChannelHook_ServerFillBuffer(entry->hook, &entry->id, &info->iid,
383 &extension_size, buffer + FIELD_OFFSET(WIRE_ORPC_EXTENT, data[0]),
384 S_OK);
385
386 TRACE("%s: extension_size = %u\n", debugstr_guid(&entry->id), extension_size);
387
388 /* FIXME: set unused portion of wire_orpc_extent->data to 0? */
389
390 wire_orpc_extent->conformance = (extension_size+7)&~7;
391 wire_orpc_extent->size = extension_size;
392 wire_orpc_extent->id = entry->id;
393 buffer += FIELD_OFFSET(WIRE_ORPC_EXTENT, data[wire_orpc_extent->conformance]);
394 }
395
396 LeaveCriticalSection(&csChannelHook);
397
398 return buffer;
399 }
400
401 static void ChannelHooks_ClientNotify(SChannelHookCallInfo *info,
402 DWORD lDataRep, WIRE_ORPC_EXTENT *first_wire_orpc_extent,
403 ULONG extension_count, HRESULT hrFault)
404 {
405 struct channel_hook_entry *entry;
406 ULONG i;
407
408 EnterCriticalSection(&csChannelHook);
409
410 LIST_FOR_EACH_ENTRY(entry, &channel_hooks, struct channel_hook_entry, entry)
411 {
412 WIRE_ORPC_EXTENT *wire_orpc_extent;
413 for (i = 0, wire_orpc_extent = first_wire_orpc_extent;
414 i < extension_count;
415 i++, wire_orpc_extent = (WIRE_ORPC_EXTENT *)&wire_orpc_extent->data[wire_orpc_extent->conformance])
416 {
417 if (IsEqualGUID(&entry->id, &wire_orpc_extent->id))
418 break;
419 }
420 if (i == extension_count) wire_orpc_extent = NULL;
421
422 IChannelHook_ClientNotify(entry->hook, &entry->id, &info->iid,
423 wire_orpc_extent ? wire_orpc_extent->size : 0,
424 wire_orpc_extent ? wire_orpc_extent->data : NULL,
425 lDataRep, hrFault);
426 }
427
428 LeaveCriticalSection(&csChannelHook);
429 }
430
431 HRESULT RPC_RegisterChannelHook(REFGUID rguid, IChannelHook *hook)
432 {
433 struct channel_hook_entry *entry;
434
435 TRACE("(%s, %p)\n", debugstr_guid(rguid), hook);
436
437 entry = HeapAlloc(GetProcessHeap(), 0, sizeof(*entry));
438 if (!entry)
439 return E_OUTOFMEMORY;
440
441 entry->id = *rguid;
442 entry->hook = hook;
443 IChannelHook_AddRef(hook);
444
445 EnterCriticalSection(&csChannelHook);
446 list_add_tail(&channel_hooks, &entry->entry);
447 LeaveCriticalSection(&csChannelHook);
448
449 return S_OK;
450 }
451
452 void RPC_UnregisterAllChannelHooks(void)
453 {
454 struct channel_hook_entry *cursor;
455 struct channel_hook_entry *cursor2;
456
457 EnterCriticalSection(&csChannelHook);
458 LIST_FOR_EACH_ENTRY_SAFE(cursor, cursor2, &channel_hooks, struct channel_hook_entry, entry)
459 HeapFree(GetProcessHeap(), 0, cursor);
460 LeaveCriticalSection(&csChannelHook);
461 DeleteCriticalSection(&csChannelHook);
462 DeleteCriticalSection(&csRegIf);
463 }
464
465 /* RPC Channel Buffer Functions */
466
467 static HRESULT WINAPI RpcChannelBuffer_QueryInterface(IRpcChannelBuffer *iface, REFIID riid, LPVOID *ppv)
468 {
469 *ppv = NULL;
470 if (IsEqualIID(riid,&IID_IRpcChannelBuffer) || IsEqualIID(riid,&IID_IUnknown))
471 {
472 *ppv = iface;
473 IRpcChannelBuffer_AddRef(iface);
474 return S_OK;
475 }
476 return E_NOINTERFACE;
477 }
478
479 static ULONG WINAPI RpcChannelBuffer_AddRef(LPRPCCHANNELBUFFER iface)
480 {
481 RpcChannelBuffer *This = (RpcChannelBuffer *)iface;
482 return InterlockedIncrement(&This->refs);
483 }
484
485 static ULONG WINAPI ServerRpcChannelBuffer_Release(LPRPCCHANNELBUFFER iface)
486 {
487 RpcChannelBuffer *This = (RpcChannelBuffer *)iface;
488 ULONG ref;
489
490 ref = InterlockedDecrement(&This->refs);
491 if (ref)
492 return ref;
493
494 HeapFree(GetProcessHeap(), 0, This);
495 return 0;
496 }
497
498 static ULONG WINAPI ClientRpcChannelBuffer_Release(LPRPCCHANNELBUFFER iface)
499 {
500 ClientRpcChannelBuffer *This = (ClientRpcChannelBuffer *)iface;
501 ULONG ref;
502
503 ref = InterlockedDecrement(&This->super.refs);
504 if (ref)
505 return ref;
506
507 if (This->event) CloseHandle(This->event);
508 RpcBindingFree(&This->bind);
509 HeapFree(GetProcessHeap(), 0, This);
510 return 0;
511 }
512
513 static HRESULT WINAPI ServerRpcChannelBuffer_GetBuffer(LPRPCCHANNELBUFFER iface, RPCOLEMESSAGE* olemsg, REFIID riid)
514 {
515 RpcChannelBuffer *This = (RpcChannelBuffer *)iface;
516 RPC_MESSAGE *msg = (RPC_MESSAGE *)olemsg;
517 RPC_STATUS status;
518 ORPCTHAT *orpcthat;
519 struct message_state *message_state;
520 ULONG extensions_size;
521 struct channel_hook_buffer_data *channel_hook_data;
522 unsigned int channel_hook_count;
523 ULONG extension_count;
524
525 TRACE("(%p)->(%p,%s)\n", This, olemsg, debugstr_guid(riid));
526
527 message_state = msg->Handle;
528 /* restore the binding handle and the real start of data */
529 msg->Handle = message_state->binding_handle;
530 msg->Buffer = (char *)msg->Buffer - message_state->prefix_data_len;
531
532 extensions_size = ChannelHooks_ServerGetSize(&message_state->channel_hook_info,
533 &channel_hook_data, &channel_hook_count, &extension_count);
534
535 msg->BufferLength += FIELD_OFFSET(WIRE_ORPCTHAT, extensions) + sizeof(DWORD);
536 if (extensions_size)
537 {
538 msg->BufferLength += FIELD_OFFSET(WIRE_ORPC_EXTENT_ARRAY, extent[2*sizeof(DWORD) + extensions_size]);
539 if (extension_count & 1)
540 msg->BufferLength += FIELD_OFFSET(WIRE_ORPC_EXTENT, data[0]);
541 }
542
543 if (message_state->bypass_rpcrt)
544 {
545 msg->Buffer = HeapAlloc(GetProcessHeap(), 0, msg->BufferLength);
546 if (msg->Buffer)
547 status = RPC_S_OK;
548 else
549 {
550 HeapFree(GetProcessHeap(), 0, channel_hook_data);
551 return E_OUTOFMEMORY;
552 }
553 }
554 else
555 status = I_RpcGetBuffer(msg);
556
557 orpcthat = msg->Buffer;
558 msg->Buffer = (char *)msg->Buffer + FIELD_OFFSET(WIRE_ORPCTHAT, extensions);
559
560 orpcthat->flags = ORPCF_NULL /* FIXME? */;
561
562 /* NDR representation of orpcthat->extensions */
563 *(DWORD *)msg->Buffer = extensions_size ? 1 : 0;
564 msg->Buffer = (char *)msg->Buffer + sizeof(DWORD);
565
566 if (extensions_size)
567 {
568 WIRE_ORPC_EXTENT_ARRAY *orpc_extent_array = msg->Buffer;
569 orpc_extent_array->size = extension_count;
570 orpc_extent_array->reserved = 0;
571 msg->Buffer = (char *)msg->Buffer + FIELD_OFFSET(WIRE_ORPC_EXTENT_ARRAY, extent);
572 /* NDR representation of orpc_extent_array->extent */
573 *(DWORD *)msg->Buffer = 1;
574 msg->Buffer = (char *)msg->Buffer + sizeof(DWORD);
575 /* NDR representation of [size_is] attribute of orpc_extent_array->extent */
576 *(DWORD *)msg->Buffer = (extension_count + 1) & ~1;
577 msg->Buffer = (char *)msg->Buffer + sizeof(DWORD);
578
579 msg->Buffer = ChannelHooks_ServerFillBuffer(&message_state->channel_hook_info,
580 msg->Buffer, channel_hook_data, channel_hook_count);
581
582 /* we must add a dummy extension if there is an odd extension
583 * count to meet the contract specified by the size_is attribute */
584 if (extension_count & 1)
585 {
586 WIRE_ORPC_EXTENT *wire_orpc_extent = msg->Buffer;
587 wire_orpc_extent->conformance = 0;
588 wire_orpc_extent->id = GUID_NULL;
589 wire_orpc_extent->size = 0;
590 msg->Buffer = (char *)msg->Buffer + FIELD_OFFSET(WIRE_ORPC_EXTENT, data[0]);
591 }
592 }
593
594 HeapFree(GetProcessHeap(), 0, channel_hook_data);
595
596 /* store the prefixed data length so that we can restore the real buffer
597 * later */
598 message_state->prefix_data_len = (char *)msg->Buffer - (char *)orpcthat;
599 msg->BufferLength -= message_state->prefix_data_len;
600 /* save away the message state again */
601 msg->Handle = message_state;
602
603 TRACE("-- %d\n", status);
604
605 return HRESULT_FROM_WIN32(status);
606 }
607
608 static HANDLE ClientRpcChannelBuffer_GetEventHandle(ClientRpcChannelBuffer *This)
609 {
610 HANDLE event = InterlockedExchangePointer(&This->event, NULL);
611
612 /* Note: must be auto-reset event so we can reuse it without a call
613 * to ResetEvent */
614 if (!event) event = CreateEventW(NULL, FALSE, FALSE, NULL);
615
616 return event;
617 }
618
619 static void ClientRpcChannelBuffer_ReleaseEventHandle(ClientRpcChannelBuffer *This, HANDLE event)
620 {
621 if (InterlockedCompareExchangePointer(&This->event, event, NULL))
622 /* already a handle cached in This */
623 CloseHandle(event);
624 }
625
626 static HRESULT WINAPI ClientRpcChannelBuffer_GetBuffer(LPRPCCHANNELBUFFER iface, RPCOLEMESSAGE* olemsg, REFIID riid)
627 {
628 ClientRpcChannelBuffer *This = (ClientRpcChannelBuffer *)iface;
629 RPC_MESSAGE *msg = (RPC_MESSAGE *)olemsg;
630 RPC_CLIENT_INTERFACE *cif;
631 RPC_STATUS status;
632 ORPCTHIS *orpcthis;
633 struct message_state *message_state;
634 ULONG extensions_size;
635 struct channel_hook_buffer_data *channel_hook_data;
636 unsigned int channel_hook_count;
637 ULONG extension_count;
638 IPID ipid;
639 HRESULT hr;
640 APARTMENT *apt = NULL;
641
642 TRACE("(%p)->(%p,%s)\n", This, olemsg, debugstr_guid(riid));
643
644 cif = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(RPC_CLIENT_INTERFACE));
645 if (!cif)
646 return E_OUTOFMEMORY;
647
648 message_state = HeapAlloc(GetProcessHeap(), 0, sizeof(*message_state));
649 if (!message_state)
650 {
651 HeapFree(GetProcessHeap(), 0, cif);
652 return E_OUTOFMEMORY;
653 }
654
655 cif->Length = sizeof(RPC_CLIENT_INTERFACE);
656 /* RPC interface ID = COM interface ID */
657 cif->InterfaceId.SyntaxGUID = *riid;
658 /* COM objects always have a version of 0.0 */
659 cif->InterfaceId.SyntaxVersion.MajorVersion = 0;
660 cif->InterfaceId.SyntaxVersion.MinorVersion = 0;
661 msg->Handle = This->bind;
662 msg->RpcInterfaceInformation = cif;
663
664 message_state->prefix_data_len = 0;
665 message_state->binding_handle = This->bind;
666
667 message_state->channel_hook_info.iid = *riid;
668 message_state->channel_hook_info.cbSize = sizeof(message_state->channel_hook_info);
669 message_state->channel_hook_info.uCausality = COM_CurrentCausalityId();
670 message_state->channel_hook_info.dwServerPid = This->server_pid;
671 message_state->channel_hook_info.iMethod = msg->ProcNum;
672 message_state->channel_hook_info.pObject = NULL; /* only present on server-side */
673 message_state->target_hwnd = NULL;
674 message_state->target_tid = 0;
675 memset(&message_state->params, 0, sizeof(message_state->params));
676
677 extensions_size = ChannelHooks_ClientGetSize(&message_state->channel_hook_info,
678 &channel_hook_data, &channel_hook_count, &extension_count);
679
680 msg->BufferLength += FIELD_OFFSET(WIRE_ORPCTHIS, extensions) + sizeof(DWORD);
681 if (extensions_size)
682 {
683 msg->BufferLength += FIELD_OFFSET(WIRE_ORPC_EXTENT_ARRAY, extent[2*sizeof(DWORD) + extensions_size]);
684 if (extension_count & 1)
685 msg->BufferLength += FIELD_OFFSET(WIRE_ORPC_EXTENT, data[0]);
686 }
687
688 RpcBindingInqObject(message_state->binding_handle, &ipid);
689 hr = ipid_get_dispatch_params(&ipid, &apt, &message_state->params.stub,
690 &message_state->params.chan,
691 &message_state->params.iid,
692 &message_state->params.iface);
693 if (hr == S_OK)
694 {
695 /* stub, chan, iface and iid are unneeded in multi-threaded case as we go
696 * via the RPC runtime */
697 if (apt->multi_threaded)
698 {
699 IRpcStubBuffer_Release(message_state->params.stub);
700 message_state->params.stub = NULL;
701 IRpcChannelBuffer_Release(message_state->params.chan);
702 message_state->params.chan = NULL;
703 message_state->params.iface = NULL;
704 }
705 else
706 {
707 message_state->params.bypass_rpcrt = TRUE;
708 message_state->target_hwnd = apartment_getwindow(apt);
709 message_state->target_tid = apt->tid;
710 /* we assume later on that this being non-NULL is the indicator that
711 * means call directly instead of going through RPC runtime */
712 if (!message_state->target_hwnd)
713 ERR("window for apartment %s is NULL\n", wine_dbgstr_longlong(apt->oxid));
714 }
715 }
716 if (apt) apartment_release(apt);
717 message_state->params.handle = ClientRpcChannelBuffer_GetEventHandle(This);
718 /* Note: message_state->params.msg is initialised in
719 * ClientRpcChannelBuffer_SendReceive */
720
721 /* shortcut the RPC runtime */
722 if (message_state->target_hwnd)
723 {
724 msg->Buffer = HeapAlloc(GetProcessHeap(), 0, msg->BufferLength);
725 if (msg->Buffer)
726 status = RPC_S_OK;
727 else
728 status = ERROR_OUTOFMEMORY;
729 }
730 else
731 status = I_RpcGetBuffer(msg);
732
733 msg->Handle = message_state;
734
735 if (status == RPC_S_OK)
736 {
737 orpcthis = msg->Buffer;
738 msg->Buffer = (char *)msg->Buffer + FIELD_OFFSET(WIRE_ORPCTHIS, extensions);
739
740 orpcthis->version.MajorVersion = COM_MAJOR_VERSION;
741 orpcthis->version.MinorVersion = COM_MINOR_VERSION;
742 orpcthis->flags = message_state->channel_hook_info.dwServerPid ? ORPCF_LOCAL : ORPCF_NULL;
743 orpcthis->reserved1 = 0;
744 orpcthis->cid = message_state->channel_hook_info.uCausality;
745
746 /* NDR representation of orpcthis->extensions */
747 *(DWORD *)msg->Buffer = extensions_size ? 1 : 0;
748 msg->Buffer = (char *)msg->Buffer + sizeof(DWORD);
749
750 if (extensions_size)
751 {
752 ORPC_EXTENT_ARRAY *orpc_extent_array = msg->Buffer;
753 orpc_extent_array->size = extension_count;
754 orpc_extent_array->reserved = 0;
755 msg->Buffer = (char *)msg->Buffer + FIELD_OFFSET(WIRE_ORPC_EXTENT_ARRAY, extent);
756 /* NDR representation of orpc_extent_array->extent */
757 *(DWORD *)msg->Buffer = 1;
758 msg->Buffer = (char *)msg->Buffer + sizeof(DWORD);
759 /* NDR representation of [size_is] attribute of orpc_extent_array->extent */
760 *(DWORD *)msg->Buffer = (extension_count + 1) & ~1;
761 msg->Buffer = (char *)msg->Buffer + sizeof(DWORD);
762
763 msg->Buffer = ChannelHooks_ClientFillBuffer(&message_state->channel_hook_info,
764 msg->Buffer, channel_hook_data, channel_hook_count);
765
766 /* we must add a dummy extension if there is an odd extension
767 * count to meet the contract specified by the size_is attribute */
768 if (extension_count & 1)
769 {
770 WIRE_ORPC_EXTENT *wire_orpc_extent = msg->Buffer;
771 wire_orpc_extent->conformance = 0;
772 wire_orpc_extent->id = GUID_NULL;
773 wire_orpc_extent->size = 0;
774 msg->Buffer = (char *)msg->Buffer + FIELD_OFFSET(WIRE_ORPC_EXTENT, data[0]);
775 }
776 }
777
778 /* store the prefixed data length so that we can restore the real buffer
779 * pointer in ClientRpcChannelBuffer_SendReceive. */
780 message_state->prefix_data_len = (char *)msg->Buffer - (char *)orpcthis;
781 msg->BufferLength -= message_state->prefix_data_len;
782 }
783
784 HeapFree(GetProcessHeap(), 0, channel_hook_data);
785
786 TRACE("-- %d\n", status);
787
788 return HRESULT_FROM_WIN32(status);
789 }
790
791 static HRESULT WINAPI ServerRpcChannelBuffer_SendReceive(LPRPCCHANNELBUFFER iface, RPCOLEMESSAGE *olemsg, ULONG *pstatus)
792 {
793 FIXME("stub\n");
794 return E_NOTIMPL;
795 }
796
797 /* this thread runs an outgoing RPC */
798 static DWORD WINAPI rpc_sendreceive_thread(LPVOID param)
799 {
800 struct dispatch_params *data = param;
801
802 /* Note: I_RpcSendReceive doesn't raise exceptions like the higher-level
803 * RPC functions do */
804 data->status = I_RpcSendReceive((RPC_MESSAGE *)data->msg);
805
806 TRACE("completed with status 0x%x\n", data->status);
807
808 SetEvent(data->handle);
809
810 return 0;
811 }
812
813 static inline HRESULT ClientRpcChannelBuffer_IsCorrectApartment(ClientRpcChannelBuffer *This, APARTMENT *apt)
814 {
815 OXID oxid;
816 if (!apt)
817 return S_FALSE;
818 if (apartment_getoxid(apt, &oxid) != S_OK)
819 return S_FALSE;
820 if (This->oxid != oxid)
821 return S_FALSE;
822 return S_OK;
823 }
824
825 static HRESULT WINAPI ClientRpcChannelBuffer_SendReceive(LPRPCCHANNELBUFFER iface, RPCOLEMESSAGE *olemsg, ULONG *pstatus)
826 {
827 ClientRpcChannelBuffer *This = (ClientRpcChannelBuffer *)iface;
828 HRESULT hr;
829 RPC_MESSAGE *msg = (RPC_MESSAGE *)olemsg;
830 RPC_STATUS status;
831 DWORD index;
832 struct message_state *message_state;
833 ORPCTHAT orpcthat;
834 ORPC_EXTENT_ARRAY orpc_ext_array;
835 WIRE_ORPC_EXTENT *first_wire_orpc_extent = NULL;
836 HRESULT hrFault = S_OK;
837
838 TRACE("(%p) iMethod=%d\n", olemsg, olemsg->iMethod);
839
840 hr = ClientRpcChannelBuffer_IsCorrectApartment(This, COM_CurrentApt());
841 if (hr != S_OK)
842 {
843 ERR("called from wrong apartment, should have been 0x%s\n",
844 wine_dbgstr_longlong(This->oxid));
845 return RPC_E_WRONG_THREAD;
846 }
847 /* This situation should be impossible in multi-threaded apartments,
848 * because the calling thread isn't re-enterable.
849 * Note: doing a COM call during the processing of a sent message is
850 * only disallowed if a client call is already being waited for
851 * completion */
852 if (!COM_CurrentApt()->multi_threaded &&
853 COM_CurrentInfo()->pending_call_count_client &&
854 InSendMessage())
855 {
856 ERR("can't make an outgoing COM call in response to a sent message\n");
857 return RPC_E_CANTCALLOUT_ININPUTSYNCCALL;
858 }
859
860 message_state = msg->Handle;
861 /* restore the binding handle and the real start of data */
862 msg->Handle = message_state->binding_handle;
863 msg->Buffer = (char *)msg->Buffer - message_state->prefix_data_len;
864 msg->BufferLength += message_state->prefix_data_len;
865
866 /* Note: this is an optimization in the Microsoft OLE runtime that we need
867 * to copy, as shown by the test_no_couninitialize_client test. without
868 * short-circuiting the RPC runtime in the case below, the test will
869 * deadlock on the loader lock due to the RPC runtime needing to create
870 * a thread to process the RPC when this function is called indirectly
871 * from DllMain */
872
873 message_state->params.msg = olemsg;
874 if (message_state->params.bypass_rpcrt)
875 {
876 TRACE("Calling apartment thread 0x%08x...\n", message_state->target_tid);
877
878 msg->ProcNum &= ~RPC_FLAGS_VALID_BIT;
879
880 if (!PostMessageW(message_state->target_hwnd, DM_EXECUTERPC, 0,
881 (LPARAM)&message_state->params))
882 {
883 ERR("PostMessage failed with error %u\n", GetLastError());
884
885 /* Note: message_state->params.iface doesn't have a reference and
886 * so doesn't need to be released */
887
888 hr = HRESULT_FROM_WIN32(GetLastError());
889 }
890 }
891 else
892 {
893 /* we use a separate thread here because we need to be able to
894 * pump the message loop in the application thread: if we do not,
895 * any windows created by this thread will hang and RPCs that try
896 * and re-enter this STA from an incoming server thread will
897 * deadlock. InstallShield is an example of that.
898 */
899 if (!QueueUserWorkItem(rpc_sendreceive_thread, &message_state->params, WT_EXECUTEDEFAULT))
900 {
901 ERR("QueueUserWorkItem failed with error %u\n", GetLastError());
902 hr = E_UNEXPECTED;
903 }
904 else
905 hr = S_OK;
906 }
907
908 if (hr == S_OK)
909 {
910 if (WaitForSingleObject(message_state->params.handle, 0))
911 {
912 COM_CurrentInfo()->pending_call_count_client++;
913 hr = CoWaitForMultipleHandles(0, INFINITE, 1, &message_state->params.handle, &index);
914 COM_CurrentInfo()->pending_call_count_client--;
915 }
916 }
917 ClientRpcChannelBuffer_ReleaseEventHandle(This, message_state->params.handle);
918
919 /* for WM shortcut, faults are returned in params->hr */
920 if (hr == S_OK)
921 hrFault = message_state->params.hr;
922
923 status = message_state->params.status;
924
925 orpcthat.flags = ORPCF_NULL;
926 orpcthat.extensions = NULL;
927
928 TRACE("RPC call status: 0x%x\n", status);
929 if (status != RPC_S_OK)
930 hr = HRESULT_FROM_WIN32(status);
931
932 TRACE("hrFault = 0x%08x\n", hrFault);
933
934 /* FIXME: this condition should be
935 * "hr == S_OK && (!hrFault || msg->BufferLength > FIELD_OFFSET(ORPCTHAT, extensions) + 4)"
936 * but we don't currently reset the message length for PostMessage
937 * dispatched calls */
938 if (hr == S_OK && hrFault == S_OK)
939 {
940 HRESULT hr2;
941 char *original_buffer = msg->Buffer;
942
943 /* handle ORPCTHAT and client extensions */
944
945 hr2 = unmarshal_ORPCTHAT(msg, &orpcthat, &orpc_ext_array, &first_wire_orpc_extent);
946 if (FAILED(hr2))
947 hr = hr2;
948
949 message_state->prefix_data_len = (char *)msg->Buffer - original_buffer;
950 msg->BufferLength -= message_state->prefix_data_len;
951 }
952 else
953 message_state->prefix_data_len = 0;
954
955 if (hr == S_OK)
956 {
957 ChannelHooks_ClientNotify(&message_state->channel_hook_info,
958 msg->DataRepresentation,
959 first_wire_orpc_extent,
960 orpcthat.extensions && first_wire_orpc_extent ? orpcthat.extensions->size : 0,
961 hrFault);
962 }
963
964 /* save away the message state again */
965 msg->Handle = message_state;
966
967 if (pstatus) *pstatus = status;
968
969 if (hr == S_OK)
970 hr = hrFault;
971
972 TRACE("-- 0x%08x\n", hr);
973
974 return hr;
975 }
976
977 static HRESULT WINAPI ServerRpcChannelBuffer_FreeBuffer(LPRPCCHANNELBUFFER iface, RPCOLEMESSAGE* olemsg)
978 {
979 RPC_MESSAGE *msg = (RPC_MESSAGE *)olemsg;
980 RPC_STATUS status;
981 struct message_state *message_state;
982
983 TRACE("(%p)\n", msg);
984
985 message_state = msg->Handle;
986 /* restore the binding handle and the real start of data */
987 msg->Handle = message_state->binding_handle;
988 msg->Buffer = (char *)msg->Buffer - message_state->prefix_data_len;
989 msg->BufferLength += message_state->prefix_data_len;
990 message_state->prefix_data_len = 0;
991
992 if (message_state->bypass_rpcrt)
993 {
994 HeapFree(GetProcessHeap(), 0, msg->Buffer);
995 status = RPC_S_OK;
996 }
997 else
998 status = I_RpcFreeBuffer(msg);
999
1000 msg->Handle = message_state;
1001
1002 TRACE("-- %d\n", status);
1003
1004 return HRESULT_FROM_WIN32(status);
1005 }
1006
1007 static HRESULT WINAPI ClientRpcChannelBuffer_FreeBuffer(LPRPCCHANNELBUFFER iface, RPCOLEMESSAGE* olemsg)
1008 {
1009 RPC_MESSAGE *msg = (RPC_MESSAGE *)olemsg;
1010 RPC_STATUS status;
1011 struct message_state *message_state;
1012
1013 TRACE("(%p)\n", msg);
1014
1015 message_state = msg->Handle;
1016 /* restore the binding handle and the real start of data */
1017 msg->Handle = message_state->binding_handle;
1018 msg->Buffer = (char *)msg->Buffer - message_state->prefix_data_len;
1019 msg->BufferLength += message_state->prefix_data_len;
1020
1021 if (message_state->params.bypass_rpcrt)
1022 {
1023 HeapFree(GetProcessHeap(), 0, msg->Buffer);
1024 status = RPC_S_OK;
1025 }
1026 else
1027 status = I_RpcFreeBuffer(msg);
1028
1029 HeapFree(GetProcessHeap(), 0, msg->RpcInterfaceInformation);
1030 msg->RpcInterfaceInformation = NULL;
1031
1032 if (message_state->params.stub)
1033 IRpcStubBuffer_Release(message_state->params.stub);
1034 if (message_state->params.chan)
1035 IRpcChannelBuffer_Release(message_state->params.chan);
1036 HeapFree(GetProcessHeap(), 0, message_state);
1037
1038 TRACE("-- %d\n", status);
1039
1040 return HRESULT_FROM_WIN32(status);
1041 }
1042
1043 static HRESULT WINAPI ClientRpcChannelBuffer_GetDestCtx(LPRPCCHANNELBUFFER iface, DWORD* pdwDestContext, void** ppvDestContext)
1044 {
1045 ClientRpcChannelBuffer *This = (ClientRpcChannelBuffer *)iface;
1046
1047 TRACE("(%p,%p)\n", pdwDestContext, ppvDestContext);
1048
1049 *pdwDestContext = This->super.dest_context;
1050 *ppvDestContext = This->super.dest_context_data;
1051
1052 return S_OK;
1053 }
1054
1055 static HRESULT WINAPI ServerRpcChannelBuffer_GetDestCtx(LPRPCCHANNELBUFFER iface, DWORD* dest_context, void** dest_context_data)
1056 {
1057 RpcChannelBuffer *This = (RpcChannelBuffer *)iface;
1058
1059 TRACE("(%p,%p)\n", dest_context, dest_context_data);
1060
1061 *dest_context = This->dest_context;
1062 *dest_context_data = This->dest_context_data;
1063 return S_OK;
1064 }
1065
1066 static HRESULT WINAPI RpcChannelBuffer_IsConnected(LPRPCCHANNELBUFFER iface)
1067 {
1068 TRACE("()\n");
1069 /* native does nothing too */
1070 return S_OK;
1071 }
1072
1073 static const IRpcChannelBufferVtbl ClientRpcChannelBufferVtbl =
1074 {
1075 RpcChannelBuffer_QueryInterface,
1076 RpcChannelBuffer_AddRef,
1077 ClientRpcChannelBuffer_Release,
1078 ClientRpcChannelBuffer_GetBuffer,
1079 ClientRpcChannelBuffer_SendReceive,
1080 ClientRpcChannelBuffer_FreeBuffer,
1081 ClientRpcChannelBuffer_GetDestCtx,
1082 RpcChannelBuffer_IsConnected
1083 };
1084
1085 static const IRpcChannelBufferVtbl ServerRpcChannelBufferVtbl =
1086 {
1087 RpcChannelBuffer_QueryInterface,
1088 RpcChannelBuffer_AddRef,
1089 ServerRpcChannelBuffer_Release,
1090 ServerRpcChannelBuffer_GetBuffer,
1091 ServerRpcChannelBuffer_SendReceive,
1092 ServerRpcChannelBuffer_FreeBuffer,
1093 ServerRpcChannelBuffer_GetDestCtx,
1094 RpcChannelBuffer_IsConnected
1095 };
1096
1097 /* returns a channel buffer for proxies */
1098 HRESULT RPC_CreateClientChannel(const OXID *oxid, const IPID *ipid,
1099 const OXID_INFO *oxid_info,
1100 DWORD dest_context, void *dest_context_data,
1101 IRpcChannelBuffer **chan)
1102 {
1103 ClientRpcChannelBuffer *This;
1104 WCHAR endpoint[200];
1105 RPC_BINDING_HANDLE bind;
1106 RPC_STATUS status;
1107 LPWSTR string_binding;
1108
1109 /* FIXME: get the endpoint from oxid_info->psa instead */
1110 get_rpc_endpoint(endpoint, oxid);
1111
1112 TRACE("proxy pipe: connecting to endpoint: %s\n", debugstr_w(endpoint));
1113
1114 status = RpcStringBindingComposeW(
1115 NULL,
1116 wszRpcTransport,
1117 NULL,
1118 endpoint,
1119 NULL,
1120 &string_binding);
1121
1122 if (status == RPC_S_OK)
1123 {
1124 status = RpcBindingFromStringBindingW(string_binding, &bind);
1125
1126 if (status == RPC_S_OK)
1127 {
1128 IPID ipid2 = *ipid; /* why can't RpcBindingSetObject take a const? */
1129 status = RpcBindingSetObject(bind, &ipid2);
1130 if (status != RPC_S_OK)
1131 RpcBindingFree(&bind);
1132 }
1133
1134 RpcStringFreeW(&string_binding);
1135 }
1136
1137 if (status != RPC_S_OK)
1138 {
1139 ERR("Couldn't get binding for endpoint %s, status = %d\n", debugstr_w(endpoint), status);
1140 return HRESULT_FROM_WIN32(status);
1141 }
1142
1143 This = HeapAlloc(GetProcessHeap(), 0, sizeof(*This));
1144 if (!This)
1145 {
1146 RpcBindingFree(&bind);
1147 return E_OUTOFMEMORY;
1148 }
1149
1150 This->super.IRpcChannelBuffer_iface.lpVtbl = &ClientRpcChannelBufferVtbl;
1151 This->super.refs = 1;
1152 This->super.dest_context = dest_context;
1153 This->super.dest_context_data = dest_context_data;
1154 This->bind = bind;
1155 apartment_getoxid(COM_CurrentApt(), &This->oxid);
1156 This->server_pid = oxid_info->dwPid;
1157 This->event = NULL;
1158
1159 *chan = &This->super.IRpcChannelBuffer_iface;
1160
1161 return S_OK;
1162 }
1163
1164 HRESULT RPC_CreateServerChannel(DWORD dest_context, void *dest_context_data, IRpcChannelBuffer **chan)
1165 {
1166 RpcChannelBuffer *This = HeapAlloc(GetProcessHeap(), 0, sizeof(*This));
1167 if (!This)
1168 return E_OUTOFMEMORY;
1169
1170 This->IRpcChannelBuffer_iface.lpVtbl = &ServerRpcChannelBufferVtbl;
1171 This->refs = 1;
1172 This->dest_context = dest_context;
1173 This->dest_context_data = dest_context_data;
1174
1175 *chan = &This->IRpcChannelBuffer_iface;
1176
1177 return S_OK;
1178 }
1179
1180 /* unmarshals ORPC_EXTENT_ARRAY according to NDR rules, but doesn't allocate
1181 * any memory */
1182 static HRESULT unmarshal_ORPC_EXTENT_ARRAY(RPC_MESSAGE *msg, const char *end,
1183 ORPC_EXTENT_ARRAY *extensions,
1184 WIRE_ORPC_EXTENT **first_wire_orpc_extent)
1185 {
1186 DWORD pointer_id;
1187 DWORD i;
1188
1189 memcpy(extensions, msg->Buffer, FIELD_OFFSET(WIRE_ORPC_EXTENT_ARRAY, extent));
1190 msg->Buffer = (char *)msg->Buffer + FIELD_OFFSET(WIRE_ORPC_EXTENT_ARRAY, extent);
1191
1192 if ((const char *)msg->Buffer + 2 * sizeof(DWORD) > end)
1193 return RPC_E_INVALID_HEADER;
1194
1195 pointer_id = *(DWORD *)msg->Buffer;
1196 msg->Buffer = (char *)msg->Buffer + sizeof(DWORD);
1197 extensions->extent = NULL;
1198
1199 if (pointer_id)
1200 {
1201 WIRE_ORPC_EXTENT *wire_orpc_extent;
1202
1203 /* conformance */
1204 if (*(DWORD *)msg->Buffer != ((extensions->size+1)&~1))
1205 return RPC_S_INVALID_BOUND;
1206
1207 msg->Buffer = (char *)msg->Buffer + sizeof(DWORD);
1208
1209 /* arbitrary limit for security (don't know what native does) */
1210 if (extensions->size > 256)
1211 {
1212 ERR("too many extensions: %d\n", extensions->size);
1213 return RPC_S_INVALID_BOUND;
1214 }
1215
1216 *first_wire_orpc_extent = wire_orpc_extent = msg->Buffer;
1217 for (i = 0; i < ((extensions->size+1)&~1); i++)
1218 {
1219 if ((const char *)&wire_orpc_extent->data[0] > end)
1220 return RPC_S_INVALID_BOUND;
1221 if (wire_orpc_extent->conformance != ((wire_orpc_extent->size+7)&~7))
1222 return RPC_S_INVALID_BOUND;
1223 if ((const char *)&wire_orpc_extent->data[wire_orpc_extent->conformance] > end)
1224 return RPC_S_INVALID_BOUND;
1225 TRACE("size %u, guid %s\n", wire_orpc_extent->size, debugstr_guid(&wire_orpc_extent->id));
1226 wire_orpc_extent = (WIRE_ORPC_EXTENT *)&wire_orpc_extent->data[wire_orpc_extent->conformance];
1227 }
1228 msg->Buffer = wire_orpc_extent;
1229 }
1230
1231 return S_OK;
1232 }
1233
1234 /* unmarshals ORPCTHIS according to NDR rules, but doesn't allocate any memory */
1235 static HRESULT unmarshal_ORPCTHIS(RPC_MESSAGE *msg, ORPCTHIS *orpcthis,
1236 ORPC_EXTENT_ARRAY *orpc_ext_array, WIRE_ORPC_EXTENT **first_wire_orpc_extent)
1237 {
1238 const char *end = (char *)msg->Buffer + msg->BufferLength;
1239
1240 *first_wire_orpc_extent = NULL;
1241
1242 if (msg->BufferLength < FIELD_OFFSET(WIRE_ORPCTHIS, extensions) + sizeof(DWORD))
1243 {
1244 ERR("invalid buffer length\n");
1245 return RPC_E_INVALID_HEADER;
1246 }
1247
1248 memcpy(orpcthis, msg->Buffer, FIELD_OFFSET(WIRE_ORPCTHIS, extensions));
1249 msg->Buffer = (char *)msg->Buffer + FIELD_OFFSET(WIRE_ORPCTHIS, extensions);
1250
1251 if ((const char *)msg->Buffer + sizeof(DWORD) > end)
1252 return RPC_E_INVALID_HEADER;
1253
1254 if (*(DWORD *)msg->Buffer)
1255 orpcthis->extensions = orpc_ext_array;
1256 else
1257 orpcthis->extensions = NULL;
1258
1259 msg->Buffer = (char *)msg->Buffer + sizeof(DWORD);
1260
1261 if (orpcthis->extensions)
1262 {
1263 HRESULT hr = unmarshal_ORPC_EXTENT_ARRAY(msg, end, orpc_ext_array,
1264 first_wire_orpc_extent);
1265 if (FAILED(hr))
1266 return hr;
1267 }
1268
1269 if ((orpcthis->version.MajorVersion != COM_MAJOR_VERSION) ||
1270 (orpcthis->version.MinorVersion > COM_MINOR_VERSION))
1271 {
1272 ERR("COM version {%d, %d} not supported\n",
1273 orpcthis->version.MajorVersion, orpcthis->version.MinorVersion);
1274 return RPC_E_VERSION_MISMATCH;
1275 }
1276
1277 if (orpcthis->flags & ~(ORPCF_LOCAL|ORPCF_RESERVED1|ORPCF_RESERVED2|ORPCF_RESERVED3|ORPCF_RESERVED4))
1278 {
1279 ERR("invalid flags 0x%x\n", orpcthis->flags & ~(ORPCF_LOCAL|ORPCF_RESERVED1|ORPCF_RESERVED2|ORPCF_RESERVED3|ORPCF_RESERVED4));
1280 return RPC_E_INVALID_HEADER;
1281 }
1282
1283 return S_OK;
1284 }
1285
1286 static HRESULT unmarshal_ORPCTHAT(RPC_MESSAGE *msg, ORPCTHAT *orpcthat,
1287 ORPC_EXTENT_ARRAY *orpc_ext_array, WIRE_ORPC_EXTENT **first_wire_orpc_extent)
1288 {
1289 const char *end = (char *)msg->Buffer + msg->BufferLength;
1290
1291 *first_wire_orpc_extent = NULL;
1292
1293 if (msg->BufferLength < FIELD_OFFSET(WIRE_ORPCTHAT, extensions) + sizeof(DWORD))
1294 {
1295 ERR("invalid buffer length\n");
1296 return RPC_E_INVALID_HEADER;
1297 }
1298
1299 memcpy(orpcthat, msg->Buffer, FIELD_OFFSET(WIRE_ORPCTHAT, extensions));
1300 msg->Buffer = (char *)msg->Buffer + FIELD_OFFSET(WIRE_ORPCTHAT, extensions);
1301
1302 if ((const char *)msg->Buffer + sizeof(DWORD) > end)
1303 return RPC_E_INVALID_HEADER;
1304
1305 if (*(DWORD *)msg->Buffer)
1306 orpcthat->extensions = orpc_ext_array;
1307 else
1308 orpcthat->extensions = NULL;
1309
1310 msg->Buffer = (char *)msg->Buffer + sizeof(DWORD);
1311
1312 if (orpcthat->extensions)
1313 {
1314 HRESULT hr = unmarshal_ORPC_EXTENT_ARRAY(msg, end, orpc_ext_array,
1315 first_wire_orpc_extent);
1316 if (FAILED(hr))
1317 return hr;
1318 }
1319
1320 if (orpcthat->flags & ~(ORPCF_LOCAL|ORPCF_RESERVED1|ORPCF_RESERVED2|ORPCF_RESERVED3|ORPCF_RESERVED4))
1321 {
1322 ERR("invalid flags 0x%x\n", orpcthat->flags & ~(ORPCF_LOCAL|ORPCF_RESERVED1|ORPCF_RESERVED2|ORPCF_RESERVED3|ORPCF_RESERVED4));
1323 return RPC_E_INVALID_HEADER;
1324 }
1325
1326 return S_OK;
1327 }
1328
1329 void RPC_ExecuteCall(struct dispatch_params *params)
1330 {
1331 struct message_state *message_state = NULL;
1332 RPC_MESSAGE *msg = (RPC_MESSAGE *)params->msg;
1333 char *original_buffer = msg->Buffer;
1334 ORPCTHIS orpcthis;
1335 ORPC_EXTENT_ARRAY orpc_ext_array;
1336 WIRE_ORPC_EXTENT *first_wire_orpc_extent;
1337 GUID old_causality_id;
1338
1339 /* handle ORPCTHIS and server extensions */
1340
1341 params->hr = unmarshal_ORPCTHIS(msg, &orpcthis, &orpc_ext_array, &first_wire_orpc_extent);
1342 if (params->hr != S_OK)
1343 {
1344 msg->Buffer = original_buffer;
1345 goto exit;
1346 }
1347
1348 message_state = HeapAlloc(GetProcessHeap(), 0, sizeof(*message_state));
1349 if (!message_state)
1350 {
1351 params->hr = E_OUTOFMEMORY;
1352 msg->Buffer = original_buffer;
1353 goto exit;
1354 }
1355
1356 message_state->prefix_data_len = (char *)msg->Buffer - original_buffer;
1357 message_state->binding_handle = msg->Handle;
1358 message_state->bypass_rpcrt = params->bypass_rpcrt;
1359
1360 message_state->channel_hook_info.iid = params->iid;
1361 message_state->channel_hook_info.cbSize = sizeof(message_state->channel_hook_info);
1362 message_state->channel_hook_info.uCausality = orpcthis.cid;
1363 message_state->channel_hook_info.dwServerPid = GetCurrentProcessId();
1364 message_state->channel_hook_info.iMethod = msg->ProcNum;
1365 message_state->channel_hook_info.pObject = params->iface;
1366
1367 if (orpcthis.extensions && first_wire_orpc_extent &&
1368 orpcthis.extensions->size)
1369 ChannelHooks_ServerNotify(&message_state->channel_hook_info, msg->DataRepresentation, first_wire_orpc_extent, orpcthis.extensions->size);
1370
1371 msg->Handle = message_state;
1372 msg->BufferLength -= message_state->prefix_data_len;
1373
1374 /* call message filter */
1375
1376 if (COM_CurrentApt()->filter)
1377 {
1378 DWORD handlecall;
1379 INTERFACEINFO interface_info;
1380 CALLTYPE calltype;
1381
1382 interface_info.pUnk = params->iface;
1383 interface_info.iid = params->iid;
1384 interface_info.wMethod = msg->ProcNum;
1385
1386 if (IsEqualGUID(&orpcthis.cid, &COM_CurrentInfo()->causality_id))
1387 calltype = CALLTYPE_NESTED;
1388 else if (COM_CurrentInfo()->pending_call_count_server == 0)
1389 calltype = CALLTYPE_TOPLEVEL;
1390 else
1391 calltype = CALLTYPE_TOPLEVEL_CALLPENDING;
1392
1393 handlecall = IMessageFilter_HandleInComingCall(COM_CurrentApt()->filter,
1394 calltype,
1395 UlongToHandle(GetCurrentProcessId()),
1396 0 /* FIXME */,
1397 &interface_info);
1398 TRACE("IMessageFilter_HandleInComingCall returned %d\n", handlecall);
1399 switch (handlecall)
1400 {
1401 case SERVERCALL_REJECTED:
1402 params->hr = RPC_E_CALL_REJECTED;
1403 goto exit_reset_state;
1404 case SERVERCALL_RETRYLATER:
1405 #if 0 /* FIXME: handle retries on the client side before enabling this code */
1406 params->hr = RPC_E_RETRY;
1407 goto exit_reset_state;
1408 #else
1409 FIXME("retry call later not implemented\n");
1410 break;
1411 #endif
1412 case SERVERCALL_ISHANDLED:
1413 default:
1414 break;
1415 }
1416 }
1417
1418 /* invoke the method */
1419
1420 /* save the old causality ID - note: any calls executed while processing
1421 * messages received during the SendReceive will appear to originate from
1422 * this call - this should be checked with what Windows does */
1423 old_causality_id = COM_CurrentInfo()->causality_id;
1424 COM_CurrentInfo()->causality_id = orpcthis.cid;
1425 COM_CurrentInfo()->pending_call_count_server++;
1426 params->hr = IRpcStubBuffer_Invoke(params->stub, params->msg, params->chan);
1427 COM_CurrentInfo()->pending_call_count_server--;
1428 COM_CurrentInfo()->causality_id = old_causality_id;
1429
1430 /* the invoke allocated a new buffer, so free the old one */
1431 if (message_state->bypass_rpcrt && original_buffer != msg->Buffer)
1432 HeapFree(GetProcessHeap(), 0, original_buffer);
1433
1434 exit_reset_state:
1435 message_state = msg->Handle;
1436 msg->Handle = message_state->binding_handle;
1437 msg->Buffer = (char *)msg->Buffer - message_state->prefix_data_len;
1438 msg->BufferLength += message_state->prefix_data_len;
1439
1440 exit:
1441 HeapFree(GetProcessHeap(), 0, message_state);
1442 if (params->handle) SetEvent(params->handle);
1443 }
1444
1445 static void __RPC_STUB dispatch_rpc(RPC_MESSAGE *msg)
1446 {
1447 struct dispatch_params *params;
1448 APARTMENT *apt;
1449 IPID ipid;
1450 HRESULT hr;
1451
1452 RpcBindingInqObject(msg->Handle, &ipid);
1453
1454 TRACE("ipid = %s, iMethod = %d\n", debugstr_guid(&ipid), msg->ProcNum);
1455
1456 params = HeapAlloc(GetProcessHeap(), 0, sizeof(*params));
1457 if (!params)
1458 {
1459 RpcRaiseException(E_OUTOFMEMORY);
1460 return;
1461 }
1462
1463 hr = ipid_get_dispatch_params(&ipid, &apt, &params->stub, &params->chan,
1464 &params->iid, &params->iface);
1465 if (hr != S_OK)
1466 {
1467 ERR("no apartment found for ipid %s\n", debugstr_guid(&ipid));
1468 HeapFree(GetProcessHeap(), 0, params);
1469 RpcRaiseException(hr);
1470 return;
1471 }
1472
1473 params->msg = (RPCOLEMESSAGE *)msg;
1474 params->status = RPC_S_OK;
1475 params->hr = S_OK;
1476 params->handle = NULL;
1477 params->bypass_rpcrt = FALSE;
1478
1479 /* Note: this is the important difference between STAs and MTAs - we
1480 * always execute RPCs to STAs in the thread that originally created the
1481 * apartment (i.e. the one that pumps messages to the window) */
1482 if (!apt->multi_threaded)
1483 {
1484 params->handle = CreateEventW(NULL, FALSE, FALSE, NULL);
1485
1486 TRACE("Calling apartment thread 0x%08x...\n", apt->tid);
1487
1488 if (PostMessageW(apartment_getwindow(apt), DM_EXECUTERPC, 0, (LPARAM)params))
1489 WaitForSingleObject(params->handle, INFINITE);
1490 else
1491 {
1492 ERR("PostMessage failed with error %u\n", GetLastError());
1493 IRpcChannelBuffer_Release(params->chan);
1494 IRpcStubBuffer_Release(params->stub);
1495 }
1496 CloseHandle(params->handle);
1497 }
1498 else
1499 {
1500 BOOL joined = FALSE;
1501 if (!COM_CurrentInfo()->apt)
1502 {
1503 apartment_joinmta();
1504 joined = TRUE;
1505 }
1506 RPC_ExecuteCall(params);
1507 if (joined)
1508 {
1509 apartment_release(COM_CurrentInfo()->apt);
1510 COM_CurrentInfo()->apt = NULL;
1511 }
1512 }
1513
1514 hr = params->hr;
1515 if (params->chan)
1516 IRpcChannelBuffer_Release(params->chan);
1517 if (params->stub)
1518 IRpcStubBuffer_Release(params->stub);
1519 HeapFree(GetProcessHeap(), 0, params);
1520
1521 apartment_release(apt);
1522
1523 /* if IRpcStubBuffer_Invoke fails, we should raise an exception to tell
1524 * the RPC runtime that the call failed */
1525 if (hr != S_OK) RpcRaiseException(hr);
1526 }
1527
1528 /* stub registration */
1529 HRESULT RPC_RegisterInterface(REFIID riid)
1530 {
1531 struct registered_if *rif;
1532 BOOL found = FALSE;
1533 HRESULT hr = S_OK;
1534
1535 TRACE("(%s)\n", debugstr_guid(riid));
1536
1537 EnterCriticalSection(&csRegIf);
1538 LIST_FOR_EACH_ENTRY(rif, &registered_interfaces, struct registered_if, entry)
1539 {
1540 if (IsEqualGUID(&rif->If.InterfaceId.SyntaxGUID, riid))
1541 {
1542 rif->refs++;
1543 found = TRUE;
1544 break;
1545 }
1546 }
1547 if (!found)
1548 {
1549 TRACE("Creating new interface\n");
1550
1551 rif = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*rif));
1552 if (rif)
1553 {
1554 RPC_STATUS status;
1555
1556 rif->refs = 1;
1557 rif->If.Length = sizeof(RPC_SERVER_INTERFACE);
1558 /* RPC interface ID = COM interface ID */
1559 rif->If.InterfaceId.SyntaxGUID = *riid;
1560 rif->If.DispatchTable = &rpc_dispatch;
1561 /* all other fields are 0, including the version asCOM objects
1562 * always have a version of 0.0 */
1563 status = RpcServerRegisterIfEx(
1564 (RPC_IF_HANDLE)&rif->If,
1565 NULL, NULL,
1566 RPC_IF_OLE | RPC_IF_AUTOLISTEN,
1567 RPC_C_LISTEN_MAX_CALLS_DEFAULT,
1568 NULL);
1569 if (status == RPC_S_OK)
1570 list_add_tail(&registered_interfaces, &rif->entry);
1571 else
1572 {
1573 ERR("RpcServerRegisterIfEx failed with error %d\n", status);
1574 HeapFree(GetProcessHeap(), 0, rif);
1575 hr = HRESULT_FROM_WIN32(status);
1576 }
1577 }
1578 else
1579 hr = E_OUTOFMEMORY;
1580 }
1581 LeaveCriticalSection(&csRegIf);
1582 return hr;
1583 }
1584
1585 /* stub unregistration */
1586 void RPC_UnregisterInterface(REFIID riid)
1587 {
1588 struct registered_if *rif;
1589 EnterCriticalSection(&csRegIf);
1590 LIST_FOR_EACH_ENTRY(rif, &registered_interfaces, struct registered_if, entry)
1591 {
1592 if (IsEqualGUID(&rif->If.InterfaceId.SyntaxGUID, riid))
1593 {
1594 if (!--rif->refs)
1595 {
1596 RpcServerUnregisterIf((RPC_IF_HANDLE)&rif->If, NULL, TRUE);
1597 list_remove(&rif->entry);
1598 HeapFree(GetProcessHeap(), 0, rif);
1599 }
1600 break;
1601 }
1602 }
1603 LeaveCriticalSection(&csRegIf);
1604 }
1605
1606 /* get the info for an OXID, including the IPID for the rem unknown interface
1607 * and the string binding */
1608 HRESULT RPC_ResolveOxid(OXID oxid, OXID_INFO *oxid_info)
1609 {
1610 TRACE("%s\n", wine_dbgstr_longlong(oxid));
1611
1612 oxid_info->dwTid = 0;
1613 oxid_info->dwPid = 0;
1614 oxid_info->dwAuthnHint = RPC_C_AUTHN_LEVEL_NONE;
1615 /* FIXME: this is a hack around not having an OXID resolver yet -
1616 * this function should contact the machine's OXID resolver and then it
1617 * should give us the IPID of the IRemUnknown interface */
1618 oxid_info->ipidRemUnknown.Data1 = 0xffffffff;
1619 oxid_info->ipidRemUnknown.Data2 = 0xffff;
1620 oxid_info->ipidRemUnknown.Data3 = 0xffff;
1621 memcpy(oxid_info->ipidRemUnknown.Data4, &oxid, sizeof(OXID));
1622 oxid_info->psa = NULL /* FIXME */;
1623
1624 return S_OK;
1625 }
1626
1627 /* make the apartment reachable by other threads and processes and create the
1628 * IRemUnknown object */
1629 void RPC_StartRemoting(struct apartment *apt)
1630 {
1631 if (!InterlockedExchange(&apt->remoting_started, TRUE))
1632 {
1633 WCHAR endpoint[200];
1634 RPC_STATUS status;
1635
1636 get_rpc_endpoint(endpoint, &apt->oxid);
1637
1638 status = RpcServerUseProtseqEpW(
1639 wszRpcTransport,
1640 RPC_C_PROTSEQ_MAX_REQS_DEFAULT,
1641 endpoint,
1642 NULL);
1643 if (status != RPC_S_OK)
1644 ERR("Couldn't register endpoint %s\n", debugstr_w(endpoint));
1645
1646 /* FIXME: move remote unknown exporting into this function */
1647 }
1648 start_apartment_remote_unknown();
1649 }
1650
1651
1652 static HRESULT create_server(REFCLSID rclsid, HANDLE *process)
1653 {
1654 static const WCHAR wszLocalServer32[] = { 'L','o','c','a','l','S','e','r','v','e','r','3','2',0 };
1655 static const WCHAR embedding[] = { ' ', '-','E','m','b','e','d','d','i','n','g',0 };
1656 HKEY key;
1657 HRESULT hres;
1658 WCHAR command[MAX_PATH+sizeof(embedding)/sizeof(WCHAR)];
1659 DWORD size = (MAX_PATH+1) * sizeof(WCHAR);
1660 STARTUPINFOW sinfo;
1661 PROCESS_INFORMATION pinfo;
1662 LONG ret;
1663
1664 hres = COM_OpenKeyForCLSID(rclsid, wszLocalServer32, KEY_READ, &key);
1665 if (FAILED(hres)) {
1666 ERR("class %s not registered\n", debugstr_guid(rclsid));
1667 return hres;
1668 }
1669
1670 ret = RegQueryValueExW(key, NULL, NULL, NULL, (LPBYTE)command, &size);
1671 RegCloseKey(key);
1672 if (ret) {
1673 WARN("No default value for LocalServer32 key\n");
1674 return REGDB_E_CLASSNOTREG; /* FIXME: check retval */
1675 }
1676
1677 memset(&sinfo,0,sizeof(sinfo));
1678 sinfo.cb = sizeof(sinfo);
1679
1680 /* EXE servers are started with the -Embedding switch. */
1681
1682 strcatW(command, embedding);
1683
1684 TRACE("activating local server %s for %s\n", debugstr_w(command), debugstr_guid(rclsid));
1685
1686 /* FIXME: Win2003 supports a ServerExecutable value that is passed into
1687 * CreateProcess */
1688 if (!CreateProcessW(NULL, command, NULL, NULL, FALSE, DETACHED_PROCESS, NULL, NULL, &sinfo, &pinfo)) {
1689 WARN("failed to run local server %s\n", debugstr_w(command));
1690 return HRESULT_FROM_WIN32(GetLastError());
1691 }
1692 *process = pinfo.hProcess;
1693 CloseHandle(pinfo.hThread);
1694
1695 return S_OK;
1696 }
1697
1698 /*
1699 * start_local_service() - start a service given its name and parameters
1700 */
1701 static DWORD start_local_service(LPCWSTR name, DWORD num, LPCWSTR *params)
1702 {
1703 SC_HANDLE handle, hsvc;
1704 DWORD r = ERROR_FUNCTION_FAILED;
1705
1706 TRACE("Starting service %s %d params\n", debugstr_w(name), num);
1707
1708 handle = OpenSCManagerW(NULL, NULL, SC_MANAGER_CONNECT);
1709 if (!handle)
1710 return r;
1711 hsvc = OpenServiceW(handle, name, SERVICE_START);
1712 if (hsvc)
1713 {
1714 if(StartServiceW(hsvc, num, params))
1715 r = ERROR_SUCCESS;
1716 else
1717 r = GetLastError();
1718 if (r == ERROR_SERVICE_ALREADY_RUNNING)
1719 r = ERROR_SUCCESS;
1720 CloseServiceHandle(hsvc);
1721 }
1722 else
1723 r = GetLastError();
1724 CloseServiceHandle(handle);
1725
1726 TRACE("StartService returned error %u (%s)\n", r, (r == ERROR_SUCCESS) ? "ok":"failed");
1727
1728 return r;
1729 }
1730
1731 /*
1732 * create_local_service() - start a COM server in a service
1733 *
1734 * To start a Local Service, we read the AppID value under
1735 * the class's CLSID key, then open the HKCR\\AppId key specified
1736 * there and check for a LocalService value.
1737 *
1738 * Note: Local Services are not supported under Windows 9x
1739 */
1740 static HRESULT create_local_service(REFCLSID rclsid)
1741 {
1742 HRESULT hres;
1743 WCHAR buf[CHARS_IN_GUID];
1744 static const WCHAR szLocalService[] = { 'L','o','c','a','l','S','e','r','v','i','c','e',0 };
1745 static const WCHAR szServiceParams[] = {'S','e','r','v','i','c','e','P','a','r','a','m','s',0};
1746 HKEY hkey;
1747 LONG r;
1748 DWORD type, sz;
1749
1750 TRACE("Attempting to start Local service for %s\n", debugstr_guid(rclsid));
1751
1752 hres = COM_OpenKeyForAppIdFromCLSID(rclsid, KEY_READ, &hkey);
1753 if (FAILED(hres))
1754 return hres;
1755
1756 /* read the LocalService and ServiceParameters values from the AppID key */
1757 sz = sizeof buf;
1758 r = RegQueryValueExW(hkey, szLocalService, NULL, &type, (LPBYTE)buf, &sz);
1759 if (r==ERROR_SUCCESS && type==REG_SZ)
1760 {
1761 DWORD num_args = 0;
1762 LPWSTR args[1] = { NULL };
1763
1764 /*
1765 * FIXME: I'm not really sure how to deal with the service parameters.
1766 * I suspect that the string returned from RegQueryValueExW
1767 * should be split into a number of arguments by spaces.
1768 * It would make more sense if ServiceParams contained a
1769 * REG_MULTI_SZ here, but it's a REG_SZ for the services
1770 * that I'm interested in for the moment.
1771 */
1772 r = RegQueryValueExW(hkey, szServiceParams, NULL, &type, NULL, &sz);
1773 if (r == ERROR_SUCCESS && type == REG_SZ && sz)
1774 {
1775 args[0] = HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY,sz);
1776 num_args++;
1777 RegQueryValueExW(hkey, szServiceParams, NULL, &type, (LPBYTE)args[0], &sz);
1778 }
1779 r = start_local_service(buf, num_args, (LPCWSTR *)args);
1780 if (r != ERROR_SUCCESS)
1781 hres = REGDB_E_CLASSNOTREG; /* FIXME: check retval */
1782 HeapFree(GetProcessHeap(),0,args[0]);
1783 }
1784 else
1785 {
1786 WARN("No LocalService value\n");
1787 hres = REGDB_E_CLASSNOTREG; /* FIXME: check retval */
1788 }
1789 RegCloseKey(hkey);
1790
1791 return hres;
1792 }
1793
1794
1795 static void get_localserver_pipe_name(WCHAR *pipefn, REFCLSID rclsid)
1796 {
1797 static const WCHAR wszPipeRef[] = {'\\','\\','.','\\','p','i','p','e','\\',0};
1798 strcpyW(pipefn, wszPipeRef);
1799 StringFromGUID2(rclsid, pipefn + sizeof(wszPipeRef)/sizeof(wszPipeRef[0]) - 1, CHARS_IN_GUID);
1800 }
1801
1802 /* FIXME: should call to rpcss instead */
1803 HRESULT RPC_GetLocalClassObject(REFCLSID rclsid, REFIID iid, LPVOID *ppv)
1804 {
1805 HRESULT hres;
1806 HANDLE hPipe;
1807 WCHAR pipefn[100];
1808 DWORD res, bufferlen;
1809 char marshalbuffer[200];
1810 IStream *pStm;
1811 LARGE_INTEGER seekto;
1812 ULARGE_INTEGER newpos;
1813 int tries = 0;
1814 IServiceProvider *local_server;
1815
1816 static const int MAXTRIES = 30; /* 30 seconds */
1817
1818 TRACE("rclsid=%s, iid=%s\n", debugstr_guid(rclsid), debugstr_guid(iid));
1819
1820 get_localserver_pipe_name(pipefn, rclsid);
1821
1822 while (tries++ < MAXTRIES) {
1823 TRACE("waiting for %s\n", debugstr_w(pipefn));
1824
1825 WaitNamedPipeW( pipefn, NMPWAIT_WAIT_FOREVER );
1826 hPipe = CreateFileW(pipefn, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, 0);
1827 if (hPipe == INVALID_HANDLE_VALUE) {
1828 DWORD index;
1829 DWORD start_ticks;
1830 HANDLE process = 0;
1831 if (tries == 1) {
1832 if ( (hres = create_local_service(rclsid)) &&
1833 (hres = create_server(rclsid, &process)) )
1834 return hres;
1835 } else {
1836 WARN("Connecting to %s, no response yet, retrying: le is %u\n", debugstr_w(pipefn), GetLastError());
1837 }
1838 /* wait for one second, even if messages arrive */
1839 start_ticks = GetTickCount();
1840 do {
1841 if (SUCCEEDED(CoWaitForMultipleHandles(0, 1000, (process != 0),
1842 &process, &index)) && process && !index)
1843 {
1844 WARN( "server for %s failed to start\n", debugstr_guid(rclsid) );
1845 CloseHandle( hPipe );
1846 CloseHandle( process );
1847 return E_NOINTERFACE;
1848 }
1849 } while (GetTickCount() - start_ticks < 1000);
1850 if (process) CloseHandle( process );
1851 continue;
1852 }
1853 bufferlen = 0;
1854 if (!ReadFile(hPipe,marshalbuffer,sizeof(marshalbuffer),&bufferlen,NULL)) {
1855 FIXME("Failed to read marshal id from classfactory of %s.\n",debugstr_guid(rclsid));
1856 Sleep(1000);
1857 continue;
1858 }
1859 TRACE("read marshal id from pipe\n");
1860 CloseHandle(hPipe);
1861 break;
1862 }
1863
1864 if (tries >= MAXTRIES)
1865 return E_NOINTERFACE;
1866
1867 hres = CreateStreamOnHGlobal(0,TRUE,&pStm);
1868 if (hres != S_OK) return hres;
1869 hres = IStream_Write(pStm,marshalbuffer,bufferlen,&res);
1870 if (hres != S_OK) goto out;
1871 seekto.u.LowPart = 0;seekto.u.HighPart = 0;
1872 hres = IStream_Seek(pStm,seekto,STREAM_SEEK_SET,&newpos);
1873
1874 TRACE("unmarshalling local server\n");
1875 hres = CoUnmarshalInterface(pStm, &IID_IServiceProvider, (void**)&local_server);
1876 if(SUCCEEDED(hres))
1877 hres = IServiceProvider_QueryService(local_server, rclsid, iid, ppv);
1878 IServiceProvider_Release(local_server);
1879 out:
1880 IStream_Release(pStm);
1881 return hres;
1882 }
1883
1884
1885 struct local_server_params
1886 {
1887 CLSID clsid;
1888 IStream *stream;
1889 HANDLE pipe;
1890 HANDLE stop_event;
1891 HANDLE thread;
1892 BOOL multi_use;
1893 };
1894
1895 /* FIXME: should call to rpcss instead */
1896 static DWORD WINAPI local_server_thread(LPVOID param)
1897 {
1898 struct local_server_params * lsp = param;
1899 WCHAR pipefn[100];
1900 HRESULT hres;
1901 IStream *pStm = lsp->stream;
1902 STATSTG ststg;
1903 unsigned char *buffer;
1904 int buflen;
1905 LARGE_INTEGER seekto;
1906 ULARGE_INTEGER newpos;
1907 ULONG res;
1908 BOOL multi_use = lsp->multi_use;
1909 OVERLAPPED ovl;
1910 HANDLE pipe_event, hPipe = lsp->pipe, new_pipe;
1911 DWORD bytes;
1912
1913 TRACE("Starting threader for %s.\n",debugstr_guid(&lsp->clsid));
1914
1915 memset(&ovl, 0, sizeof(ovl));
1916 get_localserver_pipe_name(pipefn, &lsp->clsid);
1917 ovl.hEvent = pipe_event = CreateEventW(NULL, FALSE, FALSE, NULL);
1918
1919 while (1) {
1920 if (!ConnectNamedPipe(hPipe, &ovl))
1921 {
1922 DWORD error = GetLastError();
1923 if (error == ERROR_IO_PENDING)
1924 {
1925 HANDLE handles[2] = { pipe_event, lsp->stop_event };
1926 DWORD ret;
1927 ret = WaitForMultipleObjects(2, handles, FALSE, INFINITE);
1928 if (ret != WAIT_OBJECT_0)
1929 break;
1930 }
1931 /* client already connected isn't an error */
1932 else if (error != ERROR_PIPE_CONNECTED)
1933 {
1934 ERR("ConnectNamedPipe failed with error %d\n", GetLastError());
1935 break;
1936 }
1937 }
1938
1939 TRACE("marshalling LocalServer to client\n");
1940
1941 hres = IStream_Stat(pStm,&ststg,STATFLAG_NONAME);
1942 if (hres != S_OK)
1943 break;
1944
1945 seekto.u.LowPart = 0;
1946 seekto.u.HighPart = 0;
1947 hres = IStream_Seek(pStm,seekto,STREAM_SEEK_SET,&newpos);
1948 if (hres != S_OK) {
1949 FIXME("IStream_Seek failed, %x\n",hres);
1950 break;
1951 }
1952
1953 buflen = ststg.cbSize.u.LowPart;
1954 buffer = HeapAlloc(GetProcessHeap(),0,buflen);
1955
1956 hres = IStream_Read(pStm,buffer,buflen,&res);
1957 if (hres != S_OK) {
1958 FIXME("Stream Read failed, %x\n",hres);
1959 HeapFree(GetProcessHeap(),0,buffer);
1960 break;
1961 }
1962
1963 WriteFile(hPipe,buffer,buflen,&res,&ovl);
1964 GetOverlappedResult(hPipe, &ovl, &bytes, TRUE);
1965 HeapFree(GetProcessHeap(),0,buffer);
1966
1967 FlushFileBuffers(hPipe);
1968 DisconnectNamedPipe(hPipe);
1969 TRACE("done marshalling LocalServer\n");
1970
1971 if (!multi_use)
1972 {
1973 TRACE("single use object, shutting down pipe %s\n", debugstr_w(pipefn));
1974 break;
1975 }
1976 new_pipe = CreateNamedPipeW( pipefn, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
1977 PIPE_TYPE_BYTE|PIPE_WAIT, PIPE_UNLIMITED_INSTANCES,
1978 4096, 4096, 500 /* 0.5 second timeout */, NULL );
1979 if (new_pipe == INVALID_HANDLE_VALUE)
1980 {
1981 FIXME("pipe creation failed for %s, le is %u\n", debugstr_w(pipefn), GetLastError());
1982 break;
1983 }
1984 CloseHandle(hPipe);
1985 hPipe = new_pipe;
1986 }
1987
1988 CloseHandle(pipe_event);
1989 CloseHandle(hPipe);
1990 return 0;
1991 }
1992
1993 /* starts listening for a local server */
1994 HRESULT RPC_StartLocalServer(REFCLSID clsid, IStream *stream, BOOL multi_use, void **registration)
1995 {
1996 DWORD tid, err;
1997 struct local_server_params *lsp;
1998 WCHAR pipefn[100];
1999
2000 lsp = HeapAlloc(GetProcessHeap(), 0, sizeof(*lsp));
2001 if (!lsp)
2002 return E_OUTOFMEMORY;
2003
2004 lsp->clsid = *clsid;
2005 lsp->stream = stream;
2006 IStream_AddRef(stream);
2007 lsp->stop_event = CreateEventW(NULL, FALSE, FALSE, NULL);
2008 if (!lsp->stop_event)
2009 {
2010 HeapFree(GetProcessHeap(), 0, lsp);
2011 return HRESULT_FROM_WIN32(GetLastError());
2012 }
2013 lsp->multi_use = multi_use;
2014
2015 get_localserver_pipe_name(pipefn, &lsp->clsid);
2016 lsp->pipe = CreateNamedPipeW(pipefn, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
2017 PIPE_TYPE_BYTE|PIPE_WAIT, PIPE_UNLIMITED_INSTANCES,
2018 4096, 4096, 500 /* 0.5 second timeout */, NULL);
2019 if (lsp->pipe == INVALID_HANDLE_VALUE)
2020 {
2021 err = GetLastError();
2022 FIXME("pipe creation failed for %s, le is %u\n", debugstr_w(pipefn), GetLastError());
2023 CloseHandle(lsp->stop_event);
2024 HeapFree(GetProcessHeap(), 0, lsp);
2025 return HRESULT_FROM_WIN32(err);
2026 }
2027
2028 lsp->thread = CreateThread(NULL, 0, local_server_thread, lsp, 0, &tid);
2029 if (!lsp->thread)
2030 {
2031 CloseHandle(lsp->pipe);
2032 CloseHandle(lsp->stop_event);
2033 HeapFree(GetProcessHeap(), 0, lsp);
2034 return HRESULT_FROM_WIN32(GetLastError());
2035 }
2036
2037 *registration = lsp;
2038 return S_OK;
2039 }
2040
2041 /* stops listening for a local server */
2042 void RPC_StopLocalServer(void *registration)
2043 {
2044 struct local_server_params *lsp = registration;
2045
2046 /* signal local_server_thread to stop */
2047 SetEvent(lsp->stop_event);
2048 /* wait for it to exit */
2049 WaitForSingleObject(lsp->thread, INFINITE);
2050
2051 IStream_Release(lsp->stream);
2052 CloseHandle(lsp->stop_event);
2053 CloseHandle(lsp->thread);
2054 HeapFree(GetProcessHeap(), 0, lsp);
2055 }