rpc.c 67.2 KB
Newer Older
1
/*
2
 *	RPC Manager
3
 *
4
 * Copyright 2001  Ove Kåven, TransGaming Technologies
5 6
 * Copyright 2002  Marcus Meissner
 * Copyright 2005  Mike Hearn, Rob Shearman for CodeWeavers
7 8 9 10 11 12 13 14 15 16 17 18 19
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * 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
 */

#include "config.h"
24
#include "wine/port.h"
25

26
#include <stdarg.h>
27 28
#include <string.h>

29
#define COBJMACROS
30 31
#define NONAMELESSUNION
#define NONAMELESSSTRUCT
32

33
#include "windef.h"
34
#include "winbase.h"
35
#include "winuser.h"
36
#include "winsvc.h"
37 38 39 40 41 42 43 44 45
#include "objbase.h"
#include "ole2.h"
#include "rpc.h"
#include "winerror.h"
#include "winreg.h"
#include "wine/unicode.h"

#include "compobj_private.h"

46
#include "wine/debug.h"
47

48
WINE_DEFAULT_DEBUG_CHANNEL(ole);
49

50
static void __RPC_STUB dispatch_rpc(RPC_MESSAGE *msg);
51

52 53 54 55
/* we only use one function to dispatch calls for all methods - we use the
 * RPC_IF_OLE flag to tell the RPC runtime that this is the case */
static RPC_DISPATCH_FUNCTION rpc_dispatch_table[1] = { dispatch_rpc }; /* (RO) */
static RPC_DISPATCH_TABLE rpc_dispatch = { 1, rpc_dispatch_table }; /* (RO) */
56

57 58 59
static struct list registered_interfaces = LIST_INIT(registered_interfaces); /* (CS csRegIf) */
static CRITICAL_SECTION csRegIf;
static CRITICAL_SECTION_DEBUG csRegIf_debug =
60
{
61 62
    0, 0, &csRegIf,
    { &csRegIf_debug.ProcessLocksList, &csRegIf_debug.ProcessLocksList },
63
      0, 0, { (DWORD_PTR)(__FILE__ ": dcom registered server interfaces") }
64
};
65 66
static CRITICAL_SECTION csRegIf = { &csRegIf_debug, -1, 0, 0, 0, 0 };

67 68 69 70 71 72 73 74 75 76
static struct list channel_hooks = LIST_INIT(channel_hooks); /* (CS csChannelHook) */
static CRITICAL_SECTION csChannelHook;
static CRITICAL_SECTION_DEBUG csChannelHook_debug =
{
    0, 0, &csChannelHook,
    { &csChannelHook_debug.ProcessLocksList, &csChannelHook_debug.ProcessLocksList },
      0, 0, { (DWORD_PTR)(__FILE__ ": channel hooks") }
};
static CRITICAL_SECTION csChannelHook = { &csChannelHook_debug, -1, 0, 0, 0, 0 };

77
static WCHAR wszRpcTransport[] = {'n','c','a','l','r','p','c',0};
78

79

80
struct registered_if
81
{
82 83 84
    struct list entry;
    DWORD refs; /* ref count */
    RPC_SERVER_INTERFACE If; /* interface registered with the RPC runtime */
85
};
86

87 88 89 90 91 92 93
/* get the pipe endpoint specified of the specified apartment */
static inline void get_rpc_endpoint(LPWSTR endpoint, const OXID *oxid)
{
    /* FIXME: should get endpoint from rpcss */
    static const WCHAR wszEndpointFormat[] = {'\\','p','i','p','e','\\','O','L','E','_','%','0','8','l','x','%','0','8','l','x',0};
    wsprintfW(endpoint, wszEndpointFormat, (DWORD)(*oxid >> 32),(DWORD)*oxid);
}
94

95 96 97
typedef struct
{
    const IRpcChannelBufferVtbl *lpVtbl;
98
    LONG                  refs;
99
} RpcChannelBuffer;
100

101
typedef struct
102
{
103
    RpcChannelBuffer       super; /* superclass */
104

105
    RPC_BINDING_HANDLE     bind; /* handle to the remote server */
106
    OXID                   oxid; /* apartment in which the channel is valid */
107
    DWORD                  server_pid; /* id of server process */
108 109
    DWORD                  dest_context; /* returned from GetDestCtx */
    LPVOID                 dest_context_data; /* returned from GetDestCtx */
110
    HANDLE                 event; /* cached event handle */
111
} ClientRpcChannelBuffer;
112

113 114 115 116 117
struct dispatch_params
{
    RPCOLEMESSAGE     *msg; /* message */
    IRpcStubBuffer    *stub; /* stub buffer, if applicable */
    IRpcChannelBuffer *chan; /* server channel buffer, if applicable */
118 119
    IID                iid; /* ID of interface being called */
    IUnknown          *iface; /* interface being called */
120
    HANDLE             handle; /* handle that will become signaled when call finishes */
121
    BOOL               bypass_rpcrt; /* bypass RPC runtime? */
122
    RPC_STATUS         status; /* status (out) */
123
    HRESULT            hr; /* hresult (out) */
124 125
};

126 127 128 129
struct message_state
{
    RPC_BINDING_HANDLE binding_handle;
    ULONG prefix_data_len;
130
    SChannelHookCallInfo channel_hook_info;
131
    BOOL bypass_rpcrt;
132 133

    /* client only */
134 135
    HWND target_hwnd;
    DWORD target_tid;
136
    struct dispatch_params params;
137 138 139 140 141 142 143 144 145 146
};

typedef struct
{
    ULONG conformance; /* NDR */
    GUID id;
    ULONG size;
    /* [size_is((size+7)&~7)] */ unsigned char data[1];
} WIRE_ORPC_EXTENT;

147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168
typedef struct
{
    ULONG size;
    ULONG reserved;
    unsigned char extent[1];
} WIRE_ORPC_EXTENT_ARRAY;

typedef struct
{
    ULONG version;
    ULONG flags;
    ULONG reserved1;
    GUID  cid;
    unsigned char extensions[1];
} WIRE_ORPCTHIS;

typedef struct
{
    ULONG flags;
    unsigned char extensions[1];
} WIRE_ORPCTHAT;

169 170 171 172 173 174 175 176 177 178 179 180 181 182
struct channel_hook_entry
{
    struct list entry;
    GUID id;
    IChannelHook *hook;
};

struct channel_hook_buffer_data
{
    GUID id;
    ULONG extension_size;
};


183 184 185
static HRESULT unmarshal_ORPCTHAT(RPC_MESSAGE *msg, ORPCTHAT *orpcthat,
                                  ORPC_EXTENT_ARRAY *orpc_ext_array, WIRE_ORPC_EXTENT **first_wire_orpc_extent);

186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203
/* Channel Hook Functions */

static ULONG ChannelHooks_ClientGetSize(SChannelHookCallInfo *info,
    struct channel_hook_buffer_data **data, unsigned int *hook_count,
    ULONG *extension_count)
{
    struct channel_hook_entry *entry;
    ULONG total_size = 0;
    unsigned int hook_index = 0;

    *hook_count = 0;
    *extension_count = 0;

    EnterCriticalSection(&csChannelHook);

    LIST_FOR_EACH_ENTRY(entry, &channel_hooks, struct channel_hook_entry, entry)
        (*hook_count)++;

204
    if (*hook_count)
205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266
        *data = HeapAlloc(GetProcessHeap(), 0, *hook_count * sizeof(struct channel_hook_buffer_data));
    else
        *data = NULL;

    LIST_FOR_EACH_ENTRY(entry, &channel_hooks, struct channel_hook_entry, entry)
    {
        ULONG extension_size = 0;

        IChannelHook_ClientGetSize(entry->hook, &entry->id, &info->iid, &extension_size);

        TRACE("%s: extension_size = %u\n", debugstr_guid(&entry->id), extension_size);

        extension_size = (extension_size+7)&~7;
        (*data)[hook_index].id = entry->id;
        (*data)[hook_index].extension_size = extension_size;

        /* an extension is only put onto the wire if it has data to write */
        if (extension_size)
        {
            total_size += FIELD_OFFSET(WIRE_ORPC_EXTENT, data[extension_size]);
            (*extension_count)++;
        }

        hook_index++;
    }

    LeaveCriticalSection(&csChannelHook);

    return total_size;
}

static unsigned char * ChannelHooks_ClientFillBuffer(SChannelHookCallInfo *info,
    unsigned char *buffer, struct channel_hook_buffer_data *data,
    unsigned int hook_count)
{
    struct channel_hook_entry *entry;

    EnterCriticalSection(&csChannelHook);

    LIST_FOR_EACH_ENTRY(entry, &channel_hooks, struct channel_hook_entry, entry)
    {
        unsigned int i;
        ULONG extension_size = 0;
        WIRE_ORPC_EXTENT *wire_orpc_extent = (WIRE_ORPC_EXTENT *)buffer;

        for (i = 0; i < hook_count; i++)
            if (IsEqualGUID(&entry->id, &data[i].id))
                extension_size = data[i].extension_size;

        /* an extension is only put onto the wire if it has data to write */
        if (!extension_size)
            continue;

        IChannelHook_ClientFillBuffer(entry->hook, &entry->id, &info->iid,
            &extension_size, buffer + FIELD_OFFSET(WIRE_ORPC_EXTENT, data[0]));

        TRACE("%s: extension_size = %u\n", debugstr_guid(&entry->id), extension_size);

        /* FIXME: set unused portion of wire_orpc_extent->data to 0? */

        wire_orpc_extent->conformance = (extension_size+7)&~7;
        wire_orpc_extent->size = extension_size;
267
        wire_orpc_extent->id = entry->id;
268 269 270 271 272 273 274 275
        buffer += FIELD_OFFSET(WIRE_ORPC_EXTENT, data[wire_orpc_extent->conformance]);
    }

    LeaveCriticalSection(&csChannelHook);

    return buffer;
}

276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305
static void ChannelHooks_ServerNotify(SChannelHookCallInfo *info,
    DWORD lDataRep, WIRE_ORPC_EXTENT *first_wire_orpc_extent,
    ULONG extension_count)
{
    struct channel_hook_entry *entry;
    ULONG i;

    EnterCriticalSection(&csChannelHook);

    LIST_FOR_EACH_ENTRY(entry, &channel_hooks, struct channel_hook_entry, entry)
    {
        WIRE_ORPC_EXTENT *wire_orpc_extent;
        for (i = 0, wire_orpc_extent = first_wire_orpc_extent;
             i < extension_count;
             i++, wire_orpc_extent = (WIRE_ORPC_EXTENT *)&wire_orpc_extent->data[wire_orpc_extent->conformance])
        {
            if (IsEqualGUID(&entry->id, &wire_orpc_extent->id))
                break;
        }
        if (i == extension_count) wire_orpc_extent = NULL;

        IChannelHook_ServerNotify(entry->hook, &entry->id, &info->iid,
            wire_orpc_extent ? wire_orpc_extent->size : 0,
            wire_orpc_extent ? wire_orpc_extent->data : NULL,
            lDataRep);
    }

    LeaveCriticalSection(&csChannelHook);
}

306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386
static ULONG ChannelHooks_ServerGetSize(SChannelHookCallInfo *info,
                                        struct channel_hook_buffer_data **data, unsigned int *hook_count,
                                        ULONG *extension_count)
{
    struct channel_hook_entry *entry;
    ULONG total_size = 0;
    unsigned int hook_index = 0;

    *hook_count = 0;
    *extension_count = 0;

    EnterCriticalSection(&csChannelHook);

    LIST_FOR_EACH_ENTRY(entry, &channel_hooks, struct channel_hook_entry, entry)
        (*hook_count)++;

    if (*hook_count)
        *data = HeapAlloc(GetProcessHeap(), 0, *hook_count * sizeof(struct channel_hook_buffer_data));
    else
        *data = NULL;

    LIST_FOR_EACH_ENTRY(entry, &channel_hooks, struct channel_hook_entry, entry)
    {
        ULONG extension_size = 0;

        IChannelHook_ServerGetSize(entry->hook, &entry->id, &info->iid, S_OK,
                                   &extension_size);

        TRACE("%s: extension_size = %u\n", debugstr_guid(&entry->id), extension_size);

        extension_size = (extension_size+7)&~7;
        (*data)[hook_index].id = entry->id;
        (*data)[hook_index].extension_size = extension_size;

        /* an extension is only put onto the wire if it has data to write */
        if (extension_size)
        {
            total_size += FIELD_OFFSET(WIRE_ORPC_EXTENT, data[extension_size]);
            (*extension_count)++;
        }

        hook_index++;
    }

    LeaveCriticalSection(&csChannelHook);

    return total_size;
}

static unsigned char * ChannelHooks_ServerFillBuffer(SChannelHookCallInfo *info,
                                                     unsigned char *buffer, struct channel_hook_buffer_data *data,
                                                     unsigned int hook_count)
{
    struct channel_hook_entry *entry;

    EnterCriticalSection(&csChannelHook);

    LIST_FOR_EACH_ENTRY(entry, &channel_hooks, struct channel_hook_entry, entry)
    {
        unsigned int i;
        ULONG extension_size = 0;
        WIRE_ORPC_EXTENT *wire_orpc_extent = (WIRE_ORPC_EXTENT *)buffer;

        for (i = 0; i < hook_count; i++)
            if (IsEqualGUID(&entry->id, &data[i].id))
                extension_size = data[i].extension_size;

        /* an extension is only put onto the wire if it has data to write */
        if (!extension_size)
            continue;

        IChannelHook_ServerFillBuffer(entry->hook, &entry->id, &info->iid,
                                      &extension_size, buffer + FIELD_OFFSET(WIRE_ORPC_EXTENT, data[0]),
                                      S_OK);

        TRACE("%s: extension_size = %u\n", debugstr_guid(&entry->id), extension_size);

        /* FIXME: set unused portion of wire_orpc_extent->data to 0? */

        wire_orpc_extent->conformance = (extension_size+7)&~7;
        wire_orpc_extent->size = extension_size;
387
        wire_orpc_extent->id = entry->id;
388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425
        buffer += FIELD_OFFSET(WIRE_ORPC_EXTENT, data[wire_orpc_extent->conformance]);
    }

    LeaveCriticalSection(&csChannelHook);

    return buffer;
}

static void ChannelHooks_ClientNotify(SChannelHookCallInfo *info,
                                      DWORD lDataRep, WIRE_ORPC_EXTENT *first_wire_orpc_extent,
                                      ULONG extension_count, HRESULT hrFault)
{
    struct channel_hook_entry *entry;
    ULONG i;

    EnterCriticalSection(&csChannelHook);

    LIST_FOR_EACH_ENTRY(entry, &channel_hooks, struct channel_hook_entry, entry)
    {
        WIRE_ORPC_EXTENT *wire_orpc_extent;
        for (i = 0, wire_orpc_extent = first_wire_orpc_extent;
             i < extension_count;
             i++, wire_orpc_extent = (WIRE_ORPC_EXTENT *)&wire_orpc_extent->data[wire_orpc_extent->conformance])
        {
            if (IsEqualGUID(&entry->id, &wire_orpc_extent->id))
                break;
        }
        if (i == extension_count) wire_orpc_extent = NULL;

        IChannelHook_ClientNotify(entry->hook, &entry->id, &info->iid,
                                  wire_orpc_extent ? wire_orpc_extent->size : 0,
                                  wire_orpc_extent ? wire_orpc_extent->data : NULL,
                                  lDataRep, hrFault);
    }

    LeaveCriticalSection(&csChannelHook);
}

426 427 428 429 430 431 432 433 434 435
HRESULT RPC_RegisterChannelHook(REFGUID rguid, IChannelHook *hook)
{
    struct channel_hook_entry *entry;

    TRACE("(%s, %p)\n", debugstr_guid(rguid), hook);

    entry = HeapAlloc(GetProcessHeap(), 0, sizeof(*entry));
    if (!entry)
        return E_OUTOFMEMORY;

436
    entry->id = *rguid;
437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455
    entry->hook = hook;
    IChannelHook_AddRef(hook);

    EnterCriticalSection(&csChannelHook);
    list_add_tail(&channel_hooks, &entry->entry);
    LeaveCriticalSection(&csChannelHook);

    return S_OK;
}

void RPC_UnregisterAllChannelHooks(void)
{
    struct channel_hook_entry *cursor;
    struct channel_hook_entry *cursor2;

    EnterCriticalSection(&csChannelHook);
    LIST_FOR_EACH_ENTRY_SAFE(cursor, cursor2, &channel_hooks, struct channel_hook_entry, entry)
        HeapFree(GetProcessHeap(), 0, cursor);
    LeaveCriticalSection(&csChannelHook);
456 457
    DeleteCriticalSection(&csChannelHook);
    DeleteCriticalSection(&csRegIf);
458 459 460
}

/* RPC Channel Buffer Functions */
461

462
static HRESULT WINAPI RpcChannelBuffer_QueryInterface(IRpcChannelBuffer *iface, REFIID riid, LPVOID *ppv)
463
{
464 465 466
    *ppv = NULL;
    if (IsEqualIID(riid,&IID_IRpcChannelBuffer) || IsEqualIID(riid,&IID_IUnknown))
    {
467
        *ppv = iface;
468
        IRpcChannelBuffer_AddRef(iface);
469 470 471 472
        return S_OK;
    }
    return E_NOINTERFACE;
}
473

474 475 476 477 478
static ULONG WINAPI RpcChannelBuffer_AddRef(LPRPCCHANNELBUFFER iface)
{
    RpcChannelBuffer *This = (RpcChannelBuffer *)iface;
    return InterlockedIncrement(&This->refs);
}
479

480 481 482 483
static ULONG WINAPI ServerRpcChannelBuffer_Release(LPRPCCHANNELBUFFER iface)
{
    RpcChannelBuffer *This = (RpcChannelBuffer *)iface;
    ULONG ref;
484

485 486 487
    ref = InterlockedDecrement(&This->refs);
    if (ref)
        return ref;
488

489 490 491
    HeapFree(GetProcessHeap(), 0, This);
    return 0;
}
492

493 494 495 496
static ULONG WINAPI ClientRpcChannelBuffer_Release(LPRPCCHANNELBUFFER iface)
{
    ClientRpcChannelBuffer *This = (ClientRpcChannelBuffer *)iface;
    ULONG ref;
497

498 499 500
    ref = InterlockedDecrement(&This->super.refs);
    if (ref)
        return ref;
501

502
    if (This->event) CloseHandle(This->event);
503 504 505 506
    RpcBindingFree(&This->bind);
    HeapFree(GetProcessHeap(), 0, This);
    return 0;
}
507

508
static HRESULT WINAPI ServerRpcChannelBuffer_GetBuffer(LPRPCCHANNELBUFFER iface, RPCOLEMESSAGE* olemsg, REFIID riid)
509
{
510 511 512
    RpcChannelBuffer *This = (RpcChannelBuffer *)iface;
    RPC_MESSAGE *msg = (RPC_MESSAGE *)olemsg;
    RPC_STATUS status;
513
    ORPCTHAT *orpcthat;
514
    struct message_state *message_state;
515 516 517 518
    ULONG extensions_size;
    struct channel_hook_buffer_data *channel_hook_data;
    unsigned int channel_hook_count;
    ULONG extension_count;
519

520
    TRACE("(%p)->(%p,%s)\n", This, olemsg, debugstr_guid(riid));
521

522
    message_state = msg->Handle;
523 524 525 526
    /* restore the binding handle and the real start of data */
    msg->Handle = message_state->binding_handle;
    msg->Buffer = (char *)msg->Buffer - message_state->prefix_data_len;

527 528 529
    extensions_size = ChannelHooks_ServerGetSize(&message_state->channel_hook_info,
                                                 &channel_hook_data, &channel_hook_count, &extension_count);

530
    msg->BufferLength += FIELD_OFFSET(WIRE_ORPCTHAT, extensions) + sizeof(DWORD);
531 532
    if (extensions_size)
    {
533
        msg->BufferLength += FIELD_OFFSET(WIRE_ORPC_EXTENT_ARRAY, extent[2*sizeof(DWORD) + extensions_size]);
534 535 536 537
        if (extension_count & 1)
            msg->BufferLength += FIELD_OFFSET(WIRE_ORPC_EXTENT, data[0]);
    }

538 539 540 541 542 543
    if (message_state->bypass_rpcrt)
    {
        msg->Buffer = HeapAlloc(GetProcessHeap(), 0, msg->BufferLength);
        if (msg->Buffer)
            status = RPC_S_OK;
        else
544 545 546 547
        {
            HeapFree(GetProcessHeap(), 0, channel_hook_data);
            return E_OUTOFMEMORY;
        }
548 549 550
    }
    else
        status = I_RpcGetBuffer(msg);
551

552
    orpcthat = msg->Buffer;
553
    msg->Buffer = (char *)msg->Buffer + FIELD_OFFSET(WIRE_ORPCTHAT, extensions);
554 555 556 557 558 559 560 561 562

    orpcthat->flags = ORPCF_NULL /* FIXME? */;

    /* NDR representation of orpcthat->extensions */
    *(DWORD *)msg->Buffer = extensions_size ? 1 : 0;
    msg->Buffer = (char *)msg->Buffer + sizeof(DWORD);

    if (extensions_size)
    {
563
        WIRE_ORPC_EXTENT_ARRAY *orpc_extent_array = msg->Buffer;
564 565
        orpc_extent_array->size = extension_count;
        orpc_extent_array->reserved = 0;
566
        msg->Buffer = (char *)msg->Buffer + FIELD_OFFSET(WIRE_ORPC_EXTENT_ARRAY, extent);
567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582
        /* NDR representation of orpc_extent_array->extent */
        *(DWORD *)msg->Buffer = 1;
        msg->Buffer = (char *)msg->Buffer + sizeof(DWORD);
        /* NDR representation of [size_is] attribute of orpc_extent_array->extent */
        *(DWORD *)msg->Buffer = (extension_count + 1) & ~1;
        msg->Buffer = (char *)msg->Buffer + sizeof(DWORD);

        msg->Buffer = ChannelHooks_ServerFillBuffer(&message_state->channel_hook_info,
                                                    msg->Buffer, channel_hook_data, channel_hook_count);

        /* we must add a dummy extension if there is an odd extension
         * count to meet the contract specified by the size_is attribute */
        if (extension_count & 1)
        {
            WIRE_ORPC_EXTENT *wire_orpc_extent = msg->Buffer;
            wire_orpc_extent->conformance = 0;
583
            wire_orpc_extent->id = GUID_NULL;
584 585 586 587 588
            wire_orpc_extent->size = 0;
            msg->Buffer = (char *)msg->Buffer + FIELD_OFFSET(WIRE_ORPC_EXTENT, data[0]);
        }
    }

589 590
    HeapFree(GetProcessHeap(), 0, channel_hook_data);

591 592 593 594
    /* store the prefixed data length so that we can restore the real buffer
     * later */
    message_state->prefix_data_len = (char *)msg->Buffer - (char *)orpcthat;
    msg->BufferLength -= message_state->prefix_data_len;
595 596 597
    /* save away the message state again */
    msg->Handle = message_state;

598
    TRACE("-- %d\n", status);
599 600 601 602

    return HRESULT_FROM_WIN32(status);
}

603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620
static HANDLE ClientRpcChannelBuffer_GetEventHandle(ClientRpcChannelBuffer *This)
{
    HANDLE event = InterlockedExchangePointer(&This->event, NULL);

    /* Note: must be auto-reset event so we can reuse it without a call
    * to ResetEvent */
    if (!event) event = CreateEventW(NULL, FALSE, FALSE, NULL);

    return event;
}

static void ClientRpcChannelBuffer_ReleaseEventHandle(ClientRpcChannelBuffer *This, HANDLE event)
{
    if (InterlockedCompareExchangePointer(&This->event, event, NULL))
        /* already a handle cached in This */
        CloseHandle(event);
}

621 622 623 624 625 626
static HRESULT WINAPI ClientRpcChannelBuffer_GetBuffer(LPRPCCHANNELBUFFER iface, RPCOLEMESSAGE* olemsg, REFIID riid)
{
    ClientRpcChannelBuffer *This = (ClientRpcChannelBuffer *)iface;
    RPC_MESSAGE *msg = (RPC_MESSAGE *)olemsg;
    RPC_CLIENT_INTERFACE *cif;
    RPC_STATUS status;
627 628
    ORPCTHIS *orpcthis;
    struct message_state *message_state;
629 630 631 632
    ULONG extensions_size;
    struct channel_hook_buffer_data *channel_hook_data;
    unsigned int channel_hook_count;
    ULONG extension_count;
633 634 635
    IPID ipid;
    HRESULT hr;
    APARTMENT *apt = NULL;
636

637
    TRACE("(%p)->(%p,%s)\n", This, olemsg, debugstr_guid(riid));
638 639 640 641 642

    cif = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(RPC_CLIENT_INTERFACE));
    if (!cif)
        return E_OUTOFMEMORY;

643 644 645 646 647 648 649
    message_state = HeapAlloc(GetProcessHeap(), 0, sizeof(*message_state));
    if (!message_state)
    {
        HeapFree(GetProcessHeap(), 0, cif);
        return E_OUTOFMEMORY;
    }

650 651 652 653 654 655 656
    cif->Length = sizeof(RPC_CLIENT_INTERFACE);
    /* RPC interface ID = COM interface ID */
    cif->InterfaceId.SyntaxGUID = *riid;
    /* COM objects always have a version of 0.0 */
    cif->InterfaceId.SyntaxVersion.MajorVersion = 0;
    cif->InterfaceId.SyntaxVersion.MinorVersion = 0;
    msg->Handle = This->bind;
657 658
    msg->RpcInterfaceInformation = cif;

659 660 661
    message_state->prefix_data_len = 0;
    message_state->binding_handle = This->bind;

662 663
    message_state->channel_hook_info.iid = *riid;
    message_state->channel_hook_info.cbSize = sizeof(message_state->channel_hook_info);
664
    message_state->channel_hook_info.uCausality = COM_CurrentCausalityId();
665
    message_state->channel_hook_info.dwServerPid = This->server_pid;
666 667
    message_state->channel_hook_info.iMethod = msg->ProcNum;
    message_state->channel_hook_info.pObject = NULL; /* only present on server-side */
668 669
    message_state->target_hwnd = NULL;
    message_state->target_tid = 0;
670
    memset(&message_state->params, 0, sizeof(message_state->params));
671

672
    extensions_size = ChannelHooks_ClientGetSize(&message_state->channel_hook_info,
673 674
        &channel_hook_data, &channel_hook_count, &extension_count);

675
    msg->BufferLength += FIELD_OFFSET(WIRE_ORPCTHIS, extensions) + sizeof(DWORD);
676 677
    if (extensions_size)
    {
678
        msg->BufferLength += FIELD_OFFSET(WIRE_ORPC_EXTENT_ARRAY, extent[2*sizeof(DWORD) + extensions_size]);
679 680 681 682
        if (extension_count & 1)
            msg->BufferLength += FIELD_OFFSET(WIRE_ORPC_EXTENT, data[0]);
    }

683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701
    RpcBindingInqObject(message_state->binding_handle, &ipid);
    hr = ipid_get_dispatch_params(&ipid, &apt, &message_state->params.stub,
                                  &message_state->params.chan,
                                  &message_state->params.iid,
                                  &message_state->params.iface);
    if (hr == S_OK)
    {
        /* stub, chan, iface and iid are unneeded in multi-threaded case as we go
         * via the RPC runtime */
        if (apt->multi_threaded)
        {
            IRpcStubBuffer_Release(message_state->params.stub);
            message_state->params.stub = NULL;
            IRpcChannelBuffer_Release(message_state->params.chan);
            message_state->params.chan = NULL;
            message_state->params.iface = NULL;
        }
        else
        {
702
            message_state->params.bypass_rpcrt = TRUE;
703 704 705 706 707 708 709 710 711 712 713 714 715
            message_state->target_hwnd = apartment_getwindow(apt);
            message_state->target_tid = apt->tid;
            /* we assume later on that this being non-NULL is the indicator that
             * means call directly instead of going through RPC runtime */
            if (!message_state->target_hwnd)
                ERR("window for apartment %s is NULL\n", wine_dbgstr_longlong(apt->oxid));
        }
    }
    if (apt) apartment_release(apt);
    message_state->params.handle = ClientRpcChannelBuffer_GetEventHandle(This);
    /* Note: message_state->params.msg is initialised in
     * ClientRpcChannelBuffer_SendReceive */

716 717 718 719 720 721 722 723 724 725 726
    /* shortcut the RPC runtime */
    if (message_state->target_hwnd)
    {
        msg->Buffer = HeapAlloc(GetProcessHeap(), 0, msg->BufferLength);
        if (msg->Buffer)
            status = RPC_S_OK;
        else
            status = ERROR_OUTOFMEMORY;
    }
    else
        status = I_RpcGetBuffer(msg);
727

728 729 730 731
    msg->Handle = message_state;

    if (status == RPC_S_OK)
    {
732
        orpcthis = msg->Buffer;
733
        msg->Buffer = (char *)msg->Buffer + FIELD_OFFSET(WIRE_ORPCTHIS, extensions);
734 735 736

        orpcthis->version.MajorVersion = COM_MAJOR_VERSION;
        orpcthis->version.MinorVersion = COM_MINOR_VERSION;
737
        orpcthis->flags = message_state->channel_hook_info.dwServerPid ? ORPCF_LOCAL : ORPCF_NULL;
738
        orpcthis->reserved1 = 0;
739
        orpcthis->cid = message_state->channel_hook_info.uCausality;
740 741

        /* NDR representation of orpcthis->extensions */
742
        *(DWORD *)msg->Buffer = extensions_size ? 1 : 0;
743 744
        msg->Buffer = (char *)msg->Buffer + sizeof(DWORD);

745 746 747 748 749
        if (extensions_size)
        {
            ORPC_EXTENT_ARRAY *orpc_extent_array = msg->Buffer;
            orpc_extent_array->size = extension_count;
            orpc_extent_array->reserved = 0;
750
            msg->Buffer = (char *)msg->Buffer + FIELD_OFFSET(WIRE_ORPC_EXTENT_ARRAY, extent);
751 752 753 754 755 756 757
            /* NDR representation of orpc_extent_array->extent */
            *(DWORD *)msg->Buffer = 1;
            msg->Buffer = (char *)msg->Buffer + sizeof(DWORD);
            /* NDR representation of [size_is] attribute of orpc_extent_array->extent */
            *(DWORD *)msg->Buffer = (extension_count + 1) & ~1;
            msg->Buffer = (char *)msg->Buffer + sizeof(DWORD);

758
            msg->Buffer = ChannelHooks_ClientFillBuffer(&message_state->channel_hook_info,
759 760 761 762 763 764 765 766
                msg->Buffer, channel_hook_data, channel_hook_count);

            /* we must add a dummy extension if there is an odd extension
             * count to meet the contract specified by the size_is attribute */
            if (extension_count & 1)
            {
                WIRE_ORPC_EXTENT *wire_orpc_extent = msg->Buffer;
                wire_orpc_extent->conformance = 0;
767
                wire_orpc_extent->id = GUID_NULL;
768 769 770 771 772
                wire_orpc_extent->size = 0;
                msg->Buffer = (char *)msg->Buffer + FIELD_OFFSET(WIRE_ORPC_EXTENT, data[0]);
            }
        }

773 774 775 776 777 778
        /* store the prefixed data length so that we can restore the real buffer
         * pointer in ClientRpcChannelBuffer_SendReceive. */
        message_state->prefix_data_len = (char *)msg->Buffer - (char *)orpcthis;
        msg->BufferLength -= message_state->prefix_data_len;
    }

779 780
    HeapFree(GetProcessHeap(), 0, channel_hook_data);

781
    TRACE("-- %d\n", status);
782 783

    return HRESULT_FROM_WIN32(status);
784 785
}

786 787 788 789 790 791
static HRESULT WINAPI ServerRpcChannelBuffer_SendReceive(LPRPCCHANNELBUFFER iface, RPCOLEMESSAGE *olemsg, ULONG *pstatus)
{
    FIXME("stub\n");
    return E_NOTIMPL;
}

792 793 794
/* this thread runs an outgoing RPC */
static DWORD WINAPI rpc_sendreceive_thread(LPVOID param)
{
795
    struct dispatch_params *data = param;
796

797 798
    /* Note: I_RpcSendReceive doesn't raise exceptions like the higher-level
     * RPC functions do */
799
    data->status = I_RpcSendReceive((RPC_MESSAGE *)data->msg);
800

801
    TRACE("completed with status 0x%x\n", data->status);
802 803 804

    SetEvent(data->handle);

805 806 807
    return 0;
}

808 809 810 811 812 813 814 815 816 817 818 819 820
static inline HRESULT ClientRpcChannelBuffer_IsCorrectApartment(ClientRpcChannelBuffer *This, APARTMENT *apt)
{
    OXID oxid;
    if (!apt)
        return S_FALSE;
    if (apartment_getoxid(apt, &oxid) != S_OK)
        return S_FALSE;
    if (This->oxid != oxid)
        return S_FALSE;
    return S_OK;
}

static HRESULT WINAPI ClientRpcChannelBuffer_SendReceive(LPRPCCHANNELBUFFER iface, RPCOLEMESSAGE *olemsg, ULONG *pstatus)
821
{
822 823
    ClientRpcChannelBuffer *This = (ClientRpcChannelBuffer *)iface;
    HRESULT hr;
824
    RPC_MESSAGE *msg = (RPC_MESSAGE *)olemsg;
825
    RPC_STATUS status;
826
    DWORD index;
827
    struct message_state *message_state;
828 829 830
    ORPCTHAT orpcthat;
    ORPC_EXTENT_ARRAY orpc_ext_array;
    WIRE_ORPC_EXTENT *first_wire_orpc_extent = NULL;
831
    HRESULT hrFault = S_OK;
832

833
    TRACE("(%p) iMethod=%d\n", olemsg, olemsg->iMethod);
834

835 836 837 838 839 840 841
    hr = ClientRpcChannelBuffer_IsCorrectApartment(This, COM_CurrentApt());
    if (hr != S_OK)
    {
        ERR("called from wrong apartment, should have been 0x%s\n",
            wine_dbgstr_longlong(This->oxid));
        return RPC_E_WRONG_THREAD;
    }
Austin English's avatar
Austin English committed
842 843
    /* This situation should be impossible in multi-threaded apartments,
     * because the calling thread isn't re-enterable.
844 845 846 847 848 849 850 851 852 853
     * Note: doing a COM call during the processing of a sent message is
     * only disallowed if a client call is already being waited for
     * completion */
    if (!COM_CurrentApt()->multi_threaded &&
        COM_CurrentInfo()->pending_call_count_client &&
        InSendMessage())
    {
        ERR("can't make an outgoing COM call in response to a sent message\n");
        return RPC_E_CANTCALLOUT_ININPUTSYNCCALL;
    }
854

855
    message_state = msg->Handle;
856 857 858 859 860
    /* restore the binding handle and the real start of data */
    msg->Handle = message_state->binding_handle;
    msg->Buffer = (char *)msg->Buffer - message_state->prefix_data_len;
    msg->BufferLength += message_state->prefix_data_len;

861 862 863 864 865 866 867
    /* Note: this is an optimization in the Microsoft OLE runtime that we need
     * to copy, as shown by the test_no_couninitialize_client test. without
     * short-circuiting the RPC runtime in the case below, the test will
     * deadlock on the loader lock due to the RPC runtime needing to create
     * a thread to process the RPC when this function is called indirectly
     * from DllMain */

868
    message_state->params.msg = olemsg;
869
    if (message_state->params.bypass_rpcrt)
870
    {
871
        TRACE("Calling apartment thread 0x%08x...\n", message_state->target_tid);
872

873 874
        msg->ProcNum &= ~RPC_FLAGS_VALID_BIT;

875
        if (!PostMessageW(message_state->target_hwnd, DM_EXECUTERPC, 0,
876
                          (LPARAM)&message_state->params))
877
        {
878
            ERR("PostMessage failed with error %u\n", GetLastError());
879 880 881 882

            /* Note: message_state->params.iface doesn't have a reference and
             * so doesn't need to be released */

883 884
            hr = HRESULT_FROM_WIN32(GetLastError());
        }
885 886
    }
    else
887
    {
888 889 890 891 892 893
        /* we use a separate thread here because we need to be able to
         * pump the message loop in the application thread: if we do not,
         * any windows created by this thread will hang and RPCs that try
         * and re-enter this STA from an incoming server thread will
         * deadlock. InstallShield is an example of that.
         */
894
        if (!QueueUserWorkItem(rpc_sendreceive_thread, &message_state->params, WT_EXECUTEDEFAULT))
895
        {
896
            ERR("QueueUserWorkItem failed with error %u\n", GetLastError());
897 898
            hr = E_UNEXPECTED;
        }
899 900
        else
            hr = S_OK;
901
    }
902

903
    if (hr == S_OK)
904
    {
905
        if (WaitForSingleObject(message_state->params.handle, 0))
906 907
        {
            COM_CurrentInfo()->pending_call_count_client++;
908
            hr = CoWaitForMultipleHandles(0, INFINITE, 1, &message_state->params.handle, &index);
909 910
            COM_CurrentInfo()->pending_call_count_client--;
        }
911
    }
912
    ClientRpcChannelBuffer_ReleaseEventHandle(This, message_state->params.handle);
913

914 915
    /* for WM shortcut, faults are returned in params->hr */
    if (hr == S_OK)
916
        hrFault = message_state->params.hr;
917

918
    status = message_state->params.status;
919

920 921 922
    orpcthat.flags = ORPCF_NULL;
    orpcthat.extensions = NULL;

923
    TRACE("RPC call status: 0x%x\n", status);
924
    if (status != RPC_S_OK)
925 926 927 928 929
        hr = HRESULT_FROM_WIN32(status);

    TRACE("hrFault = 0x%08x\n", hrFault);

    /* FIXME: this condition should be
930
     * "hr == S_OK && (!hrFault || msg->BufferLength > FIELD_OFFSET(ORPCTHAT, extensions) + 4)"
931 932 933
     * but we don't currently reset the message length for PostMessage
     * dispatched calls */
    if (hr == S_OK && hrFault == S_OK)
934 935 936 937 938 939 940 941 942 943
    {
        HRESULT hr2;
        char *original_buffer = msg->Buffer;

        /* handle ORPCTHAT and client extensions */

        hr2 = unmarshal_ORPCTHAT(msg, &orpcthat, &orpc_ext_array, &first_wire_orpc_extent);
        if (FAILED(hr2))
            hr = hr2;

944
        message_state->prefix_data_len = (char *)msg->Buffer - original_buffer;
945 946 947 948 949
        msg->BufferLength -= message_state->prefix_data_len;
    }
    else
        message_state->prefix_data_len = 0;

950 951 952 953 954 955 956 957
    if (hr == S_OK)
    {
        ChannelHooks_ClientNotify(&message_state->channel_hook_info,
                                  msg->DataRepresentation,
                                  first_wire_orpc_extent,
                                  orpcthat.extensions && first_wire_orpc_extent ? orpcthat.extensions->size : 0,
                                  hrFault);
    }
958 959 960 961

    /* save away the message state again */
    msg->Handle = message_state;

962 963
    if (pstatus) *pstatus = status;

964 965
    if (hr == S_OK)
        hr = hrFault;
966

967
    TRACE("-- 0x%08x\n", hr);
968 969

    return hr;
970 971
}

972
static HRESULT WINAPI ServerRpcChannelBuffer_FreeBuffer(LPRPCCHANNELBUFFER iface, RPCOLEMESSAGE* olemsg)
973
{
974 975
    RPC_MESSAGE *msg = (RPC_MESSAGE *)olemsg;
    RPC_STATUS status;
976
    struct message_state *message_state;
977 978 979

    TRACE("(%p)\n", msg);

980
    message_state = msg->Handle;
981 982 983 984 985 986
    /* restore the binding handle and the real start of data */
    msg->Handle = message_state->binding_handle;
    msg->Buffer = (char *)msg->Buffer - message_state->prefix_data_len;
    msg->BufferLength += message_state->prefix_data_len;
    message_state->prefix_data_len = 0;

987 988 989 990 991 992 993
    if (message_state->bypass_rpcrt)
    {
        HeapFree(GetProcessHeap(), 0, msg->Buffer);
        status = RPC_S_OK;
    }
    else
        status = I_RpcFreeBuffer(msg);
994

995 996
    msg->Handle = message_state;

997
    TRACE("-- %d\n", status);
998 999 1000 1001 1002 1003 1004 1005

    return HRESULT_FROM_WIN32(status);
}

static HRESULT WINAPI ClientRpcChannelBuffer_FreeBuffer(LPRPCCHANNELBUFFER iface, RPCOLEMESSAGE* olemsg)
{
    RPC_MESSAGE *msg = (RPC_MESSAGE *)olemsg;
    RPC_STATUS status;
1006
    struct message_state *message_state;
1007 1008 1009

    TRACE("(%p)\n", msg);

1010
    message_state = msg->Handle;
1011 1012 1013 1014 1015
    /* restore the binding handle and the real start of data */
    msg->Handle = message_state->binding_handle;
    msg->Buffer = (char *)msg->Buffer - message_state->prefix_data_len;
    msg->BufferLength += message_state->prefix_data_len;

1016 1017 1018 1019 1020 1021 1022
    if (message_state->params.bypass_rpcrt)
    {
        HeapFree(GetProcessHeap(), 0, msg->Buffer);
        status = RPC_S_OK;
    }
    else
        status = I_RpcFreeBuffer(msg);
1023 1024 1025

    HeapFree(GetProcessHeap(), 0, msg->RpcInterfaceInformation);
    msg->RpcInterfaceInformation = NULL;
1026 1027 1028 1029 1030

    if (message_state->params.stub)
        IRpcStubBuffer_Release(message_state->params.stub);
    if (message_state->params.chan)
        IRpcChannelBuffer_Release(message_state->params.chan);
1031
    HeapFree(GetProcessHeap(), 0, message_state);
1032

1033
    TRACE("-- %d\n", status);
1034 1035

    return HRESULT_FROM_WIN32(status);
1036 1037
}

1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050
static HRESULT WINAPI ClientRpcChannelBuffer_GetDestCtx(LPRPCCHANNELBUFFER iface, DWORD* pdwDestContext, void** ppvDestContext)
{
    ClientRpcChannelBuffer *This = (ClientRpcChannelBuffer *)iface;

    TRACE("(%p,%p)\n", pdwDestContext, ppvDestContext);

    *pdwDestContext = This->dest_context;
    *ppvDestContext = This->dest_context_data;

    return S_OK;
}

static HRESULT WINAPI ServerRpcChannelBuffer_GetDestCtx(LPRPCCHANNELBUFFER iface, DWORD* pdwDestContext, void** ppvDestContext)
1051
{
1052 1053 1054 1055 1056 1057 1058
    WARN("(%p,%p), stub!\n", pdwDestContext, ppvDestContext);

    /* FIXME: implement this by storing the dwDestContext and pvDestContext
     * values passed into IMarshal_MarshalInterface and returning them here */
    *pdwDestContext = MSHCTX_DIFFERENTMACHINE;
    *ppvDestContext = NULL;
    return S_OK;
1059
}
1060

1061 1062 1063 1064 1065 1066
static HRESULT WINAPI RpcChannelBuffer_IsConnected(LPRPCCHANNELBUFFER iface)
{
    TRACE("()\n");
    /* native does nothing too */
    return S_OK;
}
1067

1068 1069 1070 1071 1072 1073
static const IRpcChannelBufferVtbl ClientRpcChannelBufferVtbl =
{
    RpcChannelBuffer_QueryInterface,
    RpcChannelBuffer_AddRef,
    ClientRpcChannelBuffer_Release,
    ClientRpcChannelBuffer_GetBuffer,
1074
    ClientRpcChannelBuffer_SendReceive,
1075
    ClientRpcChannelBuffer_FreeBuffer,
1076
    ClientRpcChannelBuffer_GetDestCtx,
1077 1078
    RpcChannelBuffer_IsConnected
};
1079

1080 1081 1082 1083 1084 1085
static const IRpcChannelBufferVtbl ServerRpcChannelBufferVtbl =
{
    RpcChannelBuffer_QueryInterface,
    RpcChannelBuffer_AddRef,
    ServerRpcChannelBuffer_Release,
    ServerRpcChannelBuffer_GetBuffer,
1086
    ServerRpcChannelBuffer_SendReceive,
1087
    ServerRpcChannelBuffer_FreeBuffer,
1088
    ServerRpcChannelBuffer_GetDestCtx,
1089 1090
    RpcChannelBuffer_IsConnected
};
1091

1092
/* returns a channel buffer for proxies */
1093
HRESULT RPC_CreateClientChannel(const OXID *oxid, const IPID *ipid,
1094
                                const OXID_INFO *oxid_info,
1095 1096
                                DWORD dest_context, void *dest_context_data,
                                IRpcChannelBuffer **chan)
1097
{
1098 1099 1100 1101 1102 1103
    ClientRpcChannelBuffer *This;
    WCHAR                   endpoint[200];
    RPC_BINDING_HANDLE      bind;
    RPC_STATUS              status;
    LPWSTR                  string_binding;

1104
    /* FIXME: get the endpoint from oxid_info->psa instead */
1105
    get_rpc_endpoint(endpoint, oxid);
1106

1107 1108 1109 1110
    TRACE("proxy pipe: connecting to endpoint: %s\n", debugstr_w(endpoint));

    status = RpcStringBindingComposeW(
        NULL,
1111
        wszRpcTransport,
1112 1113 1114 1115 1116 1117
        NULL,
        endpoint,
        NULL,
        &string_binding);
        
    if (status == RPC_S_OK)
1118
    {
1119 1120 1121
        status = RpcBindingFromStringBindingW(string_binding, &bind);

        if (status == RPC_S_OK)
1122
        {
1123 1124
            IPID ipid2 = *ipid; /* why can't RpcBindingSetObject take a const? */
            status = RpcBindingSetObject(bind, &ipid2);
1125 1126
            if (status != RPC_S_OK)
                RpcBindingFree(&bind);
1127
        }
1128 1129

        RpcStringFreeW(&string_binding);
1130 1131
    }

1132 1133
    if (status != RPC_S_OK)
    {
1134
        ERR("Couldn't get binding for endpoint %s, status = %d\n", debugstr_w(endpoint), status);
1135
        return HRESULT_FROM_WIN32(status);
1136 1137
    }

1138 1139 1140 1141 1142 1143
    This = HeapAlloc(GetProcessHeap(), 0, sizeof(*This));
    if (!This)
    {
        RpcBindingFree(&bind);
        return E_OUTOFMEMORY;
    }
1144

1145 1146 1147
    This->super.lpVtbl = &ClientRpcChannelBufferVtbl;
    This->super.refs = 1;
    This->bind = bind;
1148
    apartment_getoxid(COM_CurrentApt(), &This->oxid);
1149
    This->server_pid = oxid_info->dwPid;
1150 1151
    This->dest_context = dest_context;
    This->dest_context_data = dest_context_data;
1152
    This->event = NULL;
1153

1154
    *chan = (IRpcChannelBuffer*)This;
1155

1156
    return S_OK;
1157 1158
}

1159
HRESULT RPC_CreateServerChannel(IRpcChannelBuffer **chan)
1160
{
1161 1162 1163 1164 1165 1166 1167 1168 1169
    RpcChannelBuffer *This = HeapAlloc(GetProcessHeap(), 0, sizeof(*This));
    if (!This)
        return E_OUTOFMEMORY;

    This->lpVtbl = &ServerRpcChannelBufferVtbl;
    This->refs = 1;
    
    *chan = (IRpcChannelBuffer*)This;

1170 1171 1172
    return S_OK;
}

1173 1174 1175 1176 1177 1178 1179 1180 1181
/* unmarshals ORPC_EXTENT_ARRAY according to NDR rules, but doesn't allocate
 * any memory */
static HRESULT unmarshal_ORPC_EXTENT_ARRAY(RPC_MESSAGE *msg, const char *end,
                                           ORPC_EXTENT_ARRAY *extensions,
                                           WIRE_ORPC_EXTENT **first_wire_orpc_extent)
{
    DWORD pointer_id;
    DWORD i;

1182 1183
    memcpy(extensions, msg->Buffer, FIELD_OFFSET(WIRE_ORPC_EXTENT_ARRAY, extent));
    msg->Buffer = (char *)msg->Buffer + FIELD_OFFSET(WIRE_ORPC_EXTENT_ARRAY, extent);
1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201

    if ((const char *)msg->Buffer + 2 * sizeof(DWORD) > end)
        return RPC_E_INVALID_HEADER;

    pointer_id = *(DWORD *)msg->Buffer;
    msg->Buffer = (char *)msg->Buffer + sizeof(DWORD);
    extensions->extent = NULL;

    if (pointer_id)
    {
        WIRE_ORPC_EXTENT *wire_orpc_extent;

        /* conformance */
        if (*(DWORD *)msg->Buffer != ((extensions->size+1)&~1))
            return RPC_S_INVALID_BOUND;

        msg->Buffer = (char *)msg->Buffer + sizeof(DWORD);

Austin English's avatar
Austin English committed
1202
        /* arbitrary limit for security (don't know what native does) */
1203 1204
        if (extensions->size > 256)
        {
1205
            ERR("too many extensions: %d\n", extensions->size);
1206 1207 1208
            return RPC_S_INVALID_BOUND;
        }

1209
        *first_wire_orpc_extent = wire_orpc_extent = msg->Buffer;
1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226
        for (i = 0; i < ((extensions->size+1)&~1); i++)
        {
            if ((const char *)&wire_orpc_extent->data[0] > end)
                return RPC_S_INVALID_BOUND;
            if (wire_orpc_extent->conformance != ((wire_orpc_extent->size+7)&~7))
                return RPC_S_INVALID_BOUND;
            if ((const char *)&wire_orpc_extent->data[wire_orpc_extent->conformance] > end)
                return RPC_S_INVALID_BOUND;
            TRACE("size %u, guid %s\n", wire_orpc_extent->size, debugstr_guid(&wire_orpc_extent->id));
            wire_orpc_extent = (WIRE_ORPC_EXTENT *)&wire_orpc_extent->data[wire_orpc_extent->conformance];
        }
        msg->Buffer = wire_orpc_extent;
    }

    return S_OK;
}

1227 1228 1229 1230 1231 1232 1233 1234
/* unmarshals ORPCTHIS according to NDR rules, but doesn't allocate any memory */
static HRESULT unmarshal_ORPCTHIS(RPC_MESSAGE *msg, ORPCTHIS *orpcthis,
    ORPC_EXTENT_ARRAY *orpc_ext_array, WIRE_ORPC_EXTENT **first_wire_orpc_extent)
{
    const char *end = (char *)msg->Buffer + msg->BufferLength;

    *first_wire_orpc_extent = NULL;

1235
    if (msg->BufferLength < FIELD_OFFSET(WIRE_ORPCTHIS, extensions) + sizeof(DWORD))
1236 1237 1238 1239 1240
    {
        ERR("invalid buffer length\n");
        return RPC_E_INVALID_HEADER;
    }

1241 1242
    memcpy(orpcthis, msg->Buffer, FIELD_OFFSET(WIRE_ORPCTHIS, extensions));
    msg->Buffer = (char *)msg->Buffer + FIELD_OFFSET(WIRE_ORPCTHIS, extensions);
1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255

    if ((const char *)msg->Buffer + sizeof(DWORD) > end)
        return RPC_E_INVALID_HEADER;

    if (*(DWORD *)msg->Buffer)
        orpcthis->extensions = orpc_ext_array;
    else
        orpcthis->extensions = NULL;

    msg->Buffer = (char *)msg->Buffer + sizeof(DWORD);

    if (orpcthis->extensions)
    {
1256 1257 1258 1259
        HRESULT hr = unmarshal_ORPC_EXTENT_ARRAY(msg, end, orpc_ext_array,
                                                 first_wire_orpc_extent);
        if (FAILED(hr))
            return hr;
1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271
    }

    if ((orpcthis->version.MajorVersion != COM_MAJOR_VERSION) ||
        (orpcthis->version.MinorVersion > COM_MINOR_VERSION))
    {
        ERR("COM version {%d, %d} not supported\n",
            orpcthis->version.MajorVersion, orpcthis->version.MinorVersion);
        return RPC_E_VERSION_MISMATCH;
    }

    if (orpcthis->flags & ~(ORPCF_LOCAL|ORPCF_RESERVED1|ORPCF_RESERVED2|ORPCF_RESERVED3|ORPCF_RESERVED4))
    {
1272
        ERR("invalid flags 0x%x\n", orpcthis->flags & ~(ORPCF_LOCAL|ORPCF_RESERVED1|ORPCF_RESERVED2|ORPCF_RESERVED3|ORPCF_RESERVED4));
1273
        return RPC_E_INVALID_HEADER;
1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285
    }

    return S_OK;
}

static HRESULT unmarshal_ORPCTHAT(RPC_MESSAGE *msg, ORPCTHAT *orpcthat,
                                  ORPC_EXTENT_ARRAY *orpc_ext_array, WIRE_ORPC_EXTENT **first_wire_orpc_extent)
{
    const char *end = (char *)msg->Buffer + msg->BufferLength;

    *first_wire_orpc_extent = NULL;

1286
    if (msg->BufferLength < FIELD_OFFSET(WIRE_ORPCTHAT, extensions) + sizeof(DWORD))
1287 1288 1289 1290 1291
    {
        ERR("invalid buffer length\n");
        return RPC_E_INVALID_HEADER;
    }

1292 1293
    memcpy(orpcthat, msg->Buffer, FIELD_OFFSET(WIRE_ORPCTHAT, extensions));
    msg->Buffer = (char *)msg->Buffer + FIELD_OFFSET(WIRE_ORPCTHAT, extensions);
1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314

    if ((const char *)msg->Buffer + sizeof(DWORD) > end)
        return RPC_E_INVALID_HEADER;

    if (*(DWORD *)msg->Buffer)
        orpcthat->extensions = orpc_ext_array;
    else
        orpcthat->extensions = NULL;

    msg->Buffer = (char *)msg->Buffer + sizeof(DWORD);

    if (orpcthat->extensions)
    {
        HRESULT hr = unmarshal_ORPC_EXTENT_ARRAY(msg, end, orpc_ext_array,
                                                 first_wire_orpc_extent);
        if (FAILED(hr))
            return hr;
    }

    if (orpcthat->flags & ~(ORPCF_LOCAL|ORPCF_RESERVED1|ORPCF_RESERVED2|ORPCF_RESERVED3|ORPCF_RESERVED4))
    {
1315
        ERR("invalid flags 0x%x\n", orpcthat->flags & ~(ORPCF_LOCAL|ORPCF_RESERVED1|ORPCF_RESERVED2|ORPCF_RESERVED3|ORPCF_RESERVED4));
1316
        return RPC_E_INVALID_HEADER;
1317 1318 1319 1320
    }

    return S_OK;
}
1321

1322
void RPC_ExecuteCall(struct dispatch_params *params)
1323
{
1324
    struct message_state *message_state = NULL;
1325 1326 1327 1328 1329
    RPC_MESSAGE *msg = (RPC_MESSAGE *)params->msg;
    char *original_buffer = msg->Buffer;
    ORPCTHIS orpcthis;
    ORPC_EXTENT_ARRAY orpc_ext_array;
    WIRE_ORPC_EXTENT *first_wire_orpc_extent;
1330
    GUID old_causality_id;
1331

1332 1333
    /* handle ORPCTHIS and server extensions */

1334 1335
    params->hr = unmarshal_ORPCTHIS(msg, &orpcthis, &orpc_ext_array, &first_wire_orpc_extent);
    if (params->hr != S_OK)
1336 1337
    {
        msg->Buffer = original_buffer;
1338
        goto exit;
1339
    }
1340 1341 1342 1343 1344

    message_state = HeapAlloc(GetProcessHeap(), 0, sizeof(*message_state));
    if (!message_state)
    {
        params->hr = E_OUTOFMEMORY;
1345
        msg->Buffer = original_buffer;
1346 1347 1348
        goto exit;
    }

1349
    message_state->prefix_data_len = (char *)msg->Buffer - original_buffer;
1350
    message_state->binding_handle = msg->Handle;
1351
    message_state->bypass_rpcrt = params->bypass_rpcrt;
1352

1353
    message_state->channel_hook_info.iid = params->iid;
1354 1355 1356 1357
    message_state->channel_hook_info.cbSize = sizeof(message_state->channel_hook_info);
    message_state->channel_hook_info.uCausality = orpcthis.cid;
    message_state->channel_hook_info.dwServerPid = GetCurrentProcessId();
    message_state->channel_hook_info.iMethod = msg->ProcNum;
1358
    message_state->channel_hook_info.pObject = params->iface;
1359 1360 1361 1362 1363

    if (orpcthis.extensions && first_wire_orpc_extent &&
        orpcthis.extensions->size)
        ChannelHooks_ServerNotify(&message_state->channel_hook_info, msg->DataRepresentation, first_wire_orpc_extent, orpcthis.extensions->size);

1364 1365 1366
    msg->Handle = message_state;
    msg->BufferLength -= message_state->prefix_data_len;

1367 1368 1369 1370 1371 1372
    /* call message filter */

    if (COM_CurrentApt()->filter)
    {
        DWORD handlecall;
        INTERFACEINFO interface_info;
1373
        CALLTYPE calltype;
1374

1375 1376
        interface_info.pUnk = params->iface;
        interface_info.iid = params->iid;
1377
        interface_info.wMethod = msg->ProcNum;
1378

1379 1380
        if (IsEqualGUID(&orpcthis.cid, &COM_CurrentInfo()->causality_id))
            calltype = CALLTYPE_NESTED;
1381
        else if (COM_CurrentInfo()->pending_call_count_server == 0)
1382
            calltype = CALLTYPE_TOPLEVEL;
1383 1384 1385
        else
            calltype = CALLTYPE_TOPLEVEL_CALLPENDING;

1386
        handlecall = IMessageFilter_HandleInComingCall(COM_CurrentApt()->filter,
1387
                                                       calltype,
1388
                                                       UlongToHandle(GetCurrentProcessId()),
1389 1390 1391 1392 1393 1394 1395
                                                       0 /* FIXME */,
                                                       &interface_info);
        TRACE("IMessageFilter_HandleInComingCall returned %d\n", handlecall);
        switch (handlecall)
        {
        case SERVERCALL_REJECTED:
            params->hr = RPC_E_CALL_REJECTED;
1396
            goto exit_reset_state;
1397 1398 1399
        case SERVERCALL_RETRYLATER:
#if 0 /* FIXME: handle retries on the client side before enabling this code */
            params->hr = RPC_E_RETRY;
1400
            goto exit_reset_state;
1401 1402 1403 1404 1405 1406 1407 1408 1409 1410
#else
            FIXME("retry call later not implemented\n");
            break;
#endif
        case SERVERCALL_ISHANDLED:
        default:
            break;
        }
    }

1411 1412
    /* invoke the method */

1413 1414 1415 1416 1417
    /* save the old causality ID - note: any calls executed while processing
     * messages received during the SendReceive will appear to originate from
     * this call - this should be checked with what Windows does */
    old_causality_id = COM_CurrentInfo()->causality_id;
    COM_CurrentInfo()->causality_id = orpcthis.cid;
1418
    COM_CurrentInfo()->pending_call_count_server++;
1419
    params->hr = IRpcStubBuffer_Invoke(params->stub, params->msg, params->chan);
1420
    COM_CurrentInfo()->pending_call_count_server--;
1421
    COM_CurrentInfo()->causality_id = old_causality_id;
1422

1423 1424 1425 1426
    /* the invoke allocated a new buffer, so free the old one */
    if (message_state->bypass_rpcrt && original_buffer != msg->Buffer)
        HeapFree(GetProcessHeap(), 0, original_buffer);

1427
exit_reset_state:
1428
    message_state = msg->Handle;
1429 1430 1431 1432 1433
    msg->Handle = message_state->binding_handle;
    msg->Buffer = (char *)msg->Buffer - message_state->prefix_data_len;
    msg->BufferLength += message_state->prefix_data_len;

exit:
1434
    HeapFree(GetProcessHeap(), 0, message_state);
1435
    if (params->handle) SetEvent(params->handle);
1436 1437
}

1438 1439
static void __RPC_STUB dispatch_rpc(RPC_MESSAGE *msg)
{
1440
    struct dispatch_params *params;
1441 1442 1443
    APARTMENT *apt;
    IPID ipid;
    HRESULT hr;
1444

1445
    RpcBindingInqObject(msg->Handle, &ipid);
1446

1447 1448
    TRACE("ipid = %s, iMethod = %d\n", debugstr_guid(&ipid), msg->ProcNum);

1449
    params = HeapAlloc(GetProcessHeap(), 0, sizeof(*params));
1450 1451 1452 1453 1454
    if (!params)
    {
        RpcRaiseException(E_OUTOFMEMORY);
        return;
    }
1455

1456 1457
    hr = ipid_get_dispatch_params(&ipid, &apt, &params->stub, &params->chan,
                                  &params->iid, &params->iface);
1458
    if (hr != S_OK)
1459
    {
1460
        ERR("no apartment found for ipid %s\n", debugstr_guid(&ipid));
1461
        HeapFree(GetProcessHeap(), 0, params);
1462 1463
        RpcRaiseException(hr);
        return;
1464 1465
    }

1466 1467
    params->msg = (RPCOLEMESSAGE *)msg;
    params->status = RPC_S_OK;
1468 1469
    params->hr = S_OK;
    params->handle = NULL;
1470
    params->bypass_rpcrt = FALSE;
1471

1472 1473 1474
    /* Note: this is the important difference between STAs and MTAs - we
     * always execute RPCs to STAs in the thread that originally created the
     * apartment (i.e. the one that pumps messages to the window) */
1475
    if (!apt->multi_threaded)
1476 1477 1478
    {
        params->handle = CreateEventW(NULL, FALSE, FALSE, NULL);

1479
        TRACE("Calling apartment thread 0x%08x...\n", apt->tid);
1480

1481
        if (PostMessageW(apartment_getwindow(apt), DM_EXECUTERPC, 0, (LPARAM)params))
1482 1483 1484
            WaitForSingleObject(params->handle, INFINITE);
        else
        {
1485
            ERR("PostMessage failed with error %u\n", GetLastError());
1486 1487 1488
            IRpcChannelBuffer_Release(params->chan);
            IRpcStubBuffer_Release(params->stub);
        }
1489 1490
        CloseHandle(params->handle);
    }
1491
    else
1492 1493 1494 1495 1496 1497 1498
    {
        BOOL joined = FALSE;
        if (!COM_CurrentInfo()->apt)
        {
            apartment_joinmta();
            joined = TRUE;
        }
1499
        RPC_ExecuteCall(params);
1500 1501 1502 1503 1504 1505
        if (joined)
        {
            apartment_release(COM_CurrentInfo()->apt);
            COM_CurrentInfo()->apt = NULL;
        }
    }
1506

1507
    hr = params->hr;
1508 1509 1510 1511
    if (params->chan)
        IRpcChannelBuffer_Release(params->chan);
    if (params->stub)
        IRpcStubBuffer_Release(params->stub);
1512
    HeapFree(GetProcessHeap(), 0, params);
1513

1514
    apartment_release(apt);
1515 1516 1517 1518

    /* if IRpcStubBuffer_Invoke fails, we should raise an exception to tell
     * the RPC runtime that the call failed */
    if (hr) RpcRaiseException(hr);
1519 1520
}

1521 1522
/* stub registration */
HRESULT RPC_RegisterInterface(REFIID riid)
1523
{
1524 1525 1526 1527 1528
    struct registered_if *rif;
    BOOL found = FALSE;
    HRESULT hr = S_OK;
    
    TRACE("(%s)\n", debugstr_guid(riid));
1529

1530 1531
    EnterCriticalSection(&csRegIf);
    LIST_FOR_EACH_ENTRY(rif, &registered_interfaces, struct registered_if, entry)
1532
    {
1533 1534 1535 1536 1537 1538
        if (IsEqualGUID(&rif->If.InterfaceId.SyntaxGUID, riid))
        {
            rif->refs++;
            found = TRUE;
            break;
        }
1539
    }
1540 1541 1542
    if (!found)
    {
        TRACE("Creating new interface\n");
1543

1544
        rif = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*rif));
1545 1546 1547 1548 1549 1550 1551 1552 1553
        if (rif)
        {
            RPC_STATUS status;

            rif->refs = 1;
            rif->If.Length = sizeof(RPC_SERVER_INTERFACE);
            /* RPC interface ID = COM interface ID */
            rif->If.InterfaceId.SyntaxGUID = *riid;
            rif->If.DispatchTable = &rpc_dispatch;
1554 1555
            /* all other fields are 0, including the version asCOM objects
             * always have a version of 0.0 */
1556 1557 1558 1559 1560 1561 1562 1563 1564 1565
            status = RpcServerRegisterIfEx(
                (RPC_IF_HANDLE)&rif->If,
                NULL, NULL,
                RPC_IF_OLE | RPC_IF_AUTOLISTEN,
                RPC_C_LISTEN_MAX_CALLS_DEFAULT,
                NULL);
            if (status == RPC_S_OK)
                list_add_tail(&registered_interfaces, &rif->entry);
            else
            {
1566
                ERR("RpcServerRegisterIfEx failed with error %d\n", status);
1567 1568 1569 1570 1571 1572 1573 1574 1575
                HeapFree(GetProcessHeap(), 0, rif);
                hr = HRESULT_FROM_WIN32(status);
            }
        }
        else
            hr = E_OUTOFMEMORY;
    }
    LeaveCriticalSection(&csRegIf);
    return hr;
1576 1577
}

1578 1579
/* stub unregistration */
void RPC_UnregisterInterface(REFIID riid)
1580
{
1581 1582 1583
    struct registered_if *rif;
    EnterCriticalSection(&csRegIf);
    LIST_FOR_EACH_ENTRY(rif, &registered_interfaces, struct registered_if, entry)
1584
    {
1585
        if (IsEqualGUID(&rif->If.InterfaceId.SyntaxGUID, riid))
1586
        {
1587 1588
            if (!--rif->refs)
            {
1589
                RpcServerUnregisterIf((RPC_IF_HANDLE)&rif->If, NULL, TRUE);
1590 1591 1592 1593
                list_remove(&rif->entry);
                HeapFree(GetProcessHeap(), 0, rif);
            }
            break;
1594
        }
1595 1596 1597
    }
    LeaveCriticalSection(&csRegIf);
}
1598

1599 1600
/* get the info for an OXID, including the IPID for the rem unknown interface
 * and the string binding */
1601 1602
HRESULT RPC_ResolveOxid(OXID oxid, OXID_INFO *oxid_info)
{
1603 1604
    TRACE("%s\n", wine_dbgstr_longlong(oxid));

1605 1606 1607 1608 1609 1610 1611 1612 1613
    oxid_info->dwTid = 0;
    oxid_info->dwPid = 0;
    oxid_info->dwAuthnHint = RPC_C_AUTHN_LEVEL_NONE;
    /* FIXME: this is a hack around not having an OXID resolver yet -
     * this function should contact the machine's OXID resolver and then it
     * should give us the IPID of the IRemUnknown interface */
    oxid_info->ipidRemUnknown.Data1 = 0xffffffff;
    oxid_info->ipidRemUnknown.Data2 = 0xffff;
    oxid_info->ipidRemUnknown.Data3 = 0xffff;
1614
    memcpy(oxid_info->ipidRemUnknown.Data4, &oxid, sizeof(OXID));
1615 1616 1617 1618 1619
    oxid_info->psa = NULL /* FIXME */;

    return S_OK;
}

1620 1621 1622
/* make the apartment reachable by other threads and processes and create the
 * IRemUnknown object */
void RPC_StartRemoting(struct apartment *apt)
1623
{
1624
    if (!InterlockedExchange(&apt->remoting_started, TRUE))
1625 1626 1627
    {
        WCHAR endpoint[200];
        RPC_STATUS status;
1628

1629
        get_rpc_endpoint(endpoint, &apt->oxid);
1630
    
1631
        status = RpcServerUseProtseqEpW(
1632
            wszRpcTransport,
1633 1634 1635 1636 1637
            RPC_C_PROTSEQ_MAX_REQS_DEFAULT,
            endpoint,
            NULL);
        if (status != RPC_S_OK)
            ERR("Couldn't register endpoint %s\n", debugstr_w(endpoint));
1638 1639

        /* FIXME: move remote unknown exporting into this function */
1640
    }
1641
    start_apartment_remote_unknown();
1642 1643
}

1644

1645
static HRESULT create_server(REFCLSID rclsid, HANDLE *process)
1646
{
1647
    static const WCHAR  wszLocalServer32[] = { 'L','o','c','a','l','S','e','r','v','e','r','3','2',0 };
1648 1649
    static const WCHAR  embedding[] = { ' ', '-','E','m','b','e','d','d','i','n','g',0 };
    HKEY                key;
1650
    HRESULT             hres;
1651
    WCHAR               command[MAX_PATH+sizeof(embedding)/sizeof(WCHAR)];
1652
    DWORD               size = (MAX_PATH+1) * sizeof(WCHAR);
1653 1654 1655
    STARTUPINFOW        sinfo;
    PROCESS_INFORMATION pinfo;

1656 1657
    hres = COM_OpenKeyForCLSID(rclsid, wszLocalServer32, KEY_READ, &key);
    if (FAILED(hres)) {
1658
        ERR("class %s not registered\n", debugstr_guid(rclsid));
1659
        return hres;
1660
    }
1661

1662
    hres = RegQueryValueExW(key, NULL, NULL, NULL, (LPBYTE)command, &size);
1663 1664 1665 1666 1667
    RegCloseKey(key);
    if (hres) {
        WARN("No default value for LocalServer32 key\n");
        return REGDB_E_CLASSNOTREG; /* FIXME: check retval */
    }
1668

1669 1670
    memset(&sinfo,0,sizeof(sinfo));
    sinfo.cb = sizeof(sinfo);
1671

1672
    /* EXE servers are started with the -Embedding switch. */
1673

1674
    strcatW(command, embedding);
1675

1676
    TRACE("activating local server %s for %s\n", debugstr_w(command), debugstr_guid(rclsid));
1677

1678 1679 1680 1681
    /* FIXME: Win2003 supports a ServerExecutable value that is passed into
     * CreateProcess */
    if (!CreateProcessW(NULL, command, NULL, NULL, FALSE, 0, NULL, NULL, &sinfo, &pinfo)) {
        WARN("failed to run local server %s\n", debugstr_w(command));
1682
        return HRESULT_FROM_WIN32(GetLastError());
1683
    }
1684
    *process = pinfo.hProcess;
1685
    CloseHandle(pinfo.hThread);
1686

1687
    return S_OK;
1688
}
1689 1690 1691 1692

/*
 * start_local_service()  - start a service given its name and parameters
 */
1693
static DWORD start_local_service(LPCWSTR name, DWORD num, LPCWSTR *params)
1694 1695
{
    SC_HANDLE handle, hsvc;
1696
    DWORD     r = ERROR_FUNCTION_FAILED;
1697

1698
    TRACE("Starting service %s %d params\n", debugstr_w(name), num);
1699

1700
    handle = OpenSCManagerW(NULL, NULL, SC_MANAGER_CONNECT);
1701 1702
    if (!handle)
        return r;
1703
    hsvc = OpenServiceW(handle, name, SERVICE_START);
1704 1705
    if (hsvc)
    {
1706
        if(StartServiceW(hsvc, num, params))
1707 1708 1709
            r = ERROR_SUCCESS;
        else
            r = GetLastError();
1710
        if (r == ERROR_SERVICE_ALREADY_RUNNING)
1711 1712 1713
            r = ERROR_SUCCESS;
        CloseServiceHandle(hsvc);
    }
1714 1715
    else
        r = GetLastError();
1716 1717
    CloseServiceHandle(handle);

1718
    TRACE("StartService returned error %u (%s)\n", r, (r == ERROR_SUCCESS) ? "ok":"failed");
1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731

    return r;
}

/*
 * create_local_service()  - start a COM server in a service
 *
 *   To start a Local Service, we read the AppID value under
 * the class's CLSID key, then open the HKCR\\AppId key specified
 * there and check for a LocalService value.
 *
 * Note:  Local Services are not supported under Windows 9x
 */
1732
static HRESULT create_local_service(REFCLSID rclsid)
1733
{
1734
    HRESULT hres;
1735
    WCHAR buf[CHARS_IN_GUID];
1736 1737
    static const WCHAR szLocalService[] = { 'L','o','c','a','l','S','e','r','v','i','c','e',0 };
    static const WCHAR szServiceParams[] = {'S','e','r','v','i','c','e','P','a','r','a','m','s',0};
1738 1739 1740 1741 1742 1743
    HKEY hkey;
    LONG r;
    DWORD type, sz;

    TRACE("Attempting to start Local service for %s\n", debugstr_guid(rclsid));

1744
    hres = COM_OpenKeyForAppIdFromCLSID(rclsid, KEY_READ, &hkey);
1745
    if (FAILED(hres))
1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770
        return hres;

    /* read the LocalService and ServiceParameters values from the AppID key */
    sz = sizeof buf;
    r = RegQueryValueExW(hkey, szLocalService, NULL, &type, (LPBYTE)buf, &sz);
    if (r==ERROR_SUCCESS && type==REG_SZ)
    {
        DWORD num_args = 0;
        LPWSTR args[1] = { NULL };

        /*
         * FIXME: I'm not really sure how to deal with the service parameters.
         *        I suspect that the string returned from RegQueryValueExW
         *        should be split into a number of arguments by spaces.
         *        It would make more sense if ServiceParams contained a
         *        REG_MULTI_SZ here, but it's a REG_SZ for the services
         *        that I'm interested in for the moment.
         */
        r = RegQueryValueExW(hkey, szServiceParams, NULL, &type, NULL, &sz);
        if (r == ERROR_SUCCESS && type == REG_SZ && sz)
        {
            args[0] = HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY,sz);
            num_args++;
            RegQueryValueExW(hkey, szServiceParams, NULL, &type, (LPBYTE)args[0], &sz);
        }
1771
        r = start_local_service(buf, num_args, (LPCWSTR *)args);
1772 1773
        if (r != ERROR_SUCCESS)
            hres = REGDB_E_CLASSNOTREG; /* FIXME: check retval */
1774 1775
        HeapFree(GetProcessHeap(),0,args[0]);
    }
1776 1777 1778 1779 1780
    else
    {
        WARN("No LocalService value\n");
        hres = REGDB_E_CLASSNOTREG; /* FIXME: check retval */
    }
1781
    RegCloseKey(hkey);
1782

1783 1784 1785
    return hres;
}

1786 1787 1788 1789 1790 1791 1792

static void get_localserver_pipe_name(WCHAR *pipefn, REFCLSID rclsid)
{
    static const WCHAR wszPipeRef[] = {'\\','\\','.','\\','p','i','p','e','\\',0};
    strcpyW(pipefn, wszPipeRef);
    StringFromGUID2(rclsid, pipefn + sizeof(wszPipeRef)/sizeof(wszPipeRef[0]) - 1, CHARS_IN_GUID);
}
1793 1794

/* FIXME: should call to rpcss instead */
1795
HRESULT RPC_GetLocalClassObject(REFCLSID rclsid, REFIID iid, LPVOID *ppv)
1796 1797 1798
{
    HRESULT        hres;
    HANDLE         hPipe;
1799
    WCHAR          pipefn[100];
1800 1801 1802 1803 1804 1805
    DWORD          res, bufferlen;
    char           marshalbuffer[200];
    IStream       *pStm;
    LARGE_INTEGER  seekto;
    ULARGE_INTEGER newpos;
    int            tries = 0;
1806

1807
    static const int MAXTRIES = 30; /* 30 seconds */
1808 1809 1810

    TRACE("rclsid=%s, iid=%s\n", debugstr_guid(rclsid), debugstr_guid(iid));

1811
    get_localserver_pipe_name(pipefn, rclsid);
1812 1813

    while (tries++ < MAXTRIES) {
1814
        TRACE("waiting for %s\n", debugstr_w(pipefn));
1815

1816 1817
        WaitNamedPipeW( pipefn, NMPWAIT_WAIT_FOREVER );
        hPipe = CreateFileW(pipefn, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, 0);
1818
        if (hPipe == INVALID_HANDLE_VALUE) {
1819
            DWORD index;
1820
            DWORD start_ticks;
1821
            HANDLE process = 0;
1822
            if (tries == 1) {
1823
                if ( (hres = create_local_service(rclsid)) &&
1824
                     (hres = create_server(rclsid, &process)) )
1825 1826
                    return hres;
            } else {
1827
                WARN("Connecting to %s, no response yet, retrying: le is %u\n", debugstr_w(pipefn), GetLastError());
1828
            }
1829 1830 1831
            /* wait for one second, even if messages arrive */
            start_ticks = GetTickCount();
            do {
1832 1833 1834 1835 1836 1837 1838 1839
                if (SUCCEEDED(CoWaitForMultipleHandles(0, 1000, (process != 0),
                                                       &process, &index)) && process && !index)
                {
                    WARN( "server for %s failed to start\n", debugstr_guid(rclsid) );
                    CloseHandle( hPipe );
                    CloseHandle( process );
                    return E_NOINTERFACE;
                }
1840
            } while (GetTickCount() - start_ticks < 1000);
1841
            if (process) CloseHandle( process );
1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862
            continue;
        }
        bufferlen = 0;
        if (!ReadFile(hPipe,marshalbuffer,sizeof(marshalbuffer),&bufferlen,NULL)) {
            FIXME("Failed to read marshal id from classfactory of %s.\n",debugstr_guid(rclsid));
            Sleep(1000);
            continue;
        }
        TRACE("read marshal id from pipe\n");
        CloseHandle(hPipe);
        break;
    }
    
    if (tries >= MAXTRIES)
        return E_NOINTERFACE;
    
    hres = CreateStreamOnHGlobal(0,TRUE,&pStm);
    if (hres) return hres;
    hres = IStream_Write(pStm,marshalbuffer,bufferlen,&res);
    if (hres) goto out;
    seekto.u.LowPart = 0;seekto.u.HighPart = 0;
1863
    hres = IStream_Seek(pStm,seekto,STREAM_SEEK_SET,&newpos);
1864 1865 1866
    
    TRACE("unmarshalling classfactory\n");
    hres = CoUnmarshalInterface(pStm,&IID_IClassFactory,ppv);
1867
out:
1868 1869
    IStream_Release(pStm);
    return hres;
1870 1871 1872
}


1873 1874 1875 1876
struct local_server_params
{
    CLSID clsid;
    IStream *stream;
1877
    HANDLE ready_event;
1878 1879
    HANDLE stop_event;
    HANDLE thread;
1880
    BOOL multi_use;
1881 1882
};

1883
/* FIXME: should call to rpcss instead */
1884 1885
static DWORD WINAPI local_server_thread(LPVOID param)
{
1886
    struct local_server_params * lsp = param;
1887
    WCHAR 		pipefn[100];
1888 1889 1890 1891 1892 1893 1894 1895
    HRESULT		hres;
    IStream		*pStm = lsp->stream;
    STATSTG		ststg;
    unsigned char	*buffer;
    int 		buflen;
    LARGE_INTEGER	seekto;
    ULARGE_INTEGER	newpos;
    ULONG		res;
1896
    BOOL multi_use = lsp->multi_use;
1897
    OVERLAPPED ovl;
1898
    HANDLE pipe_event, hPipe, new_pipe;
1899
    DWORD  bytes;
1900 1901 1902

    TRACE("Starting threader for %s.\n",debugstr_guid(&lsp->clsid));

1903
    memset(&ovl, 0, sizeof(ovl));
1904
    get_localserver_pipe_name(pipefn, &lsp->clsid);
1905
    ovl.hEvent = pipe_event = CreateEventW(NULL, FALSE, FALSE, NULL);
1906

1907 1908 1909 1910 1911 1912 1913 1914 1915 1916
    hPipe = CreateNamedPipeW( pipefn, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
                              PIPE_TYPE_BYTE|PIPE_WAIT, PIPE_UNLIMITED_INSTANCES,
                              4096, 4096, 500 /* 0.5 second timeout */, NULL );
    if (hPipe == INVALID_HANDLE_VALUE)
    {
        FIXME("pipe creation failed for %s, le is %u\n", debugstr_w(pipefn), GetLastError());
        CloseHandle(pipe_event);
        return 1;
    }

1917
    SetEvent(lsp->ready_event);
1918

1919
    while (1) {
1920
        if (!ConnectNamedPipe(hPipe, &ovl))
1921 1922
        {
            DWORD error = GetLastError();
1923 1924 1925 1926 1927 1928
            if (error == ERROR_IO_PENDING)
            {
                HANDLE handles[2] = { pipe_event, lsp->stop_event };
                DWORD ret;
                ret = WaitForMultipleObjects(2, handles, FALSE, INFINITE);
                if (ret != WAIT_OBJECT_0)
1929 1930
                {
                    CloseHandle(hPipe);
1931
                    break;
1932
                }
1933
            }
1934
            /* client already connected isn't an error */
1935
            else if (error != ERROR_PIPE_CONNECTED)
1936
            {
1937
                ERR("ConnectNamedPipe failed with error %d\n", GetLastError());
1938
                CloseHandle(hPipe);
1939 1940
                break;
            }
1941 1942 1943 1944
        }

        TRACE("marshalling IClassFactory to client\n");
        
1945
        hres = IStream_Stat(pStm,&ststg,STATFLAG_NONAME);
1946 1947 1948 1949 1950 1951
        if (hres)
        {
            CloseHandle(hPipe);
            CloseHandle(pipe_event);
            return hres;
        }
1952 1953 1954

        seekto.u.LowPart = 0;
        seekto.u.HighPart = 0;
1955
        hres = IStream_Seek(pStm,seekto,STREAM_SEEK_SET,&newpos);
1956
        if (hres) {
1957
            FIXME("IStream_Seek failed, %x\n",hres);
1958 1959
            CloseHandle(hPipe);
            CloseHandle(pipe_event);
1960 1961
            return hres;
        }
1962 1963 1964

        buflen = ststg.cbSize.u.LowPart;
        buffer = HeapAlloc(GetProcessHeap(),0,buflen);
1965 1966 1967
        
        hres = IStream_Read(pStm,buffer,buflen,&res);
        if (hres) {
1968
            FIXME("Stream Read failed, %x\n",hres);
1969 1970
            CloseHandle(hPipe);
            CloseHandle(pipe_event);
1971
            HeapFree(GetProcessHeap(),0,buffer);
1972 1973 1974
            return hres;
        }
        
1975
        WriteFile(hPipe,buffer,buflen,&res,&ovl);
1976
        GetOverlappedResult(hPipe, &ovl, &bytes, TRUE);
1977 1978
        HeapFree(GetProcessHeap(),0,buffer);

1979 1980 1981
        FlushFileBuffers(hPipe);
        DisconnectNamedPipe(hPipe);
        TRACE("done marshalling IClassFactory\n");
1982 1983 1984 1985

        if (!multi_use)
        {
            TRACE("single use object, shutting down pipe %s\n", debugstr_w(pipefn));
1986
            CloseHandle(hPipe);
1987 1988
            break;
        }
1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999
        new_pipe = CreateNamedPipeW( pipefn, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
                                     PIPE_TYPE_BYTE|PIPE_WAIT, PIPE_UNLIMITED_INSTANCES,
                                     4096, 4096, 500 /* 0.5 second timeout */, NULL );
        CloseHandle(hPipe);
        if (new_pipe == INVALID_HANDLE_VALUE)
        {
            FIXME("pipe creation failed for %s, le is %u\n", debugstr_w(pipefn), GetLastError());
            CloseHandle(pipe_event);
            return 1;
        }
        hPipe = new_pipe;
2000
    }
2001
    CloseHandle(pipe_event);
2002 2003 2004
    return 0;
}

2005
/* starts listening for a local server */
2006
HRESULT RPC_StartLocalServer(REFCLSID clsid, IStream *stream, BOOL multi_use, void **registration)
2007 2008
{
    DWORD tid;
2009 2010 2011 2012 2013
    struct local_server_params *lsp;

    lsp = HeapAlloc(GetProcessHeap(), 0, sizeof(*lsp));
    if (!lsp)
        return E_OUTOFMEMORY;
2014 2015 2016

    lsp->clsid = *clsid;
    lsp->stream = stream;
2017
    IStream_AddRef(stream);
2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030
    lsp->ready_event = CreateEventW(NULL, FALSE, FALSE, NULL);
    if (!lsp->ready_event)
    {
        HeapFree(GetProcessHeap(), 0, lsp);
        return HRESULT_FROM_WIN32(GetLastError());
    }
    lsp->stop_event = CreateEventW(NULL, FALSE, FALSE, NULL);
    if (!lsp->stop_event)
    {
        CloseHandle(lsp->ready_event);
        HeapFree(GetProcessHeap(), 0, lsp);
        return HRESULT_FROM_WIN32(GetLastError());
    }
2031
    lsp->multi_use = multi_use;
2032

2033 2034 2035 2036 2037 2038
    lsp->thread = CreateThread(NULL, 0, local_server_thread, lsp, 0, &tid);
    if (!lsp->thread)
    {
        CloseHandle(lsp->ready_event);
        CloseHandle(lsp->stop_event);
        HeapFree(GetProcessHeap(), 0, lsp);
2039
        return HRESULT_FROM_WIN32(GetLastError());
2040
    }
2041

2042 2043 2044
    WaitForSingleObject(lsp->ready_event, INFINITE);
    CloseHandle(lsp->ready_event);
    lsp->ready_event = NULL;
2045

2046
    *registration = lsp;
2047 2048 2049 2050 2051 2052
    return S_OK;
}

/* stops listening for a local server */
void RPC_StopLocalServer(void *registration)
{
2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063
    struct local_server_params *lsp = registration;

    /* signal local_server_thread to stop */
    SetEvent(lsp->stop_event);
    /* wait for it to exit */
    WaitForSingleObject(lsp->thread, INFINITE);

    IStream_Release(lsp->stream);
    CloseHandle(lsp->stop_event);
    CloseHandle(lsp->thread);
    HeapFree(GetProcessHeap(), 0, lsp);
2064
}