rpc_transport.c 113 KB
Newer Older
1 2 3
/*
 * RPC transport layer
 *
4
 * Copyright 2001 Ove Kåven, TransGaming Technologies
5 6 7
 * Copyright 2003 Mike Hearn
 * Copyright 2004 Filip Navara
 * Copyright 2006 Mike McCormack
8
 * Copyright 2006 Damjan Jovanovic
9 10 11 12 13 14 15 16 17 18 19 20 21
 *
 * 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
22
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
23 24 25
 *
 */

26 27 28
#include "ntstatus.h"
#define WIN32_NO_STATUS
#include "ws2tcpip.h"
29

30 31 32 33
#include <stdarg.h>
#include <stdio.h>
#include <string.h>
#include <assert.h>
34

35 36 37 38
#include "windef.h"
#include "winbase.h"
#include "winnls.h"
#include "winerror.h"
39
#include "wininet.h"
40
#include "winternl.h"
41
#include "winioctl.h"
42 43 44 45 46 47 48

#include "rpc.h"
#include "rpcndr.h"

#include "wine/debug.h"

#include "rpc_binding.h"
49
#include "rpc_assoc.h"
50
#include "rpc_message.h"
51
#include "rpc_server.h"
52
#include "epm_towers.h"
53

54 55
#define DEFAULT_NCACN_HTTP_TIMEOUT (60 * 1000)

56 57
WINE_DEFAULT_DEBUG_CHANNEL(rpc);

58
static RpcConnection *rpcrt4_spawn_connection(RpcConnection *old_connection);
59

60 61
/**** ncacn_np support ****/

62 63
typedef struct _RpcConnection_np
{
64 65 66
    RpcConnection common;
    HANDLE pipe;
    HANDLE listen_event;
67
    char *listen_pipe;
68
    IO_STATUS_BLOCK io_status;
69
    HANDLE event_cache;
70
    BOOL read_closed;
71 72 73 74
} RpcConnection_np;

static RpcConnection *rpcrt4_conn_np_alloc(void)
{
75
  RpcConnection_np *npc = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(RpcConnection_np));
76
  return &npc->common;
77 78
}

79
static HANDLE get_np_event(RpcConnection_np *connection)
80
{
81 82
    HANDLE event = InterlockedExchangePointer(&connection->event_cache, NULL);
    return event ? event : CreateEventW(NULL, TRUE, FALSE, NULL);
83 84
}

85
static void release_np_event(RpcConnection_np *connection, HANDLE event)
86
{
87 88 89
    event = InterlockedExchangePointer(&connection->event_cache, event);
    if (event)
        CloseHandle(event);
90 91
}

92
static RPC_STATUS rpcrt4_conn_create_pipe(RpcConnection *conn)
93
{
94
    RpcConnection_np *connection = (RpcConnection_np *) conn;
95

96 97 98 99 100 101 102 103
    TRACE("listening on %s\n", connection->listen_pipe);

    connection->pipe = CreateNamedPipeA(connection->listen_pipe, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
                                        PIPE_TYPE_MESSAGE | PIPE_READMODE_MESSAGE,
                                        PIPE_UNLIMITED_INSTANCES,
                                        RPC_MAX_PACKET_SIZE, RPC_MAX_PACKET_SIZE, 5000, NULL);
    if (connection->pipe == INVALID_HANDLE_VALUE)
    {
104
        WARN("CreateNamedPipe failed with error %ld\n", GetLastError());
105 106 107 108 109 110 111
        if (GetLastError() == ERROR_FILE_EXISTS)
            return RPC_S_DUPLICATE_ENDPOINT;
        else
            return RPC_S_CANT_CREATE_ENDPOINT;
    }

    return RPC_S_OK;
112 113
}

114
static RPC_STATUS rpcrt4_conn_open_pipe(RpcConnection *Connection, LPCSTR pname, BOOL wait)
115
{
116 117
  RpcConnection_np *npc = (RpcConnection_np *) Connection;
  HANDLE pipe;
118 119 120 121 122
  DWORD err, dwMode;

  TRACE("connecting to %s\n", pname);

  while (TRUE) {
123 124 125
    DWORD dwFlags = 0;
    if (Connection->QOS)
    {
126
        dwFlags = SECURITY_SQOS_PRESENT;
127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144
        switch (Connection->QOS->qos->ImpersonationType)
        {
            case RPC_C_IMP_LEVEL_DEFAULT:
                /* FIXME: what to do here? */
                break;
            case RPC_C_IMP_LEVEL_ANONYMOUS:
                dwFlags |= SECURITY_ANONYMOUS;
                break;
            case RPC_C_IMP_LEVEL_IDENTIFY:
                dwFlags |= SECURITY_IDENTIFICATION;
                break;
            case RPC_C_IMP_LEVEL_IMPERSONATE:
                dwFlags |= SECURITY_IMPERSONATION;
                break;
            case RPC_C_IMP_LEVEL_DELEGATE:
                dwFlags |= SECURITY_DELEGATION;
                break;
        }
145
        if (Connection->QOS->qos->IdentityTracking == RPC_C_QOS_IDENTITY_DYNAMIC)
146 147
            dwFlags |= SECURITY_CONTEXT_TRACKING;
    }
148
    pipe = CreateFileA(pname, GENERIC_READ|GENERIC_WRITE, 0, NULL,
149
                       OPEN_EXISTING, dwFlags | FILE_FLAG_OVERLAPPED, 0);
150
    if (pipe != INVALID_HANDLE_VALUE) break;
151 152
    err = GetLastError();
    if (err == ERROR_PIPE_BUSY) {
153 154 155 156
      if (WaitNamedPipeA(pname, NMPWAIT_USE_DEFAULT_WAIT)) {
        TRACE("retrying busy server\n");
        continue;
      }
157
      TRACE("connection failed, error=%lx\n", err);
158 159
      return RPC_S_SERVER_TOO_BUSY;
    }
160
    if (!wait || !WaitNamedPipeA(pname, NMPWAIT_WAIT_FOREVER)) {
161
      err = GetLastError();
162
      WARN("connection failed, error=%lx\n", err);
163 164 165 166 167 168 169
      return RPC_S_SERVER_UNAVAILABLE;
    }
  }

  /* success */
  /* pipe is connected; change to message-read mode. */
  dwMode = PIPE_READMODE_MESSAGE;
170 171
  SetNamedPipeHandleState(pipe, &dwMode, NULL, NULL);
  npc->pipe = pipe;
172 173 174 175

  return RPC_S_OK;
}

176 177 178 179 180 181 182 183 184 185 186 187
static char *ncalrpc_pipe_name(const char *endpoint)
{
  static const char prefix[] = "\\\\.\\pipe\\lrpc\\";
  char *pipe_name;

  /* protseq=ncalrpc: supposed to use NT LPC ports,
   * but we'll implement it with named pipes for now */
  pipe_name = I_RpcAllocate(sizeof(prefix) + strlen(endpoint));
  strcat(strcpy(pipe_name, prefix), endpoint);
  return pipe_name;
}

188 189
static RPC_STATUS rpcrt4_ncalrpc_open(RpcConnection* Connection)
{
190
  RpcConnection_np *npc = (RpcConnection_np *) Connection;
191 192 193
  RPC_STATUS r;
  LPSTR pname;

194
  /* already connected? */
195
  if (npc->pipe)
196 197
    return RPC_S_OK;

198
  pname = ncalrpc_pipe_name(Connection->Endpoint);
199 200
  r = rpcrt4_conn_open_pipe(Connection, pname, TRUE);
  I_RpcFree(pname);
201

202 203 204
  return r;
}

205
static RPC_STATUS rpcrt4_protseq_ncalrpc_open_endpoint(RpcServerProtseq* protseq, const char *endpoint)
206 207 208
{
  RPC_STATUS r;
  RpcConnection *Connection;
209 210 211 212 213 214 215 216
  char generated_endpoint[22];

  if (!endpoint)
  {
    static LONG lrpc_nameless_id;
    DWORD process_id = GetCurrentProcessId();
    ULONG id = InterlockedIncrement(&lrpc_nameless_id);
    snprintf(generated_endpoint, sizeof(generated_endpoint),
217
             "LRPC%08lx.%08lx", process_id, id);
218 219
    endpoint = generated_endpoint;
  }
220 221

  r = RPCRT4_CreateConnection(&Connection, TRUE, protseq->Protseq, NULL,
222
                              endpoint, NULL, NULL, NULL, NULL);
223 224 225
  if (r != RPC_S_OK)
      return r;

226 227
  ((RpcConnection_np*)Connection)->listen_pipe = ncalrpc_pipe_name(Connection->Endpoint);
  r = rpcrt4_conn_create_pipe(Connection);
228

229
  EnterCriticalSection(&protseq->cs);
230
  list_add_head(&protseq->listeners, &Connection->protseq_entry);
231
  Connection->protseq = protseq;
232 233
  LeaveCriticalSection(&protseq->cs);

234 235 236
  return r;
}

237 238 239 240 241 242 243 244 245 246 247
static char *ncacn_pipe_name(const char *endpoint)
{
  static const char prefix[] = "\\\\.";
  char *pipe_name;

  /* protseq=ncacn_np: named pipes */
  pipe_name = I_RpcAllocate(sizeof(prefix) + strlen(endpoint));
  strcat(strcpy(pipe_name, prefix), endpoint);
  return pipe_name;
}

248 249
static RPC_STATUS rpcrt4_ncacn_np_open(RpcConnection* Connection)
{
250
  RpcConnection_np *npc = (RpcConnection_np *) Connection;
251 252 253
  RPC_STATUS r;
  LPSTR pname;

254
  /* already connected? */
255
  if (npc->pipe)
256 257
    return RPC_S_OK;

258
  pname = ncacn_pipe_name(Connection->Endpoint);
259
  r = rpcrt4_conn_open_pipe(Connection, pname, FALSE);
260
  I_RpcFree(pname);
261 262 263 264

  return r;
}

265
static RPC_STATUS rpcrt4_protseq_ncacn_np_open_endpoint(RpcServerProtseq *protseq, const char *endpoint)
266
{
267 268
  RPC_STATUS r;
  RpcConnection *Connection;
269
  char generated_endpoint[26];
270 271 272 273 274 275 276

  if (!endpoint)
  {
    static LONG np_nameless_id;
    DWORD process_id = GetCurrentProcessId();
    ULONG id = InterlockedExchangeAdd(&np_nameless_id, 1 );
    snprintf(generated_endpoint, sizeof(generated_endpoint),
277
             "\\\\pipe\\\\%08lx.%03lx", process_id, id);
278 279
    endpoint = generated_endpoint;
  }
280 281

  r = RPCRT4_CreateConnection(&Connection, TRUE, protseq->Protseq, NULL,
282
                              endpoint, NULL, NULL, NULL, NULL);
283 284 285
  if (r != RPC_S_OK)
    return r;

286 287
  ((RpcConnection_np*)Connection)->listen_pipe = ncacn_pipe_name(Connection->Endpoint);
  r = rpcrt4_conn_create_pipe(Connection);
288 289

  EnterCriticalSection(&protseq->cs);
290
  list_add_head(&protseq->listeners, &Connection->protseq_entry);
291
  Connection->protseq = protseq;
292 293
  LeaveCriticalSection(&protseq->cs);

294 295 296 297 298
  return r;
}

static void rpcrt4_conn_np_handoff(RpcConnection_np *old_npc, RpcConnection_np *new_npc)
{    
299 300 301 302 303 304
    /* because of the way named pipes work, we'll transfer the connected pipe
     * to the child, then reopen the server binding to continue listening */

    new_npc->pipe = old_npc->pipe;
    old_npc->pipe = 0;
    assert(!old_npc->listen_event);
305 306 307 308
}

static RPC_STATUS rpcrt4_ncacn_np_handoff(RpcConnection *old_conn, RpcConnection *new_conn)
{
309
  DWORD len = MAX_COMPUTERNAME_LENGTH + 1;
310 311 312
  RPC_STATUS status;

  rpcrt4_conn_np_handoff((RpcConnection_np *)old_conn, (RpcConnection_np *)new_conn);
313
  status = rpcrt4_conn_create_pipe(old_conn);
314

315 316 317 318 319
  /* Store the local computer name as the NetworkAddr for ncacn_np as long as
   * we don't support named pipes over the network. */
  new_conn->NetworkAddr = HeapAlloc(GetProcessHeap(), 0, len);
  if (!GetComputerNameA(new_conn->NetworkAddr, &len))
  {
320
    ERR("Failed to retrieve the computer name, error %lu\n", GetLastError());
321 322 323
    return RPC_S_OUT_OF_RESOURCES;
  }

324 325 326
  return status;
}

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
static RPC_STATUS is_pipe_listening(const char *pipe_name)
{
  return WaitNamedPipeA(pipe_name, 1) ? RPC_S_OK : RPC_S_NOT_LISTENING;
}

static RPC_STATUS rpcrt4_ncacn_np_is_server_listening(const char *endpoint)
{
  char *pipe_name;
  RPC_STATUS status;

  pipe_name = ncacn_pipe_name(endpoint);
  status = is_pipe_listening(pipe_name);
  I_RpcFree(pipe_name);
  return status;
}

static RPC_STATUS rpcrt4_ncalrpc_np_is_server_listening(const char *endpoint)
{
  char *pipe_name;
  RPC_STATUS status;

  pipe_name = ncalrpc_pipe_name(endpoint);
  status = is_pipe_listening(pipe_name);
  I_RpcFree(pipe_name);
  return status;
}

354 355
static RPC_STATUS rpcrt4_ncalrpc_handoff(RpcConnection *old_conn, RpcConnection *new_conn)
{
356
  DWORD len = MAX_COMPUTERNAME_LENGTH + 1;
357 358 359 360 361
  RPC_STATUS status;

  TRACE("%s\n", old_conn->Endpoint);

  rpcrt4_conn_np_handoff((RpcConnection_np *)old_conn, (RpcConnection_np *)new_conn);
362
  status = rpcrt4_conn_create_pipe(old_conn);
363 364 365 366 367

  /* Store the local computer name as the NetworkAddr for ncalrpc. */
  new_conn->NetworkAddr = HeapAlloc(GetProcessHeap(), 0, len);
  if (!GetComputerNameA(new_conn->NetworkAddr, &len))
  {
368
    ERR("Failed to retrieve the computer name, error %lu\n", GetLastError());
369 370 371
    return RPC_S_OUT_OF_RESOURCES;
  }

372
  return status;
373 374
}

375
static int rpcrt4_conn_np_read(RpcConnection *conn, void *buffer, unsigned int count)
376
{
377
    RpcConnection_np *connection = (RpcConnection_np *) conn;
378
    HANDLE event;
379
    NTSTATUS status;
380

381
    event = get_np_event(connection);
382 383 384
    if (!event)
        return -1;

385 386 387 388
    if (connection->read_closed)
        status = STATUS_CANCELLED;
    else
        status = NtReadFile(connection->pipe, event, NULL, NULL, &connection->io_status, buffer, count, NULL, NULL);
389 390
    if (status == STATUS_PENDING)
    {
391 392 393 394 395 396
        /* check read_closed again before waiting to avoid a race */
        if (connection->read_closed)
        {
            IO_STATUS_BLOCK io_status;
            NtCancelIoFileEx(connection->pipe, &connection->io_status, &io_status);
        }
397
        WaitForSingleObject(event, INFINITE);
398
        status = connection->io_status.Status;
399
    }
400
    release_np_event(connection, event);
401
    return status && status != STATUS_BUFFER_OVERFLOW ? -1 : connection->io_status.Information;
402 403
}

404
static int rpcrt4_conn_np_write(RpcConnection *conn, const void *buffer, unsigned int count)
405
{
406 407
    RpcConnection_np *connection = (RpcConnection_np *) conn;
    IO_STATUS_BLOCK io_status;
408
    HANDLE event;
409
    NTSTATUS status;
410

411
    event = get_np_event(connection);
412 413 414 415 416 417 418 419 420
    if (!event)
        return -1;

    status = NtWriteFile(connection->pipe, event, NULL, NULL, &io_status, buffer, count, NULL, NULL);
    if (status == STATUS_PENDING)
    {
        WaitForSingleObject(event, INFINITE);
        status = io_status.Status;
    }
421
    release_np_event(connection, event);
422 423 424 425 426
    if (status)
        return -1;

    assert(io_status.Information == count);
    return count;
427 428
}

429
static int rpcrt4_conn_np_close(RpcConnection *conn)
430
{
431 432 433 434 435 436 437 438 439 440 441 442
    RpcConnection_np *connection = (RpcConnection_np *) conn;
    if (connection->pipe)
    {
        FlushFileBuffers(connection->pipe);
        CloseHandle(connection->pipe);
        connection->pipe = 0;
    }
    if (connection->listen_event)
    {
        CloseHandle(connection->listen_event);
        connection->listen_event = 0;
    }
443 444 445 446 447
    if (connection->event_cache)
    {
        CloseHandle(connection->event_cache);
        connection->event_cache = 0;
    }
448
    return 0;
449 450
}

451 452
static void rpcrt4_conn_np_close_read(RpcConnection *conn)
{
453 454 455 456 457
    RpcConnection_np *connection = (RpcConnection_np*)conn;
    IO_STATUS_BLOCK io_status;

    connection->read_closed = TRUE;
    NtCancelIoFileEx(connection->pipe, &connection->io_status, &io_status);
458 459
}

460
static void rpcrt4_conn_np_cancel_call(RpcConnection *conn)
461
{
462 463
    RpcConnection_np *connection = (RpcConnection_np *)conn;
    CancelIoEx(connection->pipe, NULL);
464 465
}

466
static int rpcrt4_conn_np_wait_for_incoming_data(RpcConnection *conn)
467
{
468
    return rpcrt4_conn_np_read(conn, NULL, 0);
469 470
}

471 472 473 474 475 476 477 478 479 480 481 482
static size_t rpcrt4_ncacn_np_get_top_of_tower(unsigned char *tower_data,
                                               const char *networkaddr,
                                               const char *endpoint)
{
    twr_empty_floor_t *smb_floor;
    twr_empty_floor_t *nb_floor;
    size_t size;
    size_t networkaddr_size;
    size_t endpoint_size;

    TRACE("(%p, %s, %s)\n", tower_data, networkaddr, endpoint);

483 484
    networkaddr_size = networkaddr ? strlen(networkaddr) + 1 : 1;
    endpoint_size = endpoint ? strlen(endpoint) + 1 : 1;
485 486 487 488 489 490 491 492 493 494 495 496 497
    size = sizeof(*smb_floor) + endpoint_size + sizeof(*nb_floor) + networkaddr_size;

    if (!tower_data)
        return size;

    smb_floor = (twr_empty_floor_t *)tower_data;

    tower_data += sizeof(*smb_floor);

    smb_floor->count_lhs = sizeof(smb_floor->protid);
    smb_floor->protid = EPM_PROTOCOL_SMB;
    smb_floor->count_rhs = endpoint_size;

498 499 500 501
    if (endpoint)
        memcpy(tower_data, endpoint, endpoint_size);
    else
        tower_data[0] = 0;
502 503 504 505 506 507 508 509 510 511
    tower_data += endpoint_size;

    nb_floor = (twr_empty_floor_t *)tower_data;

    tower_data += sizeof(*nb_floor);

    nb_floor->count_lhs = sizeof(nb_floor->protid);
    nb_floor->protid = EPM_PROTOCOL_NETBIOS;
    nb_floor->count_rhs = networkaddr_size;

512 513 514 515
    if (networkaddr)
        memcpy(tower_data, networkaddr, networkaddr_size);
    else
        tower_data[0] = 0;
516 517 518 519 520 521 522 523 524 525 526 527

    return size;
}

static RPC_STATUS rpcrt4_ncacn_np_parse_top_of_tower(const unsigned char *tower_data,
                                                     size_t tower_size,
                                                     char **networkaddr,
                                                     char **endpoint)
{
    const twr_empty_floor_t *smb_floor = (const twr_empty_floor_t *)tower_data;
    const twr_empty_floor_t *nb_floor;

528
    TRACE("(%p, %d, %p, %p)\n", tower_data, (int)tower_size, networkaddr, endpoint);
529 530 531 532 533 534 535 536 537

    if (tower_size < sizeof(*smb_floor))
        return EPT_S_NOT_REGISTERED;

    tower_data += sizeof(*smb_floor);
    tower_size -= sizeof(*smb_floor);

    if ((smb_floor->count_lhs != sizeof(smb_floor->protid)) ||
        (smb_floor->protid != EPM_PROTOCOL_SMB) ||
538 539
        (smb_floor->count_rhs > tower_size) ||
        (tower_data[smb_floor->count_rhs - 1] != '\0'))
540
        return EPT_S_NOT_REGISTERED;
541 542 543

    if (endpoint)
    {
544
        *endpoint = I_RpcAllocate(smb_floor->count_rhs);
545 546 547 548
        if (!*endpoint)
            return RPC_S_OUT_OF_RESOURCES;
        memcpy(*endpoint, tower_data, smb_floor->count_rhs);
    }
549 550 551 552 553 554 555 556 557 558 559 560 561
    tower_data += smb_floor->count_rhs;
    tower_size -= smb_floor->count_rhs;

    if (tower_size < sizeof(*nb_floor))
        return EPT_S_NOT_REGISTERED;

    nb_floor = (const twr_empty_floor_t *)tower_data;

    tower_data += sizeof(*nb_floor);
    tower_size -= sizeof(*nb_floor);

    if ((nb_floor->count_lhs != sizeof(nb_floor->protid)) ||
        (nb_floor->protid != EPM_PROTOCOL_NETBIOS) ||
562 563
        (nb_floor->count_rhs > tower_size) ||
        (tower_data[nb_floor->count_rhs - 1] != '\0'))
564 565
        return EPT_S_NOT_REGISTERED;

566
    if (networkaddr)
567
    {
568
        *networkaddr = I_RpcAllocate(nb_floor->count_rhs);
569 570 571 572
        if (!*networkaddr)
        {
            if (endpoint)
            {
573
                I_RpcFree(*endpoint);
574 575 576 577 578
                *endpoint = NULL;
            }
            return RPC_S_OUT_OF_RESOURCES;
        }
        memcpy(*networkaddr, tower_data, nb_floor->count_rhs);
579 580 581 582 583
    }

    return RPC_S_OK;
}

584 585 586 587 588 589 590 591 592 593 594 595 596 597
static RPC_STATUS rpcrt4_conn_np_impersonate_client(RpcConnection *conn)
{
    RpcConnection_np *npc = (RpcConnection_np *)conn;
    BOOL ret;

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

    if (conn->AuthInfo && SecIsValidHandle(&conn->ctx))
        return RPCRT4_default_impersonate_client(conn);

    ret = ImpersonateNamedPipeClient(npc->pipe);
    if (!ret)
    {
        DWORD error = GetLastError();
598
        WARN("ImpersonateNamedPipeClient failed with error %lu\n", error);
599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619
        switch (error)
        {
        case ERROR_CANNOT_IMPERSONATE:
            return RPC_S_NO_CONTEXT_AVAILABLE;
        }
    }
    return RPC_S_OK;
}

static RPC_STATUS rpcrt4_conn_np_revert_to_self(RpcConnection *conn)
{
    BOOL ret;

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

    if (conn->AuthInfo && SecIsValidHandle(&conn->ctx))
        return RPCRT4_default_revert_to_self(conn);

    ret = RevertToSelf();
    if (!ret)
    {
620
        WARN("RevertToSelf failed with error %lu\n", GetLastError());
621 622 623 624 625
        return RPC_S_NO_CONTEXT_AVAILABLE;
    }
    return RPC_S_OK;
}

626 627 628 629 630 631 632 633
typedef struct _RpcServerProtseq_np
{
    RpcServerProtseq common;
    HANDLE mgr_event;
} RpcServerProtseq_np;

static RpcServerProtseq *rpcrt4_protseq_np_alloc(void)
{
634
    RpcServerProtseq_np *ps = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*ps));
635 636 637 638 639 640 641 642 643 644 645 646 647 648
    if (ps)
        ps->mgr_event = CreateEventW(NULL, FALSE, FALSE, NULL);
    return &ps->common;
}

static void rpcrt4_protseq_np_signal_state_changed(RpcServerProtseq *protseq)
{
    RpcServerProtseq_np *npps = CONTAINING_RECORD(protseq, RpcServerProtseq_np, common);
    SetEvent(npps->mgr_event);
}

static void *rpcrt4_protseq_np_get_wait_array(RpcServerProtseq *protseq, void *prev_array, unsigned int *count)
{
    HANDLE *objs = prev_array;
649
    RpcConnection_np *conn;
650 651 652 653 654 655
    RpcServerProtseq_np *npps = CONTAINING_RECORD(protseq, RpcServerProtseq_np, common);
    
    EnterCriticalSection(&protseq->cs);
    
    /* open and count connections */
    *count = 1;
656 657
    LIST_FOR_EACH_ENTRY(conn, &protseq->listeners, RpcConnection_np, common.protseq_entry)
    {
658 659
        if (!conn->pipe && rpcrt4_conn_create_pipe(&conn->common) != RPC_S_OK)
            continue;
660 661 662 663 664
        if (!conn->listen_event)
        {
            NTSTATUS status;
            HANDLE event;

665
            event = get_np_event(conn);
666 667 668 669 670 671 672 673 674 675 676 677 678 679
            if (!event)
                continue;

            status = NtFsControlFile(conn->pipe, event, NULL, NULL, &conn->io_status, FSCTL_PIPE_LISTEN, NULL, 0, NULL, 0);
            switch (status)
            {
            case STATUS_SUCCESS:
            case STATUS_PIPE_CONNECTED:
                conn->io_status.Status = status;
                SetEvent(event);
                break;
            case STATUS_PENDING:
                break;
            default:
680
                ERR("pipe listen error %lx\n", status);
681 682 683 684 685 686
                continue;
            }

            conn->listen_event = event;
        }
        (*count)++;
687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702
    }
    
    /* make array of connections */
    if (objs)
        objs = HeapReAlloc(GetProcessHeap(), 0, objs, *count*sizeof(HANDLE));
    else
        objs = HeapAlloc(GetProcessHeap(), 0, *count*sizeof(HANDLE));
    if (!objs)
    {
        ERR("couldn't allocate objs\n");
        LeaveCriticalSection(&protseq->cs);
        return NULL;
    }
    
    objs[0] = npps->mgr_event;
    *count = 1;
703 704
    LIST_FOR_EACH_ENTRY(conn, &protseq->listeners, RpcConnection_np, common.protseq_entry)
    {
705 706
        if (conn->listen_event)
            objs[(*count)++] = conn->listen_event;
707 708 709 710 711 712 713 714 715 716 717 718 719 720 721
    }
    LeaveCriticalSection(&protseq->cs);
    return objs;
}

static void rpcrt4_protseq_np_free_wait_array(RpcServerProtseq *protseq, void *array)
{
    HeapFree(GetProcessHeap(), 0, array);
}

static int rpcrt4_protseq_np_wait_for_new_connection(RpcServerProtseq *protseq, unsigned int count, void *wait_array)
{
    HANDLE b_handle;
    HANDLE *objs = wait_array;
    DWORD res;
722
    RpcConnection *cconn = NULL;
723
    RpcConnection_np *conn;
724 725 726
    
    if (!objs)
        return -1;
727 728 729 730 731 732 733 734 735 736

    do
    {
        /* an alertable wait isn't strictly necessary, but due to our
         * overlapped I/O implementation in Wine we need to free some memory
         * by the file user APC being called, even if no completion routine was
         * specified at the time of starting the async operation */
        res = WaitForMultipleObjectsEx(count, objs, FALSE, INFINITE, TRUE);
    } while (res == WAIT_IO_COMPLETION);

737 738 739 740
    if (res == WAIT_OBJECT_0)
        return 0;
    else if (res == WAIT_FAILED)
    {
741
        ERR("wait failed with error %ld\n", GetLastError());
742 743 744 745 746 747 748
        return -1;
    }
    else
    {
        b_handle = objs[res - WAIT_OBJECT_0];
        /* find which connection got a RPC */
        EnterCriticalSection(&protseq->cs);
749
        LIST_FOR_EACH_ENTRY(conn, &protseq->listeners, RpcConnection_np, common.protseq_entry)
750 751 752
        {
            if (b_handle == conn->listen_event)
            {
753
                release_np_event(conn, conn->listen_event);
754 755
                conn->listen_event = NULL;
                if (conn->io_status.Status == STATUS_SUCCESS || conn->io_status.Status == STATUS_PIPE_CONNECTED)
756
                    cconn = rpcrt4_spawn_connection(&conn->common);
757
                else
758
                    ERR("listen failed %lx\n", conn->io_status.Status);
759 760
                break;
            }
761
        }
762
        LeaveCriticalSection(&protseq->cs);
763
        if (!cconn)
764
        {
765 766
            ERR("failed to locate connection for handle %p\n", b_handle);
            return -1;
767
        }
768 769
        RPCRT4_new_client(cconn);
        return 1;
770 771 772
    }
}

773 774 775 776 777 778 779 780 781 782
static size_t rpcrt4_ncalrpc_get_top_of_tower(unsigned char *tower_data,
                                              const char *networkaddr,
                                              const char *endpoint)
{
    twr_empty_floor_t *pipe_floor;
    size_t size;
    size_t endpoint_size;

    TRACE("(%p, %s, %s)\n", tower_data, networkaddr, endpoint);

783
    endpoint_size = strlen(endpoint) + 1;
784 785 786 787 788 789 790 791 792 793
    size = sizeof(*pipe_floor) + endpoint_size;

    if (!tower_data)
        return size;

    pipe_floor = (twr_empty_floor_t *)tower_data;

    tower_data += sizeof(*pipe_floor);

    pipe_floor->count_lhs = sizeof(pipe_floor->protid);
794
    pipe_floor->protid = EPM_PROTOCOL_PIPE;
795 796 797 798 799 800 801 802 803 804 805 806 807 808
    pipe_floor->count_rhs = endpoint_size;

    memcpy(tower_data, endpoint, endpoint_size);

    return size;
}

static RPC_STATUS rpcrt4_ncalrpc_parse_top_of_tower(const unsigned char *tower_data,
                                                    size_t tower_size,
                                                    char **networkaddr,
                                                    char **endpoint)
{
    const twr_empty_floor_t *pipe_floor = (const twr_empty_floor_t *)tower_data;

809
    TRACE("(%p, %d, %p, %p)\n", tower_data, (int)tower_size, networkaddr, endpoint);
810 811 812 813 814 815 816 817

    if (tower_size < sizeof(*pipe_floor))
        return EPT_S_NOT_REGISTERED;

    tower_data += sizeof(*pipe_floor);
    tower_size -= sizeof(*pipe_floor);

    if ((pipe_floor->count_lhs != sizeof(pipe_floor->protid)) ||
818
        (pipe_floor->protid != EPM_PROTOCOL_PIPE) ||
819 820
        (pipe_floor->count_rhs > tower_size) ||
        (tower_data[pipe_floor->count_rhs - 1] != '\0'))
821
        return EPT_S_NOT_REGISTERED;
822

823 824 825
    if (networkaddr)
        *networkaddr = NULL;

826 827
    if (endpoint)
    {
828
        *endpoint = I_RpcAllocate(pipe_floor->count_rhs);
829 830 831 832
        if (!*endpoint)
            return RPC_S_OUT_OF_RESOURCES;
        memcpy(*endpoint, tower_data, pipe_floor->count_rhs);
    }
833 834 835 836

    return RPC_S_OK;
}

837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865
static BOOL rpcrt4_ncalrpc_is_authorized(RpcConnection *conn)
{
    return FALSE;
}

static RPC_STATUS rpcrt4_ncalrpc_authorize(RpcConnection *conn, BOOL first_time,
                                           unsigned char *in_buffer,
                                           unsigned int in_size,
                                           unsigned char *out_buffer,
                                           unsigned int *out_size)
{
    /* since this protocol is local to the machine there is no need to
     * authenticate the caller */
    *out_size = 0;
    return RPC_S_OK;
}

static RPC_STATUS rpcrt4_ncalrpc_secure_packet(RpcConnection *conn,
    enum secure_packet_direction dir,
    RpcPktHdr *hdr, unsigned int hdr_size,
    unsigned char *stub_data, unsigned int stub_data_size,
    RpcAuthVerifier *auth_hdr,
    unsigned char *auth_value, unsigned int auth_value_size)
{
    /* since this protocol is local to the machine there is no need to secure
     * the packet */
    return RPC_S_OK;
}

866 867 868 869
static RPC_STATUS rpcrt4_ncalrpc_inquire_auth_client(
    RpcConnection *conn, RPC_AUTHZ_HANDLE *privs, RPC_WSTR *server_princ_name,
    ULONG *authn_level, ULONG *authn_svc, ULONG *authz_svc, ULONG flags)
{
870
    TRACE("(%p, %p, %p, %p, %p, %p, 0x%lx)\n", conn, privs,
871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890
          server_princ_name, authn_level, authn_svc, authz_svc, flags);

    if (privs)
    {
        FIXME("privs not implemented\n");
        *privs = NULL;
    }
    if (server_princ_name)
    {
        FIXME("server_princ_name not implemented\n");
        *server_princ_name = NULL;
    }
    if (authn_level) *authn_level = RPC_C_AUTHN_LEVEL_PKT_PRIVACY;
    if (authn_svc) *authn_svc = RPC_C_AUTHN_WINNT;
    if (authz_svc)
    {
        FIXME("authorization service not implemented\n");
        *authz_svc = RPC_C_AUTHZ_NONE;
    }
    if (flags)
891
        FIXME("flags 0x%lx not implemented\n", flags);
892 893 894 895

    return RPC_S_OK;
}

896 897 898 899 900 901 902
static RPC_STATUS rpcrt4_ncalrpc_inquire_client_pid(RpcConnection *conn, ULONG *pid)
{
    RpcConnection_np *connection = (RpcConnection_np *)conn;

    return GetNamedPipeClientProcessId(connection->pipe, pid) ? RPC_S_OK : RPC_S_INVALID_BINDING;
}

903 904
/**** ncacn_ip_tcp support ****/

905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950
static size_t rpcrt4_ip_tcp_get_top_of_tower(unsigned char *tower_data,
                                             const char *networkaddr,
                                             unsigned char tcp_protid,
                                             const char *endpoint)
{
    twr_tcp_floor_t *tcp_floor;
    twr_ipv4_floor_t *ipv4_floor;
    struct addrinfo *ai;
    struct addrinfo hints;
    int ret;
    size_t size = sizeof(*tcp_floor) + sizeof(*ipv4_floor);

    TRACE("(%p, %s, %s)\n", tower_data, networkaddr, endpoint);

    if (!tower_data)
        return size;

    tcp_floor = (twr_tcp_floor_t *)tower_data;
    tower_data += sizeof(*tcp_floor);

    ipv4_floor = (twr_ipv4_floor_t *)tower_data;

    tcp_floor->count_lhs = sizeof(tcp_floor->protid);
    tcp_floor->protid = tcp_protid;
    tcp_floor->count_rhs = sizeof(tcp_floor->port);

    ipv4_floor->count_lhs = sizeof(ipv4_floor->protid);
    ipv4_floor->protid = EPM_PROTOCOL_IP;
    ipv4_floor->count_rhs = sizeof(ipv4_floor->ipv4addr);

    hints.ai_flags          = AI_NUMERICHOST;
    /* FIXME: only support IPv4 at the moment. how is IPv6 represented by the EPM? */
    hints.ai_family         = PF_INET;
    hints.ai_socktype       = SOCK_STREAM;
    hints.ai_protocol       = IPPROTO_TCP;
    hints.ai_addrlen        = 0;
    hints.ai_addr           = NULL;
    hints.ai_canonname      = NULL;
    hints.ai_next           = NULL;

    ret = getaddrinfo(networkaddr, endpoint, &hints, &ai);
    if (ret)
    {
        ret = getaddrinfo("0.0.0.0", endpoint, &hints, &ai);
        if (ret)
        {
951
            ERR("getaddrinfo failed, error %u\n", WSAGetLastError());
952 953 954 955 956 957 958 959 960 961 962 963 964
            return 0;
        }
    }

    if (ai->ai_family == PF_INET)
    {
        const struct sockaddr_in *sin = (const struct sockaddr_in *)ai->ai_addr;
        tcp_floor->port = sin->sin_port;
        ipv4_floor->ipv4addr = sin->sin_addr.s_addr;
    }
    else
    {
        ERR("unexpected protocol family %d\n", ai->ai_family);
965
        freeaddrinfo(ai);
966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027
        return 0;
    }

    freeaddrinfo(ai);

    return size;
}

static RPC_STATUS rpcrt4_ip_tcp_parse_top_of_tower(const unsigned char *tower_data,
                                                   size_t tower_size,
                                                   char **networkaddr,
                                                   unsigned char tcp_protid,
                                                   char **endpoint)
{
    const twr_tcp_floor_t *tcp_floor = (const twr_tcp_floor_t *)tower_data;
    const twr_ipv4_floor_t *ipv4_floor;
    struct in_addr in_addr;

    TRACE("(%p, %d, %p, %p)\n", tower_data, (int)tower_size, networkaddr, endpoint);

    if (tower_size < sizeof(*tcp_floor))
        return EPT_S_NOT_REGISTERED;

    tower_data += sizeof(*tcp_floor);
    tower_size -= sizeof(*tcp_floor);

    if (tower_size < sizeof(*ipv4_floor))
        return EPT_S_NOT_REGISTERED;

    ipv4_floor = (const twr_ipv4_floor_t *)tower_data;

    if ((tcp_floor->count_lhs != sizeof(tcp_floor->protid)) ||
        (tcp_floor->protid != tcp_protid) ||
        (tcp_floor->count_rhs != sizeof(tcp_floor->port)) ||
        (ipv4_floor->count_lhs != sizeof(ipv4_floor->protid)) ||
        (ipv4_floor->protid != EPM_PROTOCOL_IP) ||
        (ipv4_floor->count_rhs != sizeof(ipv4_floor->ipv4addr)))
        return EPT_S_NOT_REGISTERED;

    if (endpoint)
    {
        *endpoint = I_RpcAllocate(6 /* sizeof("65535") + 1 */);
        if (!*endpoint)
            return RPC_S_OUT_OF_RESOURCES;
        sprintf(*endpoint, "%u", ntohs(tcp_floor->port));
    }

    if (networkaddr)
    {
        *networkaddr = I_RpcAllocate(INET_ADDRSTRLEN);
        if (!*networkaddr)
        {
            if (endpoint)
            {
                I_RpcFree(*endpoint);
                *endpoint = NULL;
            }
            return RPC_S_OUT_OF_RESOURCES;
        }
        in_addr.s_addr = ipv4_floor->ipv4addr;
        if (!inet_ntop(AF_INET, &in_addr, *networkaddr, INET_ADDRSTRLEN))
        {
1028
            ERR("inet_ntop: %u\n", WSAGetLastError());
1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042
            I_RpcFree(*networkaddr);
            *networkaddr = NULL;
            if (endpoint)
            {
                I_RpcFree(*endpoint);
                *endpoint = NULL;
            }
            return EPT_S_NOT_REGISTERED;
        }
    }

    return RPC_S_OK;
}

1043 1044 1045
typedef struct _RpcConnection_tcp
{
  RpcConnection common;
1046
  int sock;
1047 1048
  HANDLE sock_event;
  HANDLE cancel_event;
1049 1050
} RpcConnection_tcp;

1051 1052
static BOOL rpcrt4_sock_wait_init(RpcConnection_tcp *tcpc)
{
1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070
  static BOOL wsa_inited;
  if (!wsa_inited)
  {
    WSADATA wsadata;
    WSAStartup(MAKEWORD(2, 2), &wsadata);
    /* Note: WSAStartup can be called more than once so we don't bother with
     * making accesses to wsa_inited thread-safe */
    wsa_inited = TRUE;
  }
  tcpc->sock_event = CreateEventW(NULL, FALSE, FALSE, NULL);
  tcpc->cancel_event = CreateEventW(NULL, FALSE, FALSE, NULL);
  if (!tcpc->sock_event || !tcpc->cancel_event)
  {
    ERR("event creation failed\n");
    if (tcpc->sock_event) CloseHandle(tcpc->sock_event);
    return FALSE;
  }
  return TRUE;
1071 1072 1073 1074
}

static BOOL rpcrt4_sock_wait_for_recv(RpcConnection_tcp *tcpc)
{
1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091
  HANDLE wait_handles[2];
  DWORD res;
  if (WSAEventSelect(tcpc->sock, tcpc->sock_event, FD_READ | FD_CLOSE) == SOCKET_ERROR)
  {
    ERR("WSAEventSelect() failed with error %d\n", WSAGetLastError());
    return FALSE;
  }
  wait_handles[0] = tcpc->sock_event;
  wait_handles[1] = tcpc->cancel_event;
  res = WaitForMultipleObjects(2, wait_handles, FALSE, INFINITE);
  switch (res)
  {
  case WAIT_OBJECT_0:
    return TRUE;
  case WAIT_OBJECT_0 + 1:
    return FALSE;
  default:
1092
    ERR("WaitForMultipleObjects() failed with error %ld\n", GetLastError());
1093 1094
    return FALSE;
  }
1095 1096 1097 1098
}

static BOOL rpcrt4_sock_wait_for_send(RpcConnection_tcp *tcpc)
{
1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110
  DWORD res;
  if (WSAEventSelect(tcpc->sock, tcpc->sock_event, FD_WRITE | FD_CLOSE) == SOCKET_ERROR)
  {
    ERR("WSAEventSelect() failed with error %d\n", WSAGetLastError());
    return FALSE;
  }
  res = WaitForSingleObject(tcpc->sock_event, INFINITE);
  switch (res)
  {
  case WAIT_OBJECT_0:
    return TRUE;
  default:
1111
    ERR("WaitForMultipleObjects() failed with error %ld\n", GetLastError());
1112 1113
    return FALSE;
  }
1114 1115
}

1116 1117
static RpcConnection *rpcrt4_conn_tcp_alloc(void)
{
1118
  RpcConnection_tcp *tcpc;
1119
  tcpc = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(RpcConnection_tcp));
1120 1121 1122
  if (tcpc == NULL)
    return NULL;
  tcpc->sock = -1;
1123
  if (!rpcrt4_sock_wait_init(tcpc))
1124 1125 1126 1127
  {
    HeapFree(GetProcessHeap(), 0, tcpc);
    return NULL;
  }
1128
  return &tcpc->common;
1129 1130 1131 1132
}

static RPC_STATUS rpcrt4_ncacn_ip_tcp_open(RpcConnection* Connection)
{
1133 1134
  RpcConnection_tcp *tcpc = (RpcConnection_tcp *) Connection;
  int sock;
1135 1136 1137 1138
  int ret;
  struct addrinfo *ai;
  struct addrinfo *ai_cur;
  struct addrinfo hints;
1139 1140 1141

  TRACE("(%s, %s)\n", Connection->NetworkAddr, Connection->Endpoint);

1142
  if (tcpc->sock != -1)
1143 1144
    return RPC_S_OK;

1145
  hints.ai_flags          = 0;
1146 1147 1148 1149 1150 1151 1152 1153 1154
  hints.ai_family         = PF_UNSPEC;
  hints.ai_socktype       = SOCK_STREAM;
  hints.ai_protocol       = IPPROTO_TCP;
  hints.ai_addrlen        = 0;
  hints.ai_addr           = NULL;
  hints.ai_canonname      = NULL;
  hints.ai_next           = NULL;

  ret = getaddrinfo(Connection->NetworkAddr, Connection->Endpoint, &hints, &ai);
1155
  if (ret)
1156
  {
1157 1158
    ERR("getaddrinfo for %s:%s failed, error %u\n", Connection->NetworkAddr,
            Connection->Endpoint, WSAGetLastError());
1159
    return RPC_S_SERVER_UNAVAILABLE;
1160 1161
  }

1162
  for (ai_cur = ai; ai_cur; ai_cur = ai_cur->ai_next)
1163
  {
1164
    int val;
1165
    u_long nonblocking;
1166

1167 1168 1169 1170 1171 1172
    if (ai_cur->ai_family != AF_INET && ai_cur->ai_family != AF_INET6)
    {
      TRACE("skipping non-IP/IPv6 address family\n");
      continue;
    }

1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183
    if (TRACE_ON(rpc))
    {
      char host[256];
      char service[256];
      getnameinfo(ai_cur->ai_addr, ai_cur->ai_addrlen,
        host, sizeof(host), service, sizeof(service),
        NI_NUMERICHOST | NI_NUMERICSERV);
      TRACE("trying %s:%s\n", host, service);
    }

    sock = socket(ai_cur->ai_family, ai_cur->ai_socktype, ai_cur->ai_protocol);
1184
    if (sock == -1)
1185
    {
1186
      WARN("socket() failed: %u\n", WSAGetLastError());
1187 1188
      continue;
    }
1189

1190
    if (0>connect(sock, ai_cur->ai_addr, ai_cur->ai_addrlen))
1191
    {
1192
      WARN("connect() failed: %u\n", WSAGetLastError());
1193
      closesocket(sock);
1194
      continue;
1195
    }
1196 1197 1198

    /* RPC depends on having minimal latency so disable the Nagle algorithm */
    val = 1;
1199
    setsockopt(sock, IPPROTO_TCP, TCP_NODELAY, (char *)&val, sizeof(val));
1200 1201
    nonblocking = 1;
    ioctlsocket(sock, FIONBIO, &nonblocking);
1202

1203
    tcpc->sock = sock;
1204 1205 1206 1207 1208

    freeaddrinfo(ai);
    TRACE("connected\n");
    return RPC_S_OK;
  }
1209

1210 1211
  freeaddrinfo(ai);
  ERR("couldn't connect to %s:%s\n", Connection->NetworkAddr, Connection->Endpoint);
1212 1213 1214
  return RPC_S_SERVER_UNAVAILABLE;
}

1215
static RPC_STATUS rpcrt4_protseq_ncacn_ip_tcp_open_endpoint(RpcServerProtseq *protseq, const char *endpoint)
1216
{
1217
    RPC_STATUS status = RPC_S_CANT_CREATE_ENDPOINT;
1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234
    int sock;
    int ret;
    struct addrinfo *ai;
    struct addrinfo *ai_cur;
    struct addrinfo hints;

    TRACE("(%p, %s)\n", protseq, endpoint);

    hints.ai_flags          = AI_PASSIVE /* for non-localhost addresses */;
    hints.ai_family         = PF_UNSPEC;
    hints.ai_socktype       = SOCK_STREAM;
    hints.ai_protocol       = IPPROTO_TCP;
    hints.ai_addrlen        = 0;
    hints.ai_addr           = NULL;
    hints.ai_canonname      = NULL;
    hints.ai_next           = NULL;

1235
    ret = getaddrinfo(NULL, endpoint ? endpoint : "0", &hints, &ai);
1236 1237
    if (ret)
    {
1238
        ERR("getaddrinfo for port %s failed, error %u\n", endpoint, WSAGetLastError());
1239 1240 1241
        if ((ret == EAI_SERVICE) || (ret == EAI_NONAME))
            return RPC_S_INVALID_ENDPOINT_FORMAT;
        return RPC_S_CANT_CREATE_ENDPOINT;
1242 1243 1244 1245 1246
    }

    for (ai_cur = ai; ai_cur; ai_cur = ai_cur->ai_next)
    {
        RpcConnection_tcp *tcpc;
1247
        RPC_STATUS create_status;
1248 1249 1250
        struct sockaddr_storage sa;
        socklen_t sa_len;
        char service[NI_MAXSERV];
1251
        u_long nonblocking;
1252

1253 1254 1255 1256 1257 1258
        if (ai_cur->ai_family != AF_INET && ai_cur->ai_family != AF_INET6)
        {
            TRACE("skipping non-IP/IPv6 address family\n");
            continue;
        }

1259 1260 1261 1262 1263 1264 1265 1266 1267 1268
        if (TRACE_ON(rpc))
        {
            char host[256];
            getnameinfo(ai_cur->ai_addr, ai_cur->ai_addrlen,
                        host, sizeof(host), service, sizeof(service),
                        NI_NUMERICHOST | NI_NUMERICSERV);
            TRACE("trying %s:%s\n", host, service);
        }

        sock = socket(ai_cur->ai_family, ai_cur->ai_socktype, ai_cur->ai_protocol);
1269
        if (sock == -1)
1270
        {
1271
            WARN("socket() failed: %u\n", WSAGetLastError());
1272
            status = RPC_S_CANT_CREATE_ENDPOINT;
1273 1274 1275 1276 1277 1278
            continue;
        }

        ret = bind(sock, ai_cur->ai_addr, ai_cur->ai_addrlen);
        if (ret < 0)
        {
1279
            WARN("bind failed: %u\n", WSAGetLastError());
1280
            closesocket(sock);
1281
            if (WSAGetLastError() == WSAEADDRINUSE)
1282 1283 1284
              status = RPC_S_DUPLICATE_ENDPOINT;
            else
              status = RPC_S_CANT_CREATE_ENDPOINT;
1285 1286
            continue;
        }
1287 1288 1289 1290

        sa_len = sizeof(sa);
        if (getsockname(sock, (struct sockaddr *)&sa, &sa_len))
        {
1291
            WARN("getsockname() failed: %u\n", WSAGetLastError());
1292
            closesocket(sock);
1293 1294 1295 1296 1297 1298 1299 1300 1301
            status = RPC_S_CANT_CREATE_ENDPOINT;
            continue;
        }

        ret = getnameinfo((struct sockaddr *)&sa, sa_len,
                          NULL, 0, service, sizeof(service),
                          NI_NUMERICSERV);
        if (ret)
        {
1302
            WARN("getnameinfo failed, error %u\n", WSAGetLastError());
1303
            closesocket(sock);
1304 1305 1306 1307
            status = RPC_S_CANT_CREATE_ENDPOINT;
            continue;
        }

1308 1309
        create_status = RPCRT4_CreateConnection((RpcConnection **)&tcpc, TRUE,
                                                protseq->Protseq, NULL,
1310
                                                service, NULL, NULL, NULL, NULL);
1311
        if (create_status != RPC_S_OK)
1312
        {
1313
            closesocket(sock);
1314
            status = create_status;
1315 1316 1317
            continue;
        }

1318
        tcpc->sock = sock;
1319
        ret = listen(sock, protseq->MaxCalls);
1320 1321
        if (ret < 0)
        {
1322
            WARN("listen failed: %u\n", WSAGetLastError());
1323
            RPCRT4_ReleaseConnection(&tcpc->common);
1324
            status = RPC_S_OUT_OF_RESOURCES;
1325 1326 1327 1328 1329 1330
            continue;
        }
        /* need a non-blocking socket, otherwise accept() has a potential
         * race-condition (poll() says it is readable, connection drops,
         * and accept() blocks until the next connection comes...)
         */
1331 1332
        nonblocking = 1;
        ret = ioctlsocket(sock, FIONBIO, &nonblocking);
1333 1334 1335
        if (ret < 0)
        {
            WARN("couldn't make socket non-blocking, error %d\n", ret);
1336
            RPCRT4_ReleaseConnection(&tcpc->common);
1337
            status = RPC_S_OUT_OF_RESOURCES;
1338 1339 1340
            continue;
        }

1341
        EnterCriticalSection(&protseq->cs);
1342
        list_add_tail(&protseq->listeners, &tcpc->common.protseq_entry);
1343
        tcpc->common.protseq = protseq;
1344 1345 1346
        LeaveCriticalSection(&protseq->cs);

        freeaddrinfo(ai);
1347 1348 1349

        /* since IPv4 and IPv6 share the same port space, we only need one
         * successful bind to listen for both */
1350 1351 1352 1353
        TRACE("listening on %s\n", endpoint);
        return RPC_S_OK;
    }

1354
    freeaddrinfo(ai);
1355
    ERR("couldn't listen on port %s\n", endpoint);
1356
    return status;
1357 1358
}

1359 1360
static RPC_STATUS rpcrt4_conn_tcp_handoff(RpcConnection *old_conn, RpcConnection *new_conn)
{
1361 1362 1363 1364 1365
  int ret;
  struct sockaddr_in address;
  socklen_t addrsize;
  RpcConnection_tcp *server = (RpcConnection_tcp*) old_conn;
  RpcConnection_tcp *client = (RpcConnection_tcp*) new_conn;
1366
  u_long nonblocking;
1367 1368 1369 1370 1371 1372

  addrsize = sizeof(address);
  ret = accept(server->sock, (struct sockaddr*) &address, &addrsize);
  if (ret < 0)
  {
    ERR("Failed to accept a TCP connection: error %d\n", ret);
1373
    return RPC_S_OUT_OF_RESOURCES;
1374
  }
1375

1376 1377
  nonblocking = 1;
  ioctlsocket(ret, FIONBIO, &nonblocking);
1378
  client->sock = ret;
1379 1380 1381 1382 1383 1384 1385 1386 1387 1388

  client->common.NetworkAddr = HeapAlloc(GetProcessHeap(), 0, INET6_ADDRSTRLEN);
  ret = getnameinfo((struct sockaddr*)&address, addrsize, client->common.NetworkAddr, INET6_ADDRSTRLEN, NULL, 0, NI_NUMERICHOST);
  if (ret != 0)
  {
    ERR("Failed to retrieve the IP address, error %d\n", ret);
    return RPC_S_OUT_OF_RESOURCES;
  }

  TRACE("Accepted a new TCP connection from %s\n", client->common.NetworkAddr);
1389
  return RPC_S_OK;
1390 1391 1392 1393 1394
}

static int rpcrt4_conn_tcp_read(RpcConnection *Connection,
                                void *buffer, unsigned int count)
{
1395
  RpcConnection_tcp *tcpc = (RpcConnection_tcp *) Connection;
1396
  int bytes_read = 0;
1397
  while (bytes_read != count)
1398 1399
  {
    int r = recv(tcpc->sock, (char *)buffer + bytes_read, count - bytes_read, 0);
1400 1401 1402
    if (!r)
      return -1;
    else if (r > 0)
1403
      bytes_read += r;
1404
    else if (WSAGetLastError() == WSAEINTR)
1405
      continue;
1406
    else if (WSAGetLastError() != WSAEWOULDBLOCK)
1407
    {
1408
      WARN("recv() failed: %u\n", WSAGetLastError());
1409
      return -1;
1410
    }
1411 1412
    else
    {
1413
      if (!rpcrt4_sock_wait_for_recv(tcpc))
1414 1415
        return -1;
    }
1416
  }
1417 1418
  TRACE("%d %p %u -> %d\n", tcpc->sock, buffer, count, bytes_read);
  return bytes_read;
1419 1420 1421 1422 1423
}

static int rpcrt4_conn_tcp_write(RpcConnection *Connection,
                                 const void *buffer, unsigned int count)
{
1424
  RpcConnection_tcp *tcpc = (RpcConnection_tcp *) Connection;
1425
  int bytes_written = 0;
1426
  while (bytes_written != count)
1427
  {
1428
    int r = send(tcpc->sock, (const char *)buffer + bytes_written, count - bytes_written, 0);
1429 1430
    if (r >= 0)
      bytes_written += r;
1431
    else if (WSAGetLastError() == WSAEINTR)
1432
      continue;
1433
    else if (WSAGetLastError() != WSAEWOULDBLOCK)
1434 1435 1436
      return -1;
    else
    {
1437
      if (!rpcrt4_sock_wait_for_send(tcpc))
1438 1439
        return -1;
    }
1440
  }
1441 1442
  TRACE("%d %p %u -> %d\n", tcpc->sock, buffer, count, bytes_written);
  return bytes_written;
1443 1444
}

1445
static int rpcrt4_conn_tcp_close(RpcConnection *conn)
1446
{
1447
    RpcConnection_tcp *connection = (RpcConnection_tcp *) conn;
1448

1449
    TRACE("%d\n", connection->sock);
1450

1451 1452 1453 1454 1455 1456
    if (connection->sock != -1)
        closesocket(connection->sock);
    connection->sock = -1;
    CloseHandle(connection->sock_event);
    CloseHandle(connection->cancel_event);
    return 0;
1457 1458
}

1459 1460
static void rpcrt4_conn_tcp_close_read(RpcConnection *conn)
{
1461 1462
    RpcConnection_tcp *connection = (RpcConnection_tcp *) conn;
    shutdown(connection->sock, SD_RECEIVE);
1463 1464
}

1465
static void rpcrt4_conn_tcp_cancel_call(RpcConnection *conn)
1466
{
1467 1468 1469 1470 1471
    RpcConnection_tcp *connection = (RpcConnection_tcp *) conn;

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

    SetEvent(connection->cancel_event);
1472 1473
}

1474 1475 1476 1477 1478 1479
static RPC_STATUS rpcrt4_conn_tcp_is_server_listening(const char *endpoint)
{
    FIXME("\n");
    return RPC_S_ACCESS_DENIED;
}

1480 1481 1482 1483 1484 1485
static int rpcrt4_conn_tcp_wait_for_incoming_data(RpcConnection *Connection)
{
    RpcConnection_tcp *tcpc = (RpcConnection_tcp *) Connection;

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

1486 1487
    if (!rpcrt4_sock_wait_for_recv(tcpc))
        return -1;
1488 1489 1490
    return 0;
}

1491 1492 1493 1494 1495 1496 1497 1498
static size_t rpcrt4_ncacn_ip_tcp_get_top_of_tower(unsigned char *tower_data,
                                                   const char *networkaddr,
                                                   const char *endpoint)
{
    return rpcrt4_ip_tcp_get_top_of_tower(tower_data, networkaddr,
                                          EPM_PROTOCOL_TCP, endpoint);
}

1499 1500 1501 1502 1503 1504 1505 1506
typedef struct _RpcServerProtseq_sock
{
    RpcServerProtseq common;
    HANDLE mgr_event;
} RpcServerProtseq_sock;

static RpcServerProtseq *rpcrt4_protseq_sock_alloc(void)
{
1507
    RpcServerProtseq_sock *ps = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*ps));
1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539
    if (ps)
    {
        static BOOL wsa_inited;
        if (!wsa_inited)
        {
            WSADATA wsadata;
            WSAStartup(MAKEWORD(2, 2), &wsadata);
            /* Note: WSAStartup can be called more than once so we don't bother with
             * making accesses to wsa_inited thread-safe */
            wsa_inited = TRUE;
        }
        ps->mgr_event = CreateEventW(NULL, FALSE, FALSE, NULL);
    }
    return &ps->common;
}

static void rpcrt4_protseq_sock_signal_state_changed(RpcServerProtseq *protseq)
{
    RpcServerProtseq_sock *sockps = CONTAINING_RECORD(protseq, RpcServerProtseq_sock, common);
    SetEvent(sockps->mgr_event);
}

static void *rpcrt4_protseq_sock_get_wait_array(RpcServerProtseq *protseq, void *prev_array, unsigned int *count)
{
    HANDLE *objs = prev_array;
    RpcConnection_tcp *conn;
    RpcServerProtseq_sock *sockps = CONTAINING_RECORD(protseq, RpcServerProtseq_sock, common);

    EnterCriticalSection(&protseq->cs);

    /* open and count connections */
    *count = 1;
1540
    LIST_FOR_EACH_ENTRY(conn, &protseq->listeners, RpcConnection_tcp, common.protseq_entry)
1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559
    {
        if (conn->sock != -1)
            (*count)++;
    }

    /* make array of connections */
    if (objs)
        objs = HeapReAlloc(GetProcessHeap(), 0, objs, *count*sizeof(HANDLE));
    else
        objs = HeapAlloc(GetProcessHeap(), 0, *count*sizeof(HANDLE));
    if (!objs)
    {
        ERR("couldn't allocate objs\n");
        LeaveCriticalSection(&protseq->cs);
        return NULL;
    }

    objs[0] = sockps->mgr_event;
    *count = 1;
1560
    LIST_FOR_EACH_ENTRY(conn, &protseq->listeners, RpcConnection_tcp, common.protseq_entry)
1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587
    {
        if (conn->sock != -1)
        {
            int res = WSAEventSelect(conn->sock, conn->sock_event, FD_ACCEPT);
            if (res == SOCKET_ERROR)
                ERR("WSAEventSelect() failed with error %d\n", WSAGetLastError());
            else
            {
                objs[*count] = conn->sock_event;
                (*count)++;
            }
        }
    }
    LeaveCriticalSection(&protseq->cs);
    return objs;
}

static void rpcrt4_protseq_sock_free_wait_array(RpcServerProtseq *protseq, void *array)
{
    HeapFree(GetProcessHeap(), 0, array);
}

static int rpcrt4_protseq_sock_wait_for_new_connection(RpcServerProtseq *protseq, unsigned int count, void *wait_array)
{
    HANDLE b_handle;
    HANDLE *objs = wait_array;
    DWORD res;
1588
    RpcConnection *cconn = NULL;
1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604
    RpcConnection_tcp *conn;

    if (!objs)
        return -1;

    do
    {
        /* an alertable wait isn't strictly necessary, but due to our
         * overlapped I/O implementation in Wine we need to free some memory
         * by the file user APC being called, even if no completion routine was
         * specified at the time of starting the async operation */
        res = WaitForMultipleObjectsEx(count, objs, FALSE, INFINITE, TRUE);
    } while (res == WAIT_IO_COMPLETION);

    if (res == WAIT_OBJECT_0)
        return 0;
1605
    if (res == WAIT_FAILED)
1606
    {
1607
        ERR("wait failed with error %ld\n", GetLastError());
1608 1609
        return -1;
    }
1610 1611 1612 1613 1614

    b_handle = objs[res - WAIT_OBJECT_0];

    /* find which connection got a RPC */
    EnterCriticalSection(&protseq->cs);
1615
    LIST_FOR_EACH_ENTRY(conn, &protseq->listeners, RpcConnection_tcp, common.protseq_entry)
1616
    {
1617
        if (b_handle == conn->sock_event)
1618
        {
1619
            cconn = rpcrt4_spawn_connection(&conn->common);
1620
            break;
1621 1622
        }
    }
1623 1624 1625 1626 1627 1628 1629 1630 1631
    LeaveCriticalSection(&protseq->cs);
    if (!cconn)
    {
        ERR("failed to locate connection for handle %p\n", b_handle);
        return -1;
    }

    RPCRT4_new_client(cconn);
    return 1;
1632 1633
}

1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655
static RPC_STATUS rpcrt4_ncacn_ip_tcp_parse_top_of_tower(const unsigned char *tower_data,
                                                         size_t tower_size,
                                                         char **networkaddr,
                                                         char **endpoint)
{
    return rpcrt4_ip_tcp_parse_top_of_tower(tower_data, tower_size,
                                            networkaddr, EPM_PROTOCOL_TCP,
                                            endpoint);
}

/**** ncacn_http support ****/

/* 60 seconds is the period native uses */
#define HTTP_IDLE_TIME 60000

/* reference counted to avoid a race between a cancelled call's connection
 * being destroyed and the asynchronous InternetReadFileEx call being
 * completed */
typedef struct _RpcHttpAsyncData
{
    LONG refs;
    HANDLE completion_event;
1656
    WORD async_result;
1657
    INTERNET_BUFFERSW inet_buffers;
1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673
    CRITICAL_SECTION cs;
} RpcHttpAsyncData;

static ULONG RpcHttpAsyncData_AddRef(RpcHttpAsyncData *data)
{
    return InterlockedIncrement(&data->refs);
}

static ULONG RpcHttpAsyncData_Release(RpcHttpAsyncData *data)
{
    ULONG refs = InterlockedDecrement(&data->refs);
    if (!refs)
    {
        TRACE("destroying async data %p\n", data);
        CloseHandle(data->completion_event);
        HeapFree(GetProcessHeap(), 0, data->inet_buffers.lpvBuffer);
1674
        data->cs.DebugInfo->Spare[0] = 0;
1675 1676 1677 1678 1679 1680
        DeleteCriticalSection(&data->cs);
        HeapFree(GetProcessHeap(), 0, data);
    }
    return refs;
}

1681 1682 1683 1684 1685 1686
static void prepare_async_request(RpcHttpAsyncData *async_data)
{
    ResetEvent(async_data->completion_event);
    RpcHttpAsyncData_AddRef(async_data);
}

1687 1688
static RPC_STATUS wait_async_request(RpcHttpAsyncData *async_data, BOOL call_ret, HANDLE cancel_event)
{
1689 1690 1691
    HANDLE handles[2] = { async_data->completion_event, cancel_event };
    DWORD res;

1692 1693 1694 1695 1696 1697 1698
    if(call_ret) {
        RpcHttpAsyncData_Release(async_data);
        return RPC_S_OK;
    }

    if(GetLastError() != ERROR_IO_PENDING) {
        RpcHttpAsyncData_Release(async_data);
1699
        ERR("Request failed with error %ld\n", GetLastError());
1700 1701 1702
        return RPC_S_SERVER_UNAVAILABLE;
    }

1703 1704 1705 1706
    res = WaitForMultipleObjects(2, handles, FALSE, DEFAULT_NCACN_HTTP_TIMEOUT);
    if(res != WAIT_OBJECT_0) {
        TRACE("Cancelled\n");
        return RPC_S_CALL_CANCELLED;
1707
    }
1708

1709 1710 1711 1712 1713
    if(async_data->async_result) {
        ERR("Async request failed with error %d\n", async_data->async_result);
        return RPC_S_SERVER_UNAVAILABLE;
    }

1714 1715 1716
    return RPC_S_OK;
}

1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729
struct authinfo
{
    DWORD        scheme;
    CredHandle   cred;
    CtxtHandle   ctx;
    TimeStamp    exp;
    ULONG        attr;
    ULONG        max_token;
    char        *data;
    unsigned int data_len;
    BOOL         finished; /* finished authenticating */
};

1730 1731 1732 1733 1734 1735 1736
typedef struct _RpcConnection_http
{
    RpcConnection common;
    HINTERNET app_info;
    HINTERNET session;
    HINTERNET in_request;
    HINTERNET out_request;
1737
    WCHAR *servername;
1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763
    HANDLE timer_cancelled;
    HANDLE cancel_event;
    DWORD last_sent_time;
    ULONG bytes_received;
    ULONG flow_control_mark; /* send a control packet to the server when this many bytes received */
    ULONG flow_control_increment; /* number of bytes to increment flow_control_mark by */
    UUID connection_uuid;
    UUID in_pipe_uuid;
    UUID out_pipe_uuid;
    RpcHttpAsyncData *async_data;
} RpcConnection_http;

static RpcConnection *rpcrt4_ncacn_http_alloc(void)
{
    RpcConnection_http *httpc;
    httpc = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*httpc));
    if (!httpc) return NULL;
    httpc->async_data = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(RpcHttpAsyncData));
    if (!httpc->async_data)
    {
        HeapFree(GetProcessHeap(), 0, httpc);
        return NULL;
    }
    TRACE("async data = %p\n", httpc->async_data);
    httpc->cancel_event = CreateEventW(NULL, FALSE, FALSE, NULL);
    httpc->async_data->refs = 1;
1764
    httpc->async_data->inet_buffers.dwStructSize = sizeof(INTERNET_BUFFERSW);
1765
    InitializeCriticalSection(&httpc->async_data->cs);
1766
    httpc->async_data->cs.DebugInfo->Spare[0] = (DWORD_PTR)(__FILE__ ": RpcHttpAsyncData.cs");
1767 1768 1769 1770 1771 1772 1773 1774 1775 1776
    return &httpc->common;
}

typedef struct _HttpTimerThreadData
{
    PVOID timer_param;
    DWORD *last_sent_time;
    HANDLE timer_cancelled;
} HttpTimerThreadData;

1777
static VOID rpcrt4_http_keep_connection_active_timer_proc(PVOID param, BOOLEAN dummy)
1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804
{
    HINTERNET in_request = param;
    RpcPktHdr *idle_pkt;

    idle_pkt = RPCRT4_BuildHttpHeader(NDR_LOCAL_DATA_REPRESENTATION, 0x0001,
                                      0, 0);
    if (idle_pkt)
    {
        DWORD bytes_written;
        InternetWriteFile(in_request, idle_pkt, idle_pkt->common.frag_len, &bytes_written);
        RPCRT4_FreeHeader(idle_pkt);
    }
}

static inline DWORD rpcrt4_http_timer_calc_timeout(DWORD *last_sent_time)
{
    DWORD cur_time = GetTickCount();
    DWORD cached_last_sent_time = *last_sent_time;
    return HTTP_IDLE_TIME - (cur_time - cached_last_sent_time > HTTP_IDLE_TIME ? 0 : cur_time - cached_last_sent_time);
}

static DWORD CALLBACK rpcrt4_http_timer_thread(PVOID param)
{
    HttpTimerThreadData *data_in = param;
    HttpTimerThreadData data;
    DWORD timeout;

1805 1806
    SetThreadDescription(GetCurrentThread(), L"wine_rpcrt4_http_timer");

1807 1808 1809 1810 1811 1812 1813 1814
    data = *data_in;
    HeapFree(GetProcessHeap(), 0, data_in);

    for (timeout = HTTP_IDLE_TIME;
         WaitForSingleObject(data.timer_cancelled, timeout) == WAIT_TIMEOUT;
         timeout = rpcrt4_http_timer_calc_timeout(data.last_sent_time))
    {
        /* are we too soon after last send? */
1815
        if (GetTickCount() - *data.last_sent_time < HTTP_IDLE_TIME)
1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838
            continue;
        rpcrt4_http_keep_connection_active_timer_proc(data.timer_param, TRUE);
    }

    CloseHandle(data.timer_cancelled);
    return 0;
}

static VOID WINAPI rpcrt4_http_internet_callback(
     HINTERNET hInternet,
     DWORD_PTR dwContext,
     DWORD dwInternetStatus,
     LPVOID lpvStatusInformation,
     DWORD dwStatusInformationLength)
{
    RpcHttpAsyncData *async_data = (RpcHttpAsyncData *)dwContext;

    switch (dwInternetStatus)
    {
    case INTERNET_STATUS_REQUEST_COMPLETE:
        TRACE("INTERNET_STATUS_REQUEST_COMPLETED\n");
        if (async_data)
        {
1839 1840 1841
            INTERNET_ASYNC_RESULT *async_result = lpvStatusInformation;

            async_data->async_result = async_result->dwResult ? ERROR_SUCCESS : async_result->dwError;
1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854
            SetEvent(async_data->completion_event);
            RpcHttpAsyncData_Release(async_data);
        }
        break;
    }
}

static RPC_STATUS rpcrt4_http_check_response(HINTERNET hor)
{
    BOOL ret;
    DWORD status_code;
    DWORD size;
    DWORD index;
1855 1856
    WCHAR buf[32];
    WCHAR *status_text = buf;
1857 1858 1859 1860 1861 1862 1863
    TRACE("\n");

    index = 0;
    size = sizeof(status_code);
    ret = HttpQueryInfoW(hor, HTTP_QUERY_STATUS_CODE|HTTP_QUERY_FLAG_NUMBER, &status_code, &size, &index);
    if (!ret)
        return GetLastError();
1864
    if (status_code == HTTP_STATUS_OK)
1865 1866
        return RPC_S_OK;
    index = 0;
1867
    size = sizeof(buf);
1868
    ret = HttpQueryInfoW(hor, HTTP_QUERY_STATUS_TEXT, status_text, &size, &index);
1869 1870 1871 1872 1873 1874
    if (!ret && GetLastError() == ERROR_INSUFFICIENT_BUFFER)
    {
        status_text = HeapAlloc(GetProcessHeap(), 0, size);
        ret = HttpQueryInfoW(hor, HTTP_QUERY_STATUS_TEXT, status_text, &size, &index);
    }

1875
    ERR("server returned: %ld %s\n", status_code, ret ? debugstr_w(status_text) : "<status text unavailable>");
1876 1877
    if(status_text != buf) HeapFree(GetProcessHeap(), 0, status_text);

1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889
    if (status_code == HTTP_STATUS_DENIED)
        return ERROR_ACCESS_DENIED;
    return RPC_S_SERVER_UNAVAILABLE;
}

static RPC_STATUS rpcrt4_http_internet_connect(RpcConnection_http *httpc)
{
    LPWSTR proxy = NULL;
    LPWSTR user = NULL;
    LPWSTR password = NULL;
    LPWSTR servername = NULL;
    const WCHAR *option;
1890
    INTERNET_PORT port;
1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919

    if (httpc->common.QOS &&
        (httpc->common.QOS->qos->AdditionalSecurityInfoType == RPC_C_AUTHN_INFO_TYPE_HTTP))
    {
        const RPC_HTTP_TRANSPORT_CREDENTIALS_W *http_cred = httpc->common.QOS->qos->u.HttpCredentials;
        if (http_cred->TransportCredentials)
        {
            WCHAR *p;
            const SEC_WINNT_AUTH_IDENTITY_W *cred = http_cred->TransportCredentials;
            ULONG len = cred->DomainLength + 1 + cred->UserLength;
            user = HeapAlloc(GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR));
            if (!user)
                return RPC_S_OUT_OF_RESOURCES;
            p = user;
            if (cred->DomainLength)
            {
                memcpy(p, cred->Domain, cred->DomainLength * sizeof(WCHAR));
                p += cred->DomainLength;
                *p = '\\';
                p++;
            }
            memcpy(p, cred->User, cred->UserLength * sizeof(WCHAR));
            p[cred->UserLength] = 0;

            password = RPCRT4_strndupW(cred->Password, cred->PasswordLength);
        }
    }

    for (option = httpc->common.NetworkOptions; option;
1920
         option = (wcschr(option, ',') ? wcschr(option, ',')+1 : NULL))
1921
    {
1922
        if (!wcsnicmp(option, L"RpcProxy=", ARRAY_SIZE(L"RpcProxy=")-1))
1923
        {
1924
            const WCHAR *value_start = option + ARRAY_SIZE(L"RpcProxy=")-1;
1925 1926 1927
            const WCHAR *value_end;
            const WCHAR *p;

1928
            value_end = wcschr(option, ',');
1929
            if (!value_end)
1930
                value_end = value_start + lstrlenW(value_start);
1931 1932 1933
            for (p = value_start; p < value_end; p++)
                if (*p == ':')
                {
1934
                    port = wcstol(p+1, NULL, 10);
1935 1936 1937 1938 1939 1940
                    value_end = p;
                    break;
                }
            TRACE("RpcProxy value is %s\n", debugstr_wn(value_start, value_end-value_start));
            servername = RPCRT4_strndupW(value_start, value_end-value_start);
        }
1941
        else if (!wcsnicmp(option, L"HttpProxy=", ARRAY_SIZE(L"HttpProxy=")-1))
1942
        {
1943
            const WCHAR *value_start = option + ARRAY_SIZE(L"HttpProxy=")-1;
1944 1945
            const WCHAR *value_end;

1946
            value_end = wcschr(option, ',');
1947
            if (!value_end)
1948
                value_end = value_start + lstrlenW(value_start);
1949 1950 1951 1952 1953 1954 1955
            TRACE("HttpProxy value is %s\n", debugstr_wn(value_start, value_end-value_start));
            proxy = RPCRT4_strndupW(value_start, value_end-value_start);
        }
        else
            FIXME("unhandled option %s\n", debugstr_w(option));
    }

1956
    httpc->app_info = InternetOpenW(L"MSRPC", proxy ? INTERNET_OPEN_TYPE_PROXY : INTERNET_OPEN_TYPE_PRECONFIG,
1957 1958 1959 1960 1961
                                    NULL, NULL, INTERNET_FLAG_ASYNC);
    if (!httpc->app_info)
    {
        HeapFree(GetProcessHeap(), 0, password);
        HeapFree(GetProcessHeap(), 0, user);
1962 1963
        HeapFree(GetProcessHeap(), 0, proxy);
        HeapFree(GetProcessHeap(), 0, servername);
1964
        ERR("InternetOpenW failed with error %ld\n", GetLastError());
1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977
        return RPC_S_SERVER_UNAVAILABLE;
    }
    InternetSetStatusCallbackW(httpc->app_info, rpcrt4_http_internet_callback);

    /* if no RpcProxy option specified, set the HTTP server address to the
     * RPC server address */
    if (!servername)
    {
        servername = HeapAlloc(GetProcessHeap(), 0, (strlen(httpc->common.NetworkAddr) + 1)*sizeof(WCHAR));
        if (!servername)
        {
            HeapFree(GetProcessHeap(), 0, password);
            HeapFree(GetProcessHeap(), 0, user);
1978
            HeapFree(GetProcessHeap(), 0, proxy);
1979 1980 1981 1982 1983
            return RPC_S_OUT_OF_RESOURCES;
        }
        MultiByteToWideChar(CP_ACP, 0, httpc->common.NetworkAddr, -1, servername, strlen(httpc->common.NetworkAddr) + 1);
    }

1984 1985 1986 1987 1988
    port = (httpc->common.QOS &&
            (httpc->common.QOS->qos->AdditionalSecurityInfoType == RPC_C_AUTHN_INFO_TYPE_HTTP) &&
            (httpc->common.QOS->qos->u.HttpCredentials->Flags & RPC_C_HTTP_FLAG_USE_SSL)) ?
            INTERNET_DEFAULT_HTTPS_PORT : INTERNET_DEFAULT_HTTP_PORT;

1989 1990 1991 1992 1993
    httpc->session = InternetConnectW(httpc->app_info, servername, port, user, password,
                                      INTERNET_SERVICE_HTTP, 0, 0);

    HeapFree(GetProcessHeap(), 0, password);
    HeapFree(GetProcessHeap(), 0, user);
1994
    HeapFree(GetProcessHeap(), 0, proxy);
1995 1996 1997

    if (!httpc->session)
    {
1998
        ERR("InternetConnectW failed with error %ld\n", GetLastError());
1999
        HeapFree(GetProcessHeap(), 0, servername);
2000 2001
        return RPC_S_SERVER_UNAVAILABLE;
    }
2002
    httpc->servername = servername;
2003 2004 2005
    return RPC_S_OK;
}

2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040
static int rpcrt4_http_async_read(HINTERNET req, RpcHttpAsyncData *async_data, HANDLE cancel_event,
                                  void *buffer, unsigned int count)
{
    char *buf = buffer;
    BOOL ret;
    unsigned int bytes_left = count;
    RPC_STATUS status = RPC_S_OK;

    async_data->inet_buffers.lpvBuffer = HeapAlloc(GetProcessHeap(), 0, count);

    while (bytes_left)
    {
        async_data->inet_buffers.dwBufferLength = bytes_left;
        prepare_async_request(async_data);
        ret = InternetReadFileExW(req, &async_data->inet_buffers, IRF_ASYNC, 0);
        status = wait_async_request(async_data, ret, cancel_event);
        if (status != RPC_S_OK)
        {
            if (status == RPC_S_CALL_CANCELLED)
                TRACE("call cancelled\n");
            break;
        }

        if (!async_data->inet_buffers.dwBufferLength)
            break;
        memcpy(buf, async_data->inet_buffers.lpvBuffer,
               async_data->inet_buffers.dwBufferLength);

        bytes_left -= async_data->inet_buffers.dwBufferLength;
        buf += async_data->inet_buffers.dwBufferLength;
    }

    HeapFree(GetProcessHeap(), 0, async_data->inet_buffers.lpvBuffer);
    async_data->inet_buffers.lpvBuffer = NULL;

2041
    TRACE("%p %p %u -> %lu\n", req, buffer, count, status);
2042 2043 2044
    return status == RPC_S_OK ? count : -1;
}

2045 2046 2047 2048 2049 2050
static RPC_STATUS send_echo_request(HINTERNET req, RpcHttpAsyncData *async_data, HANDLE cancel_event)
{
    BYTE buf[20];
    BOOL ret;
    RPC_STATUS status;

2051 2052
    TRACE("sending echo request to server\n");

2053 2054 2055 2056 2057 2058 2059 2060
    prepare_async_request(async_data);
    ret = HttpSendRequestW(req, NULL, 0, NULL, 0);
    status = wait_async_request(async_data, ret, cancel_event);
    if (status != RPC_S_OK) return status;

    status = rpcrt4_http_check_response(req);
    if (status != RPC_S_OK) return status;

2061
    rpcrt4_http_async_read(req, async_data, cancel_event, buf, sizeof(buf));
2062 2063 2064 2065 2066
    /* FIXME: do something with retrieved data */

    return RPC_S_OK;
}

2067 2068
static RPC_STATUS insert_content_length_header(HINTERNET request, DWORD len)
{
2069
    WCHAR header[ARRAY_SIZE(L"Content-Length: %u\r\n") + 10];
2070

2071
    swprintf(header, ARRAY_SIZE(header), L"Content-Length: %u\r\n", len);
2072
    if ((HttpAddRequestHeadersW(request, header, -1, HTTP_ADDREQ_FLAG_REPLACE | HTTP_ADDREQ_FLAG_ADD))) return RPC_S_OK;
2073 2074 2075
    return RPC_S_SERVER_UNAVAILABLE;
}

2076
/* prepare the in pipe for use by RPC packets */
2077
static RPC_STATUS rpcrt4_http_prepare_in_pipe(HINTERNET in_request, RpcHttpAsyncData *async_data, HANDLE cancel_event,
2078 2079
                                              const UUID *connection_uuid, const UUID *in_pipe_uuid,
                                              const UUID *association_uuid, BOOL authorized)
2080 2081 2082 2083 2084
{
    BOOL ret;
    RPC_STATUS status;
    RpcPktHdr *hdr;
    INTERNET_BUFFERSW buffers_in;
2085
    DWORD bytes_written;
2086

2087 2088 2089 2090 2091 2092
    if (!authorized)
    {
        /* ask wininet to authorize, if necessary */
        status = send_echo_request(in_request, async_data, cancel_event);
        if (status != RPC_S_OK) return status;
    }
2093 2094 2095 2096
    memset(&buffers_in, 0, sizeof(buffers_in));
    buffers_in.dwStructSize = sizeof(buffers_in);
    /* FIXME: get this from the registry */
    buffers_in.dwBufferTotal = 1024 * 1024 * 1024; /* 1Gb */
2097 2098 2099
    status = insert_content_length_header(in_request, buffers_in.dwBufferTotal);
    if (status != RPC_S_OK) return status;

2100
    prepare_async_request(async_data);
2101
    ret = HttpSendRequestExW(in_request, &buffers_in, NULL, 0, 0);
2102
    status = wait_async_request(async_data, ret, cancel_event);
2103
    if (status != RPC_S_OK) return status;
2104 2105

    TRACE("sending HTTP connect header to server\n");
2106
    hdr = RPCRT4_BuildHttpConnectHeader(FALSE, connection_uuid, in_pipe_uuid, association_uuid);
2107 2108 2109 2110 2111
    if (!hdr) return RPC_S_OUT_OF_RESOURCES;
    ret = InternetWriteFile(in_request, hdr, hdr->common.frag_len, &bytes_written);
    RPCRT4_FreeHeader(hdr);
    if (!ret)
    {
2112
        ERR("InternetWriteFile failed with error %ld\n", GetLastError());
2113 2114 2115 2116 2117 2118
        return RPC_S_SERVER_UNAVAILABLE;
    }

    return RPC_S_OK;
}

2119 2120
static RPC_STATUS rpcrt4_http_read_http_packet(HINTERNET request, RpcHttpAsyncData *async_data,
                                               HANDLE cancel_event, RpcPktHdr *hdr, BYTE **data)
2121 2122
{
    unsigned short data_len;
2123
    unsigned int size;
2124

2125
    if (rpcrt4_http_async_read(request, async_data, cancel_event, hdr, sizeof(hdr->common)) < 0)
2126 2127 2128 2129 2130 2131 2132 2133
        return RPC_S_SERVER_UNAVAILABLE;
    if (hdr->common.ptype != PKT_HTTP || hdr->common.frag_len < sizeof(hdr->http))
    {
        ERR("wrong packet type received %d or wrong frag_len %d\n",
            hdr->common.ptype, hdr->common.frag_len);
        return RPC_S_PROTOCOL_ERROR;
    }

2134 2135
    size = sizeof(hdr->http) - sizeof(hdr->common);
    if (rpcrt4_http_async_read(request, async_data, cancel_event, &hdr->common + 1, size) < 0)
2136 2137 2138 2139 2140 2141 2142 2143
        return RPC_S_SERVER_UNAVAILABLE;

    data_len = hdr->common.frag_len - sizeof(hdr->http);
    if (data_len)
    {
        *data = HeapAlloc(GetProcessHeap(), 0, data_len);
        if (!*data)
            return RPC_S_OUT_OF_RESOURCES;
2144
        if (rpcrt4_http_async_read(request, async_data, cancel_event, *data, data_len) < 0)
2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155
        {
            HeapFree(GetProcessHeap(), 0, *data);
            return RPC_S_SERVER_UNAVAILABLE;
        }
    }
    else
        *data = NULL;

    if (!RPCRT4_IsValidHttpPacket(hdr, *data, data_len))
    {
        ERR("invalid http packet\n");
2156
        HeapFree(GetProcessHeap(), 0, *data);
2157 2158 2159 2160 2161 2162 2163
        return RPC_S_PROTOCOL_ERROR;
    }

    return RPC_S_OK;
}

/* prepare the out pipe for use by RPC packets */
2164 2165 2166 2167
static RPC_STATUS rpcrt4_http_prepare_out_pipe(HINTERNET out_request, RpcHttpAsyncData *async_data,
                                               HANDLE cancel_event, const UUID *connection_uuid,
                                               const UUID *out_pipe_uuid, ULONG *flow_control_increment,
                                               BOOL authorized)
2168 2169 2170 2171 2172 2173 2174
{
    BOOL ret;
    RPC_STATUS status;
    RpcPktHdr *hdr;
    BYTE *data_from_server;
    RpcPktHdr pkt_from_server;
    ULONG field1, field3;
2175
    BYTE buf[20];
2176

2177 2178 2179 2180 2181 2182 2183
    if (!authorized)
    {
        /* ask wininet to authorize, if necessary */
        status = send_echo_request(out_request, async_data, cancel_event);
        if (status != RPC_S_OK) return status;
    }
    else
2184
        rpcrt4_http_async_read(out_request, async_data, cancel_event, buf, sizeof(buf));
2185

2186
    hdr = RPCRT4_BuildHttpConnectHeader(TRUE, connection_uuid, out_pipe_uuid, NULL);
2187
    if (!hdr) return RPC_S_OUT_OF_RESOURCES;
2188

2189 2190 2191 2192 2193 2194 2195
    status = insert_content_length_header(out_request, hdr->common.frag_len);
    if (status != RPC_S_OK)
    {
        RPCRT4_FreeHeader(hdr);
        return status;
    }

2196
    TRACE("sending HTTP connect header to server\n");
2197
    prepare_async_request(async_data);
2198
    ret = HttpSendRequestW(out_request, NULL, 0, hdr, hdr->common.frag_len);
2199
    status = wait_async_request(async_data, ret, cancel_event);
2200
    RPCRT4_FreeHeader(hdr);
2201 2202
    if (status != RPC_S_OK) return status;

2203 2204 2205
    status = rpcrt4_http_check_response(out_request);
    if (status != RPC_S_OK) return status;

2206 2207
    status = rpcrt4_http_read_http_packet(out_request, async_data, cancel_event,
                                          &pkt_from_server, &data_from_server);
2208 2209 2210 2211 2212
    if (status != RPC_S_OK) return status;
    status = RPCRT4_ParseHttpPrepareHeader1(&pkt_from_server, data_from_server,
                                            &field1);
    HeapFree(GetProcessHeap(), 0, data_from_server);
    if (status != RPC_S_OK) return status;
2213
    TRACE("received (%ld) from first prepare header\n", field1);
2214

2215 2216
    for (;;)
    {
2217 2218
        status = rpcrt4_http_read_http_packet(out_request, async_data, cancel_event,
                                              &pkt_from_server, &data_from_server);
2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230
        if (status != RPC_S_OK) return status;
        if (pkt_from_server.http.flags != 0x0001) break;

        TRACE("http idle packet, waiting for real packet\n");
        HeapFree(GetProcessHeap(), 0, data_from_server);
        if (pkt_from_server.http.num_data_items != 0)
        {
            ERR("HTTP idle packet should have no data items instead of %d\n",
                pkt_from_server.http.num_data_items);
            return RPC_S_PROTOCOL_ERROR;
        }
    }
2231 2232 2233 2234 2235
    status = RPCRT4_ParseHttpPrepareHeader2(&pkt_from_server, data_from_server,
                                            &field1, flow_control_increment,
                                            &field3);
    HeapFree(GetProcessHeap(), 0, data_from_server);
    if (status != RPC_S_OK) return status;
2236
    TRACE("received (0x%08lx 0x%08lx %ld) from second prepare header\n", field1, *flow_control_increment, field3);
2237 2238 2239 2240

    return RPC_S_OK;
}

2241 2242
static UINT encode_base64(const char *bin, unsigned int len, WCHAR *base64)
{
2243
    static const char enc[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280
    UINT i = 0, x;

    while (len > 0)
    {
        /* first 6 bits, all from bin[0] */
        base64[i++] = enc[(bin[0] & 0xfc) >> 2];
        x = (bin[0] & 3) << 4;

        /* next 6 bits, 2 from bin[0] and 4 from bin[1] */
        if (len == 1)
        {
            base64[i++] = enc[x];
            base64[i++] = '=';
            base64[i++] = '=';
            break;
        }
        base64[i++] = enc[x | ((bin[1] & 0xf0) >> 4)];
        x = (bin[1] & 0x0f) << 2;

        /* next 6 bits 4 from bin[1] and 2 from bin[2] */
        if (len == 2)
        {
            base64[i++] = enc[x];
            base64[i++] = '=';
            break;
        }
        base64[i++] = enc[x | ((bin[2] & 0xc0) >> 6)];

        /* last 6 bits, all from bin [2] */
        base64[i++] = enc[bin[2] & 0x3f];
        bin += 3;
        len -= 3;
    }
    base64[i] = 0;
    return i;
}

2281
static inline char decode_char( WCHAR c )
2282
{
2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391
    if (c >= 'A' && c <= 'Z') return c - 'A';
    if (c >= 'a' && c <= 'z') return c - 'a' + 26;
    if (c >= '0' && c <= '9') return c - '0' + 52;
    if (c == '+') return 62;
    if (c == '/') return 63;
    return 64;
}

static unsigned int decode_base64( const WCHAR *base64, unsigned int len, char *buf )
{
    unsigned int i = 0;
    char c0, c1, c2, c3;
    const WCHAR *p = base64;

    while (len > 4)
    {
        if ((c0 = decode_char( p[0] )) > 63) return 0;
        if ((c1 = decode_char( p[1] )) > 63) return 0;
        if ((c2 = decode_char( p[2] )) > 63) return 0;
        if ((c3 = decode_char( p[3] )) > 63) return 0;

        if (buf)
        {
            buf[i + 0] = (c0 << 2) | (c1 >> 4);
            buf[i + 1] = (c1 << 4) | (c2 >> 2);
            buf[i + 2] = (c2 << 6) |  c3;
        }
        len -= 4;
        i += 3;
        p += 4;
    }
    if (p[2] == '=')
    {
        if ((c0 = decode_char( p[0] )) > 63) return 0;
        if ((c1 = decode_char( p[1] )) > 63) return 0;

        if (buf) buf[i] = (c0 << 2) | (c1 >> 4);
        i++;
    }
    else if (p[3] == '=')
    {
        if ((c0 = decode_char( p[0] )) > 63) return 0;
        if ((c1 = decode_char( p[1] )) > 63) return 0;
        if ((c2 = decode_char( p[2] )) > 63) return 0;

        if (buf)
        {
            buf[i + 0] = (c0 << 2) | (c1 >> 4);
            buf[i + 1] = (c1 << 4) | (c2 >> 2);
        }
        i += 2;
    }
    else
    {
        if ((c0 = decode_char( p[0] )) > 63) return 0;
        if ((c1 = decode_char( p[1] )) > 63) return 0;
        if ((c2 = decode_char( p[2] )) > 63) return 0;
        if ((c3 = decode_char( p[3] )) > 63) return 0;

        if (buf)
        {
            buf[i + 0] = (c0 << 2) | (c1 >> 4);
            buf[i + 1] = (c1 << 4) | (c2 >> 2);
            buf[i + 2] = (c2 << 6) |  c3;
        }
        i += 3;
    }
    return i;
}

static struct authinfo *alloc_authinfo(void)
{
    struct authinfo *ret;

    if (!(ret = HeapAlloc(GetProcessHeap(), 0, sizeof(*ret) ))) return NULL;

    SecInvalidateHandle(&ret->cred);
    SecInvalidateHandle(&ret->ctx);
    memset(&ret->exp, 0, sizeof(ret->exp));
    ret->scheme    = 0;
    ret->attr      = 0;
    ret->max_token = 0;
    ret->data      = NULL;
    ret->data_len  = 0;
    ret->finished  = FALSE;
    return ret;
}

static void destroy_authinfo(struct authinfo *info)
{
    if (!info) return;

    if (SecIsValidHandle(&info->ctx))
        DeleteSecurityContext(&info->ctx);
    if (SecIsValidHandle(&info->cred))
        FreeCredentialsHandle(&info->cred);

    HeapFree(GetProcessHeap(), 0, info->data);
    HeapFree(GetProcessHeap(), 0, info);
}

static const struct
{
    const WCHAR *str;
    unsigned int len;
    DWORD        scheme;
}
auth_schemes[] =
{
2392 2393 2394 2395 2396
    { L"Basic",     ARRAY_SIZE(L"Basic") - 1,     RPC_C_HTTP_AUTHN_SCHEME_BASIC },
    { L"NTLM",      ARRAY_SIZE(L"NTLM") - 1,      RPC_C_HTTP_AUTHN_SCHEME_NTLM },
    { L"Passport",  ARRAY_SIZE(L"Passport") - 1,  RPC_C_HTTP_AUTHN_SCHEME_PASSPORT },
    { L"Digest",    ARRAY_SIZE(L"Digest") - 1,    RPC_C_HTTP_AUTHN_SCHEME_DIGEST },
    { L"Negotiate", ARRAY_SIZE(L"Negotiate") - 1, RPC_C_HTTP_AUTHN_SCHEME_NEGOTIATE }
2397 2398 2399 2400 2401
};

static DWORD auth_scheme_from_header( const WCHAR *header )
{
    unsigned int i;
2402
    for (i = 0; i < ARRAY_SIZE(auth_schemes); i++)
2403
    {
2404
        if (!wcsnicmp( header, auth_schemes[i].str, auth_schemes[i].len ) &&
2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426
            (header[auth_schemes[i].len] == ' ' || !header[auth_schemes[i].len])) return auth_schemes[i].scheme;
    }
    return 0;
}

static BOOL get_authvalue(HINTERNET request, DWORD scheme, WCHAR *buffer, DWORD buflen)
{
    DWORD len, index = 0;
    for (;;)
    {
        len = buflen;
        if (!HttpQueryInfoW(request, HTTP_QUERY_WWW_AUTHENTICATE, buffer, &len, &index)) return FALSE;
        if (auth_scheme_from_header(buffer) == scheme) break;
    }
    return TRUE;
}

static RPC_STATUS do_authorization(HINTERNET request, SEC_WCHAR *servername,
                                   const RPC_HTTP_TRANSPORT_CREDENTIALS_W *creds, struct authinfo **auth_ptr)
{
    struct authinfo *info = *auth_ptr;
    SEC_WINNT_AUTH_IDENTITY_W *id = creds->TransportCredentials;
2427 2428
    RPC_STATUS status = RPC_S_SERVER_UNAVAILABLE;

2429
    if ((!info && !(info = alloc_authinfo()))) return RPC_S_SERVER_UNAVAILABLE;
2430

2431 2432 2433 2434 2435 2436
    switch (creds->AuthnSchemes[0])
    {
    case RPC_C_HTTP_AUTHN_SCHEME_BASIC:
    {
        int userlen = WideCharToMultiByte(CP_UTF8, 0, id->User, id->UserLength, NULL, 0, NULL, NULL);
        int passlen = WideCharToMultiByte(CP_UTF8, 0, id->Password, id->PasswordLength, NULL, 0, NULL, NULL);
2437

2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454
        info->data_len = userlen + passlen + 1;
        if (!(info->data = HeapAlloc(GetProcessHeap(), 0, info->data_len)))
        {
            status = RPC_S_OUT_OF_MEMORY;
            break;
        }
        WideCharToMultiByte(CP_UTF8, 0, id->User, id->UserLength, info->data, userlen, NULL, NULL);
        info->data[userlen] = ':';
        WideCharToMultiByte(CP_UTF8, 0, id->Password, id->PasswordLength, info->data + userlen + 1, passlen, NULL, NULL);

        info->scheme   = RPC_C_HTTP_AUTHN_SCHEME_BASIC;
        info->finished = TRUE;
        status = RPC_S_OK;
        break;
    }
    case RPC_C_HTTP_AUTHN_SCHEME_NTLM:
    case RPC_C_HTTP_AUTHN_SCHEME_NEGOTIATE:
2455
    {
2456

2457
        static SEC_WCHAR ntlmW[] = L"NTLM", negotiateW[] = L"Negotiate";
2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470
        SECURITY_STATUS ret;
        SecBufferDesc out_desc, in_desc;
        SecBuffer out, in;
        ULONG flags = ISC_REQ_CONNECTION|ISC_REQ_USE_DCE_STYLE|ISC_REQ_MUTUAL_AUTH|ISC_REQ_DELEGATE;
        SEC_WCHAR *scheme;
        int scheme_len;
        const WCHAR *p;
        WCHAR auth_value[2048];
        DWORD size = sizeof(auth_value);
        BOOL first = FALSE;

        if (creds->AuthnSchemes[0] == RPC_C_HTTP_AUTHN_SCHEME_NTLM) scheme = ntlmW;
        else scheme = negotiateW;
2471
        scheme_len = lstrlenW( scheme );
2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505

        if (!*auth_ptr)
        {
            TimeStamp exp;
            SecPkgInfoW *pkg_info;

            ret = AcquireCredentialsHandleW(NULL, scheme, SECPKG_CRED_OUTBOUND, NULL, id, NULL, NULL, &info->cred, &exp);
            if (ret != SEC_E_OK) break;

            ret = QuerySecurityPackageInfoW(scheme, &pkg_info);
            if (ret != SEC_E_OK) break;

            info->max_token = pkg_info->cbMaxToken;
            FreeContextBuffer(pkg_info);
            first = TRUE;
        }
        else
        {
            if (info->finished || !get_authvalue(request, creds->AuthnSchemes[0], auth_value, size)) break;
            if (auth_scheme_from_header(auth_value) != info->scheme)
            {
                ERR("authentication scheme changed\n");
                break;
            }
        }
        in.BufferType = SECBUFFER_TOKEN;
        in.cbBuffer   = 0;
        in.pvBuffer   = NULL;

        in_desc.ulVersion = 0;
        in_desc.cBuffers  = 1;
        in_desc.pBuffers  = &in;

        p = auth_value + scheme_len;
2506
        if (!first && *p == ' ')
2507
        {
2508
            int len = lstrlenW(++p);
2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547
            in.cbBuffer = decode_base64(p, len, NULL);
            if (!(in.pvBuffer = HeapAlloc(GetProcessHeap(), 0, in.cbBuffer))) break;
            decode_base64(p, len, in.pvBuffer);
        }
        out.BufferType = SECBUFFER_TOKEN;
        out.cbBuffer   = info->max_token;
        if (!(out.pvBuffer = HeapAlloc(GetProcessHeap(), 0, out.cbBuffer)))
        {
            HeapFree(GetProcessHeap(), 0, in.pvBuffer);
            break;
        }
        out_desc.ulVersion = 0;
        out_desc.cBuffers  = 1;
        out_desc.pBuffers  = &out;

        ret = InitializeSecurityContextW(first ? &info->cred : NULL, first ? NULL : &info->ctx,
                                         first ? servername : NULL, flags, 0, SECURITY_NETWORK_DREP,
                                         in.pvBuffer ? &in_desc : NULL, 0, &info->ctx, &out_desc,
                                         &info->attr, &info->exp);
        HeapFree(GetProcessHeap(), 0, in.pvBuffer);
        if (ret == SEC_E_OK)
        {
            HeapFree(GetProcessHeap(), 0, info->data);
            info->data     = out.pvBuffer;
            info->data_len = out.cbBuffer;
            info->finished = TRUE;
            TRACE("sending last auth packet\n");
            status = RPC_S_OK;
        }
        else if (ret == SEC_I_CONTINUE_NEEDED)
        {
            HeapFree(GetProcessHeap(), 0, info->data);
            info->data     = out.pvBuffer;
            info->data_len = out.cbBuffer;
            TRACE("sending next auth packet\n");
            status = RPC_S_OK;
        }
        else
        {
2548
            ERR("InitializeSecurityContextW failed with error 0x%08lx\n", ret);
2549 2550 2551 2552 2553 2554 2555
            HeapFree(GetProcessHeap(), 0, out.pvBuffer);
            break;
        }
        info->scheme = creds->AuthnSchemes[0];
        break;
    }
    default:
2556
        FIXME("scheme %lu not supported\n", creds->AuthnSchemes[0]);
2557
        break;
2558 2559
    }

2560 2561 2562 2563 2564 2565 2566 2567 2568
    if (status != RPC_S_OK)
    {
        destroy_authinfo(info);
        *auth_ptr = NULL;
        return status;
    }
    *auth_ptr = info;
    return RPC_S_OK;
}
2569

2570 2571 2572 2573 2574 2575
static RPC_STATUS insert_authorization_header(HINTERNET request, ULONG scheme, char *data, int data_len)
{
    static const WCHAR authW[] = {'A','u','t','h','o','r','i','z','a','t','i','o','n',':',' '};
    static const WCHAR basicW[] = {'B','a','s','i','c',' '};
    static const WCHAR negotiateW[] = {'N','e','g','o','t','i','a','t','e',' '};
    static const WCHAR ntlmW[] = {'N','T','L','M',' '};
2576
    int scheme_len, auth_len = ARRAY_SIZE(authW), len = ((data_len + 2) * 4) / 3;
2577 2578 2579
    const WCHAR *scheme_str;
    WCHAR *header, *ptr;
    RPC_STATUS status = RPC_S_SERVER_UNAVAILABLE;
2580

2581
    switch (scheme)
2582
    {
2583 2584
    case RPC_C_HTTP_AUTHN_SCHEME_BASIC:
        scheme_str = basicW;
2585
        scheme_len = ARRAY_SIZE(basicW);
2586 2587 2588
        break;
    case RPC_C_HTTP_AUTHN_SCHEME_NEGOTIATE:
        scheme_str = negotiateW;
2589
        scheme_len = ARRAY_SIZE(negotiateW);
2590 2591 2592
        break;
    case RPC_C_HTTP_AUTHN_SCHEME_NTLM:
        scheme_str = ntlmW;
2593
        scheme_len = ARRAY_SIZE(ntlmW);
2594 2595
        break;
    default:
2596
        ERR("unknown scheme %lu\n", scheme);
2597 2598 2599 2600 2601 2602 2603 2604 2605
        return RPC_S_SERVER_UNAVAILABLE;
    }
    if ((header = HeapAlloc(GetProcessHeap(), 0, (auth_len + scheme_len + len + 2) * sizeof(WCHAR))))
    {
        memcpy(header, authW, auth_len * sizeof(WCHAR));
        ptr = header + auth_len;
        memcpy(ptr, scheme_str, scheme_len * sizeof(WCHAR));
        ptr += scheme_len;
        len = encode_base64(data, data_len, ptr);
2606 2607 2608
        ptr[len++] = '\r';
        ptr[len++] = '\n';
        ptr[len] = 0;
2609 2610
        if (HttpAddRequestHeadersW(request, header, -1, HTTP_ADDREQ_FLAG_ADD|HTTP_ADDREQ_FLAG_REPLACE))
            status = RPC_S_OK;
2611 2612
        HeapFree(GetProcessHeap(), 0, header);
    }
2613 2614 2615
    return status;
}

2616
static void drain_content(HINTERNET request, RpcHttpAsyncData *async_data, HANDLE cancel_event)
2617 2618 2619 2620 2621 2622 2623 2624 2625
{
    DWORD count, len = 0, size = sizeof(len);
    char buf[2048];

    HttpQueryInfoW(request, HTTP_QUERY_FLAG_NUMBER|HTTP_QUERY_CONTENT_LENGTH, &len, &size, NULL);
    if (!len) return;
    for (;;)
    {
        count = min(sizeof(buf), len);
2626
        if (rpcrt4_http_async_read(request, async_data, cancel_event, buf, count) <= 0) return;
2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651
        len -= count;
    }
}

static RPC_STATUS authorize_request(RpcConnection_http *httpc, HINTERNET request)
{
    struct authinfo *info = NULL;
    RPC_STATUS status;
    BOOL ret;

    for (;;)
    {
        status = do_authorization(request, httpc->servername, httpc->common.QOS->qos->u.HttpCredentials, &info);
        if (status != RPC_S_OK) break;

        status = insert_authorization_header(request, info->scheme, info->data, info->data_len);
        if (status != RPC_S_OK) break;

        prepare_async_request(httpc->async_data);
        ret = HttpSendRequestW(request, NULL, 0, NULL, 0);
        status = wait_async_request(httpc->async_data, ret, httpc->cancel_event);
        if (status != RPC_S_OK || info->finished) break;

        status = rpcrt4_http_check_response(request);
        if (status != RPC_S_OK && status != ERROR_ACCESS_DENIED) break;
2652
        drain_content(request, httpc->async_data, httpc->cancel_event);
2653 2654
    }

2655
    if (info->scheme != RPC_C_HTTP_AUTHN_SCHEME_BASIC)
2656
        HttpAddRequestHeadersW(request, L"Authorization:\r\n", -1, HTTP_ADDREQ_FLAG_REPLACE | HTTP_ADDREQ_FLAG_ADD);
2657

2658
    destroy_authinfo(info);
2659 2660 2661
    return status;
}

2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686
static BOOL has_credentials(RpcConnection_http *httpc)
{
    RPC_HTTP_TRANSPORT_CREDENTIALS_W *creds;
    SEC_WINNT_AUTH_IDENTITY_W *id;

    if (!httpc->common.QOS || httpc->common.QOS->qos->AdditionalSecurityInfoType != RPC_C_AUTHN_INFO_TYPE_HTTP)
        return FALSE;

    creds = httpc->common.QOS->qos->u.HttpCredentials;
    if (creds->AuthenticationTarget != RPC_C_HTTP_AUTHN_TARGET_SERVER || !creds->NumberOfAuthnSchemes)
        return FALSE;

    id = creds->TransportCredentials;
    if (!id || !id->User || !id->Password) return FALSE;

    return TRUE;
}

static BOOL is_secure(RpcConnection_http *httpc)
{
    return httpc->common.QOS &&
           (httpc->common.QOS->qos->AdditionalSecurityInfoType == RPC_C_AUTHN_INFO_TYPE_HTTP) &&
           (httpc->common.QOS->qos->u.HttpCredentials->Flags & RPC_C_HTTP_FLAG_USE_SSL);
}

2687 2688
static RPC_STATUS set_auth_cookie(RpcConnection_http *httpc, const WCHAR *value)
{
2689 2690
    static WCHAR httpW[] = L"http";
    static WCHAR httpsW[] = L"https";
2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731
    URL_COMPONENTSW uc;
    DWORD len;
    WCHAR *url;
    BOOL ret;

    if (!value) return RPC_S_OK;

    uc.dwStructSize     = sizeof(uc);
    uc.lpszScheme       = is_secure(httpc) ? httpsW : httpW;
    uc.dwSchemeLength   = 0;
    uc.lpszHostName     = httpc->servername;
    uc.dwHostNameLength = 0;
    uc.nPort            = 0;
    uc.lpszUserName     = NULL;
    uc.dwUserNameLength = 0;
    uc.lpszPassword     = NULL;
    uc.dwPasswordLength = 0;
    uc.lpszUrlPath      = NULL;
    uc.dwUrlPathLength  = 0;
    uc.lpszExtraInfo    = NULL;
    uc.dwExtraInfoLength = 0;

    if (!InternetCreateUrlW(&uc, 0, NULL, &len) && (GetLastError() != ERROR_INSUFFICIENT_BUFFER))
        return RPC_S_SERVER_UNAVAILABLE;

    if (!(url = HeapAlloc(GetProcessHeap(), 0, len))) return RPC_S_OUT_OF_MEMORY;

    len = len / sizeof(WCHAR) - 1;
    if (!InternetCreateUrlW(&uc, 0, url, &len))
    {
        HeapFree(GetProcessHeap(), 0, url);
        return RPC_S_SERVER_UNAVAILABLE;
    }

    ret = InternetSetCookieW(url, NULL, value);
    HeapFree(GetProcessHeap(), 0, url);
    if (!ret) return RPC_S_SERVER_UNAVAILABLE;

    return RPC_S_OK;
}

2732 2733 2734
static RPC_STATUS rpcrt4_ncacn_http_open(RpcConnection* Connection)
{
    RpcConnection_http *httpc = (RpcConnection_http *)Connection;
2735 2736
    static const WCHAR wszRpcProxyPrefix[] = L"/rpc/rpcproxy.dll?";
    LPCWSTR wszAcceptTypes[] = { L"application/rpc", NULL };
2737
    DWORD flags;
2738 2739
    WCHAR *url;
    RPC_STATUS status;
2740
    BOOL secure, credentials;
2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756
    HttpTimerThreadData *timer_data;
    HANDLE thread;

    TRACE("(%s, %s)\n", Connection->NetworkAddr, Connection->Endpoint);

    if (Connection->server)
    {
        ERR("ncacn_http servers not supported yet\n");
        return RPC_S_SERVER_UNAVAILABLE;
    }

    if (httpc->in_request)
        return RPC_S_OK;

    httpc->async_data->completion_event = CreateEventW(NULL, FALSE, FALSE, NULL);

2757 2758 2759
    UuidCreate(&httpc->connection_uuid);
    UuidCreate(&httpc->in_pipe_uuid);
    UuidCreate(&httpc->out_pipe_uuid);
2760 2761 2762 2763 2764 2765 2766 2767 2768

    status = rpcrt4_http_internet_connect(httpc);
    if (status != RPC_S_OK)
        return status;

    url = HeapAlloc(GetProcessHeap(), 0, sizeof(wszRpcProxyPrefix) + (strlen(Connection->NetworkAddr) + 1 + strlen(Connection->Endpoint))*sizeof(WCHAR));
    if (!url)
        return RPC_S_OUT_OF_MEMORY;
    memcpy(url, wszRpcProxyPrefix, sizeof(wszRpcProxyPrefix));
2769 2770
    MultiByteToWideChar(CP_ACP, 0, Connection->NetworkAddr, -1, url+ARRAY_SIZE(wszRpcProxyPrefix)-1,
                        strlen(Connection->NetworkAddr)+1);
2771
    lstrcatW(url, L":");
2772
    MultiByteToWideChar(CP_ACP, 0, Connection->Endpoint, -1, url+lstrlenW(url), strlen(Connection->Endpoint)+1);
2773

2774 2775
    secure = is_secure(httpc);
    credentials = has_credentials(httpc);
2776

2777 2778
    flags = INTERNET_FLAG_KEEP_CONNECTION | INTERNET_FLAG_PRAGMA_NOCACHE | INTERNET_FLAG_NO_CACHE_WRITE |
            INTERNET_FLAG_NO_AUTO_REDIRECT;
2779
    if (secure) flags |= INTERNET_FLAG_SECURE;
2780
    if (credentials) flags |= INTERNET_FLAG_NO_AUTH;
2781

2782 2783 2784 2785 2786 2787
    status = set_auth_cookie(httpc, Connection->CookieAuth);
    if (status != RPC_S_OK)
    {
        HeapFree(GetProcessHeap(), 0, url);
        return status;
    }
2788
    httpc->in_request = HttpOpenRequestW(httpc->session, L"RPC_IN_DATA", url, NULL, NULL, wszAcceptTypes,
2789
                                         flags, (DWORD_PTR)httpc->async_data);
2790 2791
    if (!httpc->in_request)
    {
2792
        ERR("HttpOpenRequestW failed with error %ld\n", GetLastError());
Jacek Caban's avatar
Jacek Caban committed
2793
        HeapFree(GetProcessHeap(), 0, url);
2794 2795
        return RPC_S_SERVER_UNAVAILABLE;
    }
2796

2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810
    if (credentials)
    {
        status = authorize_request(httpc, httpc->in_request);
        if (status != RPC_S_OK)
        {
            HeapFree(GetProcessHeap(), 0, url);
            return status;
        }
        status = rpcrt4_http_check_response(httpc->in_request);
        if (status != RPC_S_OK)
        {
            HeapFree(GetProcessHeap(), 0, url);
            return status;
        }
2811
        drain_content(httpc->in_request, httpc->async_data, httpc->cancel_event);
2812
    }
2813

2814
    httpc->out_request = HttpOpenRequestW(httpc->session, L"RPC_OUT_DATA", url, NULL, NULL, wszAcceptTypes,
2815
                                          flags, (DWORD_PTR)httpc->async_data);
Jacek Caban's avatar
Jacek Caban committed
2816
    HeapFree(GetProcessHeap(), 0, url);
2817 2818
    if (!httpc->out_request)
    {
2819
        ERR("HttpOpenRequestW failed with error %ld\n", GetLastError());
2820 2821
        return RPC_S_SERVER_UNAVAILABLE;
    }
2822

2823 2824 2825 2826 2827 2828 2829 2830 2831 2832
    if (credentials)
    {
        status = authorize_request(httpc, httpc->out_request);
        if (status != RPC_S_OK)
            return status;
    }

    status = rpcrt4_http_prepare_in_pipe(httpc->in_request, httpc->async_data, httpc->cancel_event,
                                         &httpc->connection_uuid, &httpc->in_pipe_uuid,
                                         &Connection->assoc->http_uuid, credentials);
2833 2834 2835
    if (status != RPC_S_OK)
        return status;

2836 2837 2838
    status = rpcrt4_http_prepare_out_pipe(httpc->out_request, httpc->async_data, httpc->cancel_event,
                                          &httpc->connection_uuid, &httpc->out_pipe_uuid,
                                          &httpc->flow_control_increment, credentials);
2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873
    if (status != RPC_S_OK)
        return status;

    httpc->flow_control_mark = httpc->flow_control_increment / 2;
    httpc->last_sent_time = GetTickCount();
    httpc->timer_cancelled = CreateEventW(NULL, FALSE, FALSE, NULL);

    timer_data = HeapAlloc(GetProcessHeap(), 0, sizeof(*timer_data));
    if (!timer_data)
        return ERROR_OUTOFMEMORY;
    timer_data->timer_param = httpc->in_request;
    timer_data->last_sent_time = &httpc->last_sent_time;
    timer_data->timer_cancelled = httpc->timer_cancelled;
    /* FIXME: should use CreateTimerQueueTimer when implemented */
    thread = CreateThread(NULL, 0, rpcrt4_http_timer_thread, timer_data, 0, NULL);
    if (!thread)
    {
        HeapFree(GetProcessHeap(), 0, timer_data);
        return GetLastError();
    }
    CloseHandle(thread);

    return RPC_S_OK;
}

static RPC_STATUS rpcrt4_ncacn_http_handoff(RpcConnection *old_conn, RpcConnection *new_conn)
{
    assert(0);
    return RPC_S_SERVER_UNAVAILABLE;
}

static int rpcrt4_ncacn_http_read(RpcConnection *Connection,
                                void *buffer, unsigned int count)
{
  RpcConnection_http *httpc = (RpcConnection_http *) Connection;
2874
  return rpcrt4_http_async_read(httpc->out_request, httpc->async_data, httpc->cancel_event, buffer, count);
2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892
}

static RPC_STATUS rpcrt4_ncacn_http_receive_fragment(RpcConnection *Connection, RpcPktHdr **Header, void **Payload)
{
  RpcConnection_http *httpc = (RpcConnection_http *) Connection;
  RPC_STATUS status;
  DWORD hdr_length;
  LONG dwRead;
  RpcPktCommonHdr common_hdr;

  *Header = NULL;

  TRACE("(%p, %p, %p)\n", Connection, Header, Payload);

again:
  /* read packet common header */
  dwRead = rpcrt4_ncacn_http_read(Connection, &common_hdr, sizeof(common_hdr));
  if (dwRead != sizeof(common_hdr)) {
2893
    WARN("Short read of header, %ld bytes\n", dwRead);
2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925
    status = RPC_S_PROTOCOL_ERROR;
    goto fail;
  }
  if (!memcmp(&common_hdr, "HTTP/1.1", sizeof("HTTP/1.1")) ||
      !memcmp(&common_hdr, "HTTP/1.0", sizeof("HTTP/1.0")))
  {
    FIXME("server returned %s\n", debugstr_a((const char *)&common_hdr));
    status = RPC_S_PROTOCOL_ERROR;
    goto fail;
  }

  status = RPCRT4_ValidateCommonHeader(&common_hdr);
  if (status != RPC_S_OK) goto fail;

  hdr_length = RPCRT4_GetHeaderSize((RpcPktHdr*)&common_hdr);
  if (hdr_length == 0) {
    WARN("header length == 0\n");
    status = RPC_S_PROTOCOL_ERROR;
    goto fail;
  }

  *Header = HeapAlloc(GetProcessHeap(), 0, hdr_length);
  if (!*Header)
  {
    status = RPC_S_OUT_OF_RESOURCES;
    goto fail;
  }
  memcpy(*Header, &common_hdr, sizeof(common_hdr));

  /* read the rest of packet header */
  dwRead = rpcrt4_ncacn_http_read(Connection, &(*Header)->common + 1, hdr_length - sizeof(common_hdr));
  if (dwRead != hdr_length - sizeof(common_hdr)) {
2926
    WARN("bad header length, %ld bytes, hdr_length %ld\n", dwRead, hdr_length);
2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942
    status = RPC_S_PROTOCOL_ERROR;
    goto fail;
  }

  if (common_hdr.frag_len - hdr_length)
  {
    *Payload = HeapAlloc(GetProcessHeap(), 0, common_hdr.frag_len - hdr_length);
    if (!*Payload)
    {
      status = RPC_S_OUT_OF_RESOURCES;
      goto fail;
    }

    dwRead = rpcrt4_ncacn_http_read(Connection, *Payload, common_hdr.frag_len - hdr_length);
    if (dwRead != common_hdr.frag_len - hdr_length)
    {
2943
      WARN("bad data length, %ld/%ld\n", dwRead, common_hdr.frag_len - hdr_length);
2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980
      status = RPC_S_PROTOCOL_ERROR;
      goto fail;
    }
  }
  else
    *Payload = NULL;

  if ((*Header)->common.ptype == PKT_HTTP)
  {
    if (!RPCRT4_IsValidHttpPacket(*Header, *Payload, common_hdr.frag_len - hdr_length))
    {
      ERR("invalid http packet of length %d bytes\n", (*Header)->common.frag_len);
      status = RPC_S_PROTOCOL_ERROR;
      goto fail;
    }
    if ((*Header)->http.flags == 0x0001)
    {
      TRACE("http idle packet, waiting for real packet\n");
      if ((*Header)->http.num_data_items != 0)
      {
        ERR("HTTP idle packet should have no data items instead of %d\n", (*Header)->http.num_data_items);
        status = RPC_S_PROTOCOL_ERROR;
        goto fail;
      }
    }
    else if ((*Header)->http.flags == 0x0002)
    {
      ULONG bytes_transmitted;
      ULONG flow_control_increment;
      UUID pipe_uuid;
      status = RPCRT4_ParseHttpFlowControlHeader(*Header, *Payload,
                                                 Connection->server,
                                                 &bytes_transmitted,
                                                 &flow_control_increment,
                                                 &pipe_uuid);
      if (status != RPC_S_OK)
        goto fail;
2981
      TRACE("received http flow control header (0x%lx, 0x%lx, %s)\n",
2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002
            bytes_transmitted, flow_control_increment, debugstr_guid(&pipe_uuid));
      /* FIXME: do something with parsed data */
    }
    else
    {
      FIXME("unrecognised http packet with flags 0x%04x\n", (*Header)->http.flags);
      status = RPC_S_PROTOCOL_ERROR;
      goto fail;
    }
    RPCRT4_FreeHeader(*Header);
    *Header = NULL;
    HeapFree(GetProcessHeap(), 0, *Payload);
    *Payload = NULL;
    goto again;
  }

  /* success */
  status = RPC_S_OK;

  httpc->bytes_received += common_hdr.frag_len;

3003
  TRACE("httpc->bytes_received = 0x%lx\n", httpc->bytes_received);
3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014

  if (httpc->bytes_received > httpc->flow_control_mark)
  {
    RpcPktHdr *hdr = RPCRT4_BuildHttpFlowControlHeader(httpc->common.server,
                                                       httpc->bytes_received,
                                                       httpc->flow_control_increment,
                                                       &httpc->out_pipe_uuid);
    if (hdr)
    {
      DWORD bytes_written;
      BOOL ret2;
3015
      TRACE("sending flow control packet at 0x%lx\n", httpc->bytes_received);
3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039
      ret2 = InternetWriteFile(httpc->in_request, hdr, hdr->common.frag_len, &bytes_written);
      RPCRT4_FreeHeader(hdr);
      if (ret2)
        httpc->flow_control_mark = httpc->bytes_received + httpc->flow_control_increment / 2;
    }
  }

fail:
  if (status != RPC_S_OK) {
    RPCRT4_FreeHeader(*Header);
    *Header = NULL;
    HeapFree(GetProcessHeap(), 0, *Payload);
    *Payload = NULL;
  }
  return status;
}

static int rpcrt4_ncacn_http_write(RpcConnection *Connection,
                                 const void *buffer, unsigned int count)
{
  RpcConnection_http *httpc = (RpcConnection_http *) Connection;
  DWORD bytes_written;
  BOOL ret;

3040
  httpc->last_sent_time = ~0U; /* disable idle packet sending */
3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068
  ret = InternetWriteFile(httpc->in_request, buffer, count, &bytes_written);
  httpc->last_sent_time = GetTickCount();
  TRACE("%p %p %u -> %s\n", httpc->in_request, buffer, count, ret ? "TRUE" : "FALSE");
  return ret ? bytes_written : -1;
}

static int rpcrt4_ncacn_http_close(RpcConnection *Connection)
{
  RpcConnection_http *httpc = (RpcConnection_http *) Connection;

  TRACE("\n");

  SetEvent(httpc->timer_cancelled);
  if (httpc->in_request)
    InternetCloseHandle(httpc->in_request);
  httpc->in_request = NULL;
  if (httpc->out_request)
    InternetCloseHandle(httpc->out_request);
  httpc->out_request = NULL;
  if (httpc->app_info)
    InternetCloseHandle(httpc->app_info);
  httpc->app_info = NULL;
  if (httpc->session)
    InternetCloseHandle(httpc->session);
  httpc->session = NULL;
  RpcHttpAsyncData_Release(httpc->async_data);
  if (httpc->cancel_event)
    CloseHandle(httpc->cancel_event);
3069 3070
  HeapFree(GetProcessHeap(), 0, httpc->servername);
  httpc->servername = NULL;
3071 3072 3073 3074

  return 0;
}

3075 3076 3077 3078 3079
static void rpcrt4_ncacn_http_close_read(RpcConnection *conn)
{
    rpcrt4_ncacn_http_close(conn); /* FIXME */
}

3080 3081 3082 3083 3084 3085 3086
static void rpcrt4_ncacn_http_cancel_call(RpcConnection *Connection)
{
  RpcConnection_http *httpc = (RpcConnection_http *) Connection;

  SetEvent(httpc->cancel_event);
}

3087 3088 3089 3090 3091 3092
static RPC_STATUS rpcrt4_ncacn_http_is_server_listening(const char *endpoint)
{
    FIXME("\n");
    return RPC_S_ACCESS_DENIED;
}

3093 3094 3095
static int rpcrt4_ncacn_http_wait_for_incoming_data(RpcConnection *Connection)
{
  RpcConnection_http *httpc = (RpcConnection_http *) Connection;
3096 3097
  BOOL ret;
  RPC_STATUS status;
3098

3099
  prepare_async_request(httpc->async_data);
3100 3101
  ret = InternetQueryDataAvailable(httpc->out_request,
    &httpc->async_data->inet_buffers.dwBufferLength, IRF_ASYNC, 0);
3102 3103
  status = wait_async_request(httpc->async_data, ret, httpc->cancel_event);
  return status == RPC_S_OK ? 0 : -1;
3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123
}

static size_t rpcrt4_ncacn_http_get_top_of_tower(unsigned char *tower_data,
                                                 const char *networkaddr,
                                                 const char *endpoint)
{
    return rpcrt4_ip_tcp_get_top_of_tower(tower_data, networkaddr,
                                          EPM_PROTOCOL_HTTP, endpoint);
}

static RPC_STATUS rpcrt4_ncacn_http_parse_top_of_tower(const unsigned char *tower_data,
                                                       size_t tower_size,
                                                       char **networkaddr,
                                                       char **endpoint)
{
    return rpcrt4_ip_tcp_parse_top_of_tower(tower_data, tower_size,
                                            networkaddr, EPM_PROTOCOL_HTTP,
                                            endpoint);
}

3124
static const struct connection_ops conn_protseq_list[] = {
3125
  { "ncacn_np",
3126
    { EPM_PROTOCOL_NCACN, EPM_PROTOCOL_SMB },
3127
    rpcrt4_conn_np_alloc,
3128
    rpcrt4_ncacn_np_open,
3129
    rpcrt4_ncacn_np_handoff,
3130 3131 3132
    rpcrt4_conn_np_read,
    rpcrt4_conn_np_write,
    rpcrt4_conn_np_close,
3133
    rpcrt4_conn_np_close_read,
3134
    rpcrt4_conn_np_cancel_call,
3135
    rpcrt4_ncacn_np_is_server_listening,
3136
    rpcrt4_conn_np_wait_for_incoming_data,
3137 3138
    rpcrt4_ncacn_np_get_top_of_tower,
    rpcrt4_ncacn_np_parse_top_of_tower,
3139
    NULL,
3140 3141 3142
    RPCRT4_default_is_authorized,
    RPCRT4_default_authorize,
    RPCRT4_default_secure_packet,
3143 3144
    rpcrt4_conn_np_impersonate_client,
    rpcrt4_conn_np_revert_to_self,
3145
    RPCRT4_default_inquire_auth_client,
3146
    NULL
3147 3148
  },
  { "ncalrpc",
3149
    { EPM_PROTOCOL_NCALRPC, EPM_PROTOCOL_PIPE },
3150
    rpcrt4_conn_np_alloc,
3151
    rpcrt4_ncalrpc_open,
3152
    rpcrt4_ncalrpc_handoff,
3153 3154 3155
    rpcrt4_conn_np_read,
    rpcrt4_conn_np_write,
    rpcrt4_conn_np_close,
3156
    rpcrt4_conn_np_close_read,
3157
    rpcrt4_conn_np_cancel_call,
3158
    rpcrt4_ncalrpc_np_is_server_listening,
3159
    rpcrt4_conn_np_wait_for_incoming_data,
3160 3161
    rpcrt4_ncalrpc_get_top_of_tower,
    rpcrt4_ncalrpc_parse_top_of_tower,
3162
    NULL,
3163 3164 3165
    rpcrt4_ncalrpc_is_authorized,
    rpcrt4_ncalrpc_authorize,
    rpcrt4_ncalrpc_secure_packet,
3166 3167
    rpcrt4_conn_np_impersonate_client,
    rpcrt4_conn_np_revert_to_self,
3168
    rpcrt4_ncalrpc_inquire_auth_client,
3169
    rpcrt4_ncalrpc_inquire_client_pid
3170
  },
3171
  { "ncacn_ip_tcp",
3172
    { EPM_PROTOCOL_NCACN, EPM_PROTOCOL_TCP },
3173 3174 3175 3176 3177 3178
    rpcrt4_conn_tcp_alloc,
    rpcrt4_ncacn_ip_tcp_open,
    rpcrt4_conn_tcp_handoff,
    rpcrt4_conn_tcp_read,
    rpcrt4_conn_tcp_write,
    rpcrt4_conn_tcp_close,
3179
    rpcrt4_conn_tcp_close_read,
3180
    rpcrt4_conn_tcp_cancel_call,
3181
    rpcrt4_conn_tcp_is_server_listening,
3182
    rpcrt4_conn_tcp_wait_for_incoming_data,
3183 3184
    rpcrt4_ncacn_ip_tcp_get_top_of_tower,
    rpcrt4_ncacn_ip_tcp_parse_top_of_tower,
3185
    NULL,
3186 3187 3188
    RPCRT4_default_is_authorized,
    RPCRT4_default_authorize,
    RPCRT4_default_secure_packet,
3189 3190
    RPCRT4_default_impersonate_client,
    RPCRT4_default_revert_to_self,
3191
    RPCRT4_default_inquire_auth_client,
3192
    NULL
3193 3194 3195 3196 3197 3198 3199 3200 3201
  },
  { "ncacn_http",
    { EPM_PROTOCOL_NCACN, EPM_PROTOCOL_HTTP },
    rpcrt4_ncacn_http_alloc,
    rpcrt4_ncacn_http_open,
    rpcrt4_ncacn_http_handoff,
    rpcrt4_ncacn_http_read,
    rpcrt4_ncacn_http_write,
    rpcrt4_ncacn_http_close,
3202
    rpcrt4_ncacn_http_close_read,
3203
    rpcrt4_ncacn_http_cancel_call,
3204
    rpcrt4_ncacn_http_is_server_listening,
3205 3206 3207 3208
    rpcrt4_ncacn_http_wait_for_incoming_data,
    rpcrt4_ncacn_http_get_top_of_tower,
    rpcrt4_ncacn_http_parse_top_of_tower,
    rpcrt4_ncacn_http_receive_fragment,
3209 3210 3211
    RPCRT4_default_is_authorized,
    RPCRT4_default_authorize,
    RPCRT4_default_secure_packet,
3212 3213
    RPCRT4_default_impersonate_client,
    RPCRT4_default_revert_to_self,
3214
    RPCRT4_default_inquire_auth_client,
3215
    NULL
3216
  },
3217 3218 3219
};


3220 3221 3222 3223 3224 3225 3226 3227 3228
static const struct protseq_ops protseq_list[] =
{
    {
        "ncacn_np",
        rpcrt4_protseq_np_alloc,
        rpcrt4_protseq_np_signal_state_changed,
        rpcrt4_protseq_np_get_wait_array,
        rpcrt4_protseq_np_free_wait_array,
        rpcrt4_protseq_np_wait_for_new_connection,
3229
        rpcrt4_protseq_ncacn_np_open_endpoint,
3230 3231 3232 3233 3234 3235 3236 3237
    },
    {
        "ncalrpc",
        rpcrt4_protseq_np_alloc,
        rpcrt4_protseq_np_signal_state_changed,
        rpcrt4_protseq_np_get_wait_array,
        rpcrt4_protseq_np_free_wait_array,
        rpcrt4_protseq_np_wait_for_new_connection,
3238
        rpcrt4_protseq_ncalrpc_open_endpoint,
3239 3240 3241
    },
    {
        "ncacn_ip_tcp",
3242 3243 3244 3245 3246
        rpcrt4_protseq_sock_alloc,
        rpcrt4_protseq_sock_signal_state_changed,
        rpcrt4_protseq_sock_get_wait_array,
        rpcrt4_protseq_sock_free_wait_array,
        rpcrt4_protseq_sock_wait_for_new_connection,
3247
        rpcrt4_protseq_ncacn_ip_tcp_open_endpoint,
3248 3249 3250 3251
    },
};

const struct protseq_ops *rpcrt4_get_protseq_ops(const char *protseq)
3252
{
3253
  unsigned int i;
3254
  for(i = 0; i < ARRAY_SIZE(protseq_list); i++)
3255 3256 3257 3258 3259
    if (!strcmp(protseq_list[i].name, protseq))
      return &protseq_list[i];
  return NULL;
}

3260 3261
static const struct connection_ops *rpcrt4_get_conn_protseq_ops(const char *protseq)
{
3262
    unsigned int i;
3263
    for(i = 0; i < ARRAY_SIZE(conn_protseq_list); i++)
3264 3265 3266 3267 3268
        if (!strcmp(conn_protseq_list[i].name, protseq))
            return &conn_protseq_list[i];
    return NULL;
}

3269 3270
/**** interface to rest of code ****/

3271
RPC_STATUS RPCRT4_OpenClientConnection(RpcConnection* Connection)
3272 3273 3274
{
  TRACE("(Connection == ^%p)\n", Connection);

3275 3276
  assert(!Connection->server);
  return Connection->ops->open_connection_client(Connection);
3277 3278 3279 3280 3281
}

RPC_STATUS RPCRT4_CloseConnection(RpcConnection* Connection)
{
  TRACE("(Connection == ^%p)\n", Connection);
3282 3283 3284 3285 3286
  if (SecIsValidHandle(&Connection->ctx))
  {
    DeleteSecurityContext(&Connection->ctx);
    SecInvalidateHandle(&Connection->ctx);
  }
3287 3288 3289 3290
  rpcrt4_conn_close(Connection);
  return RPC_S_OK;
}

3291 3292
RPC_STATUS RPCRT4_CreateConnection(RpcConnection** Connection, BOOL server,
    LPCSTR Protseq, LPCSTR NetworkAddr, LPCSTR Endpoint,
3293
    LPCWSTR NetworkOptions, RpcAuthInfo* AuthInfo, RpcQualityOfService *QOS, LPCWSTR CookieAuth)
3294
{
3295
  static LONG next_id;
3296
  const struct connection_ops *ops;
3297 3298
  RpcConnection* NewConnection;

3299
  ops = rpcrt4_get_conn_protseq_ops(Protseq);
3300
  if (!ops)
3301 3302
  {
    FIXME("not supported for protseq %s\n", Protseq);
3303
    return RPC_S_PROTSEQ_NOT_SUPPORTED;
3304
  }
3305

3306
  NewConnection = ops->alloc();
3307
  NewConnection->ref = 1;
3308 3309 3310 3311
  NewConnection->server = server;
  NewConnection->ops = ops;
  NewConnection->NetworkAddr = RPCRT4_strdupA(NetworkAddr);
  NewConnection->Endpoint = RPCRT4_strdupA(Endpoint);
3312
  NewConnection->NetworkOptions = RPCRT4_strdupW(NetworkOptions);
3313
  NewConnection->CookieAuth = RPCRT4_strdupW(CookieAuth);
3314
  NewConnection->MaxTransmissionSize = RPC_MAX_PACKET_SIZE;
3315
  NewConnection->NextCallId = 1;
3316

3317
  SecInvalidateHandle(&NewConnection->ctx);
3318 3319
  if (AuthInfo) RpcAuthInfo_AddRef(AuthInfo);
  NewConnection->AuthInfo = AuthInfo;
3320
  NewConnection->auth_context_id = InterlockedIncrement( &next_id );
3321 3322
  if (QOS) RpcQualityOfService_AddRef(QOS);
  NewConnection->QOS = QOS;
3323

3324
  list_init(&NewConnection->conn_pool_entry);
3325
  list_init(&NewConnection->protseq_entry);
3326 3327 3328 3329 3330 3331 3332

  TRACE("connection: %p\n", NewConnection);
  *Connection = NewConnection;

  return RPC_S_OK;
}

3333
static RpcConnection *rpcrt4_spawn_connection(RpcConnection *old_connection)
3334
{
3335 3336
    RpcConnection *connection;
    RPC_STATUS err;
3337

3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352
    err = RPCRT4_CreateConnection(&connection, old_connection->server, rpcrt4_conn_get_name(old_connection),
                                  old_connection->NetworkAddr, old_connection->Endpoint, NULL,
                                  old_connection->AuthInfo, old_connection->QOS, old_connection->CookieAuth);
    if (err != RPC_S_OK)
        return NULL;

    rpcrt4_conn_handoff(old_connection, connection);
    if (old_connection->protseq)
    {
        EnterCriticalSection(&old_connection->protseq->cs);
        connection->protseq = old_connection->protseq;
        list_add_tail(&old_connection->protseq->connections, &connection->protseq_entry);
        LeaveCriticalSection(&old_connection->protseq->cs);
    }
    return connection;
3353 3354
}

3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370
void rpcrt4_conn_release_and_wait(RpcConnection *connection)
{
    HANDLE event = NULL;

    if (connection->ref > 1)
        event = connection->wait_release = CreateEventW(NULL, TRUE, FALSE, NULL);

    RPCRT4_ReleaseConnection(connection);

    if(event)
    {
        WaitForSingleObject(event, INFINITE);
        CloseHandle(event);
    }
}

3371
RpcConnection *RPCRT4_GrabConnection(RpcConnection *connection)
3372
{
3373
    LONG ref = InterlockedIncrement(&connection->ref);
3374
    TRACE("%p ref=%lu\n", connection, ref);
3375
    return connection;
3376 3377
}

3378
void RPCRT4_ReleaseConnection(RpcConnection *connection)
3379
{
3380
    LONG ref;
3381

3382 3383 3384 3385 3386
    /* protseq stores a list of active connections, but does not own references to them.
     * It may need to grab a connection from the list, which could lead to a race if
     * connection is being released, but not yet removed from the list. We handle that
     * by synchronizing on CS here. */
    if (connection->protseq)
3387 3388
    {
        EnterCriticalSection(&connection->protseq->cs);
3389
        ref = InterlockedDecrement(&connection->ref);
3390 3391 3392 3393
        if (!ref)
            list_remove(&connection->protseq_entry);
        LeaveCriticalSection(&connection->protseq->cs);
    }
3394 3395 3396 3397
    else
    {
        ref = InterlockedDecrement(&connection->ref);
    }
3398

3399
    TRACE("%p ref=%lu\n", connection, ref);
3400

3401 3402 3403 3404 3405 3406 3407 3408 3409
    if (!ref)
    {
        RPCRT4_CloseConnection(connection);
        RPCRT4_strfree(connection->Endpoint);
        RPCRT4_strfree(connection->NetworkAddr);
        HeapFree(GetProcessHeap(), 0, connection->NetworkOptions);
        HeapFree(GetProcessHeap(), 0, connection->CookieAuth);
        if (connection->AuthInfo) RpcAuthInfo_Release(connection->AuthInfo);
        if (connection->QOS) RpcQualityOfService_Release(connection->QOS);
3410

3411 3412
        /* server-only */
        if (connection->server_binding) RPCRT4_ReleaseBinding(connection->server_binding);
3413
        else if (connection->assoc) RpcAssoc_ConnectionReleased(connection->assoc);
3414

3415
        if (connection->wait_release) SetEvent(connection->wait_release);
3416

3417 3418
        HeapFree(GetProcessHeap(), 0, connection);
    }
3419
}
3420

3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434
RPC_STATUS RPCRT4_IsServerListening(const char *protseq, const char *endpoint)
{
  const struct connection_ops *ops;

  ops = rpcrt4_get_conn_protseq_ops(protseq);
  if (!ops)
  {
    FIXME("not supported for protseq %s\n", protseq);
    return RPC_S_INVALID_BINDING;
  }

  return ops->is_server_listening(endpoint);
}

3435 3436 3437 3438 3439 3440 3441
RPC_STATUS RpcTransport_GetTopOfTower(unsigned char *tower_data,
                                      size_t *tower_size,
                                      const char *protseq,
                                      const char *networkaddr,
                                      const char *endpoint)
{
    twr_empty_floor_t *protocol_floor;
3442
    const struct connection_ops *protseq_ops = rpcrt4_get_conn_protseq_ops(protseq);
3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477

    *tower_size = 0;

    if (!protseq_ops)
        return RPC_S_INVALID_RPC_PROTSEQ;

    if (!tower_data)
    {
        *tower_size = sizeof(*protocol_floor);
        *tower_size += protseq_ops->get_top_of_tower(NULL, networkaddr, endpoint);
        return RPC_S_OK;
    }

    protocol_floor = (twr_empty_floor_t *)tower_data;
    protocol_floor->count_lhs = sizeof(protocol_floor->protid);
    protocol_floor->protid = protseq_ops->epm_protocols[0];
    protocol_floor->count_rhs = 0;

    tower_data += sizeof(*protocol_floor);

    *tower_size = protseq_ops->get_top_of_tower(tower_data, networkaddr, endpoint);
    if (!*tower_size)
        return EPT_S_NOT_REGISTERED;

    *tower_size += sizeof(*protocol_floor);

    return RPC_S_OK;
}

RPC_STATUS RpcTransport_ParseTopOfTower(const unsigned char *tower_data,
                                        size_t tower_size,
                                        char **protseq,
                                        char **networkaddr,
                                        char **endpoint)
{
3478 3479
    const twr_empty_floor_t *protocol_floor;
    const twr_empty_floor_t *floor4;
3480
    const struct connection_ops *protseq_ops = NULL;
3481
    RPC_STATUS status;
3482
    unsigned int i;
3483 3484 3485 3486

    if (tower_size < sizeof(*protocol_floor))
        return EPT_S_NOT_REGISTERED;

3487
    protocol_floor = (const twr_empty_floor_t *)tower_data;
3488 3489 3490 3491 3492
    tower_data += sizeof(*protocol_floor);
    tower_size -= sizeof(*protocol_floor);
    if ((protocol_floor->count_lhs != sizeof(protocol_floor->protid)) ||
        (protocol_floor->count_rhs > tower_size))
        return EPT_S_NOT_REGISTERED;
3493 3494
    tower_data += protocol_floor->count_rhs;
    tower_size -= protocol_floor->count_rhs;
3495

3496
    floor4 = (const twr_empty_floor_t *)tower_data;
3497
    if ((tower_size < sizeof(*floor4)) ||
3498
        (floor4->count_lhs != sizeof(floor4->protid)))
3499 3500
        return EPT_S_NOT_REGISTERED;

3501
    for(i = 0; i < ARRAY_SIZE(conn_protseq_list); i++)
3502 3503
        if ((protocol_floor->protid == conn_protseq_list[i].epm_protocols[0]) &&
            (floor4->protid == conn_protseq_list[i].epm_protocols[1]))
3504
        {
3505
            protseq_ops = &conn_protseq_list[i];
3506 3507 3508 3509 3510 3511 3512 3513
            break;
        }

    if (!protseq_ops)
        return EPT_S_NOT_REGISTERED;

    status = protseq_ops->parse_top_of_tower(tower_data, tower_size, networkaddr, endpoint);

3514
    if ((status == RPC_S_OK) && protseq)
3515
    {
3516
        *protseq = I_RpcAllocate(strlen(protseq_ops->name) + 1);
3517 3518 3519 3520 3521 3522
        strcpy(*protseq, protseq_ops->name);
    }

    return status;
}

3523 3524 3525 3526 3527 3528 3529
/***********************************************************************
 *             RpcNetworkIsProtseqValidW (RPCRT4.@)
 *
 * Checks if the given protocol sequence is known by the RPC system.
 * If it is, returns RPC_S_OK, otherwise RPC_S_PROTSEQ_NOT_SUPPORTED.
 *
 */
3530
RPC_STATUS WINAPI RpcNetworkIsProtseqValidW(RPC_WSTR protseq)
3531 3532 3533 3534 3535
{
  char ps[0x10];

  WideCharToMultiByte(CP_ACP, 0, protseq, -1,
                      ps, sizeof ps, NULL, NULL);
3536
  if (rpcrt4_get_conn_protseq_ops(ps))
3537 3538 3539 3540 3541 3542 3543 3544 3545 3546
    return RPC_S_OK;

  FIXME("Unknown protseq %s\n", debugstr_w(protseq));

  return RPC_S_INVALID_RPC_PROTSEQ;
}

/***********************************************************************
 *             RpcNetworkIsProtseqValidA (RPCRT4.@)
 */
3547
RPC_STATUS WINAPI RpcNetworkIsProtseqValidA(RPC_CSTR protseq)
3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558
{
  UNICODE_STRING protseqW;

  if (RtlCreateUnicodeStringFromAsciiz(&protseqW, (char*)protseq))
  {
    RPC_STATUS ret = RpcNetworkIsProtseqValidW(protseqW.Buffer);
    RtlFreeUnicodeString(&protseqW);
    return ret;
  }
  return RPC_S_OUT_OF_MEMORY;
}
3559 3560 3561 3562 3563 3564 3565 3566 3567 3568

/***********************************************************************
 *             RpcProtseqVectorFreeA (RPCRT4.@)
 */
RPC_STATUS WINAPI RpcProtseqVectorFreeA(RPC_PROTSEQ_VECTORA **protseqs)
{
  TRACE("(%p)\n", protseqs);

  if (*protseqs)
  {
3569
    unsigned int i;
3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586
    for (i = 0; i < (*protseqs)->Count; i++)
      HeapFree(GetProcessHeap(), 0, (*protseqs)->Protseq[i]);
    HeapFree(GetProcessHeap(), 0, *protseqs);
    *protseqs = NULL;
  }
  return RPC_S_OK;
}

/***********************************************************************
 *             RpcProtseqVectorFreeW (RPCRT4.@)
 */
RPC_STATUS WINAPI RpcProtseqVectorFreeW(RPC_PROTSEQ_VECTORW **protseqs)
{
  TRACE("(%p)\n", protseqs);

  if (*protseqs)
  {
3587
    unsigned int i;
3588 3589 3590 3591 3592 3593 3594
    for (i = 0; i < (*protseqs)->Count; i++)
      HeapFree(GetProcessHeap(), 0, (*protseqs)->Protseq[i]);
    HeapFree(GetProcessHeap(), 0, *protseqs);
    *protseqs = NULL;
  }
  return RPC_S_OK;
}
3595 3596 3597 3598 3599 3600 3601

/***********************************************************************
 *             RpcNetworkInqProtseqsW (RPCRT4.@)
 */
RPC_STATUS WINAPI RpcNetworkInqProtseqsW( RPC_PROTSEQ_VECTORW** protseqs )
{
  RPC_PROTSEQ_VECTORW *pvector;
3602
  unsigned int i;
3603 3604 3605 3606
  RPC_STATUS status = RPC_S_OUT_OF_MEMORY;

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

3607
  *protseqs = HeapAlloc(GetProcessHeap(), 0, sizeof(RPC_PROTSEQ_VECTORW)+(sizeof(unsigned short*)*ARRAY_SIZE(protseq_list)));
3608 3609 3610 3611
  if (!*protseqs)
    goto end;
  pvector = *protseqs;
  pvector->Count = 0;
3612
  for (i = 0; i < ARRAY_SIZE(protseq_list); i++)
3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634
  {
    pvector->Protseq[i] = HeapAlloc(GetProcessHeap(), 0, (strlen(protseq_list[i].name)+1)*sizeof(unsigned short));
    if (pvector->Protseq[i] == NULL)
      goto end;
    MultiByteToWideChar(CP_ACP, 0, (CHAR*)protseq_list[i].name, -1,
      (WCHAR*)pvector->Protseq[i], strlen(protseq_list[i].name) + 1);
    pvector->Count++;
  }
  status = RPC_S_OK;

end:
  if (status != RPC_S_OK)
    RpcProtseqVectorFreeW(protseqs);
  return status;
}

/***********************************************************************
 *             RpcNetworkInqProtseqsA (RPCRT4.@)
 */
RPC_STATUS WINAPI RpcNetworkInqProtseqsA(RPC_PROTSEQ_VECTORA** protseqs)
{
  RPC_PROTSEQ_VECTORA *pvector;
3635
  unsigned int i;
3636 3637 3638 3639
  RPC_STATUS status = RPC_S_OUT_OF_MEMORY;

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

3640
  *protseqs = HeapAlloc(GetProcessHeap(), 0, sizeof(RPC_PROTSEQ_VECTORW)+(sizeof(unsigned char*)*ARRAY_SIZE(protseq_list)));
3641 3642 3643 3644
  if (!*protseqs)
    goto end;
  pvector = *protseqs;
  pvector->Count = 0;
3645
  for (i = 0; i < ARRAY_SIZE(protseq_list); i++)
3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659
  {
    pvector->Protseq[i] = HeapAlloc(GetProcessHeap(), 0, strlen(protseq_list[i].name)+1);
    if (pvector->Protseq[i] == NULL)
      goto end;
    strcpy((char*)pvector->Protseq[i], protseq_list[i].name);
    pvector->Count++;
  }
  status = RPC_S_OK;

end:
  if (status != RPC_S_OK)
    RpcProtseqVectorFreeA(protseqs);
  return status;
}