rpcrt4: Make RPCRT4_Receive() static.
[wine] / dlls / rpcrt4 / rpc_server.c
1 /*
2  * RPC server API
3  *
4  * Copyright 2001 Ove Kåven, TransGaming Technologies
5  * Copyright 2004 Filip Navara
6  * Copyright 2006-2008 Robert Shearman (for CodeWeavers)
7  *
8  * This library is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU Lesser General Public
10  * License as published by the Free Software Foundation; either
11  * version 2.1 of the License, or (at your option) any later version.
12  *
13  * This library is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16  * Lesser General Public License for more details.
17  *
18  * You should have received a copy of the GNU Lesser General Public
19  * License along with this library; if not, write to the Free Software
20  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
21  */
22
23 #include "config.h"
24 #include "wine/port.h"
25
26 #include <stdarg.h>
27 #include <stdio.h>
28 #include <string.h>
29 #include <assert.h>
30
31 #include "windef.h"
32 #include "winbase.h"
33 #include "winerror.h"
34
35 #include "rpc.h"
36 #include "rpcndr.h"
37 #include "excpt.h"
38
39 #include "wine/debug.h"
40 #include "wine/exception.h"
41
42 #include "rpc_server.h"
43 #include "rpc_assoc.h"
44 #include "rpc_message.h"
45 #include "rpc_defs.h"
46 #include "ncastatus.h"
47
48 WINE_DEFAULT_DEBUG_CHANNEL(rpc);
49
50 typedef struct _RpcPacket
51 {
52   struct _RpcConnection* conn;
53   RpcPktHdr* hdr;
54   RPC_MESSAGE* msg;
55   unsigned char *auth_data;
56   ULONG auth_length;
57 } RpcPacket;
58
59 typedef struct _RpcObjTypeMap
60 {
61   /* FIXME: a hash table would be better. */
62   struct _RpcObjTypeMap *next;
63   UUID Object;
64   UUID Type;
65 } RpcObjTypeMap;
66
67 static RpcObjTypeMap *RpcObjTypeMaps;
68
69 /* list of type RpcServerProtseq */
70 static struct list protseqs = LIST_INIT(protseqs);
71 static struct list server_interfaces = LIST_INIT(server_interfaces);
72 static struct list server_registered_auth_info = LIST_INIT(server_registered_auth_info);
73
74 static CRITICAL_SECTION server_cs;
75 static CRITICAL_SECTION_DEBUG server_cs_debug =
76 {
77     0, 0, &server_cs,
78     { &server_cs_debug.ProcessLocksList, &server_cs_debug.ProcessLocksList },
79       0, 0, { (DWORD_PTR)(__FILE__ ": server_cs") }
80 };
81 static CRITICAL_SECTION server_cs = { &server_cs_debug, -1, 0, 0, 0, 0 };
82
83 static CRITICAL_SECTION listen_cs;
84 static CRITICAL_SECTION_DEBUG listen_cs_debug =
85 {
86     0, 0, &listen_cs,
87     { &listen_cs_debug.ProcessLocksList, &listen_cs_debug.ProcessLocksList },
88       0, 0, { (DWORD_PTR)(__FILE__ ": listen_cs") }
89 };
90 static CRITICAL_SECTION listen_cs = { &listen_cs_debug, -1, 0, 0, 0, 0 };
91
92 static CRITICAL_SECTION server_auth_info_cs;
93 static CRITICAL_SECTION_DEBUG server_auth_info_cs_debug =
94 {
95     0, 0, &server_auth_info_cs,
96     { &server_auth_info_cs_debug.ProcessLocksList, &server_auth_info_cs_debug.ProcessLocksList },
97       0, 0, { (DWORD_PTR)(__FILE__ ": server_auth_info_cs") }
98 };
99 static CRITICAL_SECTION server_auth_info_cs = { &server_auth_info_cs_debug, -1, 0, 0, 0, 0 };
100
101 /* whether the server is currently listening */
102 static BOOL std_listen;
103 /* number of manual listeners (calls to RpcServerListen) */
104 static LONG manual_listen_count;
105 /* total listeners including auto listeners */
106 static LONG listen_count;
107
108 static UUID uuid_nil;
109
110 static inline RpcObjTypeMap *LookupObjTypeMap(UUID *ObjUuid)
111 {
112   RpcObjTypeMap *rslt = RpcObjTypeMaps;
113   RPC_STATUS dummy;
114
115   while (rslt) {
116     if (! UuidCompare(ObjUuid, &rslt->Object, &dummy)) break;
117     rslt = rslt->next;
118   }
119
120   return rslt;
121 }
122
123 static inline UUID *LookupObjType(UUID *ObjUuid)
124 {
125   RpcObjTypeMap *map = LookupObjTypeMap(ObjUuid);
126   if (map)
127     return &map->Type;
128   else
129     return &uuid_nil;
130 }
131
132 static RpcServerInterface* RPCRT4_find_interface(UUID* object,
133                                                  const RPC_SYNTAX_IDENTIFIER *if_id,
134                                                  const RPC_SYNTAX_IDENTIFIER *transfer_syntax,
135                                                  BOOL check_object)
136 {
137   UUID* MgrType = NULL;
138   RpcServerInterface* cif;
139   RPC_STATUS status;
140
141   if (check_object)
142     MgrType = LookupObjType(object);
143   EnterCriticalSection(&server_cs);
144   LIST_FOR_EACH_ENTRY(cif, &server_interfaces, RpcServerInterface, entry) {
145     if (!memcmp(if_id, &cif->If->InterfaceId, sizeof(RPC_SYNTAX_IDENTIFIER)) &&
146         (!transfer_syntax || !memcmp(transfer_syntax, &cif->If->TransferSyntax, sizeof(RPC_SYNTAX_IDENTIFIER))) &&
147         (check_object == FALSE || UuidEqual(MgrType, &cif->MgrTypeUuid, &status)) &&
148         std_listen) {
149       InterlockedIncrement(&cif->CurrentCalls);
150       break;
151     }
152   }
153   LeaveCriticalSection(&server_cs);
154   if (&cif->entry == &server_interfaces) cif = NULL;
155   TRACE("returning %p for object %s, if_id { %d.%d %s }\n", cif,
156     debugstr_guid(object), if_id->SyntaxVersion.MajorVersion,
157     if_id->SyntaxVersion.MinorVersion, debugstr_guid(&if_id->SyntaxGUID));
158   return cif;
159 }
160
161 static void RPCRT4_release_server_interface(RpcServerInterface *sif)
162 {
163   if (!InterlockedDecrement(&sif->CurrentCalls) &&
164       sif->Delete) {
165     /* sif must have been removed from server_interfaces before
166      * CallsCompletedEvent is set */
167     if (sif->CallsCompletedEvent)
168       SetEvent(sif->CallsCompletedEvent);
169     HeapFree(GetProcessHeap(), 0, sif);
170   }
171 }
172
173 static RpcPktHdr *handle_bind_error(RpcConnection *conn, RPC_STATUS error)
174 {
175     unsigned int reject_reason;
176     switch (error)
177     {
178     case RPC_S_SERVER_TOO_BUSY:
179         reject_reason = REJECT_TEMPORARY_CONGESTION;
180         break;
181     case ERROR_OUTOFMEMORY:
182     case RPC_S_OUT_OF_RESOURCES:
183         reject_reason = REJECT_LOCAL_LIMIT_EXCEEDED;
184         break;
185     case RPC_S_PROTOCOL_ERROR:
186         reject_reason = REJECT_PROTOCOL_VERSION_NOT_SUPPORTED;
187         break;
188     case RPC_S_UNKNOWN_AUTHN_SERVICE:
189         reject_reason = REJECT_UNKNOWN_AUTHN_SERVICE;
190         break;
191     case ERROR_ACCESS_DENIED:
192         reject_reason = REJECT_INVALID_CHECKSUM;
193         break;
194     default:
195         FIXME("unexpected status value %d\n", error);
196         /* fall through */
197     case RPC_S_INVALID_BOUND:
198         reject_reason = REJECT_REASON_NOT_SPECIFIED;
199         break;
200     }
201     return RPCRT4_BuildBindNackHeader(NDR_LOCAL_DATA_REPRESENTATION,
202                                       RPC_VER_MAJOR, RPC_VER_MINOR,
203                                       reject_reason);
204 }
205
206 static RPC_STATUS process_bind_packet_no_send(
207     RpcConnection *conn, RpcPktBindHdr *hdr, RPC_MESSAGE *msg,
208     unsigned char *auth_data, ULONG auth_length, RpcPktHdr **ack_response,
209     unsigned char **auth_data_out, ULONG *auth_length_out)
210 {
211   RPC_STATUS status;
212   RpcContextElement *ctxt_elem;
213   unsigned int i;
214   RpcResult *results;
215
216   /* validate data */
217   for (i = 0, ctxt_elem = msg->Buffer;
218        i < hdr->num_elements;
219        i++, ctxt_elem = (RpcContextElement *)&ctxt_elem->transfer_syntaxes[ctxt_elem->num_syntaxes])
220   {
221       if (((char *)ctxt_elem - (char *)msg->Buffer) > msg->BufferLength ||
222           ((char *)&ctxt_elem->transfer_syntaxes[ctxt_elem->num_syntaxes] - (char *)msg->Buffer) > msg->BufferLength)
223       {
224           ERR("inconsistent data in packet - packet length %d, num elements %d\n",
225               msg->BufferLength, hdr->num_elements);
226           return RPC_S_INVALID_BOUND;
227       }
228   }
229
230   if (hdr->max_tsize < RPC_MIN_PACKET_SIZE ||
231       !UuidIsNil(&conn->ActiveInterface.SyntaxGUID, &status) ||
232       conn->server_binding)
233   {
234     TRACE("packet size less than min size, or active interface syntax guid non-null\n");
235
236     return RPC_S_INVALID_BOUND;
237   }
238
239   results = HeapAlloc(GetProcessHeap(), 0,
240                       hdr->num_elements * sizeof(*results));
241   if (!results)
242     return RPC_S_OUT_OF_RESOURCES;
243
244   for (i = 0, ctxt_elem = (RpcContextElement *)msg->Buffer;
245        i < hdr->num_elements;
246        i++, ctxt_elem = (RpcContextElement *)&ctxt_elem->transfer_syntaxes[ctxt_elem->num_syntaxes])
247   {
248       RpcServerInterface* sif = NULL;
249       unsigned int j;
250
251       for (j = 0; !sif && j < ctxt_elem->num_syntaxes; j++)
252       {
253           sif = RPCRT4_find_interface(NULL, &ctxt_elem->abstract_syntax,
254                                       &ctxt_elem->transfer_syntaxes[j], FALSE);
255           if (sif)
256               break;
257       }
258       if (sif)
259       {
260           RPCRT4_release_server_interface(sif);
261           TRACE("accepting bind request on connection %p for %s\n", conn,
262                 debugstr_guid(&ctxt_elem->abstract_syntax.SyntaxGUID));
263           results[i].result = RESULT_ACCEPT;
264           results[i].reason = REASON_NONE;
265           results[i].transfer_syntax = ctxt_elem->transfer_syntaxes[j];
266
267           /* save the interface for later use */
268           /* FIXME: save linked list */
269           conn->ActiveInterface = ctxt_elem->abstract_syntax;
270       }
271       else if ((sif = RPCRT4_find_interface(NULL, &ctxt_elem->abstract_syntax,
272                                             NULL, FALSE)) != NULL)
273       {
274           RPCRT4_release_server_interface(sif);
275           TRACE("not accepting bind request on connection %p for %s - no transfer syntaxes supported\n",
276                 conn, debugstr_guid(&ctxt_elem->abstract_syntax.SyntaxGUID));
277           results[i].result = RESULT_PROVIDER_REJECTION;
278           results[i].reason = REASON_TRANSFER_SYNTAXES_NOT_SUPPORTED;
279           memset(&results[i].transfer_syntax, 0, sizeof(results[i].transfer_syntax));
280       }
281       else
282       {
283           TRACE("not accepting bind request on connection %p for %s - abstract syntax not supported\n",
284                 conn, debugstr_guid(&ctxt_elem->abstract_syntax.SyntaxGUID));
285           results[i].result = RESULT_PROVIDER_REJECTION;
286           results[i].reason = REASON_ABSTRACT_SYNTAX_NOT_SUPPORTED;
287           memset(&results[i].transfer_syntax, 0, sizeof(results[i].transfer_syntax));
288       }
289   }
290
291   /* create temporary binding */
292   status = RPCRT4_MakeBinding(&conn->server_binding, conn);
293   if (status != RPC_S_OK)
294   {
295       HeapFree(GetProcessHeap(), 0, results);
296       return status;
297   }
298
299   status = RpcServerAssoc_GetAssociation(rpcrt4_conn_get_name(conn),
300                                          conn->NetworkAddr, conn->Endpoint,
301                                          conn->NetworkOptions,
302                                          hdr->assoc_gid,
303                                          &conn->server_binding->Assoc);
304   if (status != RPC_S_OK)
305   {
306       HeapFree(GetProcessHeap(), 0, results);
307       return status;
308   }
309
310   if (auth_length)
311   {
312       status = RPCRT4_ServerConnectionAuth(conn, TRUE,
313                                            (RpcAuthVerifier *)auth_data,
314                                            auth_length, auth_data_out,
315                                            auth_length_out);
316       if (status != RPC_S_OK)
317       {
318           HeapFree(GetProcessHeap(), 0, results);
319           return status;
320       }
321   }
322
323   *ack_response = RPCRT4_BuildBindAckHeader(NDR_LOCAL_DATA_REPRESENTATION,
324                                             RPC_MAX_PACKET_SIZE,
325                                             RPC_MAX_PACKET_SIZE,
326                                             conn->server_binding->Assoc->assoc_group_id,
327                                             conn->Endpoint, hdr->num_elements,
328                                             results);
329   HeapFree(GetProcessHeap(), 0, results);
330
331   if (*ack_response)
332       conn->MaxTransmissionSize = hdr->max_tsize;
333   else
334       status = RPC_S_OUT_OF_RESOURCES;
335
336   return status;
337 }
338
339 static RPC_STATUS process_bind_packet(RpcConnection *conn, RpcPktBindHdr *hdr,
340                                       RPC_MESSAGE *msg,
341                                       unsigned char *auth_data,
342                                       ULONG auth_length)
343 {
344     RPC_STATUS status;
345     RpcPktHdr *response = NULL;
346     unsigned char *auth_data_out = NULL;
347     ULONG auth_length_out = 0;
348
349     status = process_bind_packet_no_send(conn, hdr, msg, auth_data, auth_length,
350                                          &response, &auth_data_out,
351                                          &auth_length_out);
352     if (status != RPC_S_OK)
353         response = handle_bind_error(conn, status);
354     if (response)
355         status = RPCRT4_SendWithAuth(conn, response, NULL, 0, auth_data_out, auth_length_out);
356     else
357         status = ERROR_OUTOFMEMORY;
358     RPCRT4_FreeHeader(response);
359
360     return status;
361 }
362
363
364 static RPC_STATUS process_request_packet(RpcConnection *conn, RpcPktRequestHdr *hdr, RPC_MESSAGE *msg)
365 {
366   RPC_STATUS status;
367   RpcPktHdr *response = NULL;
368   RpcServerInterface* sif;
369   RPC_DISPATCH_FUNCTION func;
370   BOOL exception;
371   UUID *object_uuid;
372   NDR_SCONTEXT context_handle;
373   void *buf = msg->Buffer;
374
375   /* fail if the connection isn't bound with an interface */
376   if (UuidIsNil(&conn->ActiveInterface.SyntaxGUID, &status)) {
377     /* FIXME: should send BindNack instead */
378     response = RPCRT4_BuildFaultHeader(NDR_LOCAL_DATA_REPRESENTATION,
379                                        status);
380
381     RPCRT4_Send(conn, response, NULL, 0);
382     RPCRT4_FreeHeader(response);
383     return RPC_S_OK;
384   }
385
386   if (hdr->common.flags & RPC_FLG_OBJECT_UUID) {
387     object_uuid = (UUID*)(hdr + 1);
388   } else {
389     object_uuid = NULL;
390   }
391
392   sif = RPCRT4_find_interface(object_uuid, &conn->ActiveInterface, NULL, TRUE);
393   if (!sif) {
394     WARN("interface %s no longer registered, returning fault packet\n", debugstr_guid(&conn->ActiveInterface.SyntaxGUID));
395     response = RPCRT4_BuildFaultHeader(NDR_LOCAL_DATA_REPRESENTATION,
396                                        NCA_S_UNK_IF);
397
398     RPCRT4_Send(conn, response, NULL, 0);
399     RPCRT4_FreeHeader(response);
400     return RPC_S_OK;
401   }
402   msg->RpcInterfaceInformation = sif->If;
403   /* copy the endpoint vector from sif to msg so that midl-generated code will use it */
404   msg->ManagerEpv = sif->MgrEpv;
405   if (object_uuid != NULL) {
406     RPCRT4_SetBindingObject(msg->Handle, object_uuid);
407   }
408
409   /* find dispatch function */
410   msg->ProcNum = hdr->opnum;
411   if (sif->Flags & RPC_IF_OLE) {
412     /* native ole32 always gives us a dispatch table with a single entry
413     * (I assume that's a wrapper for IRpcStubBuffer::Invoke) */
414     func = *sif->If->DispatchTable->DispatchTable;
415   } else {
416     if (msg->ProcNum >= sif->If->DispatchTable->DispatchTableCount) {
417       WARN("invalid procnum (%d/%d)\n", msg->ProcNum, sif->If->DispatchTable->DispatchTableCount);
418       response = RPCRT4_BuildFaultHeader(NDR_LOCAL_DATA_REPRESENTATION,
419                                          NCA_S_OP_RNG_ERROR);
420
421       RPCRT4_Send(conn, response, NULL, 0);
422       RPCRT4_FreeHeader(response);
423     }
424     func = sif->If->DispatchTable->DispatchTable[msg->ProcNum];
425   }
426
427   /* put in the drep. FIXME: is this more universally applicable?
428     perhaps we should move this outward... */
429   msg->DataRepresentation =
430     MAKELONG( MAKEWORD(hdr->common.drep[0], hdr->common.drep[1]),
431               MAKEWORD(hdr->common.drep[2], hdr->common.drep[3]));
432
433   exception = FALSE;
434
435   /* dispatch */
436   RPCRT4_SetThreadCurrentCallHandle(msg->Handle);
437   __TRY {
438     if (func) func(msg);
439   } __EXCEPT_ALL {
440     WARN("exception caught with code 0x%08x = %d\n", GetExceptionCode(), GetExceptionCode());
441     exception = TRUE;
442     if (GetExceptionCode() == STATUS_ACCESS_VIOLATION)
443       status = ERROR_NOACCESS;
444     else
445       status = GetExceptionCode();
446     response = RPCRT4_BuildFaultHeader(msg->DataRepresentation,
447                                        RPC2NCA_STATUS(status));
448   } __ENDTRY
449     RPCRT4_SetThreadCurrentCallHandle(NULL);
450
451   /* release any unmarshalled context handles */
452   while ((context_handle = RPCRT4_PopThreadContextHandle()) != NULL)
453     RpcServerAssoc_ReleaseContextHandle(conn->server_binding->Assoc, context_handle, TRUE);
454
455   if (!exception)
456     response = RPCRT4_BuildResponseHeader(msg->DataRepresentation,
457                                           msg->BufferLength);
458
459   /* send response packet */
460   if (response) {
461     status = RPCRT4_Send(conn, response, exception ? NULL : msg->Buffer,
462                          exception ? 0 : msg->BufferLength);
463     RPCRT4_FreeHeader(response);
464   } else
465     ERR("out of memory\n");
466
467   msg->RpcInterfaceInformation = NULL;
468   RPCRT4_release_server_interface(sif);
469
470   if (msg->Buffer == buf) buf = NULL;
471   TRACE("freeing Buffer=%p\n", buf);
472   I_RpcFree(buf);
473
474   return status;
475 }
476
477 static RPC_STATUS process_auth3_packet(RpcConnection *conn,
478                                        RpcPktCommonHdr *hdr,
479                                        RPC_MESSAGE *msg,
480                                        unsigned char *auth_data,
481                                        ULONG auth_length)
482 {
483     RPC_STATUS status;
484
485     if (UuidIsNil(&conn->ActiveInterface.SyntaxGUID, &status) ||
486         !auth_length || msg->BufferLength != 0)
487         status = RPC_S_PROTOCOL_ERROR;
488     else
489     {
490         status = RPCRT4_ServerConnectionAuth(conn, FALSE,
491                                              (RpcAuthVerifier *)auth_data,
492                                              auth_length, NULL, NULL);
493     }
494
495     /* FIXME: client doesn't expect a response to this message so must store
496      * status in connection so that fault packet can be returned when next
497      * packet is received */
498
499     return RPC_S_OK;
500 }
501
502 static void RPCRT4_process_packet(RpcConnection* conn, RpcPktHdr* hdr,
503                                   RPC_MESSAGE* msg, unsigned char *auth_data,
504                                   ULONG auth_length)
505 {
506   RPC_STATUS status;
507
508   msg->Handle = (RPC_BINDING_HANDLE)conn->server_binding;
509
510   switch (hdr->common.ptype) {
511     case PKT_BIND:
512       TRACE("got bind packet\n");
513
514       status = process_bind_packet(conn, &hdr->bind, msg, auth_data,
515                                    auth_length);
516       break;
517
518     case PKT_REQUEST:
519       TRACE("got request packet\n");
520
521       status = process_request_packet(conn, &hdr->request, msg);
522       break;
523
524     case PKT_AUTH3:
525       TRACE("got auth3 packet\n");
526
527       status = process_auth3_packet(conn, &hdr->common, msg, auth_data,
528                                     auth_length);
529       break;
530     default:
531       FIXME("unhandled packet type %u\n", hdr->common.ptype);
532       break;
533   }
534
535   /* clean up */
536   I_RpcFree(msg->Buffer);
537   RPCRT4_FreeHeader(hdr);
538   HeapFree(GetProcessHeap(), 0, msg);
539   HeapFree(GetProcessHeap(), 0, auth_data);
540 }
541
542 static DWORD CALLBACK RPCRT4_worker_thread(LPVOID the_arg)
543 {
544   RpcPacket *pkt = the_arg;
545   RPCRT4_process_packet(pkt->conn, pkt->hdr, pkt->msg, pkt->auth_data,
546                         pkt->auth_length);
547   HeapFree(GetProcessHeap(), 0, pkt);
548   return 0;
549 }
550
551 static DWORD CALLBACK RPCRT4_io_thread(LPVOID the_arg)
552 {
553   RpcConnection* conn = the_arg;
554   RpcPktHdr *hdr;
555   RPC_MESSAGE *msg;
556   RPC_STATUS status;
557   RpcPacket *packet;
558   unsigned char *auth_data;
559   ULONG auth_length;
560
561   TRACE("(%p)\n", conn);
562
563   for (;;) {
564     msg = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(RPC_MESSAGE));
565     if (!msg) break;
566
567     status = RPCRT4_ReceiveWithAuth(conn, &hdr, msg, &auth_data, &auth_length);
568     if (status != RPC_S_OK) {
569       WARN("receive failed with error %x\n", status);
570       HeapFree(GetProcessHeap(), 0, msg);
571       break;
572     }
573
574     switch (hdr->common.ptype) {
575     case PKT_BIND:
576       TRACE("got bind packet\n");
577
578       status = process_bind_packet(conn, &hdr->bind, msg, auth_data,
579                                    auth_length);
580       break;
581
582     case PKT_REQUEST:
583       TRACE("got request packet\n");
584
585       packet = HeapAlloc(GetProcessHeap(), 0, sizeof(RpcPacket));
586       if (!packet) {
587         I_RpcFree(msg->Buffer);
588         RPCRT4_FreeHeader(hdr);
589         HeapFree(GetProcessHeap(), 0, msg);
590         HeapFree(GetProcessHeap(), 0, auth_data);
591         goto exit;
592       }
593       packet->conn = conn;
594       packet->hdr = hdr;
595       packet->msg = msg;
596       packet->auth_data = auth_data;
597       packet->auth_length = auth_length;
598       if (!QueueUserWorkItem(RPCRT4_worker_thread, packet, WT_EXECUTELONGFUNCTION)) {
599         ERR("couldn't queue work item for worker thread, error was %d\n", GetLastError());
600         HeapFree(GetProcessHeap(), 0, packet);
601         status = RPC_S_OUT_OF_RESOURCES;
602       } else {
603         continue;
604       }
605       break;
606
607     case PKT_AUTH3:
608       TRACE("got auth3 packet\n");
609
610       status = process_auth3_packet(conn, &hdr->common, msg, auth_data,
611                                     auth_length);
612       break;
613     default:
614       FIXME("unhandled packet type %u\n", hdr->common.ptype);
615       break;
616     }
617
618     I_RpcFree(msg->Buffer);
619     RPCRT4_FreeHeader(hdr);
620     HeapFree(GetProcessHeap(), 0, msg);
621     HeapFree(GetProcessHeap(), 0, auth_data);
622
623     if (status != RPC_S_OK) {
624       WARN("processing packet failed with error %u\n", status);
625       break;
626     }
627   }
628 exit:
629   RPCRT4_DestroyConnection(conn);
630   return 0;
631 }
632
633 void RPCRT4_new_client(RpcConnection* conn)
634 {
635   HANDLE thread = CreateThread(NULL, 0, RPCRT4_io_thread, conn, 0, NULL);
636   if (!thread) {
637     DWORD err = GetLastError();
638     ERR("failed to create thread, error=%08x\n", err);
639     RPCRT4_DestroyConnection(conn);
640   }
641   /* we could set conn->thread, but then we'd have to make the io_thread wait
642    * for that, otherwise the thread might finish, destroy the connection, and
643    * free the memory we'd write to before we did, causing crashes and stuff -
644    * so let's implement that later, when we really need conn->thread */
645
646   CloseHandle( thread );
647 }
648
649 static DWORD CALLBACK RPCRT4_server_thread(LPVOID the_arg)
650 {
651   int res;
652   unsigned int count;
653   void *objs = NULL;
654   RpcServerProtseq* cps = the_arg;
655   RpcConnection* conn;
656   BOOL set_ready_event = FALSE;
657
658   TRACE("(the_arg == ^%p)\n", the_arg);
659
660   for (;;) {
661     objs = cps->ops->get_wait_array(cps, objs, &count);
662
663     if (set_ready_event)
664     {
665         /* signal to function that changed state that we are now sync'ed */
666         SetEvent(cps->server_ready_event);
667         set_ready_event = FALSE;
668     }
669
670     /* start waiting */
671     res = cps->ops->wait_for_new_connection(cps, count, objs);
672
673     if (res == -1 || (res == 0 && !std_listen))
674     {
675       /* cleanup */
676       cps->ops->free_wait_array(cps, objs);
677       EnterCriticalSection(&cps->cs);
678       for (conn = cps->conn; conn; conn = conn->Next)
679         RPCRT4_CloseConnection(conn);
680       LeaveCriticalSection(&cps->cs);
681
682       if (res == 0 && !std_listen)
683         SetEvent(cps->server_ready_event);
684       break;
685     }
686     else if (res == 0)
687       set_ready_event = TRUE;
688   }
689   return 0;
690 }
691
692 /* tells the server thread that the state has changed and waits for it to
693  * make the changes */
694 static void RPCRT4_sync_with_server_thread(RpcServerProtseq *ps)
695 {
696   /* make sure we are the only thread sync'ing the server state, otherwise
697    * there is a race with the server thread setting an older state and setting
698    * the server_ready_event when the new state hasn't yet been applied */
699   WaitForSingleObject(ps->mgr_mutex, INFINITE);
700
701   ps->ops->signal_state_changed(ps);
702
703   /* wait for server thread to make the requested changes before returning */
704   WaitForSingleObject(ps->server_ready_event, INFINITE);
705
706   ReleaseMutex(ps->mgr_mutex);
707 }
708
709 static RPC_STATUS RPCRT4_start_listen_protseq(RpcServerProtseq *ps, BOOL auto_listen)
710 {
711   RPC_STATUS status = RPC_S_OK;
712   HANDLE server_thread;
713
714   EnterCriticalSection(&listen_cs);
715   if (ps->is_listening) goto done;
716
717   if (!ps->mgr_mutex) ps->mgr_mutex = CreateMutexW(NULL, FALSE, NULL);
718   if (!ps->server_ready_event) ps->server_ready_event = CreateEventW(NULL, FALSE, FALSE, NULL);
719   server_thread = CreateThread(NULL, 0, RPCRT4_server_thread, ps, 0, NULL);
720   if (!server_thread)
721   {
722     status = RPC_S_OUT_OF_RESOURCES;
723     goto done;
724   }
725   ps->is_listening = TRUE;
726   CloseHandle(server_thread);
727
728 done:
729   LeaveCriticalSection(&listen_cs);
730   return status;
731 }
732
733 static RPC_STATUS RPCRT4_start_listen(BOOL auto_listen)
734 {
735   RPC_STATUS status = RPC_S_ALREADY_LISTENING;
736   RpcServerProtseq *cps;
737
738   TRACE("\n");
739
740   EnterCriticalSection(&listen_cs);
741   if (auto_listen || (manual_listen_count++ == 0))
742   {
743     status = RPC_S_OK;
744     if (++listen_count == 1)
745       std_listen = TRUE;
746   }
747   LeaveCriticalSection(&listen_cs);
748
749   if (std_listen)
750   {
751     EnterCriticalSection(&server_cs);
752     LIST_FOR_EACH_ENTRY(cps, &protseqs, RpcServerProtseq, entry)
753     {
754       status = RPCRT4_start_listen_protseq(cps, TRUE);
755       if (status != RPC_S_OK)
756         break;
757       
758       /* make sure server is actually listening on the interface before
759        * returning */
760       RPCRT4_sync_with_server_thread(cps);
761     }
762     LeaveCriticalSection(&server_cs);
763   }
764
765   return status;
766 }
767
768 static void RPCRT4_stop_listen(BOOL auto_listen)
769 {
770   EnterCriticalSection(&listen_cs);
771   if (auto_listen || (--manual_listen_count == 0))
772   {
773     if (listen_count != 0 && --listen_count == 0) {
774       RpcServerProtseq *cps;
775
776       std_listen = FALSE;
777       LeaveCriticalSection(&listen_cs);
778
779       LIST_FOR_EACH_ENTRY(cps, &protseqs, RpcServerProtseq, entry)
780         RPCRT4_sync_with_server_thread(cps);
781
782       return;
783     }
784     assert(listen_count >= 0);
785   }
786   LeaveCriticalSection(&listen_cs);
787 }
788
789 static BOOL RPCRT4_protseq_is_endpoint_registered(RpcServerProtseq *protseq, const char *endpoint)
790 {
791   RpcConnection *conn;
792   EnterCriticalSection(&protseq->cs);
793   for (conn = protseq->conn; conn; conn = conn->Next)
794   {
795     if (!endpoint || !strcmp(endpoint, conn->Endpoint))
796       break;
797   }
798   LeaveCriticalSection(&protseq->cs);
799   return (conn != NULL);
800 }
801
802 static RPC_STATUS RPCRT4_use_protseq(RpcServerProtseq* ps, const char *endpoint)
803 {
804   RPC_STATUS status;
805
806   EnterCriticalSection(&ps->cs);
807
808   if (RPCRT4_protseq_is_endpoint_registered(ps, endpoint))
809     status = RPC_S_OK;
810   else
811     status = ps->ops->open_endpoint(ps, endpoint);
812
813   LeaveCriticalSection(&ps->cs);
814
815   if (status != RPC_S_OK)
816     return status;
817
818   if (std_listen)
819   {
820     status = RPCRT4_start_listen_protseq(ps, FALSE);
821     if (status == RPC_S_OK)
822       RPCRT4_sync_with_server_thread(ps);
823   }
824
825   return status;
826 }
827
828 /***********************************************************************
829  *             RpcServerInqBindings (RPCRT4.@)
830  */
831 RPC_STATUS WINAPI RpcServerInqBindings( RPC_BINDING_VECTOR** BindingVector )
832 {
833   RPC_STATUS status;
834   DWORD count;
835   RpcServerProtseq* ps;
836   RpcConnection* conn;
837
838   if (BindingVector)
839     TRACE("(*BindingVector == ^%p)\n", *BindingVector);
840   else
841     ERR("(BindingVector == NULL!!?)\n");
842
843   EnterCriticalSection(&server_cs);
844   /* count connections */
845   count = 0;
846   LIST_FOR_EACH_ENTRY(ps, &protseqs, RpcServerProtseq, entry) {
847     EnterCriticalSection(&ps->cs);
848     for (conn = ps->conn; conn; conn = conn->Next)
849       count++;
850     LeaveCriticalSection(&ps->cs);
851   }
852   if (count) {
853     /* export bindings */
854     *BindingVector = HeapAlloc(GetProcessHeap(), 0,
855                               sizeof(RPC_BINDING_VECTOR) +
856                               sizeof(RPC_BINDING_HANDLE)*(count-1));
857     (*BindingVector)->Count = count;
858     count = 0;
859     LIST_FOR_EACH_ENTRY(ps, &protseqs, RpcServerProtseq, entry) {
860       EnterCriticalSection(&ps->cs);
861       for (conn = ps->conn; conn; conn = conn->Next) {
862        RPCRT4_MakeBinding((RpcBinding**)&(*BindingVector)->BindingH[count],
863                           conn);
864        count++;
865       }
866       LeaveCriticalSection(&ps->cs);
867     }
868     status = RPC_S_OK;
869   } else {
870     *BindingVector = NULL;
871     status = RPC_S_NO_BINDINGS;
872   }
873   LeaveCriticalSection(&server_cs);
874   return status;
875 }
876
877 /***********************************************************************
878  *             RpcServerUseProtseqEpA (RPCRT4.@)
879  */
880 RPC_STATUS WINAPI RpcServerUseProtseqEpA( RPC_CSTR Protseq, UINT MaxCalls, RPC_CSTR Endpoint, LPVOID SecurityDescriptor )
881 {
882   RPC_POLICY policy;
883   
884   TRACE( "(%s,%u,%s,%p)\n", Protseq, MaxCalls, Endpoint, SecurityDescriptor );
885   
886   /* This should provide the default behaviour */
887   policy.Length        = sizeof( policy );
888   policy.EndpointFlags = 0;
889   policy.NICFlags      = 0;
890   
891   return RpcServerUseProtseqEpExA( Protseq, MaxCalls, Endpoint, SecurityDescriptor, &policy );
892 }
893
894 /***********************************************************************
895  *             RpcServerUseProtseqEpW (RPCRT4.@)
896  */
897 RPC_STATUS WINAPI RpcServerUseProtseqEpW( RPC_WSTR Protseq, UINT MaxCalls, RPC_WSTR Endpoint, LPVOID SecurityDescriptor )
898 {
899   RPC_POLICY policy;
900   
901   TRACE( "(%s,%u,%s,%p)\n", debugstr_w( Protseq ), MaxCalls, debugstr_w( Endpoint ), SecurityDescriptor );
902   
903   /* This should provide the default behaviour */
904   policy.Length        = sizeof( policy );
905   policy.EndpointFlags = 0;
906   policy.NICFlags      = 0;
907   
908   return RpcServerUseProtseqEpExW( Protseq, MaxCalls, Endpoint, SecurityDescriptor, &policy );
909 }
910
911 /***********************************************************************
912  *             alloc_serverprotoseq (internal)
913  *
914  * Must be called with server_cs held.
915  */
916 static RPC_STATUS alloc_serverprotoseq(UINT MaxCalls, const char *Protseq, RpcServerProtseq **ps)
917 {
918   const struct protseq_ops *ops = rpcrt4_get_protseq_ops(Protseq);
919
920   if (!ops)
921   {
922     FIXME("protseq %s not supported\n", debugstr_a(Protseq));
923     return RPC_S_PROTSEQ_NOT_SUPPORTED;
924   }
925
926   *ps = ops->alloc();
927   if (!*ps)
928     return RPC_S_OUT_OF_RESOURCES;
929   (*ps)->MaxCalls = MaxCalls;
930   (*ps)->Protseq = RPCRT4_strdupA(Protseq);
931   (*ps)->ops = ops;
932   (*ps)->MaxCalls = 0;
933   (*ps)->conn = NULL;
934   InitializeCriticalSection(&(*ps)->cs);
935   (*ps)->is_listening = FALSE;
936   (*ps)->mgr_mutex = NULL;
937   (*ps)->server_ready_event = NULL;
938
939   list_add_head(&protseqs, &(*ps)->entry);
940
941   TRACE("new protseq %p created for %s\n", *ps, Protseq);
942
943   return RPC_S_OK;
944 }
945
946 /* must be called with server_cs held */
947 static void destroy_serverprotoseq(RpcServerProtseq *ps)
948 {
949     RPCRT4_strfree(ps->Protseq);
950     DeleteCriticalSection(&ps->cs);
951     CloseHandle(ps->mgr_mutex);
952     CloseHandle(ps->server_ready_event);
953     list_remove(&ps->entry);
954     HeapFree(GetProcessHeap(), 0, ps);
955 }
956
957 /* Finds a given protseq or creates a new one if one doesn't already exist */
958 static RPC_STATUS RPCRT4_get_or_create_serverprotseq(UINT MaxCalls, const char *Protseq, RpcServerProtseq **ps)
959 {
960     RPC_STATUS status;
961     RpcServerProtseq *cps;
962
963     EnterCriticalSection(&server_cs);
964
965     LIST_FOR_EACH_ENTRY(cps, &protseqs, RpcServerProtseq, entry)
966         if (!strcmp(cps->Protseq, Protseq))
967         {
968             TRACE("found existing protseq object for %s\n", Protseq);
969             *ps = cps;
970             LeaveCriticalSection(&server_cs);
971             return S_OK;
972         }
973
974     status = alloc_serverprotoseq(MaxCalls, Protseq, ps);
975
976     LeaveCriticalSection(&server_cs);
977
978     return status;
979 }
980
981 /***********************************************************************
982  *             RpcServerUseProtseqEpExA (RPCRT4.@)
983  */
984 RPC_STATUS WINAPI RpcServerUseProtseqEpExA( RPC_CSTR Protseq, UINT MaxCalls, RPC_CSTR Endpoint, LPVOID SecurityDescriptor,
985                                             PRPC_POLICY lpPolicy )
986 {
987   RpcServerProtseq* ps;
988   RPC_STATUS status;
989
990   TRACE("(%s,%u,%s,%p,{%u,%u,%u})\n", debugstr_a((const char *)Protseq),
991        MaxCalls, debugstr_a((const char *)Endpoint), SecurityDescriptor,
992        lpPolicy->Length, lpPolicy->EndpointFlags, lpPolicy->NICFlags );
993
994   status = RPCRT4_get_or_create_serverprotseq(MaxCalls, (const char *)Protseq, &ps);
995   if (status != RPC_S_OK)
996     return status;
997
998   return RPCRT4_use_protseq(ps, (const char *)Endpoint);
999 }
1000
1001 /***********************************************************************
1002  *             RpcServerUseProtseqEpExW (RPCRT4.@)
1003  */
1004 RPC_STATUS WINAPI RpcServerUseProtseqEpExW( RPC_WSTR Protseq, UINT MaxCalls, RPC_WSTR Endpoint, LPVOID SecurityDescriptor,
1005                                             PRPC_POLICY lpPolicy )
1006 {
1007   RpcServerProtseq* ps;
1008   RPC_STATUS status;
1009   LPSTR ProtseqA;
1010   LPSTR EndpointA;
1011
1012   TRACE("(%s,%u,%s,%p,{%u,%u,%u})\n", debugstr_w( Protseq ), MaxCalls,
1013        debugstr_w( Endpoint ), SecurityDescriptor,
1014        lpPolicy->Length, lpPolicy->EndpointFlags, lpPolicy->NICFlags );
1015
1016   ProtseqA = RPCRT4_strdupWtoA(Protseq);
1017   status = RPCRT4_get_or_create_serverprotseq(MaxCalls, ProtseqA, &ps);
1018   RPCRT4_strfree(ProtseqA);
1019   if (status != RPC_S_OK)
1020     return status;
1021
1022   EndpointA = RPCRT4_strdupWtoA(Endpoint);
1023   status = RPCRT4_use_protseq(ps, EndpointA);
1024   RPCRT4_strfree(EndpointA);
1025   return status;
1026 }
1027
1028 /***********************************************************************
1029  *             RpcServerUseProtseqA (RPCRT4.@)
1030  */
1031 RPC_STATUS WINAPI RpcServerUseProtseqA(RPC_CSTR Protseq, unsigned int MaxCalls, void *SecurityDescriptor)
1032 {
1033   RPC_STATUS status;
1034   RpcServerProtseq* ps;
1035
1036   TRACE("(Protseq == %s, MaxCalls == %d, SecurityDescriptor == ^%p)\n", debugstr_a((char*)Protseq), MaxCalls, SecurityDescriptor);
1037
1038   status = RPCRT4_get_or_create_serverprotseq(MaxCalls, (const char *)Protseq, &ps);
1039   if (status != RPC_S_OK)
1040     return status;
1041
1042   return RPCRT4_use_protseq(ps, NULL);
1043 }
1044
1045 /***********************************************************************
1046  *             RpcServerUseProtseqW (RPCRT4.@)
1047  */
1048 RPC_STATUS WINAPI RpcServerUseProtseqW(RPC_WSTR Protseq, unsigned int MaxCalls, void *SecurityDescriptor)
1049 {
1050   RPC_STATUS status;
1051   RpcServerProtseq* ps;
1052   LPSTR ProtseqA;
1053
1054   TRACE("Protseq == %s, MaxCalls == %d, SecurityDescriptor == ^%p)\n", debugstr_w(Protseq), MaxCalls, SecurityDescriptor);
1055
1056   ProtseqA = RPCRT4_strdupWtoA(Protseq);
1057   status = RPCRT4_get_or_create_serverprotseq(MaxCalls, ProtseqA, &ps);
1058   RPCRT4_strfree(ProtseqA);
1059   if (status != RPC_S_OK)
1060     return status;
1061
1062   return RPCRT4_use_protseq(ps, NULL);
1063 }
1064
1065 void RPCRT4_destroy_all_protseqs(void)
1066 {
1067     RpcServerProtseq *cps, *cursor2;
1068
1069     if (listen_count != 0)
1070         std_listen = FALSE;
1071
1072     EnterCriticalSection(&server_cs);
1073     LIST_FOR_EACH_ENTRY_SAFE(cps, cursor2, &protseqs, RpcServerProtseq, entry)
1074     {
1075         if (listen_count != 0)
1076             RPCRT4_sync_with_server_thread(cps);
1077         destroy_serverprotoseq(cps);
1078     }
1079     LeaveCriticalSection(&server_cs);
1080 }
1081
1082 /***********************************************************************
1083  *             RpcServerRegisterIf (RPCRT4.@)
1084  */
1085 RPC_STATUS WINAPI RpcServerRegisterIf( RPC_IF_HANDLE IfSpec, UUID* MgrTypeUuid, RPC_MGR_EPV* MgrEpv )
1086 {
1087   TRACE("(%p,%s,%p)\n", IfSpec, debugstr_guid(MgrTypeUuid), MgrEpv);
1088   return RpcServerRegisterIf2( IfSpec, MgrTypeUuid, MgrEpv, 0, RPC_C_LISTEN_MAX_CALLS_DEFAULT, (UINT)-1, NULL );
1089 }
1090
1091 /***********************************************************************
1092  *             RpcServerRegisterIfEx (RPCRT4.@)
1093  */
1094 RPC_STATUS WINAPI RpcServerRegisterIfEx( RPC_IF_HANDLE IfSpec, UUID* MgrTypeUuid, RPC_MGR_EPV* MgrEpv,
1095                        UINT Flags, UINT MaxCalls, RPC_IF_CALLBACK_FN* IfCallbackFn )
1096 {
1097   TRACE("(%p,%s,%p,%u,%u,%p)\n", IfSpec, debugstr_guid(MgrTypeUuid), MgrEpv, Flags, MaxCalls, IfCallbackFn);
1098   return RpcServerRegisterIf2( IfSpec, MgrTypeUuid, MgrEpv, Flags, MaxCalls, (UINT)-1, IfCallbackFn );
1099 }
1100
1101 /***********************************************************************
1102  *             RpcServerRegisterIf2 (RPCRT4.@)
1103  */
1104 RPC_STATUS WINAPI RpcServerRegisterIf2( RPC_IF_HANDLE IfSpec, UUID* MgrTypeUuid, RPC_MGR_EPV* MgrEpv,
1105                       UINT Flags, UINT MaxCalls, UINT MaxRpcSize, RPC_IF_CALLBACK_FN* IfCallbackFn )
1106 {
1107   PRPC_SERVER_INTERFACE If = IfSpec;
1108   RpcServerInterface* sif;
1109   unsigned int i;
1110
1111   TRACE("(%p,%s,%p,%u,%u,%u,%p)\n", IfSpec, debugstr_guid(MgrTypeUuid), MgrEpv, Flags, MaxCalls,
1112          MaxRpcSize, IfCallbackFn);
1113   TRACE(" interface id: %s %d.%d\n", debugstr_guid(&If->InterfaceId.SyntaxGUID),
1114                                      If->InterfaceId.SyntaxVersion.MajorVersion,
1115                                      If->InterfaceId.SyntaxVersion.MinorVersion);
1116   TRACE(" transfer syntax: %s %d.%d\n", debugstr_guid(&If->TransferSyntax.SyntaxGUID),
1117                                         If->TransferSyntax.SyntaxVersion.MajorVersion,
1118                                         If->TransferSyntax.SyntaxVersion.MinorVersion);
1119   TRACE(" dispatch table: %p\n", If->DispatchTable);
1120   if (If->DispatchTable) {
1121     TRACE("  dispatch table count: %d\n", If->DispatchTable->DispatchTableCount);
1122     for (i=0; i<If->DispatchTable->DispatchTableCount; i++) {
1123       TRACE("   entry %d: %p\n", i, If->DispatchTable->DispatchTable[i]);
1124     }
1125     TRACE("  reserved: %ld\n", If->DispatchTable->Reserved);
1126   }
1127   TRACE(" protseq endpoint count: %d\n", If->RpcProtseqEndpointCount);
1128   TRACE(" default manager epv: %p\n", If->DefaultManagerEpv);
1129   TRACE(" interpreter info: %p\n", If->InterpreterInfo);
1130
1131   sif = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(RpcServerInterface));
1132   sif->If           = If;
1133   if (MgrTypeUuid) {
1134     sif->MgrTypeUuid = *MgrTypeUuid;
1135     sif->MgrEpv       = MgrEpv;
1136   } else {
1137     memset(&sif->MgrTypeUuid, 0, sizeof(UUID));
1138     sif->MgrEpv       = If->DefaultManagerEpv;
1139   }
1140   sif->Flags        = Flags;
1141   sif->MaxCalls     = MaxCalls;
1142   sif->MaxRpcSize   = MaxRpcSize;
1143   sif->IfCallbackFn = IfCallbackFn;
1144
1145   EnterCriticalSection(&server_cs);
1146   list_add_head(&server_interfaces, &sif->entry);
1147   LeaveCriticalSection(&server_cs);
1148
1149   if (sif->Flags & RPC_IF_AUTOLISTEN)
1150       RPCRT4_start_listen(TRUE);
1151
1152   return RPC_S_OK;
1153 }
1154
1155 /***********************************************************************
1156  *             RpcServerUnregisterIf (RPCRT4.@)
1157  */
1158 RPC_STATUS WINAPI RpcServerUnregisterIf( RPC_IF_HANDLE IfSpec, UUID* MgrTypeUuid, UINT WaitForCallsToComplete )
1159 {
1160   PRPC_SERVER_INTERFACE If = IfSpec;
1161   HANDLE event = NULL;
1162   BOOL found = FALSE;
1163   BOOL completed = TRUE;
1164   RpcServerInterface *cif;
1165   RPC_STATUS status;
1166
1167   TRACE("(IfSpec == (RPC_IF_HANDLE)^%p (%s), MgrTypeUuid == %s, WaitForCallsToComplete == %u)\n",
1168     IfSpec, debugstr_guid(&If->InterfaceId.SyntaxGUID), debugstr_guid(MgrTypeUuid), WaitForCallsToComplete);
1169
1170   EnterCriticalSection(&server_cs);
1171   LIST_FOR_EACH_ENTRY(cif, &server_interfaces, RpcServerInterface, entry) {
1172     if ((!IfSpec || !memcmp(&If->InterfaceId, &cif->If->InterfaceId, sizeof(RPC_SYNTAX_IDENTIFIER))) &&
1173         UuidEqual(MgrTypeUuid, &cif->MgrTypeUuid, &status)) {
1174       list_remove(&cif->entry);
1175       TRACE("unregistering cif %p\n", cif);
1176       if (cif->CurrentCalls) {
1177         completed = FALSE;
1178         cif->Delete = TRUE;
1179         if (WaitForCallsToComplete)
1180           cif->CallsCompletedEvent = event = CreateEventW(NULL, FALSE, FALSE, NULL);
1181       }
1182       found = TRUE;
1183       break;
1184     }
1185   }
1186   LeaveCriticalSection(&server_cs);
1187
1188   if (!found) {
1189     ERR("not found for object %s\n", debugstr_guid(MgrTypeUuid));
1190     return RPC_S_UNKNOWN_IF;
1191   }
1192
1193   if (completed)
1194     HeapFree(GetProcessHeap(), 0, cif);
1195   else if (event) {
1196     /* sif will be freed when the last call is completed, so be careful not to
1197      * touch that memory here as that could happen before we get here */
1198     WaitForSingleObject(event, INFINITE);
1199     CloseHandle(event);
1200   }
1201
1202   return RPC_S_OK;
1203 }
1204
1205 /***********************************************************************
1206  *             RpcServerUnregisterIfEx (RPCRT4.@)
1207  */
1208 RPC_STATUS WINAPI RpcServerUnregisterIfEx( RPC_IF_HANDLE IfSpec, UUID* MgrTypeUuid, int RundownContextHandles )
1209 {
1210   FIXME("(IfSpec == (RPC_IF_HANDLE)^%p, MgrTypeUuid == %s, RundownContextHandles == %d): stub\n",
1211     IfSpec, debugstr_guid(MgrTypeUuid), RundownContextHandles);
1212
1213   return RPC_S_OK;
1214 }
1215
1216 /***********************************************************************
1217  *             RpcObjectSetType (RPCRT4.@)
1218  *
1219  * PARAMS
1220  *   ObjUuid  [I] "Object" UUID
1221  *   TypeUuid [I] "Type" UUID
1222  *
1223  * RETURNS
1224  *   RPC_S_OK                 The call succeeded
1225  *   RPC_S_INVALID_OBJECT     The provided object (nil) is not valid
1226  *   RPC_S_ALREADY_REGISTERED The provided object is already registered
1227  *
1228  * Maps "Object" UUIDs to "Type" UUID's.  Passing the nil UUID as the type
1229  * resets the mapping for the specified object UUID to nil (the default).
1230  * The nil object is always associated with the nil type and cannot be
1231  * reassigned.  Servers can support multiple implementations on the same
1232  * interface by registering different end-point vectors for the different
1233  * types.  There's no need to call this if a server only supports the nil
1234  * type, as is typical.
1235  */
1236 RPC_STATUS WINAPI RpcObjectSetType( UUID* ObjUuid, UUID* TypeUuid )
1237 {
1238   RpcObjTypeMap *map = RpcObjTypeMaps, *prev = NULL;
1239   RPC_STATUS dummy;
1240
1241   TRACE("(ObjUUID == %s, TypeUuid == %s).\n", debugstr_guid(ObjUuid), debugstr_guid(TypeUuid));
1242   if ((! ObjUuid) || UuidIsNil(ObjUuid, &dummy)) {
1243     /* nil uuid cannot be remapped */
1244     return RPC_S_INVALID_OBJECT;
1245   }
1246
1247   /* find the mapping for this object if there is one ... */
1248   while (map) {
1249     if (! UuidCompare(ObjUuid, &map->Object, &dummy)) break;
1250     prev = map;
1251     map = map->next;
1252   }
1253   if ((! TypeUuid) || UuidIsNil(TypeUuid, &dummy)) {
1254     /* ... and drop it from the list */
1255     if (map) {
1256       if (prev) 
1257         prev->next = map->next;
1258       else
1259         RpcObjTypeMaps = map->next;
1260       HeapFree(GetProcessHeap(), 0, map);
1261     }
1262   } else {
1263     /* ... , fail if we found it ... */
1264     if (map)
1265       return RPC_S_ALREADY_REGISTERED;
1266     /* ... otherwise create a new one and add it in. */
1267     map = HeapAlloc(GetProcessHeap(), 0, sizeof(RpcObjTypeMap));
1268     map->Object = *ObjUuid;
1269     map->Type = *TypeUuid;
1270     map->next = NULL;
1271     if (prev)
1272       prev->next = map; /* prev is the last map in the linklist */
1273     else
1274       RpcObjTypeMaps = map;
1275   }
1276
1277   return RPC_S_OK;
1278 }
1279
1280 struct rpc_server_registered_auth_info
1281 {
1282     struct list entry;
1283     TimeStamp exp;
1284     CredHandle cred;
1285     ULONG max_token;
1286     USHORT auth_type;
1287 };
1288
1289 RPC_STATUS RPCRT4_ServerGetRegisteredAuthInfo(
1290     USHORT auth_type, CredHandle *cred, TimeStamp *exp, ULONG *max_token)
1291 {
1292     RPC_STATUS status = RPC_S_UNKNOWN_AUTHN_SERVICE;
1293     struct rpc_server_registered_auth_info *auth_info;
1294
1295     EnterCriticalSection(&server_auth_info_cs);
1296     LIST_FOR_EACH_ENTRY(auth_info, &server_registered_auth_info, struct rpc_server_registered_auth_info, entry)
1297     {
1298         if (auth_info->auth_type == auth_type)
1299         {
1300             *cred = auth_info->cred;
1301             *exp = auth_info->exp;
1302             *max_token = auth_info->max_token;
1303             status = RPC_S_OK;
1304             break;
1305         }
1306     }
1307     LeaveCriticalSection(&server_auth_info_cs);
1308
1309     return status;
1310 }
1311
1312 void RPCRT4_ServerFreeAllRegisteredAuthInfo(void)
1313 {
1314     struct rpc_server_registered_auth_info *auth_info, *cursor2;
1315
1316     EnterCriticalSection(&server_auth_info_cs);
1317     LIST_FOR_EACH_ENTRY_SAFE(auth_info, cursor2, &server_registered_auth_info, struct rpc_server_registered_auth_info, entry)
1318     {
1319         FreeCredentialsHandle(&auth_info->cred);
1320         HeapFree(GetProcessHeap(), 0, auth_info);
1321     }
1322     LeaveCriticalSection(&server_auth_info_cs);
1323 }
1324
1325 /***********************************************************************
1326  *             RpcServerRegisterAuthInfoA (RPCRT4.@)
1327  */
1328 RPC_STATUS WINAPI RpcServerRegisterAuthInfoA( RPC_CSTR ServerPrincName, ULONG AuthnSvc, RPC_AUTH_KEY_RETRIEVAL_FN GetKeyFn,
1329                             LPVOID Arg )
1330 {
1331     SECURITY_STATUS sec_status;
1332     CredHandle cred;
1333     TimeStamp exp;
1334     ULONG package_count;
1335     ULONG i;
1336     PSecPkgInfoA packages;
1337     ULONG max_token;
1338     struct rpc_server_registered_auth_info *auth_info;
1339
1340     TRACE("(%s,%u,%p,%p)\n", ServerPrincName, AuthnSvc, GetKeyFn, Arg);
1341
1342     sec_status = EnumerateSecurityPackagesA(&package_count, &packages);
1343     if (sec_status != SEC_E_OK)
1344     {
1345         ERR("EnumerateSecurityPackagesA failed with error 0x%08x\n",
1346             sec_status);
1347         return RPC_S_SEC_PKG_ERROR;
1348     }
1349
1350     for (i = 0; i < package_count; i++)
1351         if (packages[i].wRPCID == AuthnSvc)
1352             break;
1353
1354     if (i == package_count)
1355     {
1356         WARN("unsupported AuthnSvc %u\n", AuthnSvc);
1357         FreeContextBuffer(packages);
1358         return RPC_S_UNKNOWN_AUTHN_SERVICE;
1359     }
1360     TRACE("found package %s for service %u\n", packages[i].Name,
1361           AuthnSvc);
1362     sec_status = AcquireCredentialsHandleA((SEC_CHAR *)ServerPrincName,
1363                                            packages[i].Name,
1364                                            SECPKG_CRED_INBOUND, NULL, NULL,
1365                                            NULL, NULL, &cred, &exp);
1366     max_token = packages[i].cbMaxToken;
1367     FreeContextBuffer(packages);
1368     if (sec_status != SEC_E_OK)
1369         return RPC_S_SEC_PKG_ERROR;
1370
1371     auth_info = HeapAlloc(GetProcessHeap(), 0, sizeof(*auth_info));
1372     if (!auth_info)
1373     {
1374         FreeCredentialsHandle(&cred);
1375         return RPC_S_OUT_OF_RESOURCES;
1376     }
1377
1378     auth_info->exp = exp;
1379     auth_info->cred = cred;
1380     auth_info->max_token = max_token;
1381     auth_info->auth_type = AuthnSvc;
1382
1383     EnterCriticalSection(&server_auth_info_cs);
1384     list_add_tail(&server_registered_auth_info, &auth_info->entry);
1385     LeaveCriticalSection(&server_auth_info_cs);
1386
1387     return RPC_S_OK;
1388 }
1389
1390 /***********************************************************************
1391  *             RpcServerRegisterAuthInfoW (RPCRT4.@)
1392  */
1393 RPC_STATUS WINAPI RpcServerRegisterAuthInfoW( RPC_WSTR ServerPrincName, ULONG AuthnSvc, RPC_AUTH_KEY_RETRIEVAL_FN GetKeyFn,
1394                             LPVOID Arg )
1395 {
1396     SECURITY_STATUS sec_status;
1397     CredHandle cred;
1398     TimeStamp exp;
1399     ULONG package_count;
1400     ULONG i;
1401     PSecPkgInfoW packages;
1402     ULONG max_token;
1403     struct rpc_server_registered_auth_info *auth_info;
1404
1405     TRACE("(%s,%u,%p,%p)\n", debugstr_w(ServerPrincName), AuthnSvc, GetKeyFn, Arg);
1406
1407     sec_status = EnumerateSecurityPackagesW(&package_count, &packages);
1408     if (sec_status != SEC_E_OK)
1409     {
1410         ERR("EnumerateSecurityPackagesW failed with error 0x%08x\n",
1411             sec_status);
1412         return RPC_S_SEC_PKG_ERROR;
1413     }
1414
1415     for (i = 0; i < package_count; i++)
1416         if (packages[i].wRPCID == AuthnSvc)
1417             break;
1418
1419     if (i == package_count)
1420     {
1421         WARN("unsupported AuthnSvc %u\n", AuthnSvc);
1422         FreeContextBuffer(packages);
1423         return RPC_S_UNKNOWN_AUTHN_SERVICE;
1424     }
1425     TRACE("found package %s for service %u\n", debugstr_w(packages[i].Name),
1426           AuthnSvc);
1427     sec_status = AcquireCredentialsHandleW((SEC_WCHAR *)ServerPrincName,
1428                                            packages[i].Name,
1429                                            SECPKG_CRED_INBOUND, NULL, NULL,
1430                                            NULL, NULL, &cred, &exp);
1431     max_token = packages[i].cbMaxToken;
1432     FreeContextBuffer(packages);
1433     if (sec_status != SEC_E_OK)
1434         return RPC_S_SEC_PKG_ERROR;
1435
1436     auth_info = HeapAlloc(GetProcessHeap(), 0, sizeof(*auth_info));
1437     if (!auth_info)
1438     {
1439         FreeCredentialsHandle(&cred);
1440         return RPC_S_OUT_OF_RESOURCES;
1441     }
1442
1443     auth_info->exp = exp;
1444     auth_info->cred = cred;
1445     auth_info->max_token = max_token;
1446     auth_info->auth_type = AuthnSvc;
1447
1448     EnterCriticalSection(&server_auth_info_cs);
1449     list_add_tail(&server_registered_auth_info, &auth_info->entry);
1450     LeaveCriticalSection(&server_auth_info_cs);
1451
1452     return RPC_S_OK;
1453 }
1454
1455 /***********************************************************************
1456  *             RpcServerListen (RPCRT4.@)
1457  */
1458 RPC_STATUS WINAPI RpcServerListen( UINT MinimumCallThreads, UINT MaxCalls, UINT DontWait )
1459 {
1460   RPC_STATUS status = RPC_S_OK;
1461
1462   TRACE("(%u,%u,%u)\n", MinimumCallThreads, MaxCalls, DontWait);
1463
1464   if (list_empty(&protseqs))
1465     return RPC_S_NO_PROTSEQS_REGISTERED;
1466
1467   status = RPCRT4_start_listen(FALSE);
1468
1469   if (DontWait || (status != RPC_S_OK)) return status;
1470
1471   return RpcMgmtWaitServerListen();
1472 }
1473
1474 /***********************************************************************
1475  *             RpcMgmtServerWaitListen (RPCRT4.@)
1476  */
1477 RPC_STATUS WINAPI RpcMgmtWaitServerListen( void )
1478 {
1479   TRACE("()\n");
1480
1481   EnterCriticalSection(&listen_cs);
1482
1483   if (!std_listen) {
1484     LeaveCriticalSection(&listen_cs);
1485     return RPC_S_NOT_LISTENING;
1486   }
1487   
1488   LeaveCriticalSection(&listen_cs);
1489
1490   FIXME("not waiting for server calls to finish\n");
1491
1492   return RPC_S_OK;
1493 }
1494
1495 /***********************************************************************
1496  *             RpcMgmtStopServerListening (RPCRT4.@)
1497  */
1498 RPC_STATUS WINAPI RpcMgmtStopServerListening ( RPC_BINDING_HANDLE Binding )
1499 {
1500   TRACE("(Binding == (RPC_BINDING_HANDLE)^%p)\n", Binding);
1501
1502   if (Binding) {
1503     FIXME("client-side invocation not implemented.\n");
1504     return RPC_S_WRONG_KIND_OF_BINDING;
1505   }
1506   
1507   RPCRT4_stop_listen(FALSE);
1508
1509   return RPC_S_OK;
1510 }
1511
1512 /***********************************************************************
1513  *             RpcMgmtEnableIdleCleanup (RPCRT4.@)
1514  */
1515 RPC_STATUS WINAPI RpcMgmtEnableIdleCleanup(void)
1516 {
1517     FIXME("(): stub\n");
1518     return RPC_S_OK;
1519 }
1520
1521 /***********************************************************************
1522  *             I_RpcServerStartListening (RPCRT4.@)
1523  */
1524 RPC_STATUS WINAPI I_RpcServerStartListening( HWND hWnd )
1525 {
1526   FIXME( "(%p): stub\n", hWnd );
1527
1528   return RPC_S_OK;
1529 }
1530
1531 /***********************************************************************
1532  *             I_RpcServerStopListening (RPCRT4.@)
1533  */
1534 RPC_STATUS WINAPI I_RpcServerStopListening( void )
1535 {
1536   FIXME( "(): stub\n" );
1537
1538   return RPC_S_OK;
1539 }
1540
1541 /***********************************************************************
1542  *             I_RpcWindowProc (RPCRT4.@)
1543  */
1544 UINT WINAPI I_RpcWindowProc( void *hWnd, UINT Message, UINT wParam, ULONG lParam )
1545 {
1546   FIXME( "(%p,%08x,%08x,%08x): stub\n", hWnd, Message, wParam, lParam );
1547
1548   return 0;
1549 }
1550
1551 /***********************************************************************
1552  *             RpcMgmtInqIfIds (RPCRT4.@)
1553  */
1554 RPC_STATUS WINAPI RpcMgmtInqIfIds(RPC_BINDING_HANDLE Binding, RPC_IF_ID_VECTOR **IfIdVector)
1555 {
1556   FIXME("(%p,%p): stub\n", Binding, IfIdVector);
1557   return RPC_S_INVALID_BINDING;
1558 }
1559
1560 /***********************************************************************
1561  *             RpcMgmtInqStats (RPCRT4.@)
1562  */
1563 RPC_STATUS WINAPI RpcMgmtInqStats(RPC_BINDING_HANDLE Binding, RPC_STATS_VECTOR **Statistics)
1564 {
1565   RPC_STATS_VECTOR *stats;
1566
1567   FIXME("(%p,%p)\n", Binding, Statistics);
1568
1569   if ((stats = HeapAlloc(GetProcessHeap(), 0, sizeof(RPC_STATS_VECTOR))))
1570   {
1571     stats->Count = 1;
1572     stats->Stats[0] = 0;
1573     *Statistics = stats;
1574     return RPC_S_OK;
1575   }
1576   return RPC_S_OUT_OF_RESOURCES;
1577 }
1578
1579 /***********************************************************************
1580  *             RpcMgmtStatsVectorFree (RPCRT4.@)
1581  */
1582 RPC_STATUS WINAPI RpcMgmtStatsVectorFree(RPC_STATS_VECTOR **StatsVector)
1583 {
1584   FIXME("(%p)\n", StatsVector);
1585
1586   if (StatsVector)
1587   {
1588     HeapFree(GetProcessHeap(), 0, *StatsVector);
1589     *StatsVector = NULL;
1590   }
1591   return RPC_S_OK;
1592 }
1593
1594 /***********************************************************************
1595  *             RpcMgmtEpEltInqBegin (RPCRT4.@)
1596  */
1597 RPC_STATUS WINAPI RpcMgmtEpEltInqBegin(RPC_BINDING_HANDLE Binding, ULONG InquiryType,
1598     RPC_IF_ID *IfId, ULONG VersOption, UUID *ObjectUuid, RPC_EP_INQ_HANDLE* InquiryContext)
1599 {
1600   FIXME("(%p,%u,%p,%u,%p,%p): stub\n",
1601         Binding, InquiryType, IfId, VersOption, ObjectUuid, InquiryContext);
1602   return RPC_S_INVALID_BINDING;
1603 }
1604
1605 /***********************************************************************
1606  *             RpcMgmtIsServerListening (RPCRT4.@)
1607  */
1608 RPC_STATUS WINAPI RpcMgmtIsServerListening(RPC_BINDING_HANDLE Binding)
1609 {
1610   FIXME("(%p): stub\n", Binding);
1611   return RPC_S_INVALID_BINDING;
1612 }
1613
1614 /***********************************************************************
1615  *             RpcMgmtSetServerStackSize (RPCRT4.@)
1616  */
1617 RPC_STATUS WINAPI RpcMgmtSetServerStackSize(ULONG ThreadStackSize)
1618 {
1619   FIXME("(0x%x): stub\n", ThreadStackSize);
1620   return RPC_S_OK;
1621 }
1622
1623 /***********************************************************************
1624  *             I_RpcGetCurrentCallHandle (RPCRT4.@)
1625  */
1626 RPC_BINDING_HANDLE WINAPI I_RpcGetCurrentCallHandle(void)
1627 {
1628     TRACE("\n");
1629     return RPCRT4_GetThreadCurrentCallHandle();
1630 }