rpc_server.c 33.3 KB
Newer Older
1 2 3 4
/*
 * RPC server API
 *
 * Copyright 2001 Ove Kven, TransGaming Technologies
5
 * Copyright 2004 Filip Navara
6 7 8 9 10 11 12 13 14 15 16 17 18
 *
 * 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
19
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
20 21 22 23 24
 *
 * TODO:
 *  - a whole lot
 */

Alexandre Julliard's avatar
Alexandre Julliard committed
25 26 27
#include "config.h"
#include "wine/port.h"

28
#include <stdarg.h>
29 30
#include <stdio.h>
#include <string.h>
31
#include <assert.h>
32 33 34 35 36 37 38

#include "windef.h"
#include "winbase.h"
#include "winerror.h"
#include "winreg.h"

#include "rpc.h"
39
#include "rpcndr.h"
40
#include "excpt.h"
41 42

#include "wine/debug.h"
43
#include "wine/exception.h"
44 45

#include "rpc_server.h"
46
#include "rpc_misc.h"
47
#include "rpc_message.h"
48 49
#include "rpc_defs.h"

50
WINE_DEFAULT_DEBUG_CHANNEL(rpc);
51

52 53 54
typedef struct _RpcPacket
{
  struct _RpcConnection* conn;
55 56
  RpcPktHdr* hdr;
  RPC_MESSAGE* msg;
57 58
} RpcPacket;

59 60 61 62 63 64 65 66 67 68
typedef struct _RpcObjTypeMap
{
  /* FIXME: a hash table would be better. */
  struct _RpcObjTypeMap *next;
  UUID Object;
  UUID Type;
} RpcObjTypeMap;

static RpcObjTypeMap *RpcObjTypeMaps;

69 70
/* list of type RpcServerProtseq */
static struct list protseqs = LIST_INIT(protseqs);
71
static struct list server_interfaces = LIST_INIT(server_interfaces);
72

73 74 75 76 77
static CRITICAL_SECTION server_cs;
static CRITICAL_SECTION_DEBUG server_cs_debug =
{
    0, 0, &server_cs,
    { &server_cs_debug.ProcessLocksList, &server_cs_debug.ProcessLocksList },
78
      0, 0, { (DWORD_PTR)(__FILE__ ": server_cs") }
79 80 81 82 83 84 85 86
};
static CRITICAL_SECTION server_cs = { &server_cs_debug, -1, 0, 0, 0, 0 };

static CRITICAL_SECTION listen_cs;
static CRITICAL_SECTION_DEBUG listen_cs_debug =
{
    0, 0, &listen_cs,
    { &listen_cs_debug.ProcessLocksList, &listen_cs_debug.ProcessLocksList },
87
      0, 0, { (DWORD_PTR)(__FILE__ ": listen_cs") }
88 89 90
};
static CRITICAL_SECTION listen_cs = { &listen_cs_debug, -1, 0, 0, 0, 0 };

91
/* whether the server is currently listening */
92
static BOOL std_listen;
93 94 95 96
/* number of manual listeners (calls to RpcServerListen) */
static LONG manual_listen_count;
/* total listeners including auto listeners */
static LONG listen_count;
97

98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121
static UUID uuid_nil;

inline static RpcObjTypeMap *LookupObjTypeMap(UUID *ObjUuid)
{
  RpcObjTypeMap *rslt = RpcObjTypeMaps;
  RPC_STATUS dummy;

  while (rslt) {
    if (! UuidCompare(ObjUuid, &rslt->Object, &dummy)) break;
    rslt = rslt->next;
  }

  return rslt;
}

inline static UUID *LookupObjType(UUID *ObjUuid)
{
  RpcObjTypeMap *map = LookupObjTypeMap(ObjUuid);
  if (map)
    return &map->Type;
  else
    return &uuid_nil;
}

122 123 124
static RpcServerInterface* RPCRT4_find_interface(UUID* object,
                                                 RPC_SYNTAX_IDENTIFIER* if_id,
                                                 BOOL check_object)
125 126
{
  UUID* MgrType = NULL;
127
  RpcServerInterface* cif;
128 129
  RPC_STATUS status;

130 131
  if (check_object)
    MgrType = LookupObjType(object);
132
  EnterCriticalSection(&server_cs);
133
  LIST_FOR_EACH_ENTRY(cif, &server_interfaces, RpcServerInterface, entry) {
134 135
    if (!memcmp(if_id, &cif->If->InterfaceId, sizeof(RPC_SYNTAX_IDENTIFIER)) &&
        (check_object == FALSE || UuidEqual(MgrType, &cif->MgrTypeUuid, &status)) &&
136 137 138 139
        std_listen) {
      InterlockedIncrement(&cif->CurrentCalls);
      break;
    }
140 141
  }
  LeaveCriticalSection(&server_cs);
142
  if (&cif->entry == &server_interfaces) cif = NULL;
143
  TRACE("returning %p for %s\n", cif, debugstr_guid(object));
144 145 146
  return cif;
}

147 148 149 150 151 152 153 154 155 156 157
static void RPCRT4_release_server_interface(RpcServerInterface *sif)
{
  if (!InterlockedDecrement(&sif->CurrentCalls) &&
      sif->CallsCompletedEvent) {
    /* sif must have been removed from server_interfaces before
     * CallsCompletedEvent is set */
    SetEvent(sif->CallsCompletedEvent);
    HeapFree(GetProcessHeap(), 0, sif);
  }
}

158 159
static WINE_EXCEPTION_FILTER(rpc_filter)
{
160
  WARN("exception caught with code 0x%08x = %d\n", GetExceptionCode(), GetExceptionCode());
161
  TRACE("returning failure packet\n");
162
  /* catch every exception */
163 164 165
  return EXCEPTION_EXECUTE_HANDLER;
}

166
static void RPCRT4_process_packet(RpcConnection* conn, RpcPktHdr* hdr, RPC_MESSAGE* msg)
167
{
168 169
  RpcServerInterface* sif;
  RPC_DISPATCH_FUNCTION func;
170 171 172 173
  UUID *object_uuid;
  RpcPktHdr *response;
  void *buf = msg->Buffer;
  RPC_STATUS status;
174

175 176 177 178 179 180 181
  switch (hdr->common.ptype) {
    case PKT_BIND:
      TRACE("got bind packet\n");

      /* FIXME: do more checks! */
      if (hdr->bind.max_tsize < RPC_MIN_PACKET_SIZE ||
          !UuidIsNil(&conn->ActiveInterface.SyntaxGUID, &status)) {
182
        TRACE("packet size less than min size, or active interface syntax guid non-null\n");
183 184 185 186 187
        sif = NULL;
      } else {
        sif = RPCRT4_find_interface(NULL, &hdr->bind.abstract, FALSE);
      }
      if (sif == NULL) {
188
        TRACE("rejecting bind request on connection %p\n", conn);
189 190 191 192
        /* Report failure to client. */
        response = RPCRT4_BuildBindNackHeader(NDR_LOCAL_DATA_REPRESENTATION,
                                              RPC_VER_MAJOR, RPC_VER_MINOR);
      } else {
193 194
        TRACE("accepting bind request on connection %p for %s\n", conn,
              debugstr_guid(&hdr->bind.abstract.SyntaxGUID));
195 196 197 198 199 200 201 202 203 204 205 206

        /* accept. */
        response = RPCRT4_BuildBindAckHeader(NDR_LOCAL_DATA_REPRESENTATION,
                                             RPC_MAX_PACKET_SIZE,
                                             RPC_MAX_PACKET_SIZE,
                                             conn->Endpoint,
                                             RESULT_ACCEPT, NO_REASON,
                                             &sif->If->TransferSyntax);

        /* save the interface for later use */
        conn->ActiveInterface = hdr->bind.abstract;
        conn->MaxTransmissionSize = hdr->bind.max_tsize;
207 208

        RPCRT4_release_server_interface(sif);
209 210
      }

211 212 213
      status = RPCRT4_Send(conn, response, NULL, 0);
      RPCRT4_FreeHeader(response);
      if (status != RPC_S_OK)
214 215 216 217
        goto fail;

      break;

218
    case PKT_REQUEST:
219 220 221 222 223 224 225 226
      TRACE("got request packet\n");

      /* fail if the connection isn't bound with an interface */
      if (UuidIsNil(&conn->ActiveInterface.SyntaxGUID, &status)) {
        response = RPCRT4_BuildFaultHeader(NDR_LOCAL_DATA_REPRESENTATION,
                                           status);

        RPCRT4_Send(conn, response, NULL, 0);
227
        RPCRT4_FreeHeader(response);
228 229 230 231 232 233 234 235 236 237
        break;
      }

      if (hdr->common.flags & RPC_FLG_OBJECT_UUID) {
        object_uuid = (UUID*)(&hdr->request + 1);
      } else {
        object_uuid = NULL;
      }

      sif = RPCRT4_find_interface(object_uuid, &conn->ActiveInterface, TRUE);
238 239 240 241
      if (!sif) {
        /* FIXME: send fault packet? */
        break;
      }
242 243 244 245 246 247 248
      msg->RpcInterfaceInformation = sif->If;
      /* copy the endpoint vector from sif to msg so that midl-generated code will use it */
      msg->ManagerEpv = sif->MgrEpv;
      if (object_uuid != NULL) {
        RPCRT4_SetBindingObject(msg->Handle, object_uuid);
      }

249
      /* find dispatch function */
250
      msg->ProcNum = hdr->request.opnum;
251 252 253 254 255
      if (sif->Flags & RPC_IF_OLE) {
        /* native ole32 always gives us a dispatch table with a single entry
         * (I assume that's a wrapper for IRpcStubBuffer::Invoke) */
        func = *sif->If->DispatchTable->DispatchTable;
      } else {
256
        if (msg->ProcNum >= sif->If->DispatchTable->DispatchTableCount) {
257 258 259
          ERR("invalid procnum\n");
          func = NULL;
        }
260
        func = sif->If->DispatchTable->DispatchTable[msg->ProcNum];
261 262 263 264
      }

      /* put in the drep. FIXME: is this more universally applicable?
         perhaps we should move this outward... */
265 266 267
      msg->DataRepresentation = 
        MAKELONG( MAKEWORD(hdr->common.drep[0], hdr->common.drep[1]),
                  MAKEWORD(hdr->common.drep[2], hdr->common.drep[3]));
268 269

      /* dispatch */
270
      __TRY {
271
        if (func) func(msg);
272
      } __EXCEPT(rpc_filter) {
273 274 275 276 277 278
        if (msg->Buffer != buf) I_RpcFreeBuffer(msg);
        /* this will cause a failure packet to be sent in I_RpcSend */
        msg->RpcFlags |= WINE_RPCFLAG_EXCEPTION;
        msg->BufferLength = sizeof(DWORD);
        I_RpcGetBuffer(msg);
        *(DWORD*)msg->Buffer = GetExceptionCode();
279
      } __ENDTRY
280 281

      /* send response packet */
282 283 284
      I_RpcSend(msg);

      msg->RpcInterfaceInformation = NULL;
285
      RPCRT4_release_server_interface(sif);
286

287
      break;
288

289
    default:
290
      FIXME("unhandled packet type\n");
291 292 293
      break;
  }

294
fail:
295
  /* clean up */
296
  if (msg->Buffer == buf) msg->Buffer = NULL;
297 298
  TRACE("freeing Buffer=%p\n", buf);
  HeapFree(GetProcessHeap(), 0, buf);
299 300 301 302 303
  RPCRT4_DestroyBinding(msg->Handle);
  msg->Handle = 0;
  I_RpcFreeBuffer(msg);
  msg->Buffer = NULL;
  RPCRT4_FreeHeader(hdr);
304
  HeapFree(GetProcessHeap(), 0, msg);
305 306 307 308
}

static DWORD CALLBACK RPCRT4_worker_thread(LPVOID the_arg)
{
309 310 311
  RpcPacket *pkt = the_arg;
  RPCRT4_process_packet(pkt->conn, pkt->hdr, pkt->msg);
  HeapFree(GetProcessHeap(), 0, pkt);
312 313 314 315 316 317
  return 0;
}

static DWORD CALLBACK RPCRT4_io_thread(LPVOID the_arg)
{
  RpcConnection* conn = (RpcConnection*)the_arg;
318 319 320 321 322
  RpcPktHdr *hdr;
  RpcBinding *pbind;
  RPC_MESSAGE *msg;
  RPC_STATUS status;
  RpcPacket *packet;
323 324

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

  for (;;) {
327
    msg = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(RPC_MESSAGE));
328

329 330 331 332 333 334 335 336
    /* create temporary binding for dispatch, it will be freed in
     * RPCRT4_process_packet */
    RPCRT4_MakeBinding(&pbind, conn);
    msg->Handle = (RPC_BINDING_HANDLE)pbind;

    status = RPCRT4_Receive(conn, &hdr, msg);
    if (status != RPC_S_OK) {
      WARN("receive failed with error %lx\n", status);
337
      HeapFree(GetProcessHeap(), 0, msg);
338 339 340
      break;
    }

341
#if 0
342
    RPCRT4_process_packet(conn, hdr, msg);
343 344 345 346
#else
    packet = HeapAlloc(GetProcessHeap(), 0, sizeof(RpcPacket));
    packet->conn = conn;
    packet->hdr = hdr;
347
    packet->msg = msg;
348
    QueueUserWorkItem(RPCRT4_worker_thread, packet, WT_EXECUTELONGFUNCTION);
349
#endif
350
    msg = NULL;
351
  }
352
  RPCRT4_DestroyConnection(conn);
353 354 355
  return 0;
}

356
void RPCRT4_new_client(RpcConnection* conn)
357
{
358 359
  HANDLE thread = CreateThread(NULL, 0, RPCRT4_io_thread, conn, 0, NULL);
  if (!thread) {
360
    DWORD err = GetLastError();
361
    ERR("failed to create thread, error=%08x\n", err);
362
    RPCRT4_DestroyConnection(conn);
363
  }
364 365 366 367 368 369
  /* we could set conn->thread, but then we'd have to make the io_thread wait
   * for that, otherwise the thread might finish, destroy the connection, and
   * free the memory we'd write to before we did, causing crashes and stuff -
   * so let's implement that later, when we really need conn->thread */

  CloseHandle( thread );
370 371
}

372 373 374 375 376 377 378 379 380 381 382 383 384
static DWORD CALLBACK RPCRT4_server_thread(LPVOID the_arg)
{
  int res;
  unsigned int count;
  void *objs = NULL;
  RpcServerProtseq* cps = the_arg;
  RpcConnection* conn;
  BOOL set_ready_event = FALSE;

  TRACE("(the_arg == ^%p)\n", the_arg);

  for (;;) {
    objs = cps->ops->get_wait_array(cps, objs, &count);
385

386 387 388
    if (set_ready_event)
    {
        /* signal to function that changed state that we are now sync'ed */
389
        SetEvent(cps->server_ready_event);
390 391 392
        set_ready_event = FALSE;
    }

393
    /* start waiting */
394 395 396 397 398
    res = cps->ops->wait_for_new_connection(cps, count, objs);
    if (res == -1)
      break;
    else if (res == 0)
    {
399 400
      if (!std_listen)
      {
401
        SetEvent(cps->server_ready_event);
402 403 404
        break;
      }
      set_ready_event = TRUE;
405 406
    }
  }
407
  cps->ops->free_wait_array(cps, objs);
408
  EnterCriticalSection(&cps->cs);
409
  /* close connections */
410 411 412 413
  conn = cps->conn;
  while (conn) {
    RPCRT4_CloseConnection(conn);
    conn = conn->Next;
414
  }
415
  LeaveCriticalSection(&cps->cs);
416 417 418
  return 0;
}

419 420
/* tells the server thread that the state has changed and waits for it to
 * make the changes */
421
static void RPCRT4_sync_with_server_thread(RpcServerProtseq *ps)
422 423 424 425
{
  /* make sure we are the only thread sync'ing the server state, otherwise
   * there is a race with the server thread setting an older state and setting
   * the server_ready_event when the new state hasn't yet been applied */
426
  WaitForSingleObject(ps->mgr_mutex, INFINITE);
427

428 429
  ps->ops->signal_state_changed(ps);

430
  /* wait for server thread to make the requested changes before returning */
431
  WaitForSingleObject(ps->server_ready_event, INFINITE);
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
  ReleaseMutex(ps->mgr_mutex);
}

static RPC_STATUS RPCRT4_start_listen_protseq(RpcServerProtseq *ps, BOOL auto_listen)
{
  RPC_STATUS status = RPC_S_OK;
  HANDLE server_thread;

  EnterCriticalSection(&listen_cs);
  if (ps->is_listening) goto done;

  if (!ps->mgr_mutex) ps->mgr_mutex = CreateMutexW(NULL, FALSE, NULL);
  if (!ps->server_ready_event) ps->server_ready_event = CreateEventW(NULL, FALSE, FALSE, NULL);
  server_thread = CreateThread(NULL, 0, RPCRT4_server_thread, ps, 0, NULL);
  if (!server_thread)
  {
    status = RPC_S_OUT_OF_RESOURCES;
    goto done;
  }
  ps->is_listening = TRUE;
  CloseHandle(server_thread);

done:
  LeaveCriticalSection(&listen_cs);
  return status;
458 459
}

460
static RPC_STATUS RPCRT4_start_listen(BOOL auto_listen)
461
{
462
  RPC_STATUS status = RPC_S_ALREADY_LISTENING;
463
  RpcServerProtseq *cps;
464

465
  TRACE("\n");
466 467

  EnterCriticalSection(&listen_cs);
468 469
  if (auto_listen || (manual_listen_count++ == 0))
  {
470
    status = RPC_S_OK;
471
    if (++listen_count == 1)
472
      std_listen = TRUE;
473
  }
474
  LeaveCriticalSection(&listen_cs);
475

476 477
  if (std_listen)
  {
478
    EnterCriticalSection(&server_cs);
479
    LIST_FOR_EACH_ENTRY(cps, &protseqs, RpcServerProtseq, entry)
480 481
    {
      status = RPCRT4_start_listen_protseq(cps, TRUE);
482 483
      if (status != RPC_S_OK)
        break;
484 485
      
      /* make sure server is actually listening on the interface before
486 487
       * returning */
      RPCRT4_sync_with_server_thread(cps);
488
    }
489
    LeaveCriticalSection(&server_cs);
490 491
  }

492
  return status;
493 494
}

495
static void RPCRT4_stop_listen(BOOL auto_listen)
496
{
497
  EnterCriticalSection(&listen_cs);
498 499 500
  if (auto_listen || (--manual_listen_count == 0))
  {
    if (listen_count != 0 && --listen_count == 0) {
501 502
      RpcServerProtseq *cps;

503 504
      std_listen = FALSE;
      LeaveCriticalSection(&listen_cs);
505

506
      LIST_FOR_EACH_ENTRY(cps, &protseqs, RpcServerProtseq, entry)
507
        RPCRT4_sync_with_server_thread(cps);
508

509 510 511 512 513
      return;
    }
    assert(listen_count >= 0);
  }
  LeaveCriticalSection(&listen_cs);
514 515
}

516
static RPC_STATUS RPCRT4_use_protseq(RpcServerProtseq* ps, LPSTR endpoint)
517
{
518 519
  RPC_STATUS status;

520
  status = ps->ops->open_endpoint(ps, endpoint);
521 522
  if (status != RPC_S_OK)
    return status;
523

524 525 526 527 528 529
  if (std_listen)
  {
    status = RPCRT4_start_listen_protseq(ps, FALSE);
    if (status == RPC_S_OK)
      RPCRT4_sync_with_server_thread(ps);
  }
530

531
  return status;
532 533 534 535 536 537 538 539 540 541
}

/***********************************************************************
 *             RpcServerInqBindings (RPCRT4.@)
 */
RPC_STATUS WINAPI RpcServerInqBindings( RPC_BINDING_VECTOR** BindingVector )
{
  RPC_STATUS status;
  DWORD count;
  RpcServerProtseq* ps;
542
  RpcConnection* conn;
543

544 545 546
  if (BindingVector)
    TRACE("(*BindingVector == ^%p)\n", *BindingVector);
  else
547
    ERR("(BindingVector == NULL!!?)\n");
548

549
  EnterCriticalSection(&server_cs);
550
  /* count connections */
551
  count = 0;
552
  LIST_FOR_EACH_ENTRY(ps, &protseqs, RpcServerProtseq, entry) {
553
    EnterCriticalSection(&ps->cs);
554 555
    conn = ps->conn;
    while (conn) {
556
      count++;
557
      conn = conn->Next;
558
    }
559
    LeaveCriticalSection(&ps->cs);
560 561 562 563 564 565 566 567
  }
  if (count) {
    /* export bindings */
    *BindingVector = HeapAlloc(GetProcessHeap(), 0,
                              sizeof(RPC_BINDING_VECTOR) +
                              sizeof(RPC_BINDING_HANDLE)*(count-1));
    (*BindingVector)->Count = count;
    count = 0;
568
    LIST_FOR_EACH_ENTRY(ps, &protseqs, RpcServerProtseq, entry) {
569
      EnterCriticalSection(&ps->cs);
570 571 572 573
      conn = ps->conn;
      while (conn) {
       RPCRT4_MakeBinding((RpcBinding**)&(*BindingVector)->BindingH[count],
                          conn);
574
       count++;
575
       conn = conn->Next;
576
      }
577
      LeaveCriticalSection(&ps->cs);
578 579 580 581 582 583 584 585 586 587 588 589 590
    }
    status = RPC_S_OK;
  } else {
    *BindingVector = NULL;
    status = RPC_S_NO_BINDINGS;
  }
  LeaveCriticalSection(&server_cs);
  return status;
}

/***********************************************************************
 *             RpcServerUseProtseqEpA (RPCRT4.@)
 */
591
RPC_STATUS WINAPI RpcServerUseProtseqEpA( RPC_CSTR Protseq, UINT MaxCalls, RPC_CSTR Endpoint, LPVOID SecurityDescriptor )
592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607
{
  RPC_POLICY policy;
  
  TRACE( "(%s,%u,%s,%p)\n", Protseq, MaxCalls, Endpoint, SecurityDescriptor );
  
  /* This should provide the default behaviour */
  policy.Length        = sizeof( policy );
  policy.EndpointFlags = 0;
  policy.NICFlags      = 0;
  
  return RpcServerUseProtseqEpExA( Protseq, MaxCalls, Endpoint, SecurityDescriptor, &policy );
}

/***********************************************************************
 *             RpcServerUseProtseqEpW (RPCRT4.@)
 */
608
RPC_STATUS WINAPI RpcServerUseProtseqEpW( RPC_WSTR Protseq, UINT MaxCalls, RPC_WSTR Endpoint, LPVOID SecurityDescriptor )
609 610 611 612 613 614 615 616 617 618 619 620 621
{
  RPC_POLICY policy;
  
  TRACE( "(%s,%u,%s,%p)\n", debugstr_w( Protseq ), MaxCalls, debugstr_w( Endpoint ), SecurityDescriptor );
  
  /* This should provide the default behaviour */
  policy.Length        = sizeof( policy );
  policy.EndpointFlags = 0;
  policy.NICFlags      = 0;
  
  return RpcServerUseProtseqEpExW( Protseq, MaxCalls, Endpoint, SecurityDescriptor, &policy );
}

622 623
/***********************************************************************
 *             alloc_serverprotoseq (internal)
624 625
 *
 * Must be called with server_cs held.
626
 */
627
static RPC_STATUS alloc_serverprotoseq(UINT MaxCalls, char *Protseq, RpcServerProtseq **ps)
628
{
629 630 631
  const struct protseq_ops *ops = rpcrt4_get_protseq_ops(Protseq);

  if (!ops)
632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649
  {
    FIXME("protseq %s not supported\n", debugstr_a(Protseq));
    return RPC_S_PROTSEQ_NOT_SUPPORTED;
  }

  *ps = ops->alloc();
  if (!*ps)
    return RPC_S_OUT_OF_RESOURCES;
  (*ps)->MaxCalls = MaxCalls;
  (*ps)->Protseq = Protseq;
  (*ps)->ops = ops;
  (*ps)->MaxCalls = 0;
  (*ps)->conn = NULL;
  InitializeCriticalSection(&(*ps)->cs);
  (*ps)->is_listening = FALSE;
  (*ps)->mgr_mutex = NULL;
  (*ps)->server_ready_event = NULL;

650 651 652 653
  list_add_head(&protseqs, &(*ps)->entry);

  TRACE("new protseq %p created for %s\n", *ps, Protseq);

654
  return RPC_S_OK;
655 656
}

657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680
/* Finds a given protseq or creates a new one if one doesn't already exist */
static RPC_STATUS RPCRT4_get_or_create_serverprotseq(UINT MaxCalls, char *Protseq, RpcServerProtseq **ps)
{
    RPC_STATUS status;
    RpcServerProtseq *cps;

    EnterCriticalSection(&server_cs);

    LIST_FOR_EACH_ENTRY(cps, &protseqs, RpcServerProtseq, entry)
        if (!strcmp(cps->Protseq, Protseq))
        {
            TRACE("found existing protseq object for %s\n", Protseq);
            *ps = cps;
            LeaveCriticalSection(&server_cs);
            return S_OK;
        }

    status = alloc_serverprotoseq(MaxCalls, Protseq, ps);

    LeaveCriticalSection(&server_cs);

    return status;
}

681 682 683
/***********************************************************************
 *             RpcServerUseProtseqEpExA (RPCRT4.@)
 */
684
RPC_STATUS WINAPI RpcServerUseProtseqEpExA( RPC_CSTR Protseq, UINT MaxCalls, RPC_CSTR Endpoint, LPVOID SecurityDescriptor,
685 686
                                            PRPC_POLICY lpPolicy )
{
687
  char *szps = (char*)Protseq, *szep = (char*)Endpoint;
688
  RpcServerProtseq* ps;
689
  RPC_STATUS status;
690

691 692
  TRACE("(%s,%u,%s,%p,{%u,%lu,%lu})\n", debugstr_a(szps), MaxCalls,
       debugstr_a(szep), SecurityDescriptor,
693 694
       lpPolicy->Length, lpPolicy->EndpointFlags, lpPolicy->NICFlags );

695
  status = RPCRT4_get_or_create_serverprotseq(MaxCalls, RPCRT4_strdupA(szps), &ps);
696 697
  if (status != RPC_S_OK)
    return status;
698

699
  return RPCRT4_use_protseq(ps, szep);
700 701 702 703 704
}

/***********************************************************************
 *             RpcServerUseProtseqEpExW (RPCRT4.@)
 */
705
RPC_STATUS WINAPI RpcServerUseProtseqEpExW( RPC_WSTR Protseq, UINT MaxCalls, RPC_WSTR Endpoint, LPVOID SecurityDescriptor,
706 707 708
                                            PRPC_POLICY lpPolicy )
{
  RpcServerProtseq* ps;
709
  RPC_STATUS status;
710
  LPSTR EndpointA;
711

712
  TRACE("(%s,%u,%s,%p,{%u,%lu,%lu})\n", debugstr_w( Protseq ), MaxCalls,
713 714 715
       debugstr_w( Endpoint ), SecurityDescriptor,
       lpPolicy->Length, lpPolicy->EndpointFlags, lpPolicy->NICFlags );

716
  status = RPCRT4_get_or_create_serverprotseq(MaxCalls, RPCRT4_strdupWtoA(Protseq), &ps);
717 718
  if (status != RPC_S_OK)
    return status;
719

720 721 722 723
  EndpointA = RPCRT4_strdupWtoA(Endpoint);
  status = RPCRT4_use_protseq(ps, EndpointA);
  RPCRT4_strfree(EndpointA);
  return status;
724 725
}

726 727 728
/***********************************************************************
 *             RpcServerUseProtseqA (RPCRT4.@)
 */
729
RPC_STATUS WINAPI RpcServerUseProtseqA(RPC_CSTR Protseq, unsigned int MaxCalls, void *SecurityDescriptor)
730
{
731
  TRACE("(Protseq == %s, MaxCalls == %d, SecurityDescriptor == ^%p)\n", debugstr_a((char*)Protseq), MaxCalls, SecurityDescriptor);
732
  return RpcServerUseProtseqEpA(Protseq, MaxCalls, NULL, SecurityDescriptor);
733 734 735 736 737
}

/***********************************************************************
 *             RpcServerUseProtseqW (RPCRT4.@)
 */
738
RPC_STATUS WINAPI RpcServerUseProtseqW(RPC_WSTR Protseq, unsigned int MaxCalls, void *SecurityDescriptor)
739
{
740
  TRACE("Protseq == %s, MaxCalls == %d, SecurityDescriptor == ^%p)\n", debugstr_w(Protseq), MaxCalls, SecurityDescriptor);
741
  return RpcServerUseProtseqEpW(Protseq, MaxCalls, NULL, SecurityDescriptor);
742 743
}

744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770
/***********************************************************************
 *             RpcServerRegisterIf (RPCRT4.@)
 */
RPC_STATUS WINAPI RpcServerRegisterIf( RPC_IF_HANDLE IfSpec, UUID* MgrTypeUuid, RPC_MGR_EPV* MgrEpv )
{
  TRACE("(%p,%s,%p)\n", IfSpec, debugstr_guid(MgrTypeUuid), MgrEpv);
  return RpcServerRegisterIf2( IfSpec, MgrTypeUuid, MgrEpv, 0, RPC_C_LISTEN_MAX_CALLS_DEFAULT, (UINT)-1, NULL );
}

/***********************************************************************
 *             RpcServerRegisterIfEx (RPCRT4.@)
 */
RPC_STATUS WINAPI RpcServerRegisterIfEx( RPC_IF_HANDLE IfSpec, UUID* MgrTypeUuid, RPC_MGR_EPV* MgrEpv,
                       UINT Flags, UINT MaxCalls, RPC_IF_CALLBACK_FN* IfCallbackFn )
{
  TRACE("(%p,%s,%p,%u,%u,%p)\n", IfSpec, debugstr_guid(MgrTypeUuid), MgrEpv, Flags, MaxCalls, IfCallbackFn);
  return RpcServerRegisterIf2( IfSpec, MgrTypeUuid, MgrEpv, Flags, MaxCalls, (UINT)-1, IfCallbackFn );
}

/***********************************************************************
 *             RpcServerRegisterIf2 (RPCRT4.@)
 */
RPC_STATUS WINAPI RpcServerRegisterIf2( RPC_IF_HANDLE IfSpec, UUID* MgrTypeUuid, RPC_MGR_EPV* MgrEpv,
                      UINT Flags, UINT MaxCalls, UINT MaxRpcSize, RPC_IF_CALLBACK_FN* IfCallbackFn )
{
  PRPC_SERVER_INTERFACE If = (PRPC_SERVER_INTERFACE)IfSpec;
  RpcServerInterface* sif;
771
  unsigned int i;
772 773 774 775 776 777

  TRACE("(%p,%s,%p,%u,%u,%u,%p)\n", IfSpec, debugstr_guid(MgrTypeUuid), MgrEpv, Flags, MaxCalls,
         MaxRpcSize, IfCallbackFn);
  TRACE(" interface id: %s %d.%d\n", debugstr_guid(&If->InterfaceId.SyntaxGUID),
                                     If->InterfaceId.SyntaxVersion.MajorVersion,
                                     If->InterfaceId.SyntaxVersion.MinorVersion);
Greg Turner's avatar
Greg Turner committed
778 779 780
  TRACE(" transfer syntax: %s %d.%d\n", debugstr_guid(&If->TransferSyntax.SyntaxGUID),
                                        If->TransferSyntax.SyntaxVersion.MajorVersion,
                                        If->TransferSyntax.SyntaxVersion.MinorVersion);
781 782 783 784 785 786 787 788 789 790 791 792 793 794
  TRACE(" dispatch table: %p\n", If->DispatchTable);
  if (If->DispatchTable) {
    TRACE("  dispatch table count: %d\n", If->DispatchTable->DispatchTableCount);
    for (i=0; i<If->DispatchTable->DispatchTableCount; i++) {
      TRACE("   entry %d: %p\n", i, If->DispatchTable->DispatchTable[i]);
    }
    TRACE("  reserved: %ld\n", If->DispatchTable->Reserved);
  }
  TRACE(" protseq endpoint count: %d\n", If->RpcProtseqEndpointCount);
  TRACE(" default manager epv: %p\n", If->DefaultManagerEpv);
  TRACE(" interpreter info: %p\n", If->InterpreterInfo);

  sif = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(RpcServerInterface));
  sif->If           = If;
795
  if (MgrTypeUuid) {
796
    memcpy(&sif->MgrTypeUuid, MgrTypeUuid, sizeof(UUID));
797 798
    sif->MgrEpv       = MgrEpv;
  } else {
799
    memset(&sif->MgrTypeUuid, 0, sizeof(UUID));
800 801
    sif->MgrEpv       = If->DefaultManagerEpv;
  }
802 803 804 805 806 807
  sif->Flags        = Flags;
  sif->MaxCalls     = MaxCalls;
  sif->MaxRpcSize   = MaxRpcSize;
  sif->IfCallbackFn = IfCallbackFn;

  EnterCriticalSection(&server_cs);
808
  list_add_head(&server_interfaces, &sif->entry);
809 810
  LeaveCriticalSection(&server_cs);

811 812
  if (sif->Flags & RPC_IF_AUTOLISTEN)
      RPCRT4_start_listen(TRUE);
813 814 815 816

  return RPC_S_OK;
}

817 818 819 820 821
/***********************************************************************
 *             RpcServerUnregisterIf (RPCRT4.@)
 */
RPC_STATUS WINAPI RpcServerUnregisterIf( RPC_IF_HANDLE IfSpec, UUID* MgrTypeUuid, UINT WaitForCallsToComplete )
{
822 823 824 825 826 827 828 829 830 831 832 833
  PRPC_SERVER_INTERFACE If = (PRPC_SERVER_INTERFACE)IfSpec;
  HANDLE event = NULL;
  BOOL found = FALSE;
  BOOL completed = TRUE;
  RpcServerInterface *cif;
  RPC_STATUS status;

  TRACE("(IfSpec == (RPC_IF_HANDLE)^%p (%s), MgrTypeUuid == %s, WaitForCallsToComplete == %u)\n",
    IfSpec, debugstr_guid(&If->InterfaceId.SyntaxGUID), debugstr_guid(MgrTypeUuid), WaitForCallsToComplete);

  EnterCriticalSection(&server_cs);
  LIST_FOR_EACH_ENTRY(cif, &server_interfaces, RpcServerInterface, entry) {
834
    if ((!IfSpec || !memcmp(&If->InterfaceId, &cif->If->InterfaceId, sizeof(RPC_SYNTAX_IDENTIFIER))) &&
835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860
        UuidEqual(MgrTypeUuid, &cif->MgrTypeUuid, &status)) {
      list_remove(&cif->entry);
      if (cif->CurrentCalls) {
        completed = FALSE;
        if (WaitForCallsToComplete)
          cif->CallsCompletedEvent = event = CreateEventW(NULL, FALSE, FALSE, NULL);
      }
      found = TRUE;
      break;
    }
  }
  LeaveCriticalSection(&server_cs);

  if (!found) {
    ERR("not found for object %s\n", debugstr_guid(MgrTypeUuid));
    return RPC_S_UNKNOWN_IF;
  }

  if (completed)
    HeapFree(GetProcessHeap(), 0, cif);
  else if (event) {
    /* sif will be freed when the last call is completed, so be careful not to
     * touch that memory here as that could happen before we get here */
    WaitForSingleObject(event, INFINITE);
    CloseHandle(event);
  }
861 862 863 864 865 866 867 868 869 870 871 872 873 874 875

  return RPC_S_OK;
}

/***********************************************************************
 *             RpcServerUnregisterIfEx (RPCRT4.@)
 */
RPC_STATUS WINAPI RpcServerUnregisterIfEx( RPC_IF_HANDLE IfSpec, UUID* MgrTypeUuid, int RundownContextHandles )
{
  FIXME("(IfSpec == (RPC_IF_HANDLE)^%p, MgrTypeUuid == %s, RundownContextHandles == %d): stub\n",
    IfSpec, debugstr_guid(MgrTypeUuid), RundownContextHandles);

  return RPC_S_OK;
}

876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 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
/***********************************************************************
 *             RpcObjectSetType (RPCRT4.@)
 *
 * PARAMS
 *   ObjUuid  [I] "Object" UUID
 *   TypeUuid [I] "Type" UUID
 *
 * RETURNS
 *   RPC_S_OK                 The call succeeded
 *   RPC_S_INVALID_OBJECT     The provided object (nil) is not valid
 *   RPC_S_ALREADY_REGISTERED The provided object is already registered
 *
 * Maps "Object" UUIDs to "Type" UUID's.  Passing the nil UUID as the type
 * resets the mapping for the specified object UUID to nil (the default).
 * The nil object is always associated with the nil type and cannot be
 * reassigned.  Servers can support multiple implementations on the same
 * interface by registering different end-point vectors for the different
 * types.  There's no need to call this if a server only supports the nil
 * type, as is typical.
 */
RPC_STATUS WINAPI RpcObjectSetType( UUID* ObjUuid, UUID* TypeUuid )
{
  RpcObjTypeMap *map = RpcObjTypeMaps, *prev = NULL;
  RPC_STATUS dummy;

  TRACE("(ObjUUID == %s, TypeUuid == %s).\n", debugstr_guid(ObjUuid), debugstr_guid(TypeUuid));
  if ((! ObjUuid) || UuidIsNil(ObjUuid, &dummy)) {
    /* nil uuid cannot be remapped */
    return RPC_S_INVALID_OBJECT;
  }

  /* find the mapping for this object if there is one ... */
  while (map) {
    if (! UuidCompare(ObjUuid, &map->Object, &dummy)) break;
    prev = map;
    map = map->next;
  }
  if ((! TypeUuid) || UuidIsNil(TypeUuid, &dummy)) {
    /* ... and drop it from the list */
    if (map) {
      if (prev) 
        prev->next = map->next;
      else
        RpcObjTypeMaps = map->next;
      HeapFree(GetProcessHeap(), 0, map);
    }
  } else {
    /* ... , fail if we found it ... */
    if (map)
      return RPC_S_ALREADY_REGISTERED;
    /* ... otherwise create a new one and add it in. */
    map = HeapAlloc(GetProcessHeap(), 0, sizeof(RpcObjTypeMap));
    memcpy(&map->Object, ObjUuid, sizeof(UUID));
    memcpy(&map->Type, TypeUuid, sizeof(UUID));
    map->next = NULL;
    if (prev)
      prev->next = map; /* prev is the last map in the linklist */
    else
      RpcObjTypeMaps = map;
  }

  return RPC_S_OK;
}

940 941 942
/***********************************************************************
 *             RpcServerRegisterAuthInfoA (RPCRT4.@)
 */
943
RPC_STATUS WINAPI RpcServerRegisterAuthInfoA( RPC_CSTR ServerPrincName, unsigned long AuthnSvc, RPC_AUTH_KEY_RETRIEVAL_FN GetKeyFn,
944 945 946 947 948 949 950 951 952 953
                            LPVOID Arg )
{
  FIXME( "(%s,%lu,%p,%p): stub\n", ServerPrincName, AuthnSvc, GetKeyFn, Arg );
  
  return RPC_S_UNKNOWN_AUTHN_SERVICE; /* We don't know any authentication services */
}

/***********************************************************************
 *             RpcServerRegisterAuthInfoW (RPCRT4.@)
 */
954
RPC_STATUS WINAPI RpcServerRegisterAuthInfoW( RPC_WSTR ServerPrincName, unsigned long AuthnSvc, RPC_AUTH_KEY_RETRIEVAL_FN GetKeyFn,
955 956 957 958 959 960 961 962 963 964 965 966
                            LPVOID Arg )
{
  FIXME( "(%s,%lu,%p,%p): stub\n", debugstr_w( ServerPrincName ), AuthnSvc, GetKeyFn, Arg );
  
  return RPC_S_UNKNOWN_AUTHN_SERVICE; /* We don't know any authentication services */
}

/***********************************************************************
 *             RpcServerListen (RPCRT4.@)
 */
RPC_STATUS WINAPI RpcServerListen( UINT MinimumCallThreads, UINT MaxCalls, UINT DontWait )
{
967
  RPC_STATUS status = RPC_S_OK;
968

969 970
  TRACE("(%u,%u,%u)\n", MinimumCallThreads, MaxCalls, DontWait);

971
  if (list_empty(&protseqs))
972 973
    return RPC_S_NO_PROTSEQS_REGISTERED;

974
  status = RPCRT4_start_listen(FALSE);
975

976
  if (DontWait || (status != RPC_S_OK)) return status;
977

978 979 980 981 982 983 984 985
  return RpcMgmtWaitServerListen();
}

/***********************************************************************
 *             RpcMgmtServerWaitListen (RPCRT4.@)
 */
RPC_STATUS WINAPI RpcMgmtWaitServerListen( void )
{
986
  TRACE("()\n");
987 988 989

  EnterCriticalSection(&listen_cs);

990 991 992 993
  if (!std_listen) {
    LeaveCriticalSection(&listen_cs);
    return RPC_S_NOT_LISTENING;
  }
994
  
995 996
  LeaveCriticalSection(&listen_cs);

997 998
  FIXME("not waiting for server calls to finish\n");

999
  return RPC_S_OK;
1000 1001
}

1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013
/***********************************************************************
 *             RpcMgmtStopServerListening (RPCRT4.@)
 */
RPC_STATUS WINAPI RpcMgmtStopServerListening ( RPC_BINDING_HANDLE Binding )
{
  TRACE("(Binding == (RPC_BINDING_HANDLE)^%p)\n", Binding);

  if (Binding) {
    FIXME("client-side invocation not implemented.\n");
    return RPC_S_WRONG_KIND_OF_BINDING;
  }
  
1014
  RPCRT4_stop_listen(FALSE);
1015 1016 1017 1018

  return RPC_S_OK;
}

1019 1020 1021 1022 1023 1024 1025 1026 1027
/***********************************************************************
 *             RpcMgmtEnableIdleCleanup (RPCRT4.@)
 */
RPC_STATUS WINAPI RpcMgmtEnableIdleCleanup(void)
{
    FIXME("(): stub\n");
    return RPC_S_OK;
}

1028 1029 1030
/***********************************************************************
 *             I_RpcServerStartListening (RPCRT4.@)
 */
1031
RPC_STATUS WINAPI I_RpcServerStartListening( HWND hWnd )
1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050
{
  FIXME( "(%p): stub\n", hWnd );

  return RPC_S_OK;
}

/***********************************************************************
 *             I_RpcServerStopListening (RPCRT4.@)
 */
RPC_STATUS WINAPI I_RpcServerStopListening( void )
{
  FIXME( "(): stub\n" );

  return RPC_S_OK;
}

/***********************************************************************
 *             I_RpcWindowProc (RPCRT4.@)
 */
1051
UINT WINAPI I_RpcWindowProc( void *hWnd, UINT Message, UINT wParam, ULONG lParam )
1052
{
1053
  FIXME( "(%p,%08x,%08x,%08x): stub\n", hWnd, Message, wParam, lParam );
1054 1055 1056

  return 0;
}
1057

1058 1059 1060
/***********************************************************************
 *             RpcMgmtInqIfIds (RPCRT4.@)
 */
1061 1062 1063 1064 1065
RPC_STATUS WINAPI RpcMgmtInqIfIds(RPC_BINDING_HANDLE Binding, RPC_IF_ID_VECTOR **IfIdVector)
{
  FIXME("(%p,%p): stub\n", Binding, IfIdVector);
  return RPC_S_INVALID_BINDING;
}
1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076

/***********************************************************************
 *             RpcMgmtEpEltInqBegin (RPCRT4.@)
 */
RPC_STATUS WINAPI RpcMgmtEpEltInqBegin(RPC_BINDING_HANDLE Binding, unsigned long InquiryType,
    RPC_IF_ID *IfId, unsigned long VersOption, UUID *ObjectUuid, RPC_EP_INQ_HANDLE* InquiryContext)
{
  FIXME("(%p,%lu,%p,%lu,%p,%p): stub\n",
        Binding, InquiryType, IfId, VersOption, ObjectUuid, InquiryContext);
  return RPC_S_INVALID_BINDING;
}
1077 1078

/***********************************************************************
1079
 *             RpcMgmtIsServerListening (RPCRT4.@)
1080 1081 1082 1083 1084 1085
 */
RPC_STATUS WINAPI RpcMgmtIsServerListening(RPC_BINDING_HANDLE Binding)
{
  FIXME("(%p): stub\n", Binding);
  return RPC_S_INVALID_BINDING;
}
1086 1087 1088 1089

/***********************************************************************
 *             RpcMgmtSetServerStackSize (RPCRT4.@)
 */
1090
RPC_STATUS WINAPI RpcMgmtSetServerStackSize(unsigned long ThreadStackSize)
1091
{
1092
  FIXME("(0x%lx): stub\n", ThreadStackSize);
1093 1094
  return RPC_S_OK;
}