rpcrt4: Move association code into a separate file.
[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  *
7  * This library is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Lesser General Public
9  * License as published by the Free Software Foundation; either
10  * version 2.1 of the License, or (at your option) any later version.
11  *
12  * This library is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General Public
18  * License along with this library; if not, write to the Free Software
19  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
20  *
21  * TODO:
22  *  - a whole lot
23  */
24
25 #include "config.h"
26 #include "wine/port.h"
27
28 #include <stdarg.h>
29 #include <stdio.h>
30 #include <string.h>
31 #include <assert.h>
32
33 #include "windef.h"
34 #include "winbase.h"
35 #include "winerror.h"
36
37 #include "rpc.h"
38 #include "rpcndr.h"
39 #include "excpt.h"
40
41 #include "wine/debug.h"
42 #include "wine/exception.h"
43
44 #include "rpc_server.h"
45 #include "rpc_assoc.h"
46 #include "rpc_message.h"
47 #include "rpc_defs.h"
48 #include "ncastatus.h"
49
50 WINE_DEFAULT_DEBUG_CHANNEL(rpc);
51
52 typedef struct _RpcPacket
53 {
54   struct _RpcConnection* conn;
55   RpcPktHdr* hdr;
56   RPC_MESSAGE* msg;
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
73 static CRITICAL_SECTION server_cs;
74 static CRITICAL_SECTION_DEBUG server_cs_debug =
75 {
76     0, 0, &server_cs,
77     { &server_cs_debug.ProcessLocksList, &server_cs_debug.ProcessLocksList },
78       0, 0, { (DWORD_PTR)(__FILE__ ": server_cs") }
79 };
80 static CRITICAL_SECTION server_cs = { &server_cs_debug, -1, 0, 0, 0, 0 };
81
82 static CRITICAL_SECTION listen_cs;
83 static CRITICAL_SECTION_DEBUG listen_cs_debug =
84 {
85     0, 0, &listen_cs,
86     { &listen_cs_debug.ProcessLocksList, &listen_cs_debug.ProcessLocksList },
87       0, 0, { (DWORD_PTR)(__FILE__ ": listen_cs") }
88 };
89 static CRITICAL_SECTION listen_cs = { &listen_cs_debug, -1, 0, 0, 0, 0 };
90
91 /* whether the server is currently listening */
92 static BOOL std_listen;
93 /* number of manual listeners (calls to RpcServerListen) */
94 static LONG manual_listen_count;
95 /* total listeners including auto listeners */
96 static LONG listen_count;
97
98 static UUID uuid_nil;
99
100 static inline RpcObjTypeMap *LookupObjTypeMap(UUID *ObjUuid)
101 {
102   RpcObjTypeMap *rslt = RpcObjTypeMaps;
103   RPC_STATUS dummy;
104
105   while (rslt) {
106     if (! UuidCompare(ObjUuid, &rslt->Object, &dummy)) break;
107     rslt = rslt->next;
108   }
109
110   return rslt;
111 }
112
113 static inline UUID *LookupObjType(UUID *ObjUuid)
114 {
115   RpcObjTypeMap *map = LookupObjTypeMap(ObjUuid);
116   if (map)
117     return &map->Type;
118   else
119     return &uuid_nil;
120 }
121
122 static RpcServerInterface* RPCRT4_find_interface(UUID* object,
123                                                  const RPC_SYNTAX_IDENTIFIER* if_id,
124                                                  BOOL check_object)
125 {
126   UUID* MgrType = NULL;
127   RpcServerInterface* cif;
128   RPC_STATUS status;
129
130   if (check_object)
131     MgrType = LookupObjType(object);
132   EnterCriticalSection(&server_cs);
133   LIST_FOR_EACH_ENTRY(cif, &server_interfaces, RpcServerInterface, entry) {
134     if (!memcmp(if_id, &cif->If->InterfaceId, sizeof(RPC_SYNTAX_IDENTIFIER)) &&
135         (check_object == FALSE || UuidEqual(MgrType, &cif->MgrTypeUuid, &status)) &&
136         std_listen) {
137       InterlockedIncrement(&cif->CurrentCalls);
138       break;
139     }
140   }
141   LeaveCriticalSection(&server_cs);
142   if (&cif->entry == &server_interfaces) cif = NULL;
143   TRACE("returning %p for %s\n", cif, debugstr_guid(object));
144   return cif;
145 }
146
147 static void RPCRT4_release_server_interface(RpcServerInterface *sif)
148 {
149   if (!InterlockedDecrement(&sif->CurrentCalls) &&
150       sif->CallsCompletedEvent) {
151     /* sif must have been removed from server_interfaces before
152      * CallsCompletedEvent is set */
153     SetEvent(sif->CallsCompletedEvent);
154     HeapFree(GetProcessHeap(), 0, sif);
155   }
156 }
157
158 static WINE_EXCEPTION_FILTER(rpc_filter)
159 {
160   WARN("exception caught with code 0x%08x = %d\n", GetExceptionCode(), GetExceptionCode());
161   TRACE("returning failure packet\n");
162   /* catch every exception */
163   return EXCEPTION_EXECUTE_HANDLER;
164 }
165
166 static void RPCRT4_process_packet(RpcConnection* conn, RpcPktHdr* hdr, RPC_MESSAGE* msg)
167 {
168   RpcServerInterface* sif;
169   RPC_DISPATCH_FUNCTION func;
170   UUID *object_uuid;
171   RpcPktHdr *response = NULL;
172   void *buf = msg->Buffer;
173   RPC_STATUS status;
174   BOOL exception;
175
176   msg->Handle = (RPC_BINDING_HANDLE)conn->server_binding;
177
178   switch (hdr->common.ptype) {
179     case PKT_BIND:
180       TRACE("got bind packet\n");
181
182       /* FIXME: do more checks! */
183       if (hdr->bind.max_tsize < RPC_MIN_PACKET_SIZE ||
184           !UuidIsNil(&conn->ActiveInterface.SyntaxGUID, &status) ||
185           conn->server_binding) {
186         TRACE("packet size less than min size, or active interface syntax guid non-null\n");
187         sif = NULL;
188       } else {
189         /* create temporary binding */
190         if (RPCRT4_MakeBinding(&conn->server_binding, conn) == RPC_S_OK &&
191             RpcServerAssoc_GetAssociation(rpcrt4_conn_get_name(conn),
192                                           conn->NetworkAddr, conn->Endpoint,
193                                           conn->NetworkOptions,
194                                           hdr->bind.assoc_gid,
195                                           &conn->server_binding->Assoc) == RPC_S_OK)
196           sif = RPCRT4_find_interface(NULL, &hdr->bind.abstract, FALSE);
197         else
198           sif = NULL;
199       }
200       if (sif == NULL) {
201         TRACE("rejecting bind request on connection %p\n", conn);
202         /* Report failure to client. */
203         response = RPCRT4_BuildBindNackHeader(NDR_LOCAL_DATA_REPRESENTATION,
204                                               RPC_VER_MAJOR, RPC_VER_MINOR);
205       } else {
206         TRACE("accepting bind request on connection %p for %s\n", conn,
207               debugstr_guid(&hdr->bind.abstract.SyntaxGUID));
208
209         /* accept. */
210         response = RPCRT4_BuildBindAckHeader(NDR_LOCAL_DATA_REPRESENTATION,
211                                              RPC_MAX_PACKET_SIZE,
212                                              RPC_MAX_PACKET_SIZE,
213                                              conn->server_binding->Assoc->assoc_group_id,
214                                              conn->Endpoint,
215                                              RESULT_ACCEPT, REASON_NONE,
216                                              &sif->If->TransferSyntax);
217
218         /* save the interface for later use */
219         conn->ActiveInterface = hdr->bind.abstract;
220         conn->MaxTransmissionSize = hdr->bind.max_tsize;
221
222         RPCRT4_release_server_interface(sif);
223       }
224
225       status = RPCRT4_Send(conn, response, NULL, 0);
226       RPCRT4_FreeHeader(response);
227       if (status != RPC_S_OK)
228         goto fail;
229
230       break;
231
232     case PKT_REQUEST:
233       TRACE("got request packet\n");
234
235       /* fail if the connection isn't bound with an interface */
236       if (UuidIsNil(&conn->ActiveInterface.SyntaxGUID, &status)) {
237         /* FIXME: should send BindNack instead */
238         response = RPCRT4_BuildFaultHeader(NDR_LOCAL_DATA_REPRESENTATION,
239                                            status);
240
241         RPCRT4_Send(conn, response, NULL, 0);
242         RPCRT4_FreeHeader(response);
243         break;
244       }
245
246       if (hdr->common.flags & RPC_FLG_OBJECT_UUID) {
247         object_uuid = (UUID*)(&hdr->request + 1);
248       } else {
249         object_uuid = NULL;
250       }
251
252       sif = RPCRT4_find_interface(object_uuid, &conn->ActiveInterface, TRUE);
253       if (!sif) {
254         WARN("interface %s no longer registered, returning fault packet\n", debugstr_guid(&conn->ActiveInterface.SyntaxGUID));
255         response = RPCRT4_BuildFaultHeader(NDR_LOCAL_DATA_REPRESENTATION,
256                                            NCA_S_UNK_IF);
257
258         RPCRT4_Send(conn, response, NULL, 0);
259         RPCRT4_FreeHeader(response);
260         break;
261       }
262       msg->RpcInterfaceInformation = sif->If;
263       /* copy the endpoint vector from sif to msg so that midl-generated code will use it */
264       msg->ManagerEpv = sif->MgrEpv;
265       if (object_uuid != NULL) {
266         RPCRT4_SetBindingObject(msg->Handle, object_uuid);
267       }
268
269       /* find dispatch function */
270       msg->ProcNum = hdr->request.opnum;
271       if (sif->Flags & RPC_IF_OLE) {
272         /* native ole32 always gives us a dispatch table with a single entry
273          * (I assume that's a wrapper for IRpcStubBuffer::Invoke) */
274         func = *sif->If->DispatchTable->DispatchTable;
275       } else {
276         if (msg->ProcNum >= sif->If->DispatchTable->DispatchTableCount) {
277           WARN("invalid procnum (%d/%d)\n", msg->ProcNum, sif->If->DispatchTable->DispatchTableCount);
278           response = RPCRT4_BuildFaultHeader(NDR_LOCAL_DATA_REPRESENTATION,
279                                              NCA_S_OP_RNG_ERROR);
280
281           RPCRT4_Send(conn, response, NULL, 0);
282           RPCRT4_FreeHeader(response);
283         }
284         func = sif->If->DispatchTable->DispatchTable[msg->ProcNum];
285       }
286
287       /* put in the drep. FIXME: is this more universally applicable?
288          perhaps we should move this outward... */
289       msg->DataRepresentation = 
290         MAKELONG( MAKEWORD(hdr->common.drep[0], hdr->common.drep[1]),
291                   MAKEWORD(hdr->common.drep[2], hdr->common.drep[3]));
292
293       exception = FALSE;
294
295       /* dispatch */
296       __TRY {
297         if (func) func(msg);
298       } __EXCEPT(rpc_filter) {
299         exception = TRUE;
300         if (GetExceptionCode() == STATUS_ACCESS_VIOLATION)
301             status = ERROR_NOACCESS;
302         else
303             status = GetExceptionCode();
304         response = RPCRT4_BuildFaultHeader(msg->DataRepresentation,
305                                            RPC2NCA_STATUS(status));
306       } __ENDTRY
307
308       if (!exception)
309         response = RPCRT4_BuildResponseHeader(msg->DataRepresentation,
310                                               msg->BufferLength);
311
312       /* send response packet */
313       if (response) {
314         status = RPCRT4_Send(conn, response, exception ? NULL : msg->Buffer,
315                              exception ? 0 : msg->BufferLength);
316         RPCRT4_FreeHeader(response);
317       } else
318         ERR("out of memory\n");
319
320       msg->RpcInterfaceInformation = NULL;
321       RPCRT4_release_server_interface(sif);
322
323       break;
324
325     default:
326       FIXME("unhandled packet type %u\n", hdr->common.ptype);
327       break;
328   }
329
330 fail:
331   /* clean up */
332   if (msg->Buffer == buf) msg->Buffer = NULL;
333   TRACE("freeing Buffer=%p\n", buf);
334   HeapFree(GetProcessHeap(), 0, buf);
335   msg->Handle = 0;
336   I_RpcFreeBuffer(msg);
337   msg->Buffer = NULL;
338   RPCRT4_FreeHeader(hdr);
339   HeapFree(GetProcessHeap(), 0, msg);
340 }
341
342 static DWORD CALLBACK RPCRT4_worker_thread(LPVOID the_arg)
343 {
344   RpcPacket *pkt = the_arg;
345   RPCRT4_process_packet(pkt->conn, pkt->hdr, pkt->msg);
346   HeapFree(GetProcessHeap(), 0, pkt);
347   return 0;
348 }
349
350 static DWORD CALLBACK RPCRT4_io_thread(LPVOID the_arg)
351 {
352   RpcConnection* conn = (RpcConnection*)the_arg;
353   RpcPktHdr *hdr;
354   RPC_MESSAGE *msg;
355   RPC_STATUS status;
356   RpcPacket *packet;
357
358   TRACE("(%p)\n", conn);
359
360   for (;;) {
361     msg = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(RPC_MESSAGE));
362
363     status = RPCRT4_Receive(conn, &hdr, msg);
364     if (status != RPC_S_OK) {
365       WARN("receive failed with error %lx\n", status);
366       HeapFree(GetProcessHeap(), 0, msg);
367       break;
368     }
369
370 #if 0
371     RPCRT4_process_packet(conn, hdr, msg);
372 #else
373     packet = HeapAlloc(GetProcessHeap(), 0, sizeof(RpcPacket));
374     packet->conn = conn;
375     packet->hdr = hdr;
376     packet->msg = msg;
377     QueueUserWorkItem(RPCRT4_worker_thread, packet, WT_EXECUTELONGFUNCTION);
378 #endif
379     msg = NULL;
380   }
381   RPCRT4_DestroyConnection(conn);
382   return 0;
383 }
384
385 void RPCRT4_new_client(RpcConnection* conn)
386 {
387   HANDLE thread = CreateThread(NULL, 0, RPCRT4_io_thread, conn, 0, NULL);
388   if (!thread) {
389     DWORD err = GetLastError();
390     ERR("failed to create thread, error=%08x\n", err);
391     RPCRT4_DestroyConnection(conn);
392   }
393   /* we could set conn->thread, but then we'd have to make the io_thread wait
394    * for that, otherwise the thread might finish, destroy the connection, and
395    * free the memory we'd write to before we did, causing crashes and stuff -
396    * so let's implement that later, when we really need conn->thread */
397
398   CloseHandle( thread );
399 }
400
401 static DWORD CALLBACK RPCRT4_server_thread(LPVOID the_arg)
402 {
403   int res;
404   unsigned int count;
405   void *objs = NULL;
406   RpcServerProtseq* cps = the_arg;
407   RpcConnection* conn;
408   BOOL set_ready_event = FALSE;
409
410   TRACE("(the_arg == ^%p)\n", the_arg);
411
412   for (;;) {
413     objs = cps->ops->get_wait_array(cps, objs, &count);
414
415     if (set_ready_event)
416     {
417         /* signal to function that changed state that we are now sync'ed */
418         SetEvent(cps->server_ready_event);
419         set_ready_event = FALSE;
420     }
421
422     /* start waiting */
423     res = cps->ops->wait_for_new_connection(cps, count, objs);
424     if (res == -1)
425       break;
426     else if (res == 0)
427     {
428       if (!std_listen)
429       {
430         SetEvent(cps->server_ready_event);
431         break;
432       }
433       set_ready_event = TRUE;
434     }
435   }
436   cps->ops->free_wait_array(cps, objs);
437   EnterCriticalSection(&cps->cs);
438   /* close connections */
439   conn = cps->conn;
440   while (conn) {
441     RPCRT4_CloseConnection(conn);
442     conn = conn->Next;
443   }
444   LeaveCriticalSection(&cps->cs);
445   return 0;
446 }
447
448 /* tells the server thread that the state has changed and waits for it to
449  * make the changes */
450 static void RPCRT4_sync_with_server_thread(RpcServerProtseq *ps)
451 {
452   /* make sure we are the only thread sync'ing the server state, otherwise
453    * there is a race with the server thread setting an older state and setting
454    * the server_ready_event when the new state hasn't yet been applied */
455   WaitForSingleObject(ps->mgr_mutex, INFINITE);
456
457   ps->ops->signal_state_changed(ps);
458
459   /* wait for server thread to make the requested changes before returning */
460   WaitForSingleObject(ps->server_ready_event, INFINITE);
461
462   ReleaseMutex(ps->mgr_mutex);
463 }
464
465 static RPC_STATUS RPCRT4_start_listen_protseq(RpcServerProtseq *ps, BOOL auto_listen)
466 {
467   RPC_STATUS status = RPC_S_OK;
468   HANDLE server_thread;
469
470   EnterCriticalSection(&listen_cs);
471   if (ps->is_listening) goto done;
472
473   if (!ps->mgr_mutex) ps->mgr_mutex = CreateMutexW(NULL, FALSE, NULL);
474   if (!ps->server_ready_event) ps->server_ready_event = CreateEventW(NULL, FALSE, FALSE, NULL);
475   server_thread = CreateThread(NULL, 0, RPCRT4_server_thread, ps, 0, NULL);
476   if (!server_thread)
477   {
478     status = RPC_S_OUT_OF_RESOURCES;
479     goto done;
480   }
481   ps->is_listening = TRUE;
482   CloseHandle(server_thread);
483
484 done:
485   LeaveCriticalSection(&listen_cs);
486   return status;
487 }
488
489 static RPC_STATUS RPCRT4_start_listen(BOOL auto_listen)
490 {
491   RPC_STATUS status = RPC_S_ALREADY_LISTENING;
492   RpcServerProtseq *cps;
493
494   TRACE("\n");
495
496   EnterCriticalSection(&listen_cs);
497   if (auto_listen || (manual_listen_count++ == 0))
498   {
499     status = RPC_S_OK;
500     if (++listen_count == 1)
501       std_listen = TRUE;
502   }
503   LeaveCriticalSection(&listen_cs);
504
505   if (std_listen)
506   {
507     EnterCriticalSection(&server_cs);
508     LIST_FOR_EACH_ENTRY(cps, &protseqs, RpcServerProtseq, entry)
509     {
510       status = RPCRT4_start_listen_protseq(cps, TRUE);
511       if (status != RPC_S_OK)
512         break;
513       
514       /* make sure server is actually listening on the interface before
515        * returning */
516       RPCRT4_sync_with_server_thread(cps);
517     }
518     LeaveCriticalSection(&server_cs);
519   }
520
521   return status;
522 }
523
524 static void RPCRT4_stop_listen(BOOL auto_listen)
525 {
526   EnterCriticalSection(&listen_cs);
527   if (auto_listen || (--manual_listen_count == 0))
528   {
529     if (listen_count != 0 && --listen_count == 0) {
530       RpcServerProtseq *cps;
531
532       std_listen = FALSE;
533       LeaveCriticalSection(&listen_cs);
534
535       LIST_FOR_EACH_ENTRY(cps, &protseqs, RpcServerProtseq, entry)
536         RPCRT4_sync_with_server_thread(cps);
537
538       return;
539     }
540     assert(listen_count >= 0);
541   }
542   LeaveCriticalSection(&listen_cs);
543 }
544
545 static RPC_STATUS RPCRT4_use_protseq(RpcServerProtseq* ps, LPSTR endpoint)
546 {
547   RPC_STATUS status;
548
549   status = ps->ops->open_endpoint(ps, endpoint);
550   if (status != RPC_S_OK)
551     return status;
552
553   if (std_listen)
554   {
555     status = RPCRT4_start_listen_protseq(ps, FALSE);
556     if (status == RPC_S_OK)
557       RPCRT4_sync_with_server_thread(ps);
558   }
559
560   return status;
561 }
562
563 /***********************************************************************
564  *             RpcServerInqBindings (RPCRT4.@)
565  */
566 RPC_STATUS WINAPI RpcServerInqBindings( RPC_BINDING_VECTOR** BindingVector )
567 {
568   RPC_STATUS status;
569   DWORD count;
570   RpcServerProtseq* ps;
571   RpcConnection* conn;
572
573   if (BindingVector)
574     TRACE("(*BindingVector == ^%p)\n", *BindingVector);
575   else
576     ERR("(BindingVector == NULL!!?)\n");
577
578   EnterCriticalSection(&server_cs);
579   /* count connections */
580   count = 0;
581   LIST_FOR_EACH_ENTRY(ps, &protseqs, RpcServerProtseq, entry) {
582     EnterCriticalSection(&ps->cs);
583     conn = ps->conn;
584     while (conn) {
585       count++;
586       conn = conn->Next;
587     }
588     LeaveCriticalSection(&ps->cs);
589   }
590   if (count) {
591     /* export bindings */
592     *BindingVector = HeapAlloc(GetProcessHeap(), 0,
593                               sizeof(RPC_BINDING_VECTOR) +
594                               sizeof(RPC_BINDING_HANDLE)*(count-1));
595     (*BindingVector)->Count = count;
596     count = 0;
597     LIST_FOR_EACH_ENTRY(ps, &protseqs, RpcServerProtseq, entry) {
598       EnterCriticalSection(&ps->cs);
599       conn = ps->conn;
600       while (conn) {
601        RPCRT4_MakeBinding((RpcBinding**)&(*BindingVector)->BindingH[count],
602                           conn);
603        count++;
604        conn = conn->Next;
605       }
606       LeaveCriticalSection(&ps->cs);
607     }
608     status = RPC_S_OK;
609   } else {
610     *BindingVector = NULL;
611     status = RPC_S_NO_BINDINGS;
612   }
613   LeaveCriticalSection(&server_cs);
614   return status;
615 }
616
617 /***********************************************************************
618  *             RpcServerUseProtseqEpA (RPCRT4.@)
619  */
620 RPC_STATUS WINAPI RpcServerUseProtseqEpA( RPC_CSTR Protseq, UINT MaxCalls, RPC_CSTR Endpoint, LPVOID SecurityDescriptor )
621 {
622   RPC_POLICY policy;
623   
624   TRACE( "(%s,%u,%s,%p)\n", Protseq, MaxCalls, Endpoint, SecurityDescriptor );
625   
626   /* This should provide the default behaviour */
627   policy.Length        = sizeof( policy );
628   policy.EndpointFlags = 0;
629   policy.NICFlags      = 0;
630   
631   return RpcServerUseProtseqEpExA( Protseq, MaxCalls, Endpoint, SecurityDescriptor, &policy );
632 }
633
634 /***********************************************************************
635  *             RpcServerUseProtseqEpW (RPCRT4.@)
636  */
637 RPC_STATUS WINAPI RpcServerUseProtseqEpW( RPC_WSTR Protseq, UINT MaxCalls, RPC_WSTR Endpoint, LPVOID SecurityDescriptor )
638 {
639   RPC_POLICY policy;
640   
641   TRACE( "(%s,%u,%s,%p)\n", debugstr_w( Protseq ), MaxCalls, debugstr_w( Endpoint ), SecurityDescriptor );
642   
643   /* This should provide the default behaviour */
644   policy.Length        = sizeof( policy );
645   policy.EndpointFlags = 0;
646   policy.NICFlags      = 0;
647   
648   return RpcServerUseProtseqEpExW( Protseq, MaxCalls, Endpoint, SecurityDescriptor, &policy );
649 }
650
651 /***********************************************************************
652  *             alloc_serverprotoseq (internal)
653  *
654  * Must be called with server_cs held.
655  */
656 static RPC_STATUS alloc_serverprotoseq(UINT MaxCalls, char *Protseq, RpcServerProtseq **ps)
657 {
658   const struct protseq_ops *ops = rpcrt4_get_protseq_ops(Protseq);
659
660   if (!ops)
661   {
662     FIXME("protseq %s not supported\n", debugstr_a(Protseq));
663     return RPC_S_PROTSEQ_NOT_SUPPORTED;
664   }
665
666   *ps = ops->alloc();
667   if (!*ps)
668     return RPC_S_OUT_OF_RESOURCES;
669   (*ps)->MaxCalls = MaxCalls;
670   (*ps)->Protseq = Protseq;
671   (*ps)->ops = ops;
672   (*ps)->MaxCalls = 0;
673   (*ps)->conn = NULL;
674   InitializeCriticalSection(&(*ps)->cs);
675   (*ps)->is_listening = FALSE;
676   (*ps)->mgr_mutex = NULL;
677   (*ps)->server_ready_event = NULL;
678
679   list_add_head(&protseqs, &(*ps)->entry);
680
681   TRACE("new protseq %p created for %s\n", *ps, Protseq);
682
683   return RPC_S_OK;
684 }
685
686 /* Finds a given protseq or creates a new one if one doesn't already exist */
687 static RPC_STATUS RPCRT4_get_or_create_serverprotseq(UINT MaxCalls, char *Protseq, RpcServerProtseq **ps)
688 {
689     RPC_STATUS status;
690     RpcServerProtseq *cps;
691
692     EnterCriticalSection(&server_cs);
693
694     LIST_FOR_EACH_ENTRY(cps, &protseqs, RpcServerProtseq, entry)
695         if (!strcmp(cps->Protseq, Protseq))
696         {
697             TRACE("found existing protseq object for %s\n", Protseq);
698             *ps = cps;
699             LeaveCriticalSection(&server_cs);
700             return S_OK;
701         }
702
703     status = alloc_serverprotoseq(MaxCalls, Protseq, ps);
704
705     LeaveCriticalSection(&server_cs);
706
707     return status;
708 }
709
710 /***********************************************************************
711  *             RpcServerUseProtseqEpExA (RPCRT4.@)
712  */
713 RPC_STATUS WINAPI RpcServerUseProtseqEpExA( RPC_CSTR Protseq, UINT MaxCalls, RPC_CSTR Endpoint, LPVOID SecurityDescriptor,
714                                             PRPC_POLICY lpPolicy )
715 {
716   char *szps = (char*)Protseq, *szep = (char*)Endpoint;
717   RpcServerProtseq* ps;
718   RPC_STATUS status;
719
720   TRACE("(%s,%u,%s,%p,{%u,%lu,%lu})\n", debugstr_a(szps), MaxCalls,
721        debugstr_a(szep), SecurityDescriptor,
722        lpPolicy->Length, lpPolicy->EndpointFlags, lpPolicy->NICFlags );
723
724   status = RPCRT4_get_or_create_serverprotseq(MaxCalls, RPCRT4_strdupA(szps), &ps);
725   if (status != RPC_S_OK)
726     return status;
727
728   return RPCRT4_use_protseq(ps, szep);
729 }
730
731 /***********************************************************************
732  *             RpcServerUseProtseqEpExW (RPCRT4.@)
733  */
734 RPC_STATUS WINAPI RpcServerUseProtseqEpExW( RPC_WSTR Protseq, UINT MaxCalls, RPC_WSTR Endpoint, LPVOID SecurityDescriptor,
735                                             PRPC_POLICY lpPolicy )
736 {
737   RpcServerProtseq* ps;
738   RPC_STATUS status;
739   LPSTR EndpointA;
740
741   TRACE("(%s,%u,%s,%p,{%u,%lu,%lu})\n", debugstr_w( Protseq ), MaxCalls,
742        debugstr_w( Endpoint ), SecurityDescriptor,
743        lpPolicy->Length, lpPolicy->EndpointFlags, lpPolicy->NICFlags );
744
745   status = RPCRT4_get_or_create_serverprotseq(MaxCalls, RPCRT4_strdupWtoA(Protseq), &ps);
746   if (status != RPC_S_OK)
747     return status;
748
749   EndpointA = RPCRT4_strdupWtoA(Endpoint);
750   status = RPCRT4_use_protseq(ps, EndpointA);
751   RPCRT4_strfree(EndpointA);
752   return status;
753 }
754
755 /***********************************************************************
756  *             RpcServerUseProtseqA (RPCRT4.@)
757  */
758 RPC_STATUS WINAPI RpcServerUseProtseqA(RPC_CSTR Protseq, unsigned int MaxCalls, void *SecurityDescriptor)
759 {
760   TRACE("(Protseq == %s, MaxCalls == %d, SecurityDescriptor == ^%p)\n", debugstr_a((char*)Protseq), MaxCalls, SecurityDescriptor);
761   return RpcServerUseProtseqEpA(Protseq, MaxCalls, NULL, SecurityDescriptor);
762 }
763
764 /***********************************************************************
765  *             RpcServerUseProtseqW (RPCRT4.@)
766  */
767 RPC_STATUS WINAPI RpcServerUseProtseqW(RPC_WSTR Protseq, unsigned int MaxCalls, void *SecurityDescriptor)
768 {
769   TRACE("Protseq == %s, MaxCalls == %d, SecurityDescriptor == ^%p)\n", debugstr_w(Protseq), MaxCalls, SecurityDescriptor);
770   return RpcServerUseProtseqEpW(Protseq, MaxCalls, NULL, SecurityDescriptor);
771 }
772
773 /***********************************************************************
774  *             RpcServerRegisterIf (RPCRT4.@)
775  */
776 RPC_STATUS WINAPI RpcServerRegisterIf( RPC_IF_HANDLE IfSpec, UUID* MgrTypeUuid, RPC_MGR_EPV* MgrEpv )
777 {
778   TRACE("(%p,%s,%p)\n", IfSpec, debugstr_guid(MgrTypeUuid), MgrEpv);
779   return RpcServerRegisterIf2( IfSpec, MgrTypeUuid, MgrEpv, 0, RPC_C_LISTEN_MAX_CALLS_DEFAULT, (UINT)-1, NULL );
780 }
781
782 /***********************************************************************
783  *             RpcServerRegisterIfEx (RPCRT4.@)
784  */
785 RPC_STATUS WINAPI RpcServerRegisterIfEx( RPC_IF_HANDLE IfSpec, UUID* MgrTypeUuid, RPC_MGR_EPV* MgrEpv,
786                        UINT Flags, UINT MaxCalls, RPC_IF_CALLBACK_FN* IfCallbackFn )
787 {
788   TRACE("(%p,%s,%p,%u,%u,%p)\n", IfSpec, debugstr_guid(MgrTypeUuid), MgrEpv, Flags, MaxCalls, IfCallbackFn);
789   return RpcServerRegisterIf2( IfSpec, MgrTypeUuid, MgrEpv, Flags, MaxCalls, (UINT)-1, IfCallbackFn );
790 }
791
792 /***********************************************************************
793  *             RpcServerRegisterIf2 (RPCRT4.@)
794  */
795 RPC_STATUS WINAPI RpcServerRegisterIf2( RPC_IF_HANDLE IfSpec, UUID* MgrTypeUuid, RPC_MGR_EPV* MgrEpv,
796                       UINT Flags, UINT MaxCalls, UINT MaxRpcSize, RPC_IF_CALLBACK_FN* IfCallbackFn )
797 {
798   PRPC_SERVER_INTERFACE If = (PRPC_SERVER_INTERFACE)IfSpec;
799   RpcServerInterface* sif;
800   unsigned int i;
801
802   TRACE("(%p,%s,%p,%u,%u,%u,%p)\n", IfSpec, debugstr_guid(MgrTypeUuid), MgrEpv, Flags, MaxCalls,
803          MaxRpcSize, IfCallbackFn);
804   TRACE(" interface id: %s %d.%d\n", debugstr_guid(&If->InterfaceId.SyntaxGUID),
805                                      If->InterfaceId.SyntaxVersion.MajorVersion,
806                                      If->InterfaceId.SyntaxVersion.MinorVersion);
807   TRACE(" transfer syntax: %s %d.%d\n", debugstr_guid(&If->TransferSyntax.SyntaxGUID),
808                                         If->TransferSyntax.SyntaxVersion.MajorVersion,
809                                         If->TransferSyntax.SyntaxVersion.MinorVersion);
810   TRACE(" dispatch table: %p\n", If->DispatchTable);
811   if (If->DispatchTable) {
812     TRACE("  dispatch table count: %d\n", If->DispatchTable->DispatchTableCount);
813     for (i=0; i<If->DispatchTable->DispatchTableCount; i++) {
814       TRACE("   entry %d: %p\n", i, If->DispatchTable->DispatchTable[i]);
815     }
816     TRACE("  reserved: %ld\n", If->DispatchTable->Reserved);
817   }
818   TRACE(" protseq endpoint count: %d\n", If->RpcProtseqEndpointCount);
819   TRACE(" default manager epv: %p\n", If->DefaultManagerEpv);
820   TRACE(" interpreter info: %p\n", If->InterpreterInfo);
821
822   sif = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(RpcServerInterface));
823   sif->If           = If;
824   if (MgrTypeUuid) {
825     memcpy(&sif->MgrTypeUuid, MgrTypeUuid, sizeof(UUID));
826     sif->MgrEpv       = MgrEpv;
827   } else {
828     memset(&sif->MgrTypeUuid, 0, sizeof(UUID));
829     sif->MgrEpv       = If->DefaultManagerEpv;
830   }
831   sif->Flags        = Flags;
832   sif->MaxCalls     = MaxCalls;
833   sif->MaxRpcSize   = MaxRpcSize;
834   sif->IfCallbackFn = IfCallbackFn;
835
836   EnterCriticalSection(&server_cs);
837   list_add_head(&server_interfaces, &sif->entry);
838   LeaveCriticalSection(&server_cs);
839
840   if (sif->Flags & RPC_IF_AUTOLISTEN)
841       RPCRT4_start_listen(TRUE);
842
843   return RPC_S_OK;
844 }
845
846 /***********************************************************************
847  *             RpcServerUnregisterIf (RPCRT4.@)
848  */
849 RPC_STATUS WINAPI RpcServerUnregisterIf( RPC_IF_HANDLE IfSpec, UUID* MgrTypeUuid, UINT WaitForCallsToComplete )
850 {
851   PRPC_SERVER_INTERFACE If = (PRPC_SERVER_INTERFACE)IfSpec;
852   HANDLE event = NULL;
853   BOOL found = FALSE;
854   BOOL completed = TRUE;
855   RpcServerInterface *cif;
856   RPC_STATUS status;
857
858   TRACE("(IfSpec == (RPC_IF_HANDLE)^%p (%s), MgrTypeUuid == %s, WaitForCallsToComplete == %u)\n",
859     IfSpec, debugstr_guid(&If->InterfaceId.SyntaxGUID), debugstr_guid(MgrTypeUuid), WaitForCallsToComplete);
860
861   EnterCriticalSection(&server_cs);
862   LIST_FOR_EACH_ENTRY(cif, &server_interfaces, RpcServerInterface, entry) {
863     if ((!IfSpec || !memcmp(&If->InterfaceId, &cif->If->InterfaceId, sizeof(RPC_SYNTAX_IDENTIFIER))) &&
864         UuidEqual(MgrTypeUuid, &cif->MgrTypeUuid, &status)) {
865       list_remove(&cif->entry);
866       if (cif->CurrentCalls) {
867         completed = FALSE;
868         if (WaitForCallsToComplete)
869           cif->CallsCompletedEvent = event = CreateEventW(NULL, FALSE, FALSE, NULL);
870       }
871       found = TRUE;
872       break;
873     }
874   }
875   LeaveCriticalSection(&server_cs);
876
877   if (!found) {
878     ERR("not found for object %s\n", debugstr_guid(MgrTypeUuid));
879     return RPC_S_UNKNOWN_IF;
880   }
881
882   if (completed)
883     HeapFree(GetProcessHeap(), 0, cif);
884   else if (event) {
885     /* sif will be freed when the last call is completed, so be careful not to
886      * touch that memory here as that could happen before we get here */
887     WaitForSingleObject(event, INFINITE);
888     CloseHandle(event);
889   }
890
891   return RPC_S_OK;
892 }
893
894 /***********************************************************************
895  *             RpcServerUnregisterIfEx (RPCRT4.@)
896  */
897 RPC_STATUS WINAPI RpcServerUnregisterIfEx( RPC_IF_HANDLE IfSpec, UUID* MgrTypeUuid, int RundownContextHandles )
898 {
899   FIXME("(IfSpec == (RPC_IF_HANDLE)^%p, MgrTypeUuid == %s, RundownContextHandles == %d): stub\n",
900     IfSpec, debugstr_guid(MgrTypeUuid), RundownContextHandles);
901
902   return RPC_S_OK;
903 }
904
905 /***********************************************************************
906  *             RpcObjectSetType (RPCRT4.@)
907  *
908  * PARAMS
909  *   ObjUuid  [I] "Object" UUID
910  *   TypeUuid [I] "Type" UUID
911  *
912  * RETURNS
913  *   RPC_S_OK                 The call succeeded
914  *   RPC_S_INVALID_OBJECT     The provided object (nil) is not valid
915  *   RPC_S_ALREADY_REGISTERED The provided object is already registered
916  *
917  * Maps "Object" UUIDs to "Type" UUID's.  Passing the nil UUID as the type
918  * resets the mapping for the specified object UUID to nil (the default).
919  * The nil object is always associated with the nil type and cannot be
920  * reassigned.  Servers can support multiple implementations on the same
921  * interface by registering different end-point vectors for the different
922  * types.  There's no need to call this if a server only supports the nil
923  * type, as is typical.
924  */
925 RPC_STATUS WINAPI RpcObjectSetType( UUID* ObjUuid, UUID* TypeUuid )
926 {
927   RpcObjTypeMap *map = RpcObjTypeMaps, *prev = NULL;
928   RPC_STATUS dummy;
929
930   TRACE("(ObjUUID == %s, TypeUuid == %s).\n", debugstr_guid(ObjUuid), debugstr_guid(TypeUuid));
931   if ((! ObjUuid) || UuidIsNil(ObjUuid, &dummy)) {
932     /* nil uuid cannot be remapped */
933     return RPC_S_INVALID_OBJECT;
934   }
935
936   /* find the mapping for this object if there is one ... */
937   while (map) {
938     if (! UuidCompare(ObjUuid, &map->Object, &dummy)) break;
939     prev = map;
940     map = map->next;
941   }
942   if ((! TypeUuid) || UuidIsNil(TypeUuid, &dummy)) {
943     /* ... and drop it from the list */
944     if (map) {
945       if (prev) 
946         prev->next = map->next;
947       else
948         RpcObjTypeMaps = map->next;
949       HeapFree(GetProcessHeap(), 0, map);
950     }
951   } else {
952     /* ... , fail if we found it ... */
953     if (map)
954       return RPC_S_ALREADY_REGISTERED;
955     /* ... otherwise create a new one and add it in. */
956     map = HeapAlloc(GetProcessHeap(), 0, sizeof(RpcObjTypeMap));
957     memcpy(&map->Object, ObjUuid, sizeof(UUID));
958     memcpy(&map->Type, TypeUuid, sizeof(UUID));
959     map->next = NULL;
960     if (prev)
961       prev->next = map; /* prev is the last map in the linklist */
962     else
963       RpcObjTypeMaps = map;
964   }
965
966   return RPC_S_OK;
967 }
968
969 /***********************************************************************
970  *             RpcServerRegisterAuthInfoA (RPCRT4.@)
971  */
972 RPC_STATUS WINAPI RpcServerRegisterAuthInfoA( RPC_CSTR ServerPrincName, ULONG AuthnSvc, RPC_AUTH_KEY_RETRIEVAL_FN GetKeyFn,
973                             LPVOID Arg )
974 {
975   FIXME( "(%s,%u,%p,%p): stub\n", ServerPrincName, AuthnSvc, GetKeyFn, Arg );
976   
977   return RPC_S_UNKNOWN_AUTHN_SERVICE; /* We don't know any authentication services */
978 }
979
980 /***********************************************************************
981  *             RpcServerRegisterAuthInfoW (RPCRT4.@)
982  */
983 RPC_STATUS WINAPI RpcServerRegisterAuthInfoW( RPC_WSTR ServerPrincName, ULONG AuthnSvc, RPC_AUTH_KEY_RETRIEVAL_FN GetKeyFn,
984                             LPVOID Arg )
985 {
986   FIXME( "(%s,%u,%p,%p): stub\n", debugstr_w( ServerPrincName ), AuthnSvc, GetKeyFn, Arg );
987   
988   return RPC_S_UNKNOWN_AUTHN_SERVICE; /* We don't know any authentication services */
989 }
990
991 /***********************************************************************
992  *             RpcServerListen (RPCRT4.@)
993  */
994 RPC_STATUS WINAPI RpcServerListen( UINT MinimumCallThreads, UINT MaxCalls, UINT DontWait )
995 {
996   RPC_STATUS status = RPC_S_OK;
997
998   TRACE("(%u,%u,%u)\n", MinimumCallThreads, MaxCalls, DontWait);
999
1000   if (list_empty(&protseqs))
1001     return RPC_S_NO_PROTSEQS_REGISTERED;
1002
1003   status = RPCRT4_start_listen(FALSE);
1004
1005   if (DontWait || (status != RPC_S_OK)) return status;
1006
1007   return RpcMgmtWaitServerListen();
1008 }
1009
1010 /***********************************************************************
1011  *             RpcMgmtServerWaitListen (RPCRT4.@)
1012  */
1013 RPC_STATUS WINAPI RpcMgmtWaitServerListen( void )
1014 {
1015   TRACE("()\n");
1016
1017   EnterCriticalSection(&listen_cs);
1018
1019   if (!std_listen) {
1020     LeaveCriticalSection(&listen_cs);
1021     return RPC_S_NOT_LISTENING;
1022   }
1023   
1024   LeaveCriticalSection(&listen_cs);
1025
1026   FIXME("not waiting for server calls to finish\n");
1027
1028   return RPC_S_OK;
1029 }
1030
1031 /***********************************************************************
1032  *             RpcMgmtStopServerListening (RPCRT4.@)
1033  */
1034 RPC_STATUS WINAPI RpcMgmtStopServerListening ( RPC_BINDING_HANDLE Binding )
1035 {
1036   TRACE("(Binding == (RPC_BINDING_HANDLE)^%p)\n", Binding);
1037
1038   if (Binding) {
1039     FIXME("client-side invocation not implemented.\n");
1040     return RPC_S_WRONG_KIND_OF_BINDING;
1041   }
1042   
1043   RPCRT4_stop_listen(FALSE);
1044
1045   return RPC_S_OK;
1046 }
1047
1048 /***********************************************************************
1049  *             RpcMgmtEnableIdleCleanup (RPCRT4.@)
1050  */
1051 RPC_STATUS WINAPI RpcMgmtEnableIdleCleanup(void)
1052 {
1053     FIXME("(): stub\n");
1054     return RPC_S_OK;
1055 }
1056
1057 /***********************************************************************
1058  *             I_RpcServerStartListening (RPCRT4.@)
1059  */
1060 RPC_STATUS WINAPI I_RpcServerStartListening( HWND hWnd )
1061 {
1062   FIXME( "(%p): stub\n", hWnd );
1063
1064   return RPC_S_OK;
1065 }
1066
1067 /***********************************************************************
1068  *             I_RpcServerStopListening (RPCRT4.@)
1069  */
1070 RPC_STATUS WINAPI I_RpcServerStopListening( void )
1071 {
1072   FIXME( "(): stub\n" );
1073
1074   return RPC_S_OK;
1075 }
1076
1077 /***********************************************************************
1078  *             I_RpcWindowProc (RPCRT4.@)
1079  */
1080 UINT WINAPI I_RpcWindowProc( void *hWnd, UINT Message, UINT wParam, ULONG lParam )
1081 {
1082   FIXME( "(%p,%08x,%08x,%08x): stub\n", hWnd, Message, wParam, lParam );
1083
1084   return 0;
1085 }
1086
1087 /***********************************************************************
1088  *             RpcMgmtInqIfIds (RPCRT4.@)
1089  */
1090 RPC_STATUS WINAPI RpcMgmtInqIfIds(RPC_BINDING_HANDLE Binding, RPC_IF_ID_VECTOR **IfIdVector)
1091 {
1092   FIXME("(%p,%p): stub\n", Binding, IfIdVector);
1093   return RPC_S_INVALID_BINDING;
1094 }
1095
1096 /***********************************************************************
1097  *             RpcMgmtEpEltInqBegin (RPCRT4.@)
1098  */
1099 RPC_STATUS WINAPI RpcMgmtEpEltInqBegin(RPC_BINDING_HANDLE Binding, ULONG InquiryType,
1100     RPC_IF_ID *IfId, ULONG VersOption, UUID *ObjectUuid, RPC_EP_INQ_HANDLE* InquiryContext)
1101 {
1102   FIXME("(%p,%u,%p,%u,%p,%p): stub\n",
1103         Binding, InquiryType, IfId, VersOption, ObjectUuid, InquiryContext);
1104   return RPC_S_INVALID_BINDING;
1105 }
1106
1107 /***********************************************************************
1108  *             RpcMgmtIsServerListening (RPCRT4.@)
1109  */
1110 RPC_STATUS WINAPI RpcMgmtIsServerListening(RPC_BINDING_HANDLE Binding)
1111 {
1112   FIXME("(%p): stub\n", Binding);
1113   return RPC_S_INVALID_BINDING;
1114 }
1115
1116 /***********************************************************************
1117  *             RpcMgmtSetServerStackSize (RPCRT4.@)
1118  */
1119 RPC_STATUS WINAPI RpcMgmtSetServerStackSize(ULONG ThreadStackSize)
1120 {
1121   FIXME("(0x%x): stub\n", ThreadStackSize);
1122   return RPC_S_OK;
1123 }