rpc_transport.c 48.5 KB
Newer Older
1 2 3 4 5 6 7
/*
 * RPC transport layer
 *
 * Copyright 2001 Ove Kven, TransGaming Technologies
 * 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
#include "config.h"

28 29 30 31
#include <stdarg.h>
#include <stdio.h>
#include <string.h>
#include <assert.h>
32
#include <errno.h>
33

34 35 36
#ifdef HAVE_UNISTD_H
# include <unistd.h>
#endif
37 38 39 40
#include <fcntl.h>
#include <stdlib.h>
#include <sys/types.h>
#ifdef HAVE_SYS_SOCKET_H
41
# include <sys/socket.h>
42 43
#endif
#ifdef HAVE_NETINET_IN_H
44
# include <netinet/in.h>
45
#endif
46 47 48
#ifdef HAVE_NETINET_TCP_H
# include <netinet/tcp.h>
#endif
49
#ifdef HAVE_ARPA_INET_H
50
# include <arpa/inet.h>
51
#endif
52 53 54
#ifdef HAVE_NETDB_H
#include <netdb.h>
#endif
55 56 57
#ifdef HAVE_SYS_POLL_H
#include <sys/poll.h>
#endif
58

59 60 61 62 63 64 65 66 67 68 69 70 71 72
#include "windef.h"
#include "winbase.h"
#include "winnls.h"
#include "winerror.h"
#include "winternl.h"
#include "wine/unicode.h"

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

#include "wine/debug.h"

#include "rpc_binding.h"
#include "rpc_message.h"
73
#include "rpc_server.h"
74
#include "epm_towers.h"
75

76 77 78 79
#ifndef SOL_TCP
# define SOL_TCP IPPROTO_TCP
#endif

80 81
WINE_DEFAULT_DEBUG_CHANNEL(rpc);

82 83
static CRITICAL_SECTION assoc_list_cs;
static CRITICAL_SECTION_DEBUG assoc_list_cs_debug =
84
{
85 86 87
    0, 0, &assoc_list_cs,
    { &assoc_list_cs_debug.ProcessLocksList, &assoc_list_cs_debug.ProcessLocksList },
      0, 0, { (DWORD_PTR)(__FILE__ ": assoc_list_cs") }
88
};
89
static CRITICAL_SECTION assoc_list_cs = { &assoc_list_cs_debug, -1, 0, 0, 0, 0 };
90

91
static struct list assoc_list = LIST_INIT(assoc_list);
92

93 94
/**** ncacn_np support ****/

95 96 97
typedef struct _RpcConnection_np
{
  RpcConnection common;
98
  HANDLE pipe;
99
  OVERLAPPED ovl;
100
  BOOL listening;
101 102 103 104
} RpcConnection_np;

static RpcConnection *rpcrt4_conn_np_alloc(void)
{
105 106 107 108 109
  RpcConnection_np *npc = HeapAlloc(GetProcessHeap(), 0, sizeof(RpcConnection_np));
  if (npc)
  {
    npc->pipe = NULL;
    memset(&npc->ovl, 0, sizeof(npc->ovl));
110
    npc->listening = FALSE;
111 112
  }
  return &npc->common;
113 114
}

115 116 117 118 119 120 121 122 123 124 125 126 127 128
static RPC_STATUS rpcrt4_conn_listen_pipe(RpcConnection_np *npc)
{
  if (npc->listening)
    return RPC_S_OK;

  npc->listening = TRUE;
  if (ConnectNamedPipe(npc->pipe, &npc->ovl))
    return RPC_S_OK;

  if (GetLastError() == ERROR_PIPE_CONNECTED) {
    SetEvent(npc->ovl.hEvent);
    return RPC_S_OK;
  }
  if (GetLastError() == ERROR_IO_PENDING) {
129
    /* will be completed in rpcrt4_protseq_np_wait_for_new_connection */
130 131 132
    return RPC_S_OK;
  }
  npc->listening = FALSE;
133
  WARN("Couldn't ConnectNamedPipe (error was %d)\n", GetLastError());
134
  return RPC_S_OUT_OF_RESOURCES;
135 136 137
}

static RPC_STATUS rpcrt4_conn_create_pipe(RpcConnection *Connection, LPCSTR pname)
138
{
139
  RpcConnection_np *npc = (RpcConnection_np *) Connection;
140 141
  TRACE("listening on %s\n", pname);

142 143 144 145
  npc->pipe = CreateNamedPipeA(pname, PIPE_ACCESS_DUPLEX,
                               PIPE_TYPE_MESSAGE | PIPE_READMODE_MESSAGE,
                               PIPE_UNLIMITED_INSTANCES,
                               RPC_MAX_PACKET_SIZE, RPC_MAX_PACKET_SIZE, 5000, NULL);
146
  if (npc->pipe == INVALID_HANDLE_VALUE) {
147
    WARN("CreateNamedPipe failed with error %d\n", GetLastError());
148 149 150 151
    if (GetLastError() == ERROR_FILE_EXISTS)
      return RPC_S_DUPLICATE_ENDPOINT;
    else
      return RPC_S_CANT_CREATE_ENDPOINT;
152 153
  }

154 155
  memset(&npc->ovl, 0, sizeof(npc->ovl));
  npc->ovl.hEvent = CreateEventW(NULL, TRUE, FALSE, NULL);
156

157 158 159
  /* Note: we don't call ConnectNamedPipe here because it must be done in the
   * server thread as the thread must be alertable */
  return RPC_S_OK;
160 161
}

162
static RPC_STATUS rpcrt4_conn_open_pipe(RpcConnection *Connection, LPCSTR pname, BOOL wait)
163
{
164 165
  RpcConnection_np *npc = (RpcConnection_np *) Connection;
  HANDLE pipe;
166 167 168 169 170
  DWORD err, dwMode;

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

  while (TRUE) {
171 172 173
    DWORD dwFlags = 0;
    if (Connection->QOS)
    {
174
        dwFlags = SECURITY_SQOS_PRESENT;
175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195
        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;
        }
        if (Connection->QOS->qos->IdentityTracking == RPC_C_QOS_IDENTIFY_DYNAMIC)
            dwFlags |= SECURITY_CONTEXT_TRACKING;
    }
196
    pipe = CreateFileA(pname, GENERIC_READ|GENERIC_WRITE, 0, NULL,
197
                       OPEN_EXISTING, dwFlags, 0);
198
    if (pipe != INVALID_HANDLE_VALUE) break;
199 200
    err = GetLastError();
    if (err == ERROR_PIPE_BUSY) {
201
      TRACE("connection failed, error=%x\n", err);
202 203 204 205 206 207
      return RPC_S_SERVER_TOO_BUSY;
    }
    if (!wait)
      return RPC_S_SERVER_UNAVAILABLE;
    if (!WaitNamedPipeA(pname, NMPWAIT_WAIT_FOREVER)) {
      err = GetLastError();
208
      WARN("connection failed, error=%x\n", err);
209 210 211 212 213
      return RPC_S_SERVER_UNAVAILABLE;
    }
  }

  /* success */
214
  memset(&npc->ovl, 0, sizeof(npc->ovl));
215 216
  /* pipe is connected; change to message-read mode. */
  dwMode = PIPE_READMODE_MESSAGE;
217 218 219
  SetNamedPipeHandleState(pipe, &dwMode, NULL, NULL);
  npc->ovl.hEvent = CreateEventW(NULL, TRUE, FALSE, NULL);
  npc->pipe = pipe;
220 221 222 223 224 225

  return RPC_S_OK;
}

static RPC_STATUS rpcrt4_ncalrpc_open(RpcConnection* Connection)
{
226
  RpcConnection_np *npc = (RpcConnection_np *) Connection;
227
  static const char prefix[] = "\\\\.\\pipe\\lrpc\\";
228 229 230
  RPC_STATUS r;
  LPSTR pname;

231
  /* already connected? */
232
  if (npc->pipe)
233 234
    return RPC_S_OK;

235 236
  /* protseq=ncalrpc: supposed to use NT LPC ports,
   * but we'll implement it with named pipes for now */
237
  pname = I_RpcAllocate(strlen(prefix) + strlen(Connection->Endpoint) + 1);
238
  strcat(strcpy(pname, prefix), Connection->Endpoint);
239 240
  r = rpcrt4_conn_open_pipe(Connection, pname, TRUE);
  I_RpcFree(pname);
241

242 243 244 245 246
  return r;
}

static RPC_STATUS rpcrt4_protseq_ncalrpc_open_endpoint(RpcServerProtseq* protseq, LPSTR endpoint)
{
247
  static const char prefix[] = "\\\\.\\pipe\\lrpc\\";
248 249 250 251 252
  RPC_STATUS r;
  LPSTR pname;
  RpcConnection *Connection;

  r = RPCRT4_CreateConnection(&Connection, TRUE, protseq->Protseq, NULL,
253
                              endpoint, NULL, NULL, NULL, NULL);
254 255 256 257 258 259 260 261
  if (r != RPC_S_OK)
      return r;

  /* protseq=ncalrpc: supposed to use NT LPC ports,
   * but we'll implement it with named pipes for now */
  pname = I_RpcAllocate(strlen(prefix) + strlen(Connection->Endpoint) + 1);
  strcat(strcpy(pname, prefix), Connection->Endpoint);
  r = rpcrt4_conn_create_pipe(Connection, pname);
262
  I_RpcFree(pname);
263

264 265 266 267 268
  EnterCriticalSection(&protseq->cs);
  Connection->Next = protseq->conn;
  protseq->conn = Connection;
  LeaveCriticalSection(&protseq->cs);

269 270 271 272 273
  return r;
}

static RPC_STATUS rpcrt4_ncacn_np_open(RpcConnection* Connection)
{
274
  RpcConnection_np *npc = (RpcConnection_np *) Connection;
275
  static const char prefix[] = "\\\\.";
276 277 278
  RPC_STATUS r;
  LPSTR pname;

279
  /* already connected? */
280
  if (npc->pipe)
281 282
    return RPC_S_OK;

283
  /* protseq=ncacn_np: named pipes */
284
  pname = I_RpcAllocate(strlen(prefix) + strlen(Connection->Endpoint) + 1);
285
  strcat(strcpy(pname, prefix), Connection->Endpoint);
286
  r = rpcrt4_conn_open_pipe(Connection, pname, FALSE);
287
  I_RpcFree(pname);
288 289 290 291

  return r;
}

292
static RPC_STATUS rpcrt4_protseq_ncacn_np_open_endpoint(RpcServerProtseq *protseq, LPSTR endpoint)
293
{
294
  static const char prefix[] = "\\\\.";
295 296 297 298 299
  RPC_STATUS r;
  LPSTR pname;
  RpcConnection *Connection;

  r = RPCRT4_CreateConnection(&Connection, TRUE, protseq->Protseq, NULL,
300
                              endpoint, NULL, NULL, NULL, NULL);
301 302 303 304 305 306 307 308
  if (r != RPC_S_OK)
    return r;

  /* protseq=ncacn_np: named pipes */
  pname = I_RpcAllocate(strlen(prefix) + strlen(Connection->Endpoint) + 1);
  strcat(strcpy(pname, prefix), Connection->Endpoint);
  r = rpcrt4_conn_create_pipe(Connection, pname);
  I_RpcFree(pname);
309 310 311 312 313 314

  EnterCriticalSection(&protseq->cs);
  Connection->Next = protseq->conn;
  protseq->conn = Connection;
  LeaveCriticalSection(&protseq->cs);

315 316 317 318 319
  return r;
}

static void rpcrt4_conn_np_handoff(RpcConnection_np *old_npc, RpcConnection_np *new_npc)
{    
320 321
  /* because of the way named pipes work, we'll transfer the connected pipe
   * to the child, then reopen the server binding to continue listening */
322

323 324 325 326
  new_npc->pipe = old_npc->pipe;
  new_npc->ovl = old_npc->ovl;
  old_npc->pipe = 0;
  memset(&old_npc->ovl, 0, sizeof(old_npc->ovl));
327 328 329 330 331 332 333
  old_npc->listening = FALSE;
}

static RPC_STATUS rpcrt4_ncacn_np_handoff(RpcConnection *old_conn, RpcConnection *new_conn)
{
  RPC_STATUS status;
  LPSTR pname;
334
  static const char prefix[] = "\\\\.";
335 336 337 338 339 340 341 342 343 344 345 346 347 348 349

  rpcrt4_conn_np_handoff((RpcConnection_np *)old_conn, (RpcConnection_np *)new_conn);

  pname = I_RpcAllocate(strlen(prefix) + strlen(old_conn->Endpoint) + 1);
  strcat(strcpy(pname, prefix), old_conn->Endpoint);
  status = rpcrt4_conn_create_pipe(old_conn, pname);
  I_RpcFree(pname);

  return status;
}

static RPC_STATUS rpcrt4_ncalrpc_handoff(RpcConnection *old_conn, RpcConnection *new_conn)
{
  RPC_STATUS status;
  LPSTR pname;
350
  static const char prefix[] = "\\\\.\\pipe\\lrpc\\";
351 352 353 354 355 356 357 358 359 360 361

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

  rpcrt4_conn_np_handoff((RpcConnection_np *)old_conn, (RpcConnection_np *)new_conn);

  pname = I_RpcAllocate(strlen(prefix) + strlen(old_conn->Endpoint) + 1);
  strcat(strcpy(pname, prefix), old_conn->Endpoint);
  status = rpcrt4_conn_create_pipe(old_conn, pname);
  I_RpcFree(pname);
    
  return status;
362 363
}

364 365 366
static int rpcrt4_conn_np_read(RpcConnection *Connection,
                        void *buffer, unsigned int count)
{
367
  RpcConnection_np *npc = (RpcConnection_np *) Connection;
368 369 370 371 372 373 374 375 376 377 378 379 380 381
  char *buf = buffer;
  BOOL ret = TRUE;
  unsigned int bytes_left = count;

  while (bytes_left)
  {
    DWORD bytes_read;
    ret = ReadFile(npc->pipe, buf, bytes_left, &bytes_read, NULL);
    if (!ret || !bytes_read)
        break;
    bytes_left -= bytes_read;
    buf += bytes_read;
  }
  return ret ? count : -1;
382 383 384 385 386
}

static int rpcrt4_conn_np_write(RpcConnection *Connection,
                             const void *buffer, unsigned int count)
{
387
  RpcConnection_np *npc = (RpcConnection_np *) Connection;
388 389 390 391 392 393 394 395 396 397 398 399 400 401
  const char *buf = buffer;
  BOOL ret = TRUE;
  unsigned int bytes_left = count;

  while (bytes_left)
  {
    DWORD bytes_written;
    ret = WriteFile(npc->pipe, buf, count, &bytes_written, NULL);
    if (!ret || !bytes_written)
        break;
    bytes_left -= bytes_written;
    buf += bytes_written;
  }
  return ret ? count : -1;
402 403 404 405
}

static int rpcrt4_conn_np_close(RpcConnection *Connection)
{
406 407 408 409 410
  RpcConnection_np *npc = (RpcConnection_np *) Connection;
  if (npc->pipe) {
    FlushFileBuffers(npc->pipe);
    CloseHandle(npc->pipe);
    npc->pipe = 0;
411
  }
412 413 414
  if (npc->ovl.hEvent) {
    CloseHandle(npc->ovl.hEvent);
    npc->ovl.hEvent = 0;
415 416 417 418
  }
  return 0;
}

419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470
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);

    networkaddr_size = strlen(networkaddr) + 1;
    endpoint_size = strlen(endpoint) + 1;
    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;

    memcpy(tower_data, endpoint, endpoint_size);
    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;

    memcpy(tower_data, networkaddr, networkaddr_size);
    tower_data += networkaddr_size;

    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;

471
    TRACE("(%p, %d, %p, %p)\n", tower_data, (int)tower_size, networkaddr, endpoint);
472 473 474 475 476 477 478 479 480 481 482

    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) ||
        (smb_floor->count_rhs > tower_size))
        return EPT_S_NOT_REGISTERED;
483 484 485

    if (endpoint)
    {
486
        *endpoint = I_RpcAllocate(smb_floor->count_rhs);
487 488 489 490
        if (!*endpoint)
            return RPC_S_OUT_OF_RESOURCES;
        memcpy(*endpoint, tower_data, smb_floor->count_rhs);
    }
491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506
    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) ||
        (nb_floor->count_rhs > tower_size))
        return EPT_S_NOT_REGISTERED;

507
    if (networkaddr)
508
    {
509
        *networkaddr = I_RpcAllocate(nb_floor->count_rhs);
510 511 512 513
        if (!*networkaddr)
        {
            if (endpoint)
            {
514
                I_RpcFree(*endpoint);
515 516 517 518 519
                *endpoint = NULL;
            }
            return RPC_S_OUT_OF_RESOURCES;
        }
        memcpy(*networkaddr, tower_data, nb_floor->count_rhs);
520 521 522 523 524
    }

    return RPC_S_OK;
}

525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547
typedef struct _RpcServerProtseq_np
{
    RpcServerProtseq common;
    HANDLE mgr_event;
} RpcServerProtseq_np;

static RpcServerProtseq *rpcrt4_protseq_np_alloc(void)
{
    RpcServerProtseq_np *ps = HeapAlloc(GetProcessHeap(), 0, sizeof(*ps));
    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;
548
    RpcConnection_np *conn;
549 550 551 552 553 554
    RpcServerProtseq_np *npps = CONTAINING_RECORD(protseq, RpcServerProtseq_np, common);
    
    EnterCriticalSection(&protseq->cs);
    
    /* open and count connections */
    *count = 1;
555
    conn = CONTAINING_RECORD(protseq->conn, RpcConnection_np, common);
556
    while (conn) {
557
        rpcrt4_conn_listen_pipe(conn);
558
        if (conn->ovl.hEvent)
559
            (*count)++;
560
        conn = CONTAINING_RECORD(conn->common.Next, RpcConnection_np, common);
561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576
    }
    
    /* 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;
577
    conn = CONTAINING_RECORD(protseq->conn, RpcConnection_np, common);
578
    while (conn) {
579
        if ((objs[*count] = conn->ovl.hEvent))
580
            (*count)++;
581
        conn = CONTAINING_RECORD(conn->common.Next, RpcConnection_np, common);
582 583 584 585 586 587 588 589 590 591 592 593 594 595 596
    }
    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;
597 598
    RpcConnection *cconn;
    RpcConnection_np *conn;
599 600 601 602 603 604 605 606 607
    
    if (!objs)
        return -1;
    
    res = WaitForMultipleObjects(count, objs, FALSE, INFINITE);
    if (res == WAIT_OBJECT_0)
        return 0;
    else if (res == WAIT_FAILED)
    {
608
        ERR("wait failed with error %d\n", GetLastError());
609 610 611 612 613 614 615
        return -1;
    }
    else
    {
        b_handle = objs[res - WAIT_OBJECT_0];
        /* find which connection got a RPC */
        EnterCriticalSection(&protseq->cs);
616
        conn = CONTAINING_RECORD(protseq->conn, RpcConnection_np, common);
617
        while (conn) {
618 619
            if (b_handle == conn->ovl.hEvent) break;
            conn = CONTAINING_RECORD(conn->common.Next, RpcConnection_np, common);
620 621 622
        }
        cconn = NULL;
        if (conn)
623
            RPCRT4_SpawnConnection(&cconn, &conn->common);
624 625 626 627 628 629 630 631 632 633 634 635
        else
            ERR("failed to locate connection for handle %p\n", b_handle);
        LeaveCriticalSection(&protseq->cs);
        if (cconn)
        {
            RPCRT4_new_client(cconn);
            return 1;
        }
        else return -1;
    }
}

636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672
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);

    endpoint_size = strlen(networkaddr) + 1;
    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);
    pipe_floor->protid = EPM_PROTOCOL_SMB;
    pipe_floor->count_rhs = endpoint_size;

    memcpy(tower_data, endpoint, endpoint_size);
    tower_data += 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;

673
    TRACE("(%p, %d, %p, %p)\n", tower_data, (int)tower_size, networkaddr, endpoint);
674 675 676 677 678 679 680 681 682 683 684 685 686 687

    *networkaddr = NULL;
    *endpoint = NULL;

    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)) ||
        (pipe_floor->protid != EPM_PROTOCOL_SMB) ||
        (pipe_floor->count_rhs > tower_size))
        return EPT_S_NOT_REGISTERED;
688 689 690

    if (endpoint)
    {
691
        *endpoint = I_RpcAllocate(pipe_floor->count_rhs);
692 693 694 695
        if (!*endpoint)
            return RPC_S_OUT_OF_RESOURCES;
        memcpy(*endpoint, tower_data, pipe_floor->count_rhs);
    }
696 697 698 699

    return RPC_S_OK;
}

700 701
/**** ncacn_ip_tcp support ****/

702 703 704
typedef struct _RpcConnection_tcp
{
  RpcConnection common;
705
  int sock;
706 707 708 709
} RpcConnection_tcp;

static RpcConnection *rpcrt4_conn_tcp_alloc(void)
{
710
  RpcConnection_tcp *tcpc;
711
  tcpc = HeapAlloc(GetProcessHeap(), 0, sizeof(RpcConnection_tcp));
712 713 714
  if (tcpc == NULL)
    return NULL;
  tcpc->sock = -1;
715
  return &tcpc->common;
716 717 718 719
}

static RPC_STATUS rpcrt4_ncacn_ip_tcp_open(RpcConnection* Connection)
{
720 721
  RpcConnection_tcp *tcpc = (RpcConnection_tcp *) Connection;
  int sock;
722 723 724 725
  int ret;
  struct addrinfo *ai;
  struct addrinfo *ai_cur;
  struct addrinfo hints;
726 727 728

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

729
  if (tcpc->sock != -1)
730 731
    return RPC_S_OK;

732
  hints.ai_flags          = 0;
733 734 735 736 737 738 739 740 741
  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);
742
  if (ret)
743
  {
744 745
    ERR("getaddrinfo for %s:%s failed: %s\n", Connection->NetworkAddr,
      Connection->Endpoint, gai_strerror(ret));
746
    return RPC_S_SERVER_UNAVAILABLE;
747 748
  }

749
  for (ai_cur = ai; ai_cur; ai_cur = ai_cur->ai_next)
750
  {
751 752
    int val;

753 754 755 756 757 758 759 760 761 762 763 764 765
    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);
    if (sock < 0)
    {
766
      WARN("socket() failed: %s\n", strerror(errno));
767 768
      continue;
    }
769

770
    if (0>connect(sock, ai_cur->ai_addr, ai_cur->ai_addrlen))
771
    {
772 773 774
      WARN("connect() failed: %s\n", strerror(errno));
      close(sock);
      continue;
775
    }
776 777 778 779 780

    /* RPC depends on having minimal latency so disable the Nagle algorithm */
    val = 1;
    setsockopt(sock, SOL_TCP, TCP_NODELAY, &val, sizeof(val));

781
    tcpc->sock = sock;
782 783 784 785 786

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

788 789
  freeaddrinfo(ai);
  ERR("couldn't connect to %s:%s\n", Connection->NetworkAddr, Connection->Endpoint);
790 791 792
  return RPC_S_SERVER_UNAVAILABLE;
}

793 794
static RPC_STATUS rpcrt4_protseq_ncacn_ip_tcp_open_endpoint(RpcServerProtseq *protseq, LPSTR endpoint)
{
795
    RPC_STATUS status = RPC_S_CANT_CREATE_ENDPOINT;
796 797 798 799 800
    int sock;
    int ret;
    struct addrinfo *ai;
    struct addrinfo *ai_cur;
    struct addrinfo hints;
801
    RpcConnection *first_connection = NULL;
802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818

    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;

    ret = getaddrinfo(NULL, endpoint, &hints, &ai);
    if (ret)
    {
        ERR("getaddrinfo for port %s failed: %s\n", endpoint,
            gai_strerror(ret));
819 820 821
        if ((ret == EAI_SERVICE) || (ret == EAI_NONAME))
            return RPC_S_INVALID_ENDPOINT_FORMAT;
        return RPC_S_CANT_CREATE_ENDPOINT;
822 823 824 825 826
    }

    for (ai_cur = ai; ai_cur; ai_cur = ai_cur->ai_next)
    {
        RpcConnection_tcp *tcpc;
827 828
        RPC_STATUS create_status;

829 830 831 832 833 834 835 836 837 838 839 840 841 842
        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);
        if (sock < 0)
        {
            WARN("socket() failed: %s\n", strerror(errno));
843
            status = RPC_S_CANT_CREATE_ENDPOINT;
844 845 846 847 848 849 850 851
            continue;
        }

        ret = bind(sock, ai_cur->ai_addr, ai_cur->ai_addrlen);
        if (ret < 0)
        {
            WARN("bind failed: %s\n", strerror(errno));
            close(sock);
852 853 854 855
            if (errno == EADDRINUSE)
              status = RPC_S_DUPLICATE_ENDPOINT;
            else
              status = RPC_S_CANT_CREATE_ENDPOINT;
856 857
            continue;
        }
858 859
        create_status = RPCRT4_CreateConnection((RpcConnection **)&tcpc, TRUE,
                                                protseq->Protseq, NULL,
860 861
                                                endpoint, NULL, NULL, NULL,
                                                NULL);
862
        if (create_status != RPC_S_OK)
863 864
        {
            close(sock);
865
            status = create_status;
866 867 868
            continue;
        }

869
        tcpc->sock = sock;
870
        ret = listen(sock, protseq->MaxCalls);
871 872 873
        if (ret < 0)
        {
            WARN("listen failed: %s\n", strerror(errno));
874
            RPCRT4_DestroyConnection(&tcpc->common);
875
            status = RPC_S_OUT_OF_RESOURCES;
876 877 878 879 880 881 882 883 884 885
            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...)
         */
        ret = fcntl(sock, F_SETFL, O_NONBLOCK);
        if (ret < 0)
        {
            WARN("couldn't make socket non-blocking, error %d\n", ret);
886
            RPCRT4_DestroyConnection(&tcpc->common);
887
            status = RPC_S_OUT_OF_RESOURCES;
888 889 890
            continue;
        }

891 892 893 894 895 896 897 898 899 900 901 902 903 904 905
        tcpc->common.Next = first_connection;
        first_connection = &tcpc->common;
    }

    freeaddrinfo(ai);

    /* if at least one connection was created for an endpoint then
     * return success */
    if (first_connection)
    {
        RpcConnection *conn;

        /* find last element in list */
        for (conn = first_connection; conn->Next; conn = conn->Next)
            ;
906 907

        EnterCriticalSection(&protseq->cs);
908 909
        conn->Next = protseq->conn;
        protseq->conn = first_connection;
910
        LeaveCriticalSection(&protseq->cs);
911
        
912 913 914 915 916
        TRACE("listening on %s\n", endpoint);
        return RPC_S_OK;
    }

    ERR("couldn't listen on port %s\n", endpoint);
917
    return status;
918 919
}

920 921
static RPC_STATUS rpcrt4_conn_tcp_handoff(RpcConnection *old_conn, RpcConnection *new_conn)
{
922 923 924 925 926 927 928 929 930 931 932
  int ret;
  struct sockaddr_in address;
  socklen_t addrsize;
  RpcConnection_tcp *server = (RpcConnection_tcp*) old_conn;
  RpcConnection_tcp *client = (RpcConnection_tcp*) new_conn;

  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);
933
    return RPC_S_OUT_OF_RESOURCES;
934
  }
935 936
  /* reset to blocking behaviour */
  fcntl(ret, F_SETFL, 0);
937 938 939
  client->sock = ret;
  TRACE("Accepted a new TCP connection\n");
  return RPC_S_OK;
940 941 942 943 944
}

static int rpcrt4_conn_tcp_read(RpcConnection *Connection,
                                void *buffer, unsigned int count)
{
945
  RpcConnection_tcp *tcpc = (RpcConnection_tcp *) Connection;
946
  int r = recv(tcpc->sock, buffer, count, MSG_WAITALL);
947 948
  TRACE("%d %p %u -> %d\n", tcpc->sock, buffer, count, r);
  return r;
949 950 951 952 953
}

static int rpcrt4_conn_tcp_write(RpcConnection *Connection,
                                 const void *buffer, unsigned int count)
{
954 955 956 957
  RpcConnection_tcp *tcpc = (RpcConnection_tcp *) Connection;
  int r = write(tcpc->sock, buffer, count);
  TRACE("%d %p %u -> %d\n", tcpc->sock, buffer, count, r);
  return r;
958 959 960 961
}

static int rpcrt4_conn_tcp_close(RpcConnection *Connection)
{
962 963 964
  RpcConnection_tcp *tcpc = (RpcConnection_tcp *) Connection;

  TRACE("%d\n", tcpc->sock);
965

966
  if (tcpc->sock != -1)
967
    close(tcpc->sock);
968
  tcpc->sock = -1;
969
  return 0;
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
static size_t rpcrt4_ncacn_ip_tcp_get_top_of_tower(unsigned char *tower_data,
                                                   const char *networkaddr,
                                                   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 = EPM_PROTOCOL_TCP;
    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);

1001
    hints.ai_flags          = AI_NUMERICHOST;
1002 1003 1004 1005 1006 1007 1008 1009 1010 1011
    /* 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);
1012
    if (ret)
1013
    {
1014
        ret = getaddrinfo("0.0.0.0", endpoint, &hints, &ai);
1015
        if (ret)
1016 1017 1018 1019
        {
            ERR("getaddrinfo failed: %s\n", gai_strerror(ret));
            return 0;
        }
1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047
    }

    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);
        return 0;
    }

    freeaddrinfo(ai);

    return size;
}

static RPC_STATUS rpcrt4_ncacn_ip_tcp_parse_top_of_tower(const unsigned char *tower_data,
                                                         size_t tower_size,
                                                         char **networkaddr,
                                                         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;

1048
    TRACE("(%p, %d, %p, %p)\n", tower_data, (int)tower_size, networkaddr, endpoint);
1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068

    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 != EPM_PROTOCOL_TCP) ||
        (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;

1069
    if (endpoint)
1070
    {
1071
        *endpoint = I_RpcAllocate(6 /* sizeof("65535") + 1 */);
1072 1073 1074
        if (!*endpoint)
            return RPC_S_OUT_OF_RESOURCES;
        sprintf(*endpoint, "%u", ntohs(tcp_floor->port));
1075
    }
1076 1077

    if (networkaddr)
1078
    {
1079
        *networkaddr = I_RpcAllocate(INET_ADDRSTRLEN);
1080 1081 1082 1083
        if (!*networkaddr)
        {
            if (endpoint)
            {
1084
                I_RpcFree(*endpoint);
1085 1086 1087 1088 1089 1090 1091 1092
                *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))
        {
            ERR("inet_ntop: %s\n", strerror(errno));
1093
            I_RpcFree(*networkaddr);
1094 1095 1096
            *networkaddr = NULL;
            if (endpoint)
            {
1097
                I_RpcFree(*endpoint);
1098 1099 1100 1101
                *endpoint = NULL;
            }
            return EPT_S_NOT_REGISTERED;
        }
1102 1103 1104 1105 1106
    }

    return RPC_S_OK;
}

1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244
typedef struct _RpcServerProtseq_sock
{
    RpcServerProtseq common;
    int mgr_event_rcv;
    int mgr_event_snd;
} RpcServerProtseq_sock;

static RpcServerProtseq *rpcrt4_protseq_sock_alloc(void)
{
    RpcServerProtseq_sock *ps = HeapAlloc(GetProcessHeap(), 0, sizeof(*ps));
    if (ps)
    {
        int fds[2];
        if (!socketpair(PF_UNIX, SOCK_DGRAM, 0, fds))
        {
            fcntl(fds[0], F_SETFL, O_NONBLOCK);
            fcntl(fds[1], F_SETFL, O_NONBLOCK);
            ps->mgr_event_rcv = fds[0];
            ps->mgr_event_snd = fds[1];
        }
        else
        {
            ERR("socketpair failed with error %s\n", strerror(errno));
            HeapFree(GetProcessHeap(), 0, ps);
            return NULL;
        }
    }
    return &ps->common;
}

static void rpcrt4_protseq_sock_signal_state_changed(RpcServerProtseq *protseq)
{
    RpcServerProtseq_sock *sockps = CONTAINING_RECORD(protseq, RpcServerProtseq_sock, common);
    char dummy = 1;
    write(sockps->mgr_event_snd, &dummy, sizeof(dummy));
}

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

    EnterCriticalSection(&protseq->cs);
    
    /* open and count connections */
    *count = 1;
    conn = (RpcConnection_tcp *)protseq->conn;
    while (conn) {
        if (conn->sock != -1)
            (*count)++;
        conn = (RpcConnection_tcp *)conn->common.Next;
    }
    
    /* make array of connections */
    if (poll_info)
        poll_info = HeapReAlloc(GetProcessHeap(), 0, poll_info, *count*sizeof(*poll_info));
    else
        poll_info = HeapAlloc(GetProcessHeap(), 0, *count*sizeof(*poll_info));
    if (!poll_info)
    {
        ERR("couldn't allocate poll_info\n");
        LeaveCriticalSection(&protseq->cs);
        return NULL;
    }

    poll_info[0].fd = sockps->mgr_event_rcv;
    poll_info[0].events = POLLIN;
    *count = 1;
    conn =  CONTAINING_RECORD(protseq->conn, RpcConnection_tcp, common);
    while (conn) {
        if (conn->sock != -1)
        {
            poll_info[*count].fd = conn->sock;
            poll_info[*count].events = POLLIN;
            (*count)++;
        }
        conn = CONTAINING_RECORD(conn->common.Next, RpcConnection_tcp, common);
    }
    LeaveCriticalSection(&protseq->cs);
    return poll_info;
}

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)
{
    struct pollfd *poll_info = wait_array;
    int ret, i;
    RpcConnection *cconn;
    RpcConnection_tcp *conn;
    
    if (!poll_info)
        return -1;
    
    ret = poll(poll_info, count, -1);
    if (ret < 0)
    {
        ERR("poll failed with error %d\n", ret);
        return -1;
    }

    for (i = 0; i < count; i++)
        if (poll_info[i].revents & POLLIN)
        {
            /* RPC server event */
            if (i == 0)
            {
                char dummy;
                read(poll_info[0].fd, &dummy, sizeof(dummy));
                return 0;
            }

            /* find which connection got a RPC */
            EnterCriticalSection(&protseq->cs);
            conn = CONTAINING_RECORD(protseq->conn, RpcConnection_tcp, common);
            while (conn) {
                if (poll_info[i].fd == conn->sock) break;
                conn = CONTAINING_RECORD(conn->common.Next, RpcConnection_tcp, common);
            }
            cconn = NULL;
            if (conn)
                RPCRT4_SpawnConnection(&cconn, &conn->common);
            else
                ERR("failed to locate connection for fd %d\n", poll_info[i].fd);
            LeaveCriticalSection(&protseq->cs);
            if (cconn)
                RPCRT4_new_client(cconn);
            else
                return -1;
        }

    return 1;
}

1245
static const struct connection_ops conn_protseq_list[] = {
1246
  { "ncacn_np",
1247
    { EPM_PROTOCOL_NCACN, EPM_PROTOCOL_SMB },
1248
    rpcrt4_conn_np_alloc,
1249
    rpcrt4_ncacn_np_open,
1250
    rpcrt4_ncacn_np_handoff,
1251 1252 1253
    rpcrt4_conn_np_read,
    rpcrt4_conn_np_write,
    rpcrt4_conn_np_close,
1254 1255
    rpcrt4_ncacn_np_get_top_of_tower,
    rpcrt4_ncacn_np_parse_top_of_tower,
1256 1257
  },
  { "ncalrpc",
1258
    { EPM_PROTOCOL_NCALRPC, EPM_PROTOCOL_PIPE },
1259
    rpcrt4_conn_np_alloc,
1260
    rpcrt4_ncalrpc_open,
1261
    rpcrt4_ncalrpc_handoff,
1262 1263 1264
    rpcrt4_conn_np_read,
    rpcrt4_conn_np_write,
    rpcrt4_conn_np_close,
1265 1266
    rpcrt4_ncalrpc_get_top_of_tower,
    rpcrt4_ncalrpc_parse_top_of_tower,
1267
  },
1268
  { "ncacn_ip_tcp",
1269
    { EPM_PROTOCOL_NCACN, EPM_PROTOCOL_TCP },
1270 1271 1272 1273 1274 1275
    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,
1276 1277
    rpcrt4_ncacn_ip_tcp_get_top_of_tower,
    rpcrt4_ncacn_ip_tcp_parse_top_of_tower,
1278
  }
1279 1280 1281
};


1282 1283 1284 1285 1286 1287 1288 1289 1290
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,
1291
        rpcrt4_protseq_ncacn_np_open_endpoint,
1292 1293 1294 1295 1296 1297 1298 1299
    },
    {
        "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,
1300
        rpcrt4_protseq_ncalrpc_open_endpoint,
1301 1302 1303
    },
    {
        "ncacn_ip_tcp",
1304 1305 1306 1307 1308
        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,
1309
        rpcrt4_protseq_ncacn_ip_tcp_open_endpoint,
1310 1311 1312 1313 1314 1315
    },
};

#define ARRAYSIZE(a) (sizeof((a)) / sizeof((a)[0]))

const struct protseq_ops *rpcrt4_get_protseq_ops(const char *protseq)
1316 1317
{
  int i;
1318
  for(i=0; i<ARRAYSIZE(protseq_list); i++)
1319 1320 1321 1322 1323
    if (!strcmp(protseq_list[i].name, protseq))
      return &protseq_list[i];
  return NULL;
}

1324 1325 1326 1327 1328 1329 1330 1331 1332
static const struct connection_ops *rpcrt4_get_conn_protseq_ops(const char *protseq)
{
    int i;
    for(i=0; i<ARRAYSIZE(conn_protseq_list); i++)
        if (!strcmp(conn_protseq_list[i].name, protseq))
            return &conn_protseq_list[i];
    return NULL;
}

1333 1334
/**** interface to rest of code ****/

1335
RPC_STATUS RPCRT4_OpenClientConnection(RpcConnection* Connection)
1336 1337 1338
{
  TRACE("(Connection == ^%p)\n", Connection);

1339 1340
  assert(!Connection->server);
  return Connection->ops->open_connection_client(Connection);
1341 1342 1343 1344 1345
}

RPC_STATUS RPCRT4_CloseConnection(RpcConnection* Connection)
{
  TRACE("(Connection == ^%p)\n", Connection);
1346 1347 1348 1349 1350
  if (SecIsValidHandle(&Connection->ctx))
  {
    DeleteSecurityContext(&Connection->ctx);
    SecInvalidateHandle(&Connection->ctx);
  }
1351 1352 1353 1354
  rpcrt4_conn_close(Connection);
  return RPC_S_OK;
}

1355 1356
RPC_STATUS RPCRT4_CreateConnection(RpcConnection** Connection, BOOL server,
    LPCSTR Protseq, LPCSTR NetworkAddr, LPCSTR Endpoint,
1357
    LPCWSTR NetworkOptions, RpcAuthInfo* AuthInfo, RpcQualityOfService *QOS,
1358
    RpcBinding* Binding)
1359
{
1360
  const struct connection_ops *ops;
1361 1362
  RpcConnection* NewConnection;

1363
  ops = rpcrt4_get_conn_protseq_ops(Protseq);
1364
  if (!ops)
1365 1366
  {
    FIXME("not supported for protseq %s\n", Protseq);
1367
    return RPC_S_PROTSEQ_NOT_SUPPORTED;
1368
  }
1369

1370
  NewConnection = ops->alloc();
1371
  NewConnection->Next = NULL;
1372 1373 1374 1375
  NewConnection->server = server;
  NewConnection->ops = ops;
  NewConnection->NetworkAddr = RPCRT4_strdupA(NetworkAddr);
  NewConnection->Endpoint = RPCRT4_strdupA(Endpoint);
1376
  NewConnection->NetworkOptions = RPCRT4_strdupW(NetworkOptions);
1377 1378
  NewConnection->Used = Binding;
  NewConnection->MaxTransmissionSize = RPC_MAX_PACKET_SIZE;
1379
  memset(&NewConnection->ActiveInterface, 0, sizeof(NewConnection->ActiveInterface));
1380
  NewConnection->NextCallId = 1;
1381

1382
  SecInvalidateHandle(&NewConnection->ctx);
1383 1384
  memset(&NewConnection->exp, 0, sizeof(NewConnection->exp));
  NewConnection->attr = 0;
1385 1386
  if (AuthInfo) RpcAuthInfo_AddRef(AuthInfo);
  NewConnection->AuthInfo = AuthInfo;
1387 1388
  NewConnection->encryption_auth_len = 0;
  NewConnection->signature_auth_len = 0;
1389 1390
  if (QOS) RpcQualityOfService_AddRef(QOS);
  NewConnection->QOS = QOS;
1391

1392
  list_init(&NewConnection->conn_pool_entry);
1393 1394 1395 1396 1397 1398 1399

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

  return RPC_S_OK;
}

1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434
RPC_STATUS RPCRT4_GetAssociation(LPCSTR Protseq, LPCSTR NetworkAddr,
                                 LPCSTR Endpoint, LPCWSTR NetworkOptions,
                                 RpcAssoc **assoc_out)
{
  RpcAssoc *assoc;

  EnterCriticalSection(&assoc_list_cs);
  LIST_FOR_EACH_ENTRY(assoc, &assoc_list, RpcAssoc, entry)
  {
    if (!strcmp(Protseq, assoc->Protseq) &&
        !strcmp(NetworkAddr, assoc->NetworkAddr) &&
        !strcmp(Endpoint, assoc->Endpoint) &&
        ((!assoc->NetworkOptions && !NetworkOptions) || !strcmpW(NetworkOptions, assoc->NetworkOptions)))
    {
      assoc->refs++;
      *assoc_out = assoc;
      LeaveCriticalSection(&assoc_list_cs);
      TRACE("using existing assoc %p\n", assoc);
      return RPC_S_OK;
    }
  }

  assoc = HeapAlloc(GetProcessHeap(), 0, sizeof(*assoc));
  if (!assoc)
  {
    LeaveCriticalSection(&assoc_list_cs);
    return RPC_S_OUT_OF_RESOURCES;
  }
  assoc->refs = 1;
  list_init(&assoc->connection_pool);
  InitializeCriticalSection(&assoc->cs);
  assoc->Protseq = RPCRT4_strdupA(Protseq);
  assoc->NetworkAddr = RPCRT4_strdupA(NetworkAddr);
  assoc->Endpoint = RPCRT4_strdupA(Endpoint);
  assoc->NetworkOptions = NetworkOptions ? RPCRT4_strdupW(NetworkOptions) : NULL;
1435
  assoc->assoc_group_id = 0;
1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482
  list_add_head(&assoc_list, &assoc->entry);
  *assoc_out = assoc;

  LeaveCriticalSection(&assoc_list_cs);

  TRACE("new assoc %p\n", assoc);

  return RPC_S_OK;
}

ULONG RpcAssoc_Release(RpcAssoc *assoc)
{
  ULONG refs;

  EnterCriticalSection(&assoc_list_cs);
  refs = --assoc->refs;
  if (!refs)
    list_remove(&assoc->entry);
  LeaveCriticalSection(&assoc_list_cs);

  if (!refs)
  {
    RpcConnection *Connection, *cursor2;

    TRACE("destroying assoc %p\n", assoc);

    LIST_FOR_EACH_ENTRY_SAFE(Connection, cursor2, &assoc->connection_pool, RpcConnection, conn_pool_entry)
    {
      list_remove(&Connection->conn_pool_entry);
      RPCRT4_DestroyConnection(Connection);
    }

    HeapFree(GetProcessHeap(), 0, assoc->NetworkOptions);
    HeapFree(GetProcessHeap(), 0, assoc->Endpoint);
    HeapFree(GetProcessHeap(), 0, assoc->NetworkAddr);
    HeapFree(GetProcessHeap(), 0, assoc->Protseq);

    HeapFree(GetProcessHeap(), 0, assoc);
  }

  return refs;
}

RpcConnection *RpcAssoc_GetIdleConnection(RpcAssoc *assoc,
    const RPC_SYNTAX_IDENTIFIER *InterfaceId,
    const RPC_SYNTAX_IDENTIFIER *TransferSyntax, const RpcAuthInfo *AuthInfo,
    const RpcQualityOfService *QOS)
1483 1484 1485
{
  RpcConnection *Connection;
  /* try to find a compatible connection from the connection pool */
1486 1487
  EnterCriticalSection(&assoc->cs);
  LIST_FOR_EACH_ENTRY(Connection, &assoc->connection_pool, RpcConnection, conn_pool_entry)
1488 1489 1490 1491
    if (!memcmp(&Connection->ActiveInterface, InterfaceId,
                sizeof(RPC_SYNTAX_IDENTIFIER)) &&
        RpcAuthInfo_IsEqual(Connection->AuthInfo, AuthInfo) &&
        RpcQualityOfService_IsEqual(Connection->QOS, QOS))
1492 1493
    {
      list_remove(&Connection->conn_pool_entry);
1494
      LeaveCriticalSection(&assoc->cs);
1495 1496 1497 1498
      TRACE("got connection from pool %p\n", Connection);
      return Connection;
    }

1499
  LeaveCriticalSection(&assoc->cs);
1500 1501 1502
  return NULL;
}

1503
void RpcAssoc_ReleaseIdleConnection(RpcAssoc *assoc, RpcConnection *Connection)
1504 1505
{
  assert(!Connection->server);
1506
  EnterCriticalSection(&assoc->cs);
1507
  if (!assoc->assoc_group_id) assoc->assoc_group_id = Connection->assoc_group_id;
1508 1509
  list_add_head(&assoc->connection_pool, &Connection->conn_pool_entry);
  LeaveCriticalSection(&assoc->cs);
1510 1511 1512
}


1513 1514 1515 1516
RPC_STATUS RPCRT4_SpawnConnection(RpcConnection** Connection, RpcConnection* OldConnection)
{
  RPC_STATUS err;

1517
  err = RPCRT4_CreateConnection(Connection, OldConnection->server,
1518 1519
                                rpcrt4_conn_get_name(OldConnection),
                                OldConnection->NetworkAddr,
1520
                                OldConnection->Endpoint, NULL,
1521 1522
                                OldConnection->AuthInfo, OldConnection->QOS,
                                NULL);
1523 1524
  if (err == RPC_S_OK)
    rpcrt4_conn_handoff(OldConnection, *Connection);
1525 1526 1527 1528 1529 1530 1531 1532 1533 1534
  return err;
}

RPC_STATUS RPCRT4_DestroyConnection(RpcConnection* Connection)
{
  TRACE("connection: %p\n", Connection);

  RPCRT4_CloseConnection(Connection);
  RPCRT4_strfree(Connection->Endpoint);
  RPCRT4_strfree(Connection->NetworkAddr);
1535
  HeapFree(GetProcessHeap(), 0, Connection->NetworkOptions);
1536
  if (Connection->AuthInfo) RpcAuthInfo_Release(Connection->AuthInfo);
1537
  if (Connection->QOS) RpcQualityOfService_Release(Connection->QOS);
1538 1539 1540
  HeapFree(GetProcessHeap(), 0, Connection);
  return RPC_S_OK;
}
1541

1542 1543 1544 1545 1546 1547 1548
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;
1549
    const struct connection_ops *protseq_ops = rpcrt4_get_conn_protseq_ops(protseq);
1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584

    *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)
{
1585 1586
    const twr_empty_floor_t *protocol_floor;
    const twr_empty_floor_t *floor4;
1587
    const struct connection_ops *protseq_ops = NULL;
1588 1589 1590 1591 1592 1593
    RPC_STATUS status;
    int i;

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

1594
    protocol_floor = (const twr_empty_floor_t *)tower_data;
1595 1596 1597 1598 1599
    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;
1600 1601
    tower_data += protocol_floor->count_rhs;
    tower_size -= protocol_floor->count_rhs;
1602

1603
    floor4 = (const twr_empty_floor_t *)tower_data;
1604
    if ((tower_size < sizeof(*floor4)) ||
1605
        (floor4->count_lhs != sizeof(floor4->protid)))
1606 1607
        return EPT_S_NOT_REGISTERED;

1608 1609 1610
    for(i = 0; i < ARRAYSIZE(conn_protseq_list); i++)
        if ((protocol_floor->protid == conn_protseq_list[i].epm_protocols[0]) &&
            (floor4->protid == conn_protseq_list[i].epm_protocols[1]))
1611
        {
1612
            protseq_ops = &conn_protseq_list[i];
1613 1614 1615 1616 1617 1618 1619 1620
            break;
        }

    if (!protseq_ops)
        return EPT_S_NOT_REGISTERED;

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

1621
    if ((status == RPC_S_OK) && protseq)
1622
    {
1623
        *protseq = I_RpcAllocate(strlen(protseq_ops->name) + 1);
1624 1625 1626 1627 1628 1629
        strcpy(*protseq, protseq_ops->name);
    }

    return status;
}

1630 1631 1632 1633 1634 1635 1636
/***********************************************************************
 *             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.
 *
 */
1637
RPC_STATUS WINAPI RpcNetworkIsProtseqValidW(RPC_WSTR protseq)
1638 1639 1640 1641 1642
{
  char ps[0x10];

  WideCharToMultiByte(CP_ACP, 0, protseq, -1,
                      ps, sizeof ps, NULL, NULL);
1643
  if (rpcrt4_get_conn_protseq_ops(ps))
1644 1645 1646 1647 1648 1649 1650 1651 1652 1653
    return RPC_S_OK;

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

  return RPC_S_INVALID_RPC_PROTSEQ;
}

/***********************************************************************
 *             RpcNetworkIsProtseqValidA (RPCRT4.@)
 */
1654
RPC_STATUS WINAPI RpcNetworkIsProtseqValidA(RPC_CSTR protseq)
1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665
{
  UNICODE_STRING protseqW;

  if (RtlCreateUnicodeStringFromAsciiz(&protseqW, (char*)protseq))
  {
    RPC_STATUS ret = RpcNetworkIsProtseqValidW(protseqW.Buffer);
    RtlFreeUnicodeString(&protseqW);
    return ret;
  }
  return RPC_S_OUT_OF_MEMORY;
}