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