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