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