rpcrt4: Handle marshaling/unmarshaling full pointers.
[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 #include "winreg.h"
37
38 #include "rpc.h"
39 #include "rpcndr.h"
40 #include "excpt.h"
41
42 #include "wine/debug.h"
43 #include "wine/exception.h"
44
45 #include "rpc_server.h"
46 #include "rpc_misc.h"
47 #include "rpc_message.h"
48 #include "rpc_defs.h"
49
50 #define MAX_THREADS 128
51
52 WINE_DEFAULT_DEBUG_CHANNEL(rpc);
53
54 typedef struct _RpcPacket
55 {
56   struct _RpcPacket* next;
57   struct _RpcConnection* conn;
58   RpcPktHdr* hdr;
59   RPC_MESSAGE* msg;
60 } RpcPacket;
61
62 typedef struct _RpcObjTypeMap
63 {
64   /* FIXME: a hash table would be better. */
65   struct _RpcObjTypeMap *next;
66   UUID Object;
67   UUID Type;
68 } RpcObjTypeMap;
69
70 static RpcObjTypeMap *RpcObjTypeMaps;
71
72 static RpcServerProtseq* protseqs;
73 static RpcServerInterface* ifs;
74
75 static CRITICAL_SECTION server_cs;
76 static CRITICAL_SECTION_DEBUG server_cs_debug =
77 {
78     0, 0, &server_cs,
79     { &server_cs_debug.ProcessLocksList, &server_cs_debug.ProcessLocksList },
80       0, 0, { (DWORD_PTR)(__FILE__ ": server_cs") }
81 };
82 static CRITICAL_SECTION server_cs = { &server_cs_debug, -1, 0, 0, 0, 0 };
83
84 static CRITICAL_SECTION listen_cs;
85 static CRITICAL_SECTION_DEBUG listen_cs_debug =
86 {
87     0, 0, &listen_cs,
88     { &listen_cs_debug.ProcessLocksList, &listen_cs_debug.ProcessLocksList },
89       0, 0, { (DWORD_PTR)(__FILE__ ": listen_cs") }
90 };
91 static CRITICAL_SECTION listen_cs = { &listen_cs_debug, -1, 0, 0, 0, 0 };
92
93 /* whether the server is currently listening */
94 static BOOL std_listen;
95 /* number of manual listeners (calls to RpcServerListen) */
96 static LONG manual_listen_count;
97 /* total listeners including auto listeners */
98 static LONG listen_count;
99 /* set on change of configuration (e.g. listening on new protseq) */
100 static HANDLE mgr_event;
101 /* mutex for ensuring only one thread can change state at a time */
102 static HANDLE mgr_mutex;
103 /* set when server thread has finished opening connections */
104 static HANDLE server_ready_event;
105
106 static CRITICAL_SECTION spacket_cs;
107 static CRITICAL_SECTION_DEBUG spacket_cs_debug =
108 {
109     0, 0, &spacket_cs,
110     { &spacket_cs_debug.ProcessLocksList, &spacket_cs_debug.ProcessLocksList },
111       0, 0, { (DWORD_PTR)(__FILE__ ": spacket_cs") }
112 };
113 static CRITICAL_SECTION spacket_cs = { &spacket_cs_debug, -1, 0, 0, 0, 0 };
114
115 static RpcPacket* spacket_head;
116 static RpcPacket* spacket_tail;
117 static HANDLE server_sem;
118
119 static LONG worker_count, worker_free, worker_tls;
120
121 static UUID uuid_nil;
122
123 inline static RpcObjTypeMap *LookupObjTypeMap(UUID *ObjUuid)
124 {
125   RpcObjTypeMap *rslt = RpcObjTypeMaps;
126   RPC_STATUS dummy;
127
128   while (rslt) {
129     if (! UuidCompare(ObjUuid, &rslt->Object, &dummy)) break;
130     rslt = rslt->next;
131   }
132
133   return rslt;
134 }
135
136 inline static UUID *LookupObjType(UUID *ObjUuid)
137 {
138   RpcObjTypeMap *map = LookupObjTypeMap(ObjUuid);
139   if (map)
140     return &map->Type;
141   else
142     return &uuid_nil;
143 }
144
145 static RpcServerInterface* RPCRT4_find_interface(UUID* object,
146                                                  RPC_SYNTAX_IDENTIFIER* if_id,
147                                                  BOOL check_object)
148 {
149   UUID* MgrType = NULL;
150   RpcServerInterface* cif = NULL;
151   RPC_STATUS status;
152
153   if (check_object)
154     MgrType = LookupObjType(object);
155   EnterCriticalSection(&server_cs);
156   cif = ifs;
157   while (cif) {
158     if (!memcmp(if_id, &cif->If->InterfaceId, sizeof(RPC_SYNTAX_IDENTIFIER)) &&
159         (check_object == FALSE || UuidEqual(MgrType, &cif->MgrTypeUuid, &status)) &&
160         std_listen) break;
161     cif = cif->Next;
162   }
163   LeaveCriticalSection(&server_cs);
164   TRACE("returning %p for %s\n", cif, debugstr_guid(object));
165   return cif;
166 }
167
168 static void RPCRT4_push_packet(RpcPacket* packet)
169 {
170   packet->next = NULL;
171   EnterCriticalSection(&spacket_cs);
172   if (spacket_tail) {
173     spacket_tail->next = packet;
174     spacket_tail = packet;
175   } else {
176     spacket_head = packet;
177     spacket_tail = packet;
178   }
179   LeaveCriticalSection(&spacket_cs);
180 }
181
182 static RpcPacket* RPCRT4_pop_packet(void)
183 {
184   RpcPacket* packet;
185   EnterCriticalSection(&spacket_cs);
186   packet = spacket_head;
187   if (packet) {
188     spacket_head = packet->next;
189     if (!spacket_head) spacket_tail = NULL;
190   }
191   LeaveCriticalSection(&spacket_cs);
192   if (packet) packet->next = NULL;
193   return packet;
194 }
195
196 typedef struct {
197   PRPC_MESSAGE msg;
198   void* buf;
199 } packet_state;
200
201 static WINE_EXCEPTION_FILTER(rpc_filter)
202 {
203   packet_state* state;
204   PRPC_MESSAGE msg;
205   state = TlsGetValue(worker_tls);
206   msg = state->msg;
207   if (msg->Buffer != state->buf) I_RpcFreeBuffer(msg);
208   msg->RpcFlags |= WINE_RPCFLAG_EXCEPTION;
209   msg->BufferLength = sizeof(DWORD);
210   I_RpcGetBuffer(msg);
211   *(DWORD*)msg->Buffer = GetExceptionCode();
212   WARN("exception caught with code 0x%08lx = %ld\n", *(DWORD*)msg->Buffer, *(DWORD*)msg->Buffer);
213   TRACE("returning failure packet\n");
214   return EXCEPTION_EXECUTE_HANDLER;
215 }
216
217 static void RPCRT4_process_packet(RpcConnection* conn, RpcPktHdr* hdr, RPC_MESSAGE* msg)
218 {
219   RpcServerInterface* sif;
220   RPC_DISPATCH_FUNCTION func;
221   packet_state state;
222   UUID *object_uuid;
223   RpcPktHdr *response;
224   void *buf = msg->Buffer;
225   RPC_STATUS status;
226
227   state.msg = msg;
228   state.buf = buf;
229   TlsSetValue(worker_tls, &state);
230
231   switch (hdr->common.ptype) {
232     case PKT_BIND:
233       TRACE("got bind packet\n");
234
235       /* FIXME: do more checks! */
236       if (hdr->bind.max_tsize < RPC_MIN_PACKET_SIZE ||
237           !UuidIsNil(&conn->ActiveInterface.SyntaxGUID, &status)) {
238         TRACE("packet size less than min size, or active interface syntax guid non-null\n");
239         sif = NULL;
240       } else {
241         sif = RPCRT4_find_interface(NULL, &hdr->bind.abstract, FALSE);
242       }
243       if (sif == NULL) {
244         TRACE("rejecting bind request on connection %p\n", conn);
245         /* Report failure to client. */
246         response = RPCRT4_BuildBindNackHeader(NDR_LOCAL_DATA_REPRESENTATION,
247                                               RPC_VER_MAJOR, RPC_VER_MINOR);
248       } else {
249         TRACE("accepting bind request on connection %p\n", conn);
250
251         /* accept. */
252         response = RPCRT4_BuildBindAckHeader(NDR_LOCAL_DATA_REPRESENTATION,
253                                              RPC_MAX_PACKET_SIZE,
254                                              RPC_MAX_PACKET_SIZE,
255                                              conn->Endpoint,
256                                              RESULT_ACCEPT, NO_REASON,
257                                              &sif->If->TransferSyntax);
258
259         /* save the interface for later use */
260         conn->ActiveInterface = hdr->bind.abstract;
261         conn->MaxTransmissionSize = hdr->bind.max_tsize;
262       }
263
264       status = RPCRT4_Send(conn, response, NULL, 0);
265       RPCRT4_FreeHeader(response);
266       if (status != RPC_S_OK)
267         goto fail;
268
269       break;
270
271     case PKT_REQUEST:
272       TRACE("got request packet\n");
273
274       /* fail if the connection isn't bound with an interface */
275       if (UuidIsNil(&conn->ActiveInterface.SyntaxGUID, &status)) {
276         response = RPCRT4_BuildFaultHeader(NDR_LOCAL_DATA_REPRESENTATION,
277                                            status);
278
279         RPCRT4_Send(conn, response, NULL, 0);
280         RPCRT4_FreeHeader(response);
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   HeapFree(GetProcessHeap(), 0, msg);
349 }
350
351 static DWORD CALLBACK RPCRT4_worker_thread(LPVOID the_arg)
352 {
353   DWORD obj;
354   RpcPacket* pkt;
355
356   for (;;) {
357     /* idle timeout after 5s */
358     obj = WaitForSingleObject(server_sem, 5000);
359     if (obj == WAIT_TIMEOUT) {
360       /* if another idle thread exist, self-destruct */
361       if (worker_free > 1) break;
362       continue;
363     }
364     pkt = RPCRT4_pop_packet();
365     if (!pkt) continue;
366     InterlockedDecrement(&worker_free);
367     for (;;) {
368       RPCRT4_process_packet(pkt->conn, pkt->hdr, pkt->msg);
369       HeapFree(GetProcessHeap(), 0, pkt);
370       /* try to grab another packet here without waiting
371        * on the semaphore, in case it hits max */
372       pkt = RPCRT4_pop_packet();
373       if (!pkt) break;
374       /* decrement semaphore */
375       WaitForSingleObject(server_sem, 0);
376     }
377     InterlockedIncrement(&worker_free);
378   }
379   InterlockedDecrement(&worker_free);
380   InterlockedDecrement(&worker_count);
381   return 0;
382 }
383
384 static void RPCRT4_create_worker_if_needed(void)
385 {
386   if (!worker_free && worker_count < MAX_THREADS) {
387     HANDLE thread;
388     InterlockedIncrement(&worker_count);
389     InterlockedIncrement(&worker_free);
390     thread = CreateThread(NULL, 0, RPCRT4_worker_thread, NULL, 0, NULL);
391     if (thread) CloseHandle(thread);
392     else {
393       InterlockedDecrement(&worker_free);
394       InterlockedDecrement(&worker_count);
395     }
396   }
397 }
398
399 static DWORD CALLBACK RPCRT4_io_thread(LPVOID the_arg)
400 {
401   RpcConnection* conn = (RpcConnection*)the_arg;
402   RpcPktHdr *hdr;
403   RpcBinding *pbind;
404   RPC_MESSAGE *msg;
405   RPC_STATUS status;
406   RpcPacket *packet;
407
408   TRACE("(%p)\n", conn);
409
410   for (;;) {
411     msg = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(RPC_MESSAGE));
412
413     /* create temporary binding for dispatch, it will be freed in
414      * RPCRT4_process_packet */
415     RPCRT4_MakeBinding(&pbind, conn);
416     msg->Handle = (RPC_BINDING_HANDLE)pbind;
417
418     status = RPCRT4_Receive(conn, &hdr, msg);
419     if (status != RPC_S_OK) {
420       WARN("receive failed with error %lx\n", status);
421       HeapFree(GetProcessHeap(), 0, msg);
422       break;
423     }
424
425 #if 0
426     RPCRT4_process_packet(conn, hdr, msg);
427 #else
428     packet = HeapAlloc(GetProcessHeap(), 0, sizeof(RpcPacket));
429     packet->conn = conn;
430     packet->hdr = hdr;
431     packet->msg = msg;
432     RPCRT4_create_worker_if_needed();
433     RPCRT4_push_packet(packet);
434     ReleaseSemaphore(server_sem, 1, NULL);
435 #endif
436     msg = NULL;
437   }
438   RPCRT4_DestroyConnection(conn);
439   return 0;
440 }
441
442 static void RPCRT4_new_client(RpcConnection* conn)
443 {
444   HANDLE thread = CreateThread(NULL, 0, RPCRT4_io_thread, conn, 0, NULL);
445   if (!thread) {
446     DWORD err = GetLastError();
447     ERR("failed to create thread, error=%08lx\n", err);
448     RPCRT4_DestroyConnection(conn);
449   }
450   /* we could set conn->thread, but then we'd have to make the io_thread wait
451    * for that, otherwise the thread might finish, destroy the connection, and
452    * free the memory we'd write to before we did, causing crashes and stuff -
453    * so let's implement that later, when we really need conn->thread */
454
455   CloseHandle( thread );
456 }
457
458 static DWORD CALLBACK RPCRT4_server_thread(LPVOID the_arg)
459 {
460   HANDLE m_event = mgr_event, b_handle;
461   HANDLE *objs = NULL;
462   DWORD count, res;
463   RpcServerProtseq* cps;
464   RpcConnection* conn;
465   RpcConnection* cconn;
466   BOOL set_ready_event = FALSE;
467
468   TRACE("(the_arg == ^%p)\n", the_arg);
469
470   for (;;) {
471     EnterCriticalSection(&server_cs);
472     /* open and count connections */
473     count = 1;
474     cps = protseqs;
475     while (cps) {
476       conn = cps->conn;
477       while (conn) {
478         RPCRT4_OpenConnection(conn);
479         if (rpcrt4_conn_get_wait_object(conn))
480           count++;
481         conn = conn->Next;
482       }
483       cps = cps->Next;
484     }
485     /* make array of connections */
486     if (objs)
487       objs = HeapReAlloc(GetProcessHeap(), 0, objs, count*sizeof(HANDLE));
488     else
489       objs = HeapAlloc(GetProcessHeap(), 0, count*sizeof(HANDLE));
490
491     objs[0] = m_event;
492     count = 1;
493     cps = protseqs;
494     while (cps) {
495       conn = cps->conn;
496       while (conn) {
497         if ((objs[count] = rpcrt4_conn_get_wait_object(conn)))
498           count++;
499         conn = conn->Next;
500       }
501       cps = cps->Next;
502     }
503     LeaveCriticalSection(&server_cs);
504
505     if (set_ready_event)
506     {
507         /* signal to function that changed state that we are now sync'ed */
508         SetEvent(server_ready_event);
509         set_ready_event = FALSE;
510     }
511
512     /* start waiting */
513     res = WaitForMultipleObjects(count, objs, FALSE, INFINITE);
514     if (res == WAIT_OBJECT_0) {
515       if (!std_listen)
516       {
517         SetEvent(server_ready_event);
518         break;
519       }
520       set_ready_event = TRUE;
521     }
522     else if (res == WAIT_FAILED) {
523       ERR("wait failed\n");
524     }
525     else {
526       b_handle = objs[res - WAIT_OBJECT_0];
527       /* find which connection got a RPC */
528       EnterCriticalSection(&server_cs);
529       conn = NULL;
530       cps = protseqs;
531       while (cps) {
532         conn = cps->conn;
533         while (conn) {
534           if (b_handle == rpcrt4_conn_get_wait_object(conn)) break;
535           conn = conn->Next;
536         }
537         if (conn) break;
538         cps = cps->Next;
539       }
540       cconn = NULL;
541       if (conn)
542         RPCRT4_SpawnConnection(&cconn, conn);
543       else
544         ERR("failed to locate connection for handle %p\n", b_handle);
545       LeaveCriticalSection(&server_cs);
546       if (cconn) RPCRT4_new_client(cconn);
547     }
548   }
549   HeapFree(GetProcessHeap(), 0, objs);
550   EnterCriticalSection(&server_cs);
551   /* close connections */
552   cps = protseqs;
553   while (cps) {
554     conn = cps->conn;
555     while (conn) {
556       RPCRT4_CloseConnection(conn);
557       conn = conn->Next;
558     }
559     cps = cps->Next;
560   }
561   LeaveCriticalSection(&server_cs);
562   return 0;
563 }
564
565 /* tells the server thread that the state has changed and waits for it to
566  * make the changes */
567 static void RPCRT4_sync_with_server_thread(void)
568 {
569   /* make sure we are the only thread sync'ing the server state, otherwise
570    * there is a race with the server thread setting an older state and setting
571    * the server_ready_event when the new state hasn't yet been applied */
572   WaitForSingleObject(mgr_mutex, INFINITE);
573
574   SetEvent(mgr_event);
575   /* wait for server thread to make the requested changes before returning */
576   WaitForSingleObject(server_ready_event, INFINITE);
577
578   ReleaseMutex(mgr_mutex);
579 }
580
581 static RPC_STATUS RPCRT4_start_listen(BOOL auto_listen)
582 {
583   RPC_STATUS status = RPC_S_ALREADY_LISTENING;
584
585   TRACE("\n");
586
587   EnterCriticalSection(&listen_cs);
588   if (auto_listen || (manual_listen_count++ == 0))
589   {
590     status = RPC_S_OK;
591     if (++listen_count == 1) {
592       HANDLE server_thread;
593       /* first listener creates server thread */
594       if (!mgr_mutex) mgr_mutex = CreateMutexW(NULL, FALSE, NULL);
595       if (!mgr_event) mgr_event = CreateEventW(NULL, FALSE, FALSE, NULL);
596       if (!server_ready_event) server_ready_event = CreateEventW(NULL, FALSE, FALSE, NULL);
597       if (!server_sem) server_sem = CreateSemaphoreW(NULL, 0, MAX_THREADS, NULL);
598       if (!worker_tls) worker_tls = TlsAlloc();
599       std_listen = TRUE;
600       server_thread = CreateThread(NULL, 0, RPCRT4_server_thread, NULL, 0, NULL);
601       CloseHandle(server_thread);
602     }
603   }
604   LeaveCriticalSection(&listen_cs);
605
606   return status;
607 }
608
609 static void RPCRT4_stop_listen(BOOL auto_listen)
610 {
611   EnterCriticalSection(&listen_cs);
612   if (auto_listen || (--manual_listen_count == 0))
613   {
614     if (listen_count != 0 && --listen_count == 0) {
615       std_listen = FALSE;
616       LeaveCriticalSection(&listen_cs);
617       RPCRT4_sync_with_server_thread();
618       return;
619     }
620     assert(listen_count >= 0);
621   }
622   LeaveCriticalSection(&listen_cs);
623 }
624
625 static RPC_STATUS RPCRT4_use_protseq(RpcServerProtseq* ps)
626 {
627   RPCRT4_CreateConnection(&ps->conn, TRUE, ps->Protseq, NULL, ps->Endpoint,
628                           NULL, NULL, NULL);
629
630   EnterCriticalSection(&server_cs);
631   ps->Next = protseqs;
632   protseqs = ps;
633   LeaveCriticalSection(&server_cs);
634
635   if (std_listen) RPCRT4_sync_with_server_thread();
636
637   return RPC_S_OK;
638 }
639
640 /***********************************************************************
641  *             RpcServerInqBindings (RPCRT4.@)
642  */
643 RPC_STATUS WINAPI RpcServerInqBindings( RPC_BINDING_VECTOR** BindingVector )
644 {
645   RPC_STATUS status;
646   DWORD count;
647   RpcServerProtseq* ps;
648   RpcConnection* conn;
649
650   if (BindingVector)
651     TRACE("(*BindingVector == ^%p)\n", *BindingVector);
652   else
653     ERR("(BindingVector == NULL!!?)\n");
654
655   EnterCriticalSection(&server_cs);
656   /* count connections */
657   count = 0;
658   ps = protseqs;
659   while (ps) {
660     conn = ps->conn;
661     while (conn) {
662       count++;
663       conn = conn->Next;
664     }
665     ps = ps->Next;
666   }
667   if (count) {
668     /* export bindings */
669     *BindingVector = HeapAlloc(GetProcessHeap(), 0,
670                               sizeof(RPC_BINDING_VECTOR) +
671                               sizeof(RPC_BINDING_HANDLE)*(count-1));
672     (*BindingVector)->Count = count;
673     count = 0;
674     ps = protseqs;
675     while (ps) {
676       conn = ps->conn;
677       while (conn) {
678        RPCRT4_MakeBinding((RpcBinding**)&(*BindingVector)->BindingH[count],
679                           conn);
680        count++;
681        conn = conn->Next;
682       }
683       ps = ps->Next;
684     }
685     status = RPC_S_OK;
686   } else {
687     *BindingVector = NULL;
688     status = RPC_S_NO_BINDINGS;
689   }
690   LeaveCriticalSection(&server_cs);
691   return status;
692 }
693
694 /***********************************************************************
695  *             RpcServerUseProtseqEpA (RPCRT4.@)
696  */
697 RPC_STATUS WINAPI RpcServerUseProtseqEpA( unsigned char *Protseq, UINT MaxCalls, unsigned char *Endpoint, LPVOID SecurityDescriptor )
698 {
699   RPC_POLICY policy;
700   
701   TRACE( "(%s,%u,%s,%p)\n", Protseq, MaxCalls, Endpoint, SecurityDescriptor );
702   
703   /* This should provide the default behaviour */
704   policy.Length        = sizeof( policy );
705   policy.EndpointFlags = 0;
706   policy.NICFlags      = 0;
707   
708   return RpcServerUseProtseqEpExA( Protseq, MaxCalls, Endpoint, SecurityDescriptor, &policy );
709 }
710
711 /***********************************************************************
712  *             RpcServerUseProtseqEpW (RPCRT4.@)
713  */
714 RPC_STATUS WINAPI RpcServerUseProtseqEpW( LPWSTR Protseq, UINT MaxCalls, LPWSTR Endpoint, LPVOID SecurityDescriptor )
715 {
716   RPC_POLICY policy;
717   
718   TRACE( "(%s,%u,%s,%p)\n", debugstr_w( Protseq ), MaxCalls, debugstr_w( Endpoint ), SecurityDescriptor );
719   
720   /* This should provide the default behaviour */
721   policy.Length        = sizeof( policy );
722   policy.EndpointFlags = 0;
723   policy.NICFlags      = 0;
724   
725   return RpcServerUseProtseqEpExW( Protseq, MaxCalls, Endpoint, SecurityDescriptor, &policy );
726 }
727
728 /***********************************************************************
729  *             alloc_serverprotoseq (internal)
730  */
731 static RpcServerProtseq *alloc_serverprotoseq(UINT MaxCalls, char *Protseq, char *Endpoint)
732 {
733   RpcServerProtseq* ps;
734
735   ps = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(RpcServerProtseq));
736   ps->MaxCalls = MaxCalls;
737   ps->Protseq = Protseq;
738   ps->Endpoint = Endpoint;
739
740   return ps;
741 }
742
743 /***********************************************************************
744  *             RpcServerUseProtseqEpExA (RPCRT4.@)
745  */
746 RPC_STATUS WINAPI RpcServerUseProtseqEpExA( unsigned char *Protseq, UINT MaxCalls, unsigned char *Endpoint, LPVOID SecurityDescriptor,
747                                             PRPC_POLICY lpPolicy )
748 {
749   char *szps = (char*)Protseq, *szep = (char*)Endpoint;
750   RpcServerProtseq* ps;
751
752   TRACE("(%s,%u,%s,%p,{%u,%lu,%lu})\n", debugstr_a(szps), MaxCalls,
753        debugstr_a(szep), SecurityDescriptor,
754        lpPolicy->Length, lpPolicy->EndpointFlags, lpPolicy->NICFlags );
755
756   ps = alloc_serverprotoseq(MaxCalls, RPCRT4_strdupA(szps), RPCRT4_strdupA(szep));
757
758   return RPCRT4_use_protseq(ps);
759 }
760
761 /***********************************************************************
762  *             RpcServerUseProtseqEpExW (RPCRT4.@)
763  */
764 RPC_STATUS WINAPI RpcServerUseProtseqEpExW( LPWSTR Protseq, UINT MaxCalls, LPWSTR Endpoint, LPVOID SecurityDescriptor,
765                                             PRPC_POLICY lpPolicy )
766 {
767   RpcServerProtseq* ps;
768
769   TRACE("(%s,%u,%s,%p,{%u,%lu,%lu})\n", debugstr_w( Protseq ), MaxCalls,
770        debugstr_w( Endpoint ), SecurityDescriptor,
771        lpPolicy->Length, lpPolicy->EndpointFlags, lpPolicy->NICFlags );
772
773   ps = alloc_serverprotoseq(MaxCalls, RPCRT4_strdupWtoA(Protseq),
774                             RPCRT4_strdupWtoA(Endpoint));
775
776   return RPCRT4_use_protseq(ps);
777 }
778
779 /***********************************************************************
780  *             RpcServerUseProtseqA (RPCRT4.@)
781  */
782 RPC_STATUS WINAPI RpcServerUseProtseqA(unsigned char *Protseq, unsigned int MaxCalls, void *SecurityDescriptor)
783 {
784   TRACE("(Protseq == %s, MaxCalls == %d, SecurityDescriptor == ^%p)\n", debugstr_a((char*)Protseq), MaxCalls, SecurityDescriptor);
785   return RpcServerUseProtseqEpA(Protseq, MaxCalls, NULL, SecurityDescriptor);
786 }
787
788 /***********************************************************************
789  *             RpcServerUseProtseqW (RPCRT4.@)
790  */
791 RPC_STATUS WINAPI RpcServerUseProtseqW(LPWSTR Protseq, unsigned int MaxCalls, void *SecurityDescriptor)
792 {
793   TRACE("Protseq == %s, MaxCalls == %d, SecurityDescriptor == ^%p)\n", debugstr_w(Protseq), MaxCalls, SecurityDescriptor);
794   return RpcServerUseProtseqEpW(Protseq, MaxCalls, NULL, SecurityDescriptor);
795 }
796
797 /***********************************************************************
798  *             RpcServerRegisterIf (RPCRT4.@)
799  */
800 RPC_STATUS WINAPI RpcServerRegisterIf( RPC_IF_HANDLE IfSpec, UUID* MgrTypeUuid, RPC_MGR_EPV* MgrEpv )
801 {
802   TRACE("(%p,%s,%p)\n", IfSpec, debugstr_guid(MgrTypeUuid), MgrEpv);
803   return RpcServerRegisterIf2( IfSpec, MgrTypeUuid, MgrEpv, 0, RPC_C_LISTEN_MAX_CALLS_DEFAULT, (UINT)-1, NULL );
804 }
805
806 /***********************************************************************
807  *             RpcServerRegisterIfEx (RPCRT4.@)
808  */
809 RPC_STATUS WINAPI RpcServerRegisterIfEx( RPC_IF_HANDLE IfSpec, UUID* MgrTypeUuid, RPC_MGR_EPV* MgrEpv,
810                        UINT Flags, UINT MaxCalls, RPC_IF_CALLBACK_FN* IfCallbackFn )
811 {
812   TRACE("(%p,%s,%p,%u,%u,%p)\n", IfSpec, debugstr_guid(MgrTypeUuid), MgrEpv, Flags, MaxCalls, IfCallbackFn);
813   return RpcServerRegisterIf2( IfSpec, MgrTypeUuid, MgrEpv, Flags, MaxCalls, (UINT)-1, IfCallbackFn );
814 }
815
816 /***********************************************************************
817  *             RpcServerRegisterIf2 (RPCRT4.@)
818  */
819 RPC_STATUS WINAPI RpcServerRegisterIf2( RPC_IF_HANDLE IfSpec, UUID* MgrTypeUuid, RPC_MGR_EPV* MgrEpv,
820                       UINT Flags, UINT MaxCalls, UINT MaxRpcSize, RPC_IF_CALLBACK_FN* IfCallbackFn )
821 {
822   PRPC_SERVER_INTERFACE If = (PRPC_SERVER_INTERFACE)IfSpec;
823   RpcServerInterface* sif;
824   unsigned int i;
825
826   TRACE("(%p,%s,%p,%u,%u,%u,%p)\n", IfSpec, debugstr_guid(MgrTypeUuid), MgrEpv, Flags, MaxCalls,
827          MaxRpcSize, IfCallbackFn);
828   TRACE(" interface id: %s %d.%d\n", debugstr_guid(&If->InterfaceId.SyntaxGUID),
829                                      If->InterfaceId.SyntaxVersion.MajorVersion,
830                                      If->InterfaceId.SyntaxVersion.MinorVersion);
831   TRACE(" transfer syntax: %s %d.%d\n", debugstr_guid(&If->TransferSyntax.SyntaxGUID),
832                                         If->TransferSyntax.SyntaxVersion.MajorVersion,
833                                         If->TransferSyntax.SyntaxVersion.MinorVersion);
834   TRACE(" dispatch table: %p\n", If->DispatchTable);
835   if (If->DispatchTable) {
836     TRACE("  dispatch table count: %d\n", If->DispatchTable->DispatchTableCount);
837     for (i=0; i<If->DispatchTable->DispatchTableCount; i++) {
838       TRACE("   entry %d: %p\n", i, If->DispatchTable->DispatchTable[i]);
839     }
840     TRACE("  reserved: %ld\n", If->DispatchTable->Reserved);
841   }
842   TRACE(" protseq endpoint count: %d\n", If->RpcProtseqEndpointCount);
843   TRACE(" default manager epv: %p\n", If->DefaultManagerEpv);
844   TRACE(" interpreter info: %p\n", If->InterpreterInfo);
845
846   sif = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(RpcServerInterface));
847   sif->If           = If;
848   if (MgrTypeUuid) {
849     memcpy(&sif->MgrTypeUuid, MgrTypeUuid, sizeof(UUID));
850     sif->MgrEpv       = MgrEpv;
851   } else {
852     memset(&sif->MgrTypeUuid, 0, sizeof(UUID));
853     sif->MgrEpv       = If->DefaultManagerEpv;
854   }
855   sif->Flags        = Flags;
856   sif->MaxCalls     = MaxCalls;
857   sif->MaxRpcSize   = MaxRpcSize;
858   sif->IfCallbackFn = IfCallbackFn;
859
860   EnterCriticalSection(&server_cs);
861   sif->Next = ifs;
862   ifs = sif;
863   LeaveCriticalSection(&server_cs);
864
865   if (sif->Flags & RPC_IF_AUTOLISTEN) {
866     RPCRT4_start_listen(TRUE);
867
868     /* make sure server is actually listening on the interface before
869      * returning */
870     RPCRT4_sync_with_server_thread();
871   }
872
873   return RPC_S_OK;
874 }
875
876 /***********************************************************************
877  *             RpcServerUnregisterIf (RPCRT4.@)
878  */
879 RPC_STATUS WINAPI RpcServerUnregisterIf( RPC_IF_HANDLE IfSpec, UUID* MgrTypeUuid, UINT WaitForCallsToComplete )
880 {
881   FIXME("(IfSpec == (RPC_IF_HANDLE)^%p, MgrTypeUuid == %s, WaitForCallsToComplete == %u): stub\n",
882     IfSpec, debugstr_guid(MgrTypeUuid), WaitForCallsToComplete);
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( unsigned char *ServerPrincName, unsigned long AuthnSvc, RPC_AUTH_KEY_RETRIEVAL_FN GetKeyFn,
966                             LPVOID Arg )
967 {
968   FIXME( "(%s,%lu,%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( LPWSTR ServerPrincName, unsigned long AuthnSvc, RPC_AUTH_KEY_RETRIEVAL_FN GetKeyFn,
977                             LPVOID Arg )
978 {
979   FIXME( "(%s,%lu,%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;
990
991   TRACE("(%u,%u,%u)\n", MinimumCallThreads, MaxCalls, DontWait);
992
993   if (!protseqs)
994     return RPC_S_NO_PROTSEQS_REGISTERED;
995
996   status = RPCRT4_start_listen(FALSE);
997
998   if (status == RPC_S_OK)
999     RPCRT4_sync_with_server_thread();
1000
1001   if (DontWait || (status != RPC_S_OK)) return status;
1002
1003   return RpcMgmtWaitServerListen();
1004 }
1005
1006 /***********************************************************************
1007  *             RpcMgmtServerWaitListen (RPCRT4.@)
1008  */
1009 RPC_STATUS WINAPI RpcMgmtWaitServerListen( void )
1010 {
1011   TRACE("()\n");
1012
1013   EnterCriticalSection(&listen_cs);
1014
1015   if (!std_listen) {
1016     LeaveCriticalSection(&listen_cs);
1017     return RPC_S_NOT_LISTENING;
1018   }
1019   
1020   LeaveCriticalSection(&listen_cs);
1021
1022   FIXME("not waiting for server calls to finish\n");
1023
1024   return RPC_S_OK;
1025 }
1026
1027 /***********************************************************************
1028  *             RpcMgmtStopServerListening (RPCRT4.@)
1029  */
1030 RPC_STATUS WINAPI RpcMgmtStopServerListening ( RPC_BINDING_HANDLE Binding )
1031 {
1032   TRACE("(Binding == (RPC_BINDING_HANDLE)^%p)\n", Binding);
1033
1034   if (Binding) {
1035     FIXME("client-side invocation not implemented.\n");
1036     return RPC_S_WRONG_KIND_OF_BINDING;
1037   }
1038   
1039   RPCRT4_stop_listen(FALSE);
1040
1041   return RPC_S_OK;
1042 }
1043
1044 /***********************************************************************
1045  *             I_RpcServerStartListening (RPCRT4.@)
1046  */
1047 RPC_STATUS WINAPI I_RpcServerStartListening( HWND hWnd )
1048 {
1049   FIXME( "(%p): stub\n", hWnd );
1050
1051   return RPC_S_OK;
1052 }
1053
1054 /***********************************************************************
1055  *             I_RpcServerStopListening (RPCRT4.@)
1056  */
1057 RPC_STATUS WINAPI I_RpcServerStopListening( void )
1058 {
1059   FIXME( "(): stub\n" );
1060
1061   return RPC_S_OK;
1062 }
1063
1064 /***********************************************************************
1065  *             I_RpcWindowProc (RPCRT4.@)
1066  */
1067 UINT WINAPI I_RpcWindowProc( void *hWnd, UINT Message, UINT wParam, ULONG lParam )
1068 {
1069   FIXME( "(%p,%08x,%08x,%08lx): stub\n", hWnd, Message, wParam, lParam );
1070
1071   return 0;
1072 }
1073
1074 /***********************************************************************
1075  *             RpcMgmtInqIfIds (RPCRT4.@)
1076  */
1077 RPC_STATUS WINAPI RpcMgmtInqIfIds(RPC_BINDING_HANDLE Binding, RPC_IF_ID_VECTOR **IfIdVector)
1078 {
1079   FIXME("(%p,%p): stub\n", Binding, IfIdVector);
1080   return RPC_S_INVALID_BINDING;
1081 }
1082
1083 /***********************************************************************
1084  *             RpcMgmtEpEltInqBegin (RPCRT4.@)
1085  */
1086 RPC_STATUS WINAPI RpcMgmtEpEltInqBegin(RPC_BINDING_HANDLE Binding, unsigned long InquiryType,
1087     RPC_IF_ID *IfId, unsigned long VersOption, UUID *ObjectUuid, RPC_EP_INQ_HANDLE* InquiryContext)
1088 {
1089   FIXME("(%p,%lu,%p,%lu,%p,%p): stub\n",
1090         Binding, InquiryType, IfId, VersOption, ObjectUuid, InquiryContext);
1091   return RPC_S_INVALID_BINDING;
1092 }
1093
1094 /***********************************************************************
1095  *             RpcMgmtEpEltInqBegin (RPCRT4.@)
1096  */
1097 RPC_STATUS WINAPI RpcMgmtIsServerListening(RPC_BINDING_HANDLE Binding)
1098 {
1099   FIXME("(%p): stub\n", Binding);
1100   return RPC_S_INVALID_BINDING;
1101 }