rpcrt4: Constify NDR function tables.
[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
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       if (RPCRT4_Send(conn, response, NULL, 0) != RPC_S_OK)
265         goto fail;
266
267       break;
268
269     case PKT_REQUEST:
270       TRACE("got request packet\n");
271
272       /* fail if the connection isn't bound with an interface */
273       if (UuidIsNil(&conn->ActiveInterface.SyntaxGUID, &status)) {
274         response = RPCRT4_BuildFaultHeader(NDR_LOCAL_DATA_REPRESENTATION,
275                                            status);
276
277         RPCRT4_Send(conn, response, NULL, 0);
278         break;
279       }
280
281       if (hdr->common.flags & RPC_FLG_OBJECT_UUID) {
282         object_uuid = (UUID*)(&hdr->request + 1);
283       } else {
284         object_uuid = NULL;
285       }
286
287       sif = RPCRT4_find_interface(object_uuid, &conn->ActiveInterface, TRUE);
288       msg->RpcInterfaceInformation = sif->If;
289       /* copy the endpoint vector from sif to msg so that midl-generated code will use it */
290       msg->ManagerEpv = sif->MgrEpv;
291       if (object_uuid != NULL) {
292         RPCRT4_SetBindingObject(msg->Handle, object_uuid);
293       }
294
295       /* find dispatch function */
296       msg->ProcNum = hdr->request.opnum;
297       if (sif->Flags & RPC_IF_OLE) {
298         /* native ole32 always gives us a dispatch table with a single entry
299          * (I assume that's a wrapper for IRpcStubBuffer::Invoke) */
300         func = *sif->If->DispatchTable->DispatchTable;
301       } else {
302         if (msg->ProcNum >= sif->If->DispatchTable->DispatchTableCount) {
303           ERR("invalid procnum\n");
304           func = NULL;
305         }
306         func = sif->If->DispatchTable->DispatchTable[msg->ProcNum];
307       }
308
309       /* put in the drep. FIXME: is this more universally applicable?
310          perhaps we should move this outward... */
311       msg->DataRepresentation = 
312         MAKELONG( MAKEWORD(hdr->common.drep[0], hdr->common.drep[1]),
313                   MAKEWORD(hdr->common.drep[2], hdr->common.drep[3]));
314
315       /* dispatch */
316       __TRY {
317         if (func) func(msg);
318       } __EXCEPT(rpc_filter) {
319         /* failure packet was created in rpc_filter */
320       } __ENDTRY
321
322       /* send response packet */
323       I_RpcSend(msg);
324
325       msg->RpcInterfaceInformation = NULL;
326
327       break;
328
329     default:
330       FIXME("unhandled packet type\n");
331       break;
332   }
333
334 fail:
335   /* clean up */
336   if (msg->Buffer == buf) msg->Buffer = NULL;
337   TRACE("freeing Buffer=%p\n", buf);
338   HeapFree(GetProcessHeap(), 0, buf);
339   RPCRT4_DestroyBinding(msg->Handle);
340   msg->Handle = 0;
341   I_RpcFreeBuffer(msg);
342   msg->Buffer = NULL;
343   RPCRT4_FreeHeader(hdr);
344   TlsSetValue(worker_tls, NULL);
345 }
346
347 static DWORD CALLBACK RPCRT4_worker_thread(LPVOID the_arg)
348 {
349   DWORD obj;
350   RpcPacket* pkt;
351
352   for (;;) {
353     /* idle timeout after 5s */
354     obj = WaitForSingleObject(server_sem, 5000);
355     if (obj == WAIT_TIMEOUT) {
356       /* if another idle thread exist, self-destruct */
357       if (worker_free > 1) break;
358       continue;
359     }
360     pkt = RPCRT4_pop_packet();
361     if (!pkt) continue;
362     InterlockedDecrement(&worker_free);
363     for (;;) {
364       RPCRT4_process_packet(pkt->conn, pkt->hdr, pkt->msg);
365       HeapFree(GetProcessHeap(), 0, pkt);
366       /* try to grab another packet here without waiting
367        * on the semaphore, in case it hits max */
368       pkt = RPCRT4_pop_packet();
369       if (!pkt) break;
370       /* decrement semaphore */
371       WaitForSingleObject(server_sem, 0);
372     }
373     InterlockedIncrement(&worker_free);
374   }
375   InterlockedDecrement(&worker_free);
376   InterlockedDecrement(&worker_count);
377   return 0;
378 }
379
380 static void RPCRT4_create_worker_if_needed(void)
381 {
382   if (!worker_free && worker_count < MAX_THREADS) {
383     HANDLE thread;
384     InterlockedIncrement(&worker_count);
385     InterlockedIncrement(&worker_free);
386     thread = CreateThread(NULL, 0, RPCRT4_worker_thread, NULL, 0, NULL);
387     if (thread) CloseHandle(thread);
388     else {
389       InterlockedDecrement(&worker_free);
390       InterlockedDecrement(&worker_count);
391     }
392   }
393 }
394
395 static DWORD CALLBACK RPCRT4_io_thread(LPVOID the_arg)
396 {
397   RpcConnection* conn = (RpcConnection*)the_arg;
398   RpcPktHdr *hdr;
399   RpcBinding *pbind;
400   RPC_MESSAGE *msg;
401   RPC_STATUS status;
402   RpcPacket *packet;
403
404   TRACE("(%p)\n", conn);
405
406   for (;;) {
407     msg = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(RPC_MESSAGE));
408
409     /* create temporary binding for dispatch, it will be freed in
410      * RPCRT4_process_packet */
411     RPCRT4_MakeBinding(&pbind, conn);
412     msg->Handle = (RPC_BINDING_HANDLE)pbind;
413
414     status = RPCRT4_Receive(conn, &hdr, msg);
415     if (status != RPC_S_OK) {
416       WARN("receive failed with error %lx\n", status);
417       break;
418     }
419
420 #if 0
421     RPCRT4_process_packet(conn, hdr, msg);
422 #else
423     packet = HeapAlloc(GetProcessHeap(), 0, sizeof(RpcPacket));
424     packet->conn = conn;
425     packet->hdr = hdr;
426     packet->msg = msg;
427     RPCRT4_create_worker_if_needed();
428     RPCRT4_push_packet(packet);
429     ReleaseSemaphore(server_sem, 1, NULL);
430 #endif
431     msg = NULL;
432   }
433   HeapFree(GetProcessHeap(), 0, msg);
434   RPCRT4_DestroyConnection(conn);
435   return 0;
436 }
437
438 static void RPCRT4_new_client(RpcConnection* conn)
439 {
440   HANDLE thread = CreateThread(NULL, 0, RPCRT4_io_thread, conn, 0, NULL);
441   if (!thread) {
442     DWORD err = GetLastError();
443     ERR("failed to create thread, error=%08lx\n", err);
444     RPCRT4_DestroyConnection(conn);
445   }
446   /* we could set conn->thread, but then we'd have to make the io_thread wait
447    * for that, otherwise the thread might finish, destroy the connection, and
448    * free the memory we'd write to before we did, causing crashes and stuff -
449    * so let's implement that later, when we really need conn->thread */
450
451   CloseHandle( thread );
452 }
453
454 static DWORD CALLBACK RPCRT4_server_thread(LPVOID the_arg)
455 {
456   HANDLE m_event = mgr_event, b_handle;
457   HANDLE *objs = NULL;
458   DWORD count, res;
459   RpcServerProtseq* cps;
460   RpcConnection* conn;
461   RpcConnection* cconn;
462   BOOL set_ready_event = FALSE;
463
464   TRACE("(the_arg == ^%p)\n", the_arg);
465
466   for (;;) {
467     EnterCriticalSection(&server_cs);
468     /* open and count connections */
469     count = 1;
470     cps = protseqs;
471     while (cps) {
472       conn = cps->conn;
473       while (conn) {
474         RPCRT4_OpenConnection(conn);
475         if (conn->ovl.hEvent) count++;
476         conn = conn->Next;
477       }
478       cps = cps->Next;
479     }
480     /* make array of connections */
481     if (objs)
482         objs = HeapReAlloc(GetProcessHeap(), 0, objs, count*sizeof(HANDLE));
483     else
484         objs = HeapAlloc(GetProcessHeap(), 0, count*sizeof(HANDLE));
485
486     objs[0] = m_event;
487     count = 1;
488     cps = protseqs;
489     while (cps) {
490       conn = cps->conn;
491       while (conn) {
492         if (conn->ovl.hEvent) objs[count++] = conn->ovl.hEvent;
493         conn = conn->Next;
494       }
495       cps = cps->Next;
496     }
497     LeaveCriticalSection(&server_cs);
498
499     if (set_ready_event)
500     {
501         /* signal to function that changed state that we are now sync'ed */
502         SetEvent(server_ready_event);
503         set_ready_event = FALSE;
504     }
505
506     /* start waiting */
507     res = WaitForMultipleObjects(count, objs, FALSE, INFINITE);
508     if (res == WAIT_OBJECT_0) {
509       if (!std_listen)
510       {
511         SetEvent(server_ready_event);
512         break;
513       }
514       set_ready_event = TRUE;
515     }
516     else if (res == WAIT_FAILED) {
517       ERR("wait failed\n");
518     }
519     else {
520       b_handle = objs[res - WAIT_OBJECT_0];
521       /* find which connection got a RPC */
522       EnterCriticalSection(&server_cs);
523       conn = NULL;
524       cps = protseqs;
525       while (cps) {
526         conn = cps->conn;
527         while (conn) {
528           if (conn->ovl.hEvent == b_handle) break;
529           conn = conn->Next;
530         }
531         if (conn) break;
532         cps = cps->Next;
533       }
534       cconn = NULL;
535       if (conn) RPCRT4_SpawnConnection(&cconn, conn);
536       LeaveCriticalSection(&server_cs);
537       if (!conn) {
538         ERR("failed to locate connection for handle %p\n", b_handle);
539       }
540       if (cconn) RPCRT4_new_client(cconn);
541     }
542   }
543   HeapFree(GetProcessHeap(), 0, objs);
544   EnterCriticalSection(&server_cs);
545   /* close connections */
546   cps = protseqs;
547   while (cps) {
548     conn = cps->conn;
549     while (conn) {
550       RPCRT4_CloseConnection(conn);
551       conn = conn->Next;
552     }
553     cps = cps->Next;
554   }
555   LeaveCriticalSection(&server_cs);
556   return 0;
557 }
558
559 /* tells the server thread that the state has changed and waits for it to
560  * make the changes */
561 static void RPCRT4_sync_with_server_thread(void)
562 {
563   /* make sure we are the only thread sync'ing the server state, otherwise
564    * there is a race with the server thread setting an older state and setting
565    * the server_ready_event when the new state hasn't yet been applied */
566   WaitForSingleObject(mgr_mutex, INFINITE);
567
568   SetEvent(mgr_event);
569   /* wait for server thread to make the requested changes before returning */
570   WaitForSingleObject(server_ready_event, INFINITE);
571
572   ReleaseMutex(mgr_mutex);
573 }
574
575 static RPC_STATUS RPCRT4_start_listen(BOOL auto_listen)
576 {
577   RPC_STATUS status = RPC_S_ALREADY_LISTENING;
578
579   TRACE("\n");
580
581   EnterCriticalSection(&listen_cs);
582   if (auto_listen || (manual_listen_count++ == 0))
583   {
584     status = RPC_S_OK;
585     if (++listen_count == 1) {
586       HANDLE server_thread;
587       /* first listener creates server thread */
588       if (!mgr_mutex) mgr_mutex = CreateMutexW(NULL, FALSE, NULL);
589       if (!mgr_event) mgr_event = CreateEventW(NULL, FALSE, FALSE, NULL);
590       if (!server_ready_event) server_ready_event = CreateEventW(NULL, FALSE, FALSE, NULL);
591       if (!server_sem) server_sem = CreateSemaphoreW(NULL, 0, MAX_THREADS, NULL);
592       if (!worker_tls) worker_tls = TlsAlloc();
593       std_listen = TRUE;
594       server_thread = CreateThread(NULL, 0, RPCRT4_server_thread, NULL, 0, NULL);
595       CloseHandle(server_thread);
596     }
597   }
598   LeaveCriticalSection(&listen_cs);
599
600   return status;
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( (char*)Protseq ), MaxCalls,
730        debugstr_a( (char*)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((char*)Protseq);
736   ps->Endpoint = RPCRT4_strdupA((char*)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((char*)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     RPCRT4_start_listen(TRUE);
849
850     /* make sure server is actually listening on the interface before
851      * returning */
852     RPCRT4_sync_with_server_thread();
853   }
854
855   return RPC_S_OK;
856 }
857
858 /***********************************************************************
859  *             RpcServerUnregisterIf (RPCRT4.@)
860  */
861 RPC_STATUS WINAPI RpcServerUnregisterIf( RPC_IF_HANDLE IfSpec, UUID* MgrTypeUuid, UINT WaitForCallsToComplete )
862 {
863   FIXME("(IfSpec == (RPC_IF_HANDLE)^%p, MgrTypeUuid == %s, WaitForCallsToComplete == %u): stub\n",
864     IfSpec, debugstr_guid(MgrTypeUuid), WaitForCallsToComplete);
865
866   return RPC_S_OK;
867 }
868
869 /***********************************************************************
870  *             RpcServerUnregisterIfEx (RPCRT4.@)
871  */
872 RPC_STATUS WINAPI RpcServerUnregisterIfEx( RPC_IF_HANDLE IfSpec, UUID* MgrTypeUuid, int RundownContextHandles )
873 {
874   FIXME("(IfSpec == (RPC_IF_HANDLE)^%p, MgrTypeUuid == %s, RundownContextHandles == %d): stub\n",
875     IfSpec, debugstr_guid(MgrTypeUuid), RundownContextHandles);
876
877   return RPC_S_OK;
878 }
879
880 /***********************************************************************
881  *             RpcObjectSetType (RPCRT4.@)
882  *
883  * PARAMS
884  *   ObjUuid  [I] "Object" UUID
885  *   TypeUuid [I] "Type" UUID
886  *
887  * RETURNS
888  *   RPC_S_OK                 The call succeeded
889  *   RPC_S_INVALID_OBJECT     The provided object (nil) is not valid
890  *   RPC_S_ALREADY_REGISTERED The provided object is already registered
891  *
892  * Maps "Object" UUIDs to "Type" UUID's.  Passing the nil UUID as the type
893  * resets the mapping for the specified object UUID to nil (the default).
894  * The nil object is always associated with the nil type and cannot be
895  * reassigned.  Servers can support multiple implementations on the same
896  * interface by registering different end-point vectors for the different
897  * types.  There's no need to call this if a server only supports the nil
898  * type, as is typical.
899  */
900 RPC_STATUS WINAPI RpcObjectSetType( UUID* ObjUuid, UUID* TypeUuid )
901 {
902   RpcObjTypeMap *map = RpcObjTypeMaps, *prev = NULL;
903   RPC_STATUS dummy;
904
905   TRACE("(ObjUUID == %s, TypeUuid == %s).\n", debugstr_guid(ObjUuid), debugstr_guid(TypeUuid));
906   if ((! ObjUuid) || UuidIsNil(ObjUuid, &dummy)) {
907     /* nil uuid cannot be remapped */
908     return RPC_S_INVALID_OBJECT;
909   }
910
911   /* find the mapping for this object if there is one ... */
912   while (map) {
913     if (! UuidCompare(ObjUuid, &map->Object, &dummy)) break;
914     prev = map;
915     map = map->next;
916   }
917   if ((! TypeUuid) || UuidIsNil(TypeUuid, &dummy)) {
918     /* ... and drop it from the list */
919     if (map) {
920       if (prev) 
921         prev->next = map->next;
922       else
923         RpcObjTypeMaps = map->next;
924       HeapFree(GetProcessHeap(), 0, map);
925     }
926   } else {
927     /* ... , fail if we found it ... */
928     if (map)
929       return RPC_S_ALREADY_REGISTERED;
930     /* ... otherwise create a new one and add it in. */
931     map = HeapAlloc(GetProcessHeap(), 0, sizeof(RpcObjTypeMap));
932     memcpy(&map->Object, ObjUuid, sizeof(UUID));
933     memcpy(&map->Type, TypeUuid, sizeof(UUID));
934     map->next = NULL;
935     if (prev)
936       prev->next = map; /* prev is the last map in the linklist */
937     else
938       RpcObjTypeMaps = map;
939   }
940
941   return RPC_S_OK;
942 }
943
944 /***********************************************************************
945  *             RpcServerRegisterAuthInfoA (RPCRT4.@)
946  */
947 RPC_STATUS WINAPI RpcServerRegisterAuthInfoA( unsigned char *ServerPrincName, unsigned long AuthnSvc, RPC_AUTH_KEY_RETRIEVAL_FN GetKeyFn,
948                             LPVOID Arg )
949 {
950   FIXME( "(%s,%lu,%p,%p): stub\n", ServerPrincName, AuthnSvc, GetKeyFn, Arg );
951   
952   return RPC_S_UNKNOWN_AUTHN_SERVICE; /* We don't know any authentication services */
953 }
954
955 /***********************************************************************
956  *             RpcServerRegisterAuthInfoW (RPCRT4.@)
957  */
958 RPC_STATUS WINAPI RpcServerRegisterAuthInfoW( LPWSTR ServerPrincName, unsigned long AuthnSvc, RPC_AUTH_KEY_RETRIEVAL_FN GetKeyFn,
959                             LPVOID Arg )
960 {
961   FIXME( "(%s,%lu,%p,%p): stub\n", debugstr_w( ServerPrincName ), AuthnSvc, GetKeyFn, Arg );
962   
963   return RPC_S_UNKNOWN_AUTHN_SERVICE; /* We don't know any authentication services */
964 }
965
966 /***********************************************************************
967  *             RpcServerListen (RPCRT4.@)
968  */
969 RPC_STATUS WINAPI RpcServerListen( UINT MinimumCallThreads, UINT MaxCalls, UINT DontWait )
970 {
971   RPC_STATUS status;
972
973   TRACE("(%u,%u,%u)\n", MinimumCallThreads, MaxCalls, DontWait);
974
975   if (!protseqs)
976     return RPC_S_NO_PROTSEQS_REGISTERED;
977
978   status = RPCRT4_start_listen(FALSE);
979
980   if (status == RPC_S_OK)
981     RPCRT4_sync_with_server_thread();
982
983   if (DontWait || (status != RPC_S_OK)) return status;
984
985   return RpcMgmtWaitServerListen();
986 }
987
988 /***********************************************************************
989  *             RpcMgmtServerWaitListen (RPCRT4.@)
990  */
991 RPC_STATUS WINAPI RpcMgmtWaitServerListen( void )
992 {
993   TRACE("()\n");
994
995   EnterCriticalSection(&listen_cs);
996
997   if (!std_listen) {
998     LeaveCriticalSection(&listen_cs);
999     return RPC_S_NOT_LISTENING;
1000   }
1001   
1002   LeaveCriticalSection(&listen_cs);
1003
1004   return RPC_S_OK;
1005 }
1006
1007 /***********************************************************************
1008  *             RpcMgmtStopServerListening (RPCRT4.@)
1009  */
1010 RPC_STATUS WINAPI RpcMgmtStopServerListening ( RPC_BINDING_HANDLE Binding )
1011 {
1012   TRACE("(Binding == (RPC_BINDING_HANDLE)^%p)\n", Binding);
1013
1014   if (Binding) {
1015     FIXME("client-side invocation not implemented.\n");
1016     return RPC_S_WRONG_KIND_OF_BINDING;
1017   }
1018   
1019   RPCRT4_stop_listen(FALSE);
1020
1021   return RPC_S_OK;
1022 }
1023
1024 /***********************************************************************
1025  *             I_RpcServerStartListening (RPCRT4.@)
1026  */
1027 RPC_STATUS WINAPI I_RpcServerStartListening( HWND hWnd )
1028 {
1029   FIXME( "(%p): stub\n", hWnd );
1030
1031   return RPC_S_OK;
1032 }
1033
1034 /***********************************************************************
1035  *             I_RpcServerStopListening (RPCRT4.@)
1036  */
1037 RPC_STATUS WINAPI I_RpcServerStopListening( void )
1038 {
1039   FIXME( "(): stub\n" );
1040
1041   return RPC_S_OK;
1042 }
1043
1044 /***********************************************************************
1045  *             I_RpcWindowProc (RPCRT4.@)
1046  */
1047 UINT WINAPI I_RpcWindowProc( void *hWnd, UINT Message, UINT wParam, ULONG lParam )
1048 {
1049   FIXME( "(%p,%08x,%08x,%08lx): stub\n", hWnd, Message, wParam, lParam );
1050
1051   return 0;
1052 }