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