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