ntoskrnl.exe: Defer deallocation of in_buff in dispatch_ioctl.
[wine.git] / dlls / rpcrt4 / rpc_server.c
blobd77354d65f8c26d1152e30076fb393bd7142852f
1 /*
2 * RPC server API
4 * Copyright 2001 Ove Kåven, TransGaming Technologies
5 * Copyright 2004 Filip Navara
6 * Copyright 2006-2008 Robert Shearman (for CodeWeavers)
8 * This library is free software; you can redistribute it and/or
9 * modify it under the terms of the GNU Lesser General Public
10 * License as published by the Free Software Foundation; either
11 * version 2.1 of the License, or (at your option) any later version.
13 * This library is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 * Lesser General Public License for more details.
18 * You should have received a copy of the GNU Lesser General Public
19 * License along with this library; if not, write to the Free Software
20 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
23 #include "config.h"
24 #include "wine/port.h"
26 #include <stdarg.h>
27 #include <stdio.h>
28 #include <string.h>
29 #include <assert.h>
31 #include "windef.h"
32 #include "winbase.h"
33 #include "winerror.h"
35 #include "rpc.h"
36 #include "rpcndr.h"
37 #include "excpt.h"
39 #include "wine/debug.h"
40 #include "wine/exception.h"
42 #include "rpc_server.h"
43 #include "rpc_assoc.h"
44 #include "rpc_message.h"
45 #include "rpc_defs.h"
46 #include "ncastatus.h"
47 #include "secext.h"
49 WINE_DEFAULT_DEBUG_CHANNEL(rpc);
51 typedef struct _RpcPacket
53 struct _RpcConnection* conn;
54 RpcPktHdr* hdr;
55 RPC_MESSAGE* msg;
56 unsigned char *auth_data;
57 ULONG auth_length;
58 } RpcPacket;
60 typedef struct _RpcObjTypeMap
62 /* FIXME: a hash table would be better. */
63 struct _RpcObjTypeMap *next;
64 UUID Object;
65 UUID Type;
66 } RpcObjTypeMap;
68 static RpcObjTypeMap *RpcObjTypeMaps;
70 /* list of type RpcServerProtseq */
71 static struct list protseqs = LIST_INIT(protseqs);
72 static struct list server_interfaces = LIST_INIT(server_interfaces);
73 static struct list server_registered_auth_info = LIST_INIT(server_registered_auth_info);
75 static CRITICAL_SECTION server_cs;
76 static CRITICAL_SECTION_DEBUG server_cs_debug =
78 0, 0, &server_cs,
79 { &server_cs_debug.ProcessLocksList, &server_cs_debug.ProcessLocksList },
80 0, 0, { (DWORD_PTR)(__FILE__ ": server_cs") }
82 static CRITICAL_SECTION server_cs = { &server_cs_debug, -1, 0, 0, 0, 0 };
84 static CRITICAL_SECTION listen_cs;
85 static CRITICAL_SECTION_DEBUG listen_cs_debug =
87 0, 0, &listen_cs,
88 { &listen_cs_debug.ProcessLocksList, &listen_cs_debug.ProcessLocksList },
89 0, 0, { (DWORD_PTR)(__FILE__ ": listen_cs") }
91 static CRITICAL_SECTION listen_cs = { &listen_cs_debug, -1, 0, 0, 0, 0 };
93 static CRITICAL_SECTION server_auth_info_cs;
94 static CRITICAL_SECTION_DEBUG server_auth_info_cs_debug =
96 0, 0, &server_auth_info_cs,
97 { &server_auth_info_cs_debug.ProcessLocksList, &server_auth_info_cs_debug.ProcessLocksList },
98 0, 0, { (DWORD_PTR)(__FILE__ ": server_auth_info_cs") }
100 static CRITICAL_SECTION server_auth_info_cs = { &server_auth_info_cs_debug, -1, 0, 0, 0, 0 };
102 /* whether the server is currently listening */
103 static BOOL std_listen;
104 /* number of manual listeners (calls to RpcServerListen) */
105 static LONG manual_listen_count;
106 /* total listeners including auto listeners */
107 static LONG listen_count;
108 /* event set once all listening is finished */
109 static HANDLE listen_done_event;
111 static UUID uuid_nil;
113 static inline RpcObjTypeMap *LookupObjTypeMap(UUID *ObjUuid)
115 RpcObjTypeMap *rslt = RpcObjTypeMaps;
116 RPC_STATUS dummy;
118 while (rslt) {
119 if (! UuidCompare(ObjUuid, &rslt->Object, &dummy)) break;
120 rslt = rslt->next;
123 return rslt;
126 static inline UUID *LookupObjType(UUID *ObjUuid)
128 RpcObjTypeMap *map = LookupObjTypeMap(ObjUuid);
129 if (map)
130 return &map->Type;
131 else
132 return &uuid_nil;
135 static RpcServerInterface* RPCRT4_find_interface(UUID* object,
136 const RPC_SYNTAX_IDENTIFIER *if_id,
137 const RPC_SYNTAX_IDENTIFIER *transfer_syntax,
138 BOOL check_object)
140 UUID* MgrType = NULL;
141 RpcServerInterface* cif;
142 RPC_STATUS status;
144 if (check_object)
145 MgrType = LookupObjType(object);
146 EnterCriticalSection(&server_cs);
147 LIST_FOR_EACH_ENTRY(cif, &server_interfaces, RpcServerInterface, entry) {
148 if (!memcmp(if_id, &cif->If->InterfaceId, sizeof(RPC_SYNTAX_IDENTIFIER)) &&
149 (!transfer_syntax || !memcmp(transfer_syntax, &cif->If->TransferSyntax, sizeof(RPC_SYNTAX_IDENTIFIER))) &&
150 (check_object == FALSE || UuidEqual(MgrType, &cif->MgrTypeUuid, &status)) &&
151 std_listen) {
152 InterlockedIncrement(&cif->CurrentCalls);
153 break;
156 LeaveCriticalSection(&server_cs);
157 if (&cif->entry == &server_interfaces) cif = NULL;
158 TRACE("returning %p for object %s, if_id { %d.%d %s }\n", cif,
159 debugstr_guid(object), if_id->SyntaxVersion.MajorVersion,
160 if_id->SyntaxVersion.MinorVersion, debugstr_guid(&if_id->SyntaxGUID));
161 return cif;
164 static void RPCRT4_release_server_interface(RpcServerInterface *sif)
166 if (!InterlockedDecrement(&sif->CurrentCalls) &&
167 sif->Delete) {
168 /* sif must have been removed from server_interfaces before
169 * CallsCompletedEvent is set */
170 if (sif->CallsCompletedEvent)
171 SetEvent(sif->CallsCompletedEvent);
172 HeapFree(GetProcessHeap(), 0, sif);
176 static RpcPktHdr *handle_bind_error(RpcConnection *conn, RPC_STATUS error)
178 unsigned int reject_reason;
179 switch (error)
181 case RPC_S_SERVER_TOO_BUSY:
182 reject_reason = REJECT_TEMPORARY_CONGESTION;
183 break;
184 case ERROR_OUTOFMEMORY:
185 case RPC_S_OUT_OF_RESOURCES:
186 reject_reason = REJECT_LOCAL_LIMIT_EXCEEDED;
187 break;
188 case RPC_S_PROTOCOL_ERROR:
189 reject_reason = REJECT_PROTOCOL_VERSION_NOT_SUPPORTED;
190 break;
191 case RPC_S_UNKNOWN_AUTHN_SERVICE:
192 reject_reason = REJECT_UNKNOWN_AUTHN_SERVICE;
193 break;
194 case ERROR_ACCESS_DENIED:
195 reject_reason = REJECT_INVALID_CHECKSUM;
196 break;
197 default:
198 FIXME("unexpected status value %d\n", error);
199 /* fall through */
200 case RPC_S_INVALID_BOUND:
201 reject_reason = REJECT_REASON_NOT_SPECIFIED;
202 break;
204 return RPCRT4_BuildBindNackHeader(NDR_LOCAL_DATA_REPRESENTATION,
205 RPC_VER_MAJOR, RPC_VER_MINOR,
206 reject_reason);
209 static RPC_STATUS process_bind_packet_no_send(
210 RpcConnection *conn, RpcPktBindHdr *hdr, RPC_MESSAGE *msg,
211 unsigned char *auth_data, ULONG auth_length, RpcPktHdr **ack_response,
212 unsigned char **auth_data_out, ULONG *auth_length_out)
214 RPC_STATUS status;
215 RpcContextElement *ctxt_elem;
216 unsigned int i;
217 RpcResult *results;
219 /* validate data */
220 for (i = 0, ctxt_elem = msg->Buffer;
221 i < hdr->num_elements;
222 i++, ctxt_elem = (RpcContextElement *)&ctxt_elem->transfer_syntaxes[ctxt_elem->num_syntaxes])
224 if (((char *)ctxt_elem - (char *)msg->Buffer) > msg->BufferLength ||
225 ((char *)&ctxt_elem->transfer_syntaxes[ctxt_elem->num_syntaxes] - (char *)msg->Buffer) > msg->BufferLength)
227 ERR("inconsistent data in packet - packet length %d, num elements %d\n",
228 msg->BufferLength, hdr->num_elements);
229 return RPC_S_INVALID_BOUND;
233 if (hdr->max_tsize < RPC_MIN_PACKET_SIZE ||
234 !UuidIsNil(&conn->ActiveInterface.SyntaxGUID, &status) ||
235 conn->server_binding)
237 TRACE("packet size less than min size, or active interface syntax guid non-null\n");
239 return RPC_S_INVALID_BOUND;
242 results = HeapAlloc(GetProcessHeap(), 0,
243 hdr->num_elements * sizeof(*results));
244 if (!results)
245 return RPC_S_OUT_OF_RESOURCES;
247 for (i = 0, ctxt_elem = (RpcContextElement *)msg->Buffer;
248 i < hdr->num_elements;
249 i++, ctxt_elem = (RpcContextElement *)&ctxt_elem->transfer_syntaxes[ctxt_elem->num_syntaxes])
251 RpcServerInterface* sif = NULL;
252 unsigned int j;
254 for (j = 0; !sif && j < ctxt_elem->num_syntaxes; j++)
256 sif = RPCRT4_find_interface(NULL, &ctxt_elem->abstract_syntax,
257 &ctxt_elem->transfer_syntaxes[j], FALSE);
258 if (sif)
259 break;
261 if (sif)
263 RPCRT4_release_server_interface(sif);
264 TRACE("accepting bind request on connection %p for %s\n", conn,
265 debugstr_guid(&ctxt_elem->abstract_syntax.SyntaxGUID));
266 results[i].result = RESULT_ACCEPT;
267 results[i].reason = REASON_NONE;
268 results[i].transfer_syntax = ctxt_elem->transfer_syntaxes[j];
270 /* save the interface for later use */
271 /* FIXME: save linked list */
272 conn->ActiveInterface = ctxt_elem->abstract_syntax;
274 else if ((sif = RPCRT4_find_interface(NULL, &ctxt_elem->abstract_syntax,
275 NULL, FALSE)) != NULL)
277 RPCRT4_release_server_interface(sif);
278 TRACE("not accepting bind request on connection %p for %s - no transfer syntaxes supported\n",
279 conn, debugstr_guid(&ctxt_elem->abstract_syntax.SyntaxGUID));
280 results[i].result = RESULT_PROVIDER_REJECTION;
281 results[i].reason = REASON_TRANSFER_SYNTAXES_NOT_SUPPORTED;
282 memset(&results[i].transfer_syntax, 0, sizeof(results[i].transfer_syntax));
284 else
286 TRACE("not accepting bind request on connection %p for %s - abstract syntax not supported\n",
287 conn, debugstr_guid(&ctxt_elem->abstract_syntax.SyntaxGUID));
288 results[i].result = RESULT_PROVIDER_REJECTION;
289 results[i].reason = REASON_ABSTRACT_SYNTAX_NOT_SUPPORTED;
290 memset(&results[i].transfer_syntax, 0, sizeof(results[i].transfer_syntax));
294 /* create temporary binding */
295 status = RPCRT4_MakeBinding(&conn->server_binding, conn);
296 if (status != RPC_S_OK)
298 HeapFree(GetProcessHeap(), 0, results);
299 return status;
302 status = RpcServerAssoc_GetAssociation(rpcrt4_conn_get_name(conn),
303 conn->NetworkAddr, conn->Endpoint,
304 conn->NetworkOptions,
305 hdr->assoc_gid,
306 &conn->server_binding->Assoc);
307 if (status != RPC_S_OK)
309 HeapFree(GetProcessHeap(), 0, results);
310 return status;
313 if (auth_length)
315 status = RPCRT4_ServerConnectionAuth(conn, TRUE,
316 (RpcAuthVerifier *)auth_data,
317 auth_length, auth_data_out,
318 auth_length_out);
319 if (status != RPC_S_OK)
321 HeapFree(GetProcessHeap(), 0, results);
322 return status;
326 *ack_response = RPCRT4_BuildBindAckHeader(NDR_LOCAL_DATA_REPRESENTATION,
327 RPC_MAX_PACKET_SIZE,
328 RPC_MAX_PACKET_SIZE,
329 conn->server_binding->Assoc->assoc_group_id,
330 conn->Endpoint, hdr->num_elements,
331 results);
332 HeapFree(GetProcessHeap(), 0, results);
334 if (*ack_response)
335 conn->MaxTransmissionSize = hdr->max_tsize;
336 else
337 status = RPC_S_OUT_OF_RESOURCES;
339 return status;
342 static RPC_STATUS process_bind_packet(RpcConnection *conn, RpcPktBindHdr *hdr,
343 RPC_MESSAGE *msg,
344 unsigned char *auth_data,
345 ULONG auth_length)
347 RPC_STATUS status;
348 RpcPktHdr *response = NULL;
349 unsigned char *auth_data_out = NULL;
350 ULONG auth_length_out = 0;
352 status = process_bind_packet_no_send(conn, hdr, msg, auth_data, auth_length,
353 &response, &auth_data_out,
354 &auth_length_out);
355 if (status != RPC_S_OK)
356 response = handle_bind_error(conn, status);
357 if (response)
358 status = RPCRT4_SendWithAuth(conn, response, NULL, 0, auth_data_out, auth_length_out);
359 else
360 status = ERROR_OUTOFMEMORY;
361 RPCRT4_FreeHeader(response);
363 return status;
367 static RPC_STATUS process_request_packet(RpcConnection *conn, RpcPktRequestHdr *hdr, RPC_MESSAGE *msg)
369 RPC_STATUS status;
370 RpcPktHdr *response = NULL;
371 RpcServerInterface* sif;
372 RPC_DISPATCH_FUNCTION func;
373 BOOL exception;
374 UUID *object_uuid;
375 NDR_SCONTEXT context_handle;
376 void *buf = msg->Buffer;
378 /* fail if the connection isn't bound with an interface */
379 if (UuidIsNil(&conn->ActiveInterface.SyntaxGUID, &status)) {
380 /* FIXME: should send BindNack instead */
381 response = RPCRT4_BuildFaultHeader(NDR_LOCAL_DATA_REPRESENTATION,
382 status);
384 RPCRT4_Send(conn, response, NULL, 0);
385 RPCRT4_FreeHeader(response);
386 return RPC_S_OK;
389 if (hdr->common.flags & RPC_FLG_OBJECT_UUID) {
390 object_uuid = (UUID*)(hdr + 1);
391 } else {
392 object_uuid = NULL;
395 sif = RPCRT4_find_interface(object_uuid, &conn->ActiveInterface, NULL, TRUE);
396 if (!sif) {
397 WARN("interface %s no longer registered, returning fault packet\n", debugstr_guid(&conn->ActiveInterface.SyntaxGUID));
398 response = RPCRT4_BuildFaultHeader(NDR_LOCAL_DATA_REPRESENTATION,
399 NCA_S_UNK_IF);
401 RPCRT4_Send(conn, response, NULL, 0);
402 RPCRT4_FreeHeader(response);
403 return RPC_S_OK;
405 msg->RpcInterfaceInformation = sif->If;
406 /* copy the endpoint vector from sif to msg so that midl-generated code will use it */
407 msg->ManagerEpv = sif->MgrEpv;
408 if (object_uuid != NULL) {
409 RPCRT4_SetBindingObject(msg->Handle, object_uuid);
412 /* find dispatch function */
413 msg->ProcNum = hdr->opnum;
414 if (sif->Flags & RPC_IF_OLE) {
415 /* native ole32 always gives us a dispatch table with a single entry
416 * (I assume that's a wrapper for IRpcStubBuffer::Invoke) */
417 func = *sif->If->DispatchTable->DispatchTable;
418 } else {
419 if (msg->ProcNum >= sif->If->DispatchTable->DispatchTableCount) {
420 WARN("invalid procnum (%d/%d)\n", msg->ProcNum, sif->If->DispatchTable->DispatchTableCount);
421 response = RPCRT4_BuildFaultHeader(NDR_LOCAL_DATA_REPRESENTATION,
422 NCA_S_OP_RNG_ERROR);
424 RPCRT4_Send(conn, response, NULL, 0);
425 RPCRT4_FreeHeader(response);
427 func = sif->If->DispatchTable->DispatchTable[msg->ProcNum];
430 /* put in the drep. FIXME: is this more universally applicable?
431 perhaps we should move this outward... */
432 msg->DataRepresentation =
433 MAKELONG( MAKEWORD(hdr->common.drep[0], hdr->common.drep[1]),
434 MAKEWORD(hdr->common.drep[2], hdr->common.drep[3]));
436 exception = FALSE;
438 /* dispatch */
439 RPCRT4_SetThreadCurrentCallHandle(msg->Handle);
440 __TRY {
441 if (func) func(msg);
442 } __EXCEPT_ALL {
443 WARN("exception caught with code 0x%08x = %d\n", GetExceptionCode(), GetExceptionCode());
444 exception = TRUE;
445 if (GetExceptionCode() == STATUS_ACCESS_VIOLATION)
446 status = ERROR_NOACCESS;
447 else
448 status = GetExceptionCode();
449 response = RPCRT4_BuildFaultHeader(msg->DataRepresentation,
450 RPC2NCA_STATUS(status));
451 } __ENDTRY
452 RPCRT4_SetThreadCurrentCallHandle(NULL);
454 /* release any unmarshalled context handles */
455 while ((context_handle = RPCRT4_PopThreadContextHandle()) != NULL)
456 RpcServerAssoc_ReleaseContextHandle(conn->server_binding->Assoc, context_handle, TRUE);
458 if (!exception)
459 response = RPCRT4_BuildResponseHeader(msg->DataRepresentation,
460 msg->BufferLength);
462 /* send response packet */
463 if (response) {
464 status = RPCRT4_Send(conn, response, exception ? NULL : msg->Buffer,
465 exception ? 0 : msg->BufferLength);
466 RPCRT4_FreeHeader(response);
467 } else
468 ERR("out of memory\n");
470 msg->RpcInterfaceInformation = NULL;
471 RPCRT4_release_server_interface(sif);
473 if (msg->Buffer == buf) buf = NULL;
474 TRACE("freeing Buffer=%p\n", buf);
475 I_RpcFree(buf);
477 return status;
480 static RPC_STATUS process_auth3_packet(RpcConnection *conn,
481 RpcPktCommonHdr *hdr,
482 RPC_MESSAGE *msg,
483 unsigned char *auth_data,
484 ULONG auth_length)
486 RPC_STATUS status;
488 if (UuidIsNil(&conn->ActiveInterface.SyntaxGUID, &status) ||
489 !auth_length || msg->BufferLength != 0)
490 status = RPC_S_PROTOCOL_ERROR;
491 else
493 status = RPCRT4_ServerConnectionAuth(conn, FALSE,
494 (RpcAuthVerifier *)auth_data,
495 auth_length, NULL, NULL);
498 /* FIXME: client doesn't expect a response to this message so must store
499 * status in connection so that fault packet can be returned when next
500 * packet is received */
502 return RPC_S_OK;
505 static void RPCRT4_process_packet(RpcConnection* conn, RpcPktHdr* hdr,
506 RPC_MESSAGE* msg, unsigned char *auth_data,
507 ULONG auth_length)
509 msg->Handle = (RPC_BINDING_HANDLE)conn->server_binding;
511 switch (hdr->common.ptype) {
512 case PKT_BIND:
513 TRACE("got bind packet\n");
514 process_bind_packet(conn, &hdr->bind, msg, auth_data, auth_length);
515 break;
517 case PKT_REQUEST:
518 TRACE("got request packet\n");
519 process_request_packet(conn, &hdr->request, msg);
520 break;
522 case PKT_AUTH3:
523 TRACE("got auth3 packet\n");
524 process_auth3_packet(conn, &hdr->common, msg, auth_data, auth_length);
525 break;
526 default:
527 FIXME("unhandled packet type %u\n", hdr->common.ptype);
528 break;
531 /* clean up */
532 I_RpcFree(msg->Buffer);
533 RPCRT4_FreeHeader(hdr);
534 HeapFree(GetProcessHeap(), 0, msg);
535 HeapFree(GetProcessHeap(), 0, auth_data);
538 static DWORD CALLBACK RPCRT4_worker_thread(LPVOID the_arg)
540 RpcPacket *pkt = the_arg;
541 RPCRT4_process_packet(pkt->conn, pkt->hdr, pkt->msg, pkt->auth_data,
542 pkt->auth_length);
543 RPCRT4_ReleaseConnection(pkt->conn);
544 HeapFree(GetProcessHeap(), 0, pkt);
545 return 0;
548 static DWORD CALLBACK RPCRT4_io_thread(LPVOID the_arg)
550 RpcConnection* conn = the_arg;
551 RpcPktHdr *hdr;
552 RPC_MESSAGE *msg;
553 RPC_STATUS status;
554 RpcPacket *packet;
555 unsigned char *auth_data;
556 ULONG auth_length;
558 TRACE("(%p)\n", conn);
560 for (;;) {
561 msg = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(RPC_MESSAGE));
562 if (!msg) break;
564 status = RPCRT4_ReceiveWithAuth(conn, &hdr, msg, &auth_data, &auth_length);
565 if (status != RPC_S_OK) {
566 WARN("receive failed with error %x\n", status);
567 HeapFree(GetProcessHeap(), 0, msg);
568 break;
571 switch (hdr->common.ptype) {
572 case PKT_BIND:
573 TRACE("got bind packet\n");
575 status = process_bind_packet(conn, &hdr->bind, msg, auth_data,
576 auth_length);
577 break;
579 case PKT_REQUEST:
580 TRACE("got request packet\n");
582 packet = HeapAlloc(GetProcessHeap(), 0, sizeof(RpcPacket));
583 if (!packet) {
584 I_RpcFree(msg->Buffer);
585 RPCRT4_FreeHeader(hdr);
586 HeapFree(GetProcessHeap(), 0, msg);
587 HeapFree(GetProcessHeap(), 0, auth_data);
588 goto exit;
590 packet->conn = RPCRT4_GrabConnection( conn );
591 packet->hdr = hdr;
592 packet->msg = msg;
593 packet->auth_data = auth_data;
594 packet->auth_length = auth_length;
595 if (!QueueUserWorkItem(RPCRT4_worker_thread, packet, WT_EXECUTELONGFUNCTION)) {
596 ERR("couldn't queue work item for worker thread, error was %d\n", GetLastError());
597 HeapFree(GetProcessHeap(), 0, packet);
598 status = RPC_S_OUT_OF_RESOURCES;
599 } else {
600 continue;
602 break;
604 case PKT_AUTH3:
605 TRACE("got auth3 packet\n");
607 status = process_auth3_packet(conn, &hdr->common, msg, auth_data,
608 auth_length);
609 break;
610 default:
611 FIXME("unhandled packet type %u\n", hdr->common.ptype);
612 break;
615 I_RpcFree(msg->Buffer);
616 RPCRT4_FreeHeader(hdr);
617 HeapFree(GetProcessHeap(), 0, msg);
618 HeapFree(GetProcessHeap(), 0, auth_data);
620 if (status != RPC_S_OK) {
621 WARN("processing packet failed with error %u\n", status);
622 break;
625 exit:
626 RPCRT4_ReleaseConnection(conn);
627 return 0;
630 void RPCRT4_new_client(RpcConnection* conn)
632 HANDLE thread = CreateThread(NULL, 0, RPCRT4_io_thread, conn, 0, NULL);
633 if (!thread) {
634 DWORD err = GetLastError();
635 ERR("failed to create thread, error=%08x\n", err);
636 RPCRT4_ReleaseConnection(conn);
638 /* we could set conn->thread, but then we'd have to make the io_thread wait
639 * for that, otherwise the thread might finish, destroy the connection, and
640 * free the memory we'd write to before we did, causing crashes and stuff -
641 * so let's implement that later, when we really need conn->thread */
643 CloseHandle( thread );
646 static DWORD CALLBACK RPCRT4_server_thread(LPVOID the_arg)
648 int res;
649 unsigned int count;
650 void *objs = NULL;
651 RpcServerProtseq* cps = the_arg;
652 RpcConnection* conn;
653 BOOL set_ready_event = FALSE;
655 TRACE("(the_arg == ^%p)\n", the_arg);
657 for (;;) {
658 objs = cps->ops->get_wait_array(cps, objs, &count);
660 if (set_ready_event)
662 /* signal to function that changed state that we are now sync'ed */
663 SetEvent(cps->server_ready_event);
664 set_ready_event = FALSE;
667 /* start waiting */
668 res = cps->ops->wait_for_new_connection(cps, count, objs);
670 if (res == -1 || (res == 0 && !std_listen))
672 /* cleanup */
673 cps->ops->free_wait_array(cps, objs);
674 EnterCriticalSection(&cps->cs);
675 for (conn = cps->conn; conn; conn = conn->Next)
676 RPCRT4_CloseConnection(conn);
677 LeaveCriticalSection(&cps->cs);
679 if (res == 0 && !std_listen)
680 SetEvent(cps->server_ready_event);
681 break;
683 else if (res == 0)
684 set_ready_event = TRUE;
686 return 0;
689 /* tells the server thread that the state has changed and waits for it to
690 * make the changes */
691 static void RPCRT4_sync_with_server_thread(RpcServerProtseq *ps)
693 /* make sure we are the only thread sync'ing the server state, otherwise
694 * there is a race with the server thread setting an older state and setting
695 * the server_ready_event when the new state hasn't yet been applied */
696 WaitForSingleObject(ps->mgr_mutex, INFINITE);
698 ps->ops->signal_state_changed(ps);
700 /* wait for server thread to make the requested changes before returning */
701 WaitForSingleObject(ps->server_ready_event, INFINITE);
703 ReleaseMutex(ps->mgr_mutex);
706 static RPC_STATUS RPCRT4_start_listen_protseq(RpcServerProtseq *ps, BOOL auto_listen)
708 RPC_STATUS status = RPC_S_OK;
709 HANDLE server_thread;
711 EnterCriticalSection(&listen_cs);
712 if (ps->is_listening) goto done;
714 if (!ps->mgr_mutex) ps->mgr_mutex = CreateMutexW(NULL, FALSE, NULL);
715 if (!ps->server_ready_event) ps->server_ready_event = CreateEventW(NULL, FALSE, FALSE, NULL);
716 server_thread = CreateThread(NULL, 0, RPCRT4_server_thread, ps, 0, NULL);
717 if (!server_thread)
719 status = RPC_S_OUT_OF_RESOURCES;
720 goto done;
722 ps->is_listening = TRUE;
723 CloseHandle(server_thread);
725 done:
726 LeaveCriticalSection(&listen_cs);
727 return status;
730 static RPC_STATUS RPCRT4_start_listen(BOOL auto_listen)
732 RPC_STATUS status = RPC_S_ALREADY_LISTENING;
733 RpcServerProtseq *cps;
735 TRACE("\n");
737 EnterCriticalSection(&listen_cs);
738 if (auto_listen || (manual_listen_count++ == 0))
740 status = RPC_S_OK;
741 if (++listen_count == 1)
742 std_listen = TRUE;
744 LeaveCriticalSection(&listen_cs);
746 if (std_listen)
748 EnterCriticalSection(&server_cs);
749 LIST_FOR_EACH_ENTRY(cps, &protseqs, RpcServerProtseq, entry)
751 status = RPCRT4_start_listen_protseq(cps, TRUE);
752 if (status != RPC_S_OK)
753 break;
755 /* make sure server is actually listening on the interface before
756 * returning */
757 RPCRT4_sync_with_server_thread(cps);
759 LeaveCriticalSection(&server_cs);
762 return status;
765 static RPC_STATUS RPCRT4_stop_listen(BOOL auto_listen)
767 RPC_STATUS status = RPC_S_OK;
769 EnterCriticalSection(&listen_cs);
771 if (!std_listen)
773 status = RPC_S_NOT_LISTENING;
774 goto done;
777 if (auto_listen || (--manual_listen_count == 0))
779 if (listen_count != 0 && --listen_count == 0) {
780 RpcServerProtseq *cps;
782 std_listen = FALSE;
783 LeaveCriticalSection(&listen_cs);
785 LIST_FOR_EACH_ENTRY(cps, &protseqs, RpcServerProtseq, entry)
786 RPCRT4_sync_with_server_thread(cps);
788 EnterCriticalSection(&listen_cs);
789 if (listen_done_event) SetEvent( listen_done_event );
790 listen_done_event = 0;
791 goto done;
793 assert(listen_count >= 0);
796 done:
797 LeaveCriticalSection(&listen_cs);
798 return status;
801 static BOOL RPCRT4_protseq_is_endpoint_registered(RpcServerProtseq *protseq, const char *endpoint)
803 RpcConnection *conn;
804 EnterCriticalSection(&protseq->cs);
805 for (conn = protseq->conn; conn; conn = conn->Next)
807 if (!endpoint || !strcmp(endpoint, conn->Endpoint))
808 break;
810 LeaveCriticalSection(&protseq->cs);
811 return (conn != NULL);
814 static RPC_STATUS RPCRT4_use_protseq(RpcServerProtseq* ps, const char *endpoint)
816 RPC_STATUS status;
818 EnterCriticalSection(&ps->cs);
820 if (RPCRT4_protseq_is_endpoint_registered(ps, endpoint))
821 status = RPC_S_OK;
822 else
823 status = ps->ops->open_endpoint(ps, endpoint);
825 LeaveCriticalSection(&ps->cs);
827 if (status != RPC_S_OK)
828 return status;
830 if (std_listen)
832 status = RPCRT4_start_listen_protseq(ps, FALSE);
833 if (status == RPC_S_OK)
834 RPCRT4_sync_with_server_thread(ps);
837 return status;
840 /***********************************************************************
841 * RpcServerInqBindings (RPCRT4.@)
843 RPC_STATUS WINAPI RpcServerInqBindings( RPC_BINDING_VECTOR** BindingVector )
845 RPC_STATUS status;
846 DWORD count;
847 RpcServerProtseq* ps;
848 RpcConnection* conn;
850 if (BindingVector)
851 TRACE("(*BindingVector == ^%p)\n", *BindingVector);
852 else
853 ERR("(BindingVector == NULL!!?)\n");
855 EnterCriticalSection(&server_cs);
856 /* count connections */
857 count = 0;
858 LIST_FOR_EACH_ENTRY(ps, &protseqs, RpcServerProtseq, entry) {
859 EnterCriticalSection(&ps->cs);
860 for (conn = ps->conn; conn; conn = conn->Next)
861 count++;
862 LeaveCriticalSection(&ps->cs);
864 if (count) {
865 /* export bindings */
866 *BindingVector = HeapAlloc(GetProcessHeap(), 0,
867 sizeof(RPC_BINDING_VECTOR) +
868 sizeof(RPC_BINDING_HANDLE)*(count-1));
869 (*BindingVector)->Count = count;
870 count = 0;
871 LIST_FOR_EACH_ENTRY(ps, &protseqs, RpcServerProtseq, entry) {
872 EnterCriticalSection(&ps->cs);
873 for (conn = ps->conn; conn; conn = conn->Next) {
874 RPCRT4_MakeBinding((RpcBinding**)&(*BindingVector)->BindingH[count],
875 conn);
876 count++;
878 LeaveCriticalSection(&ps->cs);
880 status = RPC_S_OK;
881 } else {
882 *BindingVector = NULL;
883 status = RPC_S_NO_BINDINGS;
885 LeaveCriticalSection(&server_cs);
886 return status;
889 /***********************************************************************
890 * RpcServerUseProtseqEpA (RPCRT4.@)
892 RPC_STATUS WINAPI RpcServerUseProtseqEpA( RPC_CSTR Protseq, UINT MaxCalls, RPC_CSTR Endpoint, LPVOID SecurityDescriptor )
894 RPC_POLICY policy;
896 TRACE( "(%s,%u,%s,%p)\n", Protseq, MaxCalls, Endpoint, SecurityDescriptor );
898 /* This should provide the default behaviour */
899 policy.Length = sizeof( policy );
900 policy.EndpointFlags = 0;
901 policy.NICFlags = 0;
903 return RpcServerUseProtseqEpExA( Protseq, MaxCalls, Endpoint, SecurityDescriptor, &policy );
906 /***********************************************************************
907 * RpcServerUseProtseqEpW (RPCRT4.@)
909 RPC_STATUS WINAPI RpcServerUseProtseqEpW( RPC_WSTR Protseq, UINT MaxCalls, RPC_WSTR Endpoint, LPVOID SecurityDescriptor )
911 RPC_POLICY policy;
913 TRACE( "(%s,%u,%s,%p)\n", debugstr_w( Protseq ), MaxCalls, debugstr_w( Endpoint ), SecurityDescriptor );
915 /* This should provide the default behaviour */
916 policy.Length = sizeof( policy );
917 policy.EndpointFlags = 0;
918 policy.NICFlags = 0;
920 return RpcServerUseProtseqEpExW( Protseq, MaxCalls, Endpoint, SecurityDescriptor, &policy );
923 /***********************************************************************
924 * alloc_serverprotoseq (internal)
926 * Must be called with server_cs held.
928 static RPC_STATUS alloc_serverprotoseq(UINT MaxCalls, const char *Protseq, RpcServerProtseq **ps)
930 const struct protseq_ops *ops = rpcrt4_get_protseq_ops(Protseq);
932 if (!ops)
934 FIXME("protseq %s not supported\n", debugstr_a(Protseq));
935 return RPC_S_PROTSEQ_NOT_SUPPORTED;
938 *ps = ops->alloc();
939 if (!*ps)
940 return RPC_S_OUT_OF_RESOURCES;
941 (*ps)->MaxCalls = MaxCalls;
942 (*ps)->Protseq = RPCRT4_strdupA(Protseq);
943 (*ps)->ops = ops;
944 (*ps)->MaxCalls = 0;
945 (*ps)->conn = NULL;
946 InitializeCriticalSection(&(*ps)->cs);
947 (*ps)->cs.DebugInfo->Spare[0] = (DWORD_PTR)(__FILE__ ": RpcServerProtseq.cs");
948 (*ps)->is_listening = FALSE;
949 (*ps)->mgr_mutex = NULL;
950 (*ps)->server_ready_event = NULL;
952 list_add_head(&protseqs, &(*ps)->entry);
954 TRACE("new protseq %p created for %s\n", *ps, Protseq);
956 return RPC_S_OK;
959 /* must be called with server_cs held */
960 static void destroy_serverprotoseq(RpcServerProtseq *ps)
962 RPCRT4_strfree(ps->Protseq);
963 ps->cs.DebugInfo->Spare[0] = 0;
964 DeleteCriticalSection(&ps->cs);
965 CloseHandle(ps->mgr_mutex);
966 CloseHandle(ps->server_ready_event);
967 list_remove(&ps->entry);
968 HeapFree(GetProcessHeap(), 0, ps);
971 /* Finds a given protseq or creates a new one if one doesn't already exist */
972 static RPC_STATUS RPCRT4_get_or_create_serverprotseq(UINT MaxCalls, const char *Protseq, RpcServerProtseq **ps)
974 RPC_STATUS status;
975 RpcServerProtseq *cps;
977 EnterCriticalSection(&server_cs);
979 LIST_FOR_EACH_ENTRY(cps, &protseqs, RpcServerProtseq, entry)
980 if (!strcmp(cps->Protseq, Protseq))
982 TRACE("found existing protseq object for %s\n", Protseq);
983 *ps = cps;
984 LeaveCriticalSection(&server_cs);
985 return S_OK;
988 status = alloc_serverprotoseq(MaxCalls, Protseq, ps);
990 LeaveCriticalSection(&server_cs);
992 return status;
995 /***********************************************************************
996 * RpcServerUseProtseqEpExA (RPCRT4.@)
998 RPC_STATUS WINAPI RpcServerUseProtseqEpExA( RPC_CSTR Protseq, UINT MaxCalls, RPC_CSTR Endpoint, LPVOID SecurityDescriptor,
999 PRPC_POLICY lpPolicy )
1001 RpcServerProtseq* ps;
1002 RPC_STATUS status;
1004 TRACE("(%s,%u,%s,%p,{%u,%u,%u})\n", debugstr_a((const char *)Protseq),
1005 MaxCalls, debugstr_a((const char *)Endpoint), SecurityDescriptor,
1006 lpPolicy->Length, lpPolicy->EndpointFlags, lpPolicy->NICFlags );
1008 status = RPCRT4_get_or_create_serverprotseq(MaxCalls, (const char *)Protseq, &ps);
1009 if (status != RPC_S_OK)
1010 return status;
1012 return RPCRT4_use_protseq(ps, (const char *)Endpoint);
1015 /***********************************************************************
1016 * RpcServerUseProtseqEpExW (RPCRT4.@)
1018 RPC_STATUS WINAPI RpcServerUseProtseqEpExW( RPC_WSTR Protseq, UINT MaxCalls, RPC_WSTR Endpoint, LPVOID SecurityDescriptor,
1019 PRPC_POLICY lpPolicy )
1021 RpcServerProtseq* ps;
1022 RPC_STATUS status;
1023 LPSTR ProtseqA;
1024 LPSTR EndpointA;
1026 TRACE("(%s,%u,%s,%p,{%u,%u,%u})\n", debugstr_w( Protseq ), MaxCalls,
1027 debugstr_w( Endpoint ), SecurityDescriptor,
1028 lpPolicy->Length, lpPolicy->EndpointFlags, lpPolicy->NICFlags );
1030 ProtseqA = RPCRT4_strdupWtoA(Protseq);
1031 status = RPCRT4_get_or_create_serverprotseq(MaxCalls, ProtseqA, &ps);
1032 RPCRT4_strfree(ProtseqA);
1033 if (status != RPC_S_OK)
1034 return status;
1036 EndpointA = RPCRT4_strdupWtoA(Endpoint);
1037 status = RPCRT4_use_protseq(ps, EndpointA);
1038 RPCRT4_strfree(EndpointA);
1039 return status;
1042 /***********************************************************************
1043 * RpcServerUseProtseqA (RPCRT4.@)
1045 RPC_STATUS WINAPI RpcServerUseProtseqA(RPC_CSTR Protseq, unsigned int MaxCalls, void *SecurityDescriptor)
1047 RPC_STATUS status;
1048 RpcServerProtseq* ps;
1050 TRACE("(Protseq == %s, MaxCalls == %d, SecurityDescriptor == ^%p)\n", debugstr_a((char*)Protseq), MaxCalls, SecurityDescriptor);
1052 status = RPCRT4_get_or_create_serverprotseq(MaxCalls, (const char *)Protseq, &ps);
1053 if (status != RPC_S_OK)
1054 return status;
1056 return RPCRT4_use_protseq(ps, NULL);
1059 /***********************************************************************
1060 * RpcServerUseProtseqW (RPCRT4.@)
1062 RPC_STATUS WINAPI RpcServerUseProtseqW(RPC_WSTR Protseq, unsigned int MaxCalls, void *SecurityDescriptor)
1064 RPC_STATUS status;
1065 RpcServerProtseq* ps;
1066 LPSTR ProtseqA;
1068 TRACE("Protseq == %s, MaxCalls == %d, SecurityDescriptor == ^%p)\n", debugstr_w(Protseq), MaxCalls, SecurityDescriptor);
1070 ProtseqA = RPCRT4_strdupWtoA(Protseq);
1071 status = RPCRT4_get_or_create_serverprotseq(MaxCalls, ProtseqA, &ps);
1072 RPCRT4_strfree(ProtseqA);
1073 if (status != RPC_S_OK)
1074 return status;
1076 return RPCRT4_use_protseq(ps, NULL);
1079 void RPCRT4_destroy_all_protseqs(void)
1081 RpcServerProtseq *cps, *cursor2;
1083 if (listen_count != 0)
1084 std_listen = FALSE;
1086 EnterCriticalSection(&server_cs);
1087 LIST_FOR_EACH_ENTRY_SAFE(cps, cursor2, &protseqs, RpcServerProtseq, entry)
1089 if (listen_count != 0)
1090 RPCRT4_sync_with_server_thread(cps);
1091 destroy_serverprotoseq(cps);
1093 LeaveCriticalSection(&server_cs);
1094 DeleteCriticalSection(&server_cs);
1095 DeleteCriticalSection(&listen_cs);
1098 /***********************************************************************
1099 * RpcServerRegisterIf (RPCRT4.@)
1101 RPC_STATUS WINAPI RpcServerRegisterIf( RPC_IF_HANDLE IfSpec, UUID* MgrTypeUuid, RPC_MGR_EPV* MgrEpv )
1103 TRACE("(%p,%s,%p)\n", IfSpec, debugstr_guid(MgrTypeUuid), MgrEpv);
1104 return RpcServerRegisterIf3( IfSpec, MgrTypeUuid, MgrEpv, 0, RPC_C_LISTEN_MAX_CALLS_DEFAULT, (UINT)-1, NULL, NULL );
1107 /***********************************************************************
1108 * RpcServerRegisterIfEx (RPCRT4.@)
1110 RPC_STATUS WINAPI RpcServerRegisterIfEx( RPC_IF_HANDLE IfSpec, UUID* MgrTypeUuid, RPC_MGR_EPV* MgrEpv,
1111 UINT Flags, UINT MaxCalls, RPC_IF_CALLBACK_FN* IfCallbackFn )
1113 TRACE("(%p,%s,%p,%u,%u,%p)\n", IfSpec, debugstr_guid(MgrTypeUuid), MgrEpv, Flags, MaxCalls, IfCallbackFn);
1114 return RpcServerRegisterIf3( IfSpec, MgrTypeUuid, MgrEpv, Flags, MaxCalls, (UINT)-1, IfCallbackFn, NULL );
1117 /***********************************************************************
1118 * RpcServerRegisterIf2 (RPCRT4.@)
1120 RPC_STATUS WINAPI RpcServerRegisterIf2( RPC_IF_HANDLE IfSpec, UUID* MgrTypeUuid, RPC_MGR_EPV* MgrEpv,
1121 UINT Flags, UINT MaxCalls, UINT MaxRpcSize, RPC_IF_CALLBACK_FN* IfCallbackFn )
1123 return RpcServerRegisterIf3( IfSpec, MgrTypeUuid, MgrEpv, Flags, MaxCalls, MaxRpcSize, IfCallbackFn, NULL );
1126 /***********************************************************************
1127 * RpcServerRegisterIf3 (RPCRT4.@)
1129 RPC_STATUS WINAPI RpcServerRegisterIf3( RPC_IF_HANDLE IfSpec, UUID* MgrTypeUuid, RPC_MGR_EPV* MgrEpv,
1130 UINT Flags, UINT MaxCalls, UINT MaxRpcSize, RPC_IF_CALLBACK_FN* IfCallbackFn, void* SecurityDescriptor)
1132 PRPC_SERVER_INTERFACE If = IfSpec;
1133 RpcServerInterface* sif;
1134 unsigned int i;
1136 TRACE("(%p,%s,%p,%u,%u,%u,%p,%p)\n", IfSpec, debugstr_guid(MgrTypeUuid), MgrEpv, Flags, MaxCalls,
1137 MaxRpcSize, IfCallbackFn, SecurityDescriptor);
1139 if (SecurityDescriptor)
1140 FIXME("Unsupported SecurityDescriptor argument.\n");
1142 TRACE(" interface id: %s %d.%d\n", debugstr_guid(&If->InterfaceId.SyntaxGUID),
1143 If->InterfaceId.SyntaxVersion.MajorVersion,
1144 If->InterfaceId.SyntaxVersion.MinorVersion);
1145 TRACE(" transfer syntax: %s %d.%d\n", debugstr_guid(&If->TransferSyntax.SyntaxGUID),
1146 If->TransferSyntax.SyntaxVersion.MajorVersion,
1147 If->TransferSyntax.SyntaxVersion.MinorVersion);
1148 TRACE(" dispatch table: %p\n", If->DispatchTable);
1149 if (If->DispatchTable) {
1150 TRACE(" dispatch table count: %d\n", If->DispatchTable->DispatchTableCount);
1151 for (i=0; i<If->DispatchTable->DispatchTableCount; i++) {
1152 TRACE(" entry %d: %p\n", i, If->DispatchTable->DispatchTable[i]);
1154 TRACE(" reserved: %ld\n", If->DispatchTable->Reserved);
1156 TRACE(" protseq endpoint count: %d\n", If->RpcProtseqEndpointCount);
1157 TRACE(" default manager epv: %p\n", If->DefaultManagerEpv);
1158 TRACE(" interpreter info: %p\n", If->InterpreterInfo);
1160 sif = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(RpcServerInterface));
1161 sif->If = If;
1162 if (MgrTypeUuid) {
1163 sif->MgrTypeUuid = *MgrTypeUuid;
1164 sif->MgrEpv = MgrEpv;
1165 } else {
1166 memset(&sif->MgrTypeUuid, 0, sizeof(UUID));
1167 sif->MgrEpv = If->DefaultManagerEpv;
1169 sif->Flags = Flags;
1170 sif->MaxCalls = MaxCalls;
1171 sif->MaxRpcSize = MaxRpcSize;
1172 sif->IfCallbackFn = IfCallbackFn;
1174 EnterCriticalSection(&server_cs);
1175 list_add_head(&server_interfaces, &sif->entry);
1176 LeaveCriticalSection(&server_cs);
1178 if (sif->Flags & RPC_IF_AUTOLISTEN)
1179 RPCRT4_start_listen(TRUE);
1181 return RPC_S_OK;
1184 /***********************************************************************
1185 * RpcServerUnregisterIf (RPCRT4.@)
1187 RPC_STATUS WINAPI RpcServerUnregisterIf( RPC_IF_HANDLE IfSpec, UUID* MgrTypeUuid, UINT WaitForCallsToComplete )
1189 PRPC_SERVER_INTERFACE If = IfSpec;
1190 HANDLE event = NULL;
1191 BOOL found = FALSE;
1192 BOOL completed = TRUE;
1193 RpcServerInterface *cif;
1194 RPC_STATUS status;
1196 TRACE("(IfSpec == (RPC_IF_HANDLE)^%p (%s), MgrTypeUuid == %s, WaitForCallsToComplete == %u)\n",
1197 IfSpec, debugstr_guid(&If->InterfaceId.SyntaxGUID), debugstr_guid(MgrTypeUuid), WaitForCallsToComplete);
1199 EnterCriticalSection(&server_cs);
1200 LIST_FOR_EACH_ENTRY(cif, &server_interfaces, RpcServerInterface, entry) {
1201 if ((!IfSpec || !memcmp(&If->InterfaceId, &cif->If->InterfaceId, sizeof(RPC_SYNTAX_IDENTIFIER))) &&
1202 UuidEqual(MgrTypeUuid, &cif->MgrTypeUuid, &status)) {
1203 list_remove(&cif->entry);
1204 TRACE("unregistering cif %p\n", cif);
1205 if (cif->CurrentCalls) {
1206 completed = FALSE;
1207 cif->Delete = TRUE;
1208 if (WaitForCallsToComplete)
1209 cif->CallsCompletedEvent = event = CreateEventW(NULL, FALSE, FALSE, NULL);
1211 found = TRUE;
1212 break;
1215 LeaveCriticalSection(&server_cs);
1217 if (!found) {
1218 ERR("not found for object %s\n", debugstr_guid(MgrTypeUuid));
1219 return RPC_S_UNKNOWN_IF;
1222 if (completed)
1223 HeapFree(GetProcessHeap(), 0, cif);
1224 else if (event) {
1225 /* sif will be freed when the last call is completed, so be careful not to
1226 * touch that memory here as that could happen before we get here */
1227 WaitForSingleObject(event, INFINITE);
1228 CloseHandle(event);
1231 return RPC_S_OK;
1234 /***********************************************************************
1235 * RpcServerUnregisterIfEx (RPCRT4.@)
1237 RPC_STATUS WINAPI RpcServerUnregisterIfEx( RPC_IF_HANDLE IfSpec, UUID* MgrTypeUuid, int RundownContextHandles )
1239 FIXME("(IfSpec == (RPC_IF_HANDLE)^%p, MgrTypeUuid == %s, RundownContextHandles == %d): stub\n",
1240 IfSpec, debugstr_guid(MgrTypeUuid), RundownContextHandles);
1242 return RPC_S_OK;
1245 /***********************************************************************
1246 * RpcObjectSetType (RPCRT4.@)
1248 * PARAMS
1249 * ObjUuid [I] "Object" UUID
1250 * TypeUuid [I] "Type" UUID
1252 * RETURNS
1253 * RPC_S_OK The call succeeded
1254 * RPC_S_INVALID_OBJECT The provided object (nil) is not valid
1255 * RPC_S_ALREADY_REGISTERED The provided object is already registered
1257 * Maps "Object" UUIDs to "Type" UUIDs. Passing the nil UUID as the type
1258 * resets the mapping for the specified object UUID to nil (the default).
1259 * The nil object is always associated with the nil type and cannot be
1260 * reassigned. Servers can support multiple implementations on the same
1261 * interface by registering different end-point vectors for the different
1262 * types. There's no need to call this if a server only supports the nil
1263 * type, as is typical.
1265 RPC_STATUS WINAPI RpcObjectSetType( UUID* ObjUuid, UUID* TypeUuid )
1267 RpcObjTypeMap *map = RpcObjTypeMaps, *prev = NULL;
1268 RPC_STATUS dummy;
1270 TRACE("(ObjUUID == %s, TypeUuid == %s).\n", debugstr_guid(ObjUuid), debugstr_guid(TypeUuid));
1271 if ((! ObjUuid) || UuidIsNil(ObjUuid, &dummy)) {
1272 /* nil uuid cannot be remapped */
1273 return RPC_S_INVALID_OBJECT;
1276 /* find the mapping for this object if there is one ... */
1277 while (map) {
1278 if (! UuidCompare(ObjUuid, &map->Object, &dummy)) break;
1279 prev = map;
1280 map = map->next;
1282 if ((! TypeUuid) || UuidIsNil(TypeUuid, &dummy)) {
1283 /* ... and drop it from the list */
1284 if (map) {
1285 if (prev)
1286 prev->next = map->next;
1287 else
1288 RpcObjTypeMaps = map->next;
1289 HeapFree(GetProcessHeap(), 0, map);
1291 } else {
1292 /* ... , fail if we found it ... */
1293 if (map)
1294 return RPC_S_ALREADY_REGISTERED;
1295 /* ... otherwise create a new one and add it in. */
1296 map = HeapAlloc(GetProcessHeap(), 0, sizeof(RpcObjTypeMap));
1297 map->Object = *ObjUuid;
1298 map->Type = *TypeUuid;
1299 map->next = NULL;
1300 if (prev)
1301 prev->next = map; /* prev is the last map in the linklist */
1302 else
1303 RpcObjTypeMaps = map;
1306 return RPC_S_OK;
1309 struct rpc_server_registered_auth_info
1311 struct list entry;
1312 TimeStamp exp;
1313 BOOL cred_acquired;
1314 CredHandle cred;
1315 ULONG max_token;
1316 USHORT auth_type;
1317 WCHAR *principal;
1320 static RPC_STATUS find_security_package(ULONG auth_type, SecPkgInfoW **packages_buf, SecPkgInfoW **ret)
1322 SECURITY_STATUS sec_status;
1323 SecPkgInfoW *packages;
1324 ULONG package_count;
1325 ULONG i;
1327 sec_status = EnumerateSecurityPackagesW(&package_count, &packages);
1328 if (sec_status != SEC_E_OK)
1330 ERR("EnumerateSecurityPackagesW failed with error 0x%08x\n", sec_status);
1331 return RPC_S_SEC_PKG_ERROR;
1334 for (i = 0; i < package_count; i++)
1335 if (packages[i].wRPCID == auth_type)
1336 break;
1338 if (i == package_count)
1340 WARN("unsupported AuthnSvc %u\n", auth_type);
1341 FreeContextBuffer(packages);
1342 return RPC_S_UNKNOWN_AUTHN_SERVICE;
1345 TRACE("found package %s for service %u\n", debugstr_w(packages[i].Name), auth_type);
1346 *packages_buf = packages;
1347 *ret = packages + i;
1348 return RPC_S_OK;
1351 RPC_STATUS RPCRT4_ServerGetRegisteredAuthInfo(
1352 USHORT auth_type, CredHandle *cred, TimeStamp *exp, ULONG *max_token)
1354 RPC_STATUS status = RPC_S_UNKNOWN_AUTHN_SERVICE;
1355 struct rpc_server_registered_auth_info *auth_info;
1357 EnterCriticalSection(&server_auth_info_cs);
1358 LIST_FOR_EACH_ENTRY(auth_info, &server_registered_auth_info, struct rpc_server_registered_auth_info, entry)
1360 if (auth_info->auth_type == auth_type)
1362 if (!auth_info->cred_acquired)
1364 SecPkgInfoW *packages, *package;
1365 SECURITY_STATUS sec_status;
1367 status = find_security_package(auth_info->auth_type, &packages, &package);
1368 if (status != RPC_S_OK)
1369 break;
1371 sec_status = AcquireCredentialsHandleW((SEC_WCHAR *)auth_info->principal, package->Name,
1372 SECPKG_CRED_INBOUND, NULL, NULL, NULL, NULL,
1373 &auth_info->cred, &auth_info->exp);
1374 FreeContextBuffer(packages);
1375 if (sec_status != SEC_E_OK)
1377 status = RPC_S_SEC_PKG_ERROR;
1378 break;
1381 auth_info->cred_acquired = TRUE;
1384 *cred = auth_info->cred;
1385 *exp = auth_info->exp;
1386 *max_token = auth_info->max_token;
1387 status = RPC_S_OK;
1388 break;
1391 LeaveCriticalSection(&server_auth_info_cs);
1393 return status;
1396 void RPCRT4_ServerFreeAllRegisteredAuthInfo(void)
1398 struct rpc_server_registered_auth_info *auth_info, *cursor2;
1400 EnterCriticalSection(&server_auth_info_cs);
1401 LIST_FOR_EACH_ENTRY_SAFE(auth_info, cursor2, &server_registered_auth_info, struct rpc_server_registered_auth_info, entry)
1403 if (auth_info->cred_acquired)
1404 FreeCredentialsHandle(&auth_info->cred);
1405 HeapFree(GetProcessHeap(), 0, auth_info->principal);
1406 HeapFree(GetProcessHeap(), 0, auth_info);
1408 LeaveCriticalSection(&server_auth_info_cs);
1409 DeleteCriticalSection(&server_auth_info_cs);
1412 /***********************************************************************
1413 * RpcServerRegisterAuthInfoA (RPCRT4.@)
1415 RPC_STATUS WINAPI RpcServerRegisterAuthInfoA( RPC_CSTR ServerPrincName, ULONG AuthnSvc, RPC_AUTH_KEY_RETRIEVAL_FN GetKeyFn,
1416 LPVOID Arg )
1418 WCHAR *principal_name = NULL;
1419 RPC_STATUS status;
1421 TRACE("(%s,%u,%p,%p)\n", ServerPrincName, AuthnSvc, GetKeyFn, Arg);
1423 if(ServerPrincName && !(principal_name = RPCRT4_strdupAtoW((const char*)ServerPrincName)))
1424 return RPC_S_OUT_OF_RESOURCES;
1426 status = RpcServerRegisterAuthInfoW(principal_name, AuthnSvc, GetKeyFn, Arg);
1428 HeapFree(GetProcessHeap(), 0, principal_name);
1429 return status;
1432 /***********************************************************************
1433 * RpcServerRegisterAuthInfoW (RPCRT4.@)
1435 RPC_STATUS WINAPI RpcServerRegisterAuthInfoW( RPC_WSTR ServerPrincName, ULONG AuthnSvc, RPC_AUTH_KEY_RETRIEVAL_FN GetKeyFn,
1436 LPVOID Arg )
1438 struct rpc_server_registered_auth_info *auth_info;
1439 SecPkgInfoW *packages, *package;
1440 ULONG max_token;
1441 RPC_STATUS status;
1443 TRACE("(%s,%u,%p,%p)\n", debugstr_w(ServerPrincName), AuthnSvc, GetKeyFn, Arg);
1445 status = find_security_package(AuthnSvc, &packages, &package);
1446 if (status != RPC_S_OK)
1447 return status;
1449 max_token = package->cbMaxToken;
1450 FreeContextBuffer(packages);
1452 auth_info = HeapAlloc(GetProcessHeap(), 0, sizeof(*auth_info));
1453 if (!auth_info)
1454 return RPC_S_OUT_OF_RESOURCES;
1456 if (!ServerPrincName) {
1457 auth_info->principal = NULL;
1458 }else if (!(auth_info->principal = RPCRT4_strdupW(ServerPrincName))) {
1459 HeapFree(GetProcessHeap(), 0, auth_info);
1460 return RPC_S_OUT_OF_RESOURCES;
1463 auth_info->max_token = max_token;
1464 auth_info->auth_type = AuthnSvc;
1466 EnterCriticalSection(&server_auth_info_cs);
1467 list_add_tail(&server_registered_auth_info, &auth_info->entry);
1468 LeaveCriticalSection(&server_auth_info_cs);
1470 return RPC_S_OK;
1473 /******************************************************************************
1474 * RpcServerInqDefaultPrincNameA (rpcrt4.@)
1476 RPC_STATUS RPC_ENTRY RpcServerInqDefaultPrincNameA(ULONG AuthnSvc, RPC_CSTR *PrincName)
1478 RPC_STATUS ret;
1479 RPC_WSTR principalW;
1481 TRACE("%u, %p\n", AuthnSvc, PrincName);
1483 if ((ret = RpcServerInqDefaultPrincNameW( AuthnSvc, &principalW )) == RPC_S_OK)
1485 if (!(*PrincName = (RPC_CSTR)RPCRT4_strdupWtoA( principalW ))) return RPC_S_OUT_OF_MEMORY;
1486 RpcStringFreeW( &principalW );
1488 return ret;
1491 /******************************************************************************
1492 * RpcServerInqDefaultPrincNameW (rpcrt4.@)
1494 RPC_STATUS RPC_ENTRY RpcServerInqDefaultPrincNameW(ULONG AuthnSvc, RPC_WSTR *PrincName)
1496 ULONG len = 0;
1498 FIXME("%u, %p\n", AuthnSvc, PrincName);
1500 if (AuthnSvc != RPC_C_AUTHN_WINNT) return RPC_S_UNKNOWN_AUTHN_SERVICE;
1502 GetUserNameExW( NameSamCompatible, NULL, &len );
1503 if (GetLastError() != ERROR_MORE_DATA) return RPC_S_INTERNAL_ERROR;
1505 if (!(*PrincName = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) )))
1506 return RPC_S_OUT_OF_MEMORY;
1508 GetUserNameExW( NameSamCompatible, *PrincName, &len );
1509 return RPC_S_OK;
1512 /***********************************************************************
1513 * RpcServerListen (RPCRT4.@)
1515 RPC_STATUS WINAPI RpcServerListen( UINT MinimumCallThreads, UINT MaxCalls, UINT DontWait )
1517 RPC_STATUS status = RPC_S_OK;
1519 TRACE("(%u,%u,%u)\n", MinimumCallThreads, MaxCalls, DontWait);
1521 if (list_empty(&protseqs))
1522 return RPC_S_NO_PROTSEQS_REGISTERED;
1524 status = RPCRT4_start_listen(FALSE);
1526 if (DontWait || (status != RPC_S_OK)) return status;
1528 return RpcMgmtWaitServerListen();
1531 /***********************************************************************
1532 * RpcMgmtServerWaitListen (RPCRT4.@)
1534 RPC_STATUS WINAPI RpcMgmtWaitServerListen( void )
1536 HANDLE event;
1538 TRACE("()\n");
1540 EnterCriticalSection(&listen_cs);
1542 if (!std_listen) {
1543 LeaveCriticalSection(&listen_cs);
1544 return RPC_S_NOT_LISTENING;
1546 if (listen_done_event) {
1547 LeaveCriticalSection(&listen_cs);
1548 return RPC_S_ALREADY_LISTENING;
1550 event = CreateEventW( NULL, TRUE, FALSE, NULL );
1551 listen_done_event = event;
1553 LeaveCriticalSection(&listen_cs);
1555 TRACE( "waiting for server calls to finish\n" );
1556 WaitForSingleObject( event, INFINITE );
1557 TRACE( "done waiting\n" );
1559 CloseHandle( event );
1560 return RPC_S_OK;
1563 /***********************************************************************
1564 * RpcMgmtStopServerListening (RPCRT4.@)
1566 RPC_STATUS WINAPI RpcMgmtStopServerListening ( RPC_BINDING_HANDLE Binding )
1568 TRACE("(Binding == (RPC_BINDING_HANDLE)^%p)\n", Binding);
1570 if (Binding) {
1571 FIXME("client-side invocation not implemented.\n");
1572 return RPC_S_WRONG_KIND_OF_BINDING;
1575 return RPCRT4_stop_listen(FALSE);
1578 /***********************************************************************
1579 * RpcMgmtEnableIdleCleanup (RPCRT4.@)
1581 RPC_STATUS WINAPI RpcMgmtEnableIdleCleanup(void)
1583 FIXME("(): stub\n");
1584 return RPC_S_OK;
1587 /***********************************************************************
1588 * I_RpcServerStartListening (RPCRT4.@)
1590 RPC_STATUS WINAPI I_RpcServerStartListening( HWND hWnd )
1592 FIXME( "(%p): stub\n", hWnd );
1594 return RPC_S_OK;
1597 /***********************************************************************
1598 * I_RpcServerStopListening (RPCRT4.@)
1600 RPC_STATUS WINAPI I_RpcServerStopListening( void )
1602 FIXME( "(): stub\n" );
1604 return RPC_S_OK;
1607 /***********************************************************************
1608 * I_RpcWindowProc (RPCRT4.@)
1610 UINT WINAPI I_RpcWindowProc( void *hWnd, UINT Message, UINT wParam, ULONG lParam )
1612 FIXME( "(%p,%08x,%08x,%08x): stub\n", hWnd, Message, wParam, lParam );
1614 return 0;
1617 /***********************************************************************
1618 * RpcMgmtInqIfIds (RPCRT4.@)
1620 RPC_STATUS WINAPI RpcMgmtInqIfIds(RPC_BINDING_HANDLE Binding, RPC_IF_ID_VECTOR **IfIdVector)
1622 FIXME("(%p,%p): stub\n", Binding, IfIdVector);
1623 return RPC_S_INVALID_BINDING;
1626 /***********************************************************************
1627 * RpcMgmtInqStats (RPCRT4.@)
1629 RPC_STATUS WINAPI RpcMgmtInqStats(RPC_BINDING_HANDLE Binding, RPC_STATS_VECTOR **Statistics)
1631 RPC_STATS_VECTOR *stats;
1633 FIXME("(%p,%p)\n", Binding, Statistics);
1635 if ((stats = HeapAlloc(GetProcessHeap(), 0, sizeof(RPC_STATS_VECTOR))))
1637 stats->Count = 1;
1638 stats->Stats[0] = 0;
1639 *Statistics = stats;
1640 return RPC_S_OK;
1642 return RPC_S_OUT_OF_RESOURCES;
1645 /***********************************************************************
1646 * RpcMgmtStatsVectorFree (RPCRT4.@)
1648 RPC_STATUS WINAPI RpcMgmtStatsVectorFree(RPC_STATS_VECTOR **StatsVector)
1650 FIXME("(%p)\n", StatsVector);
1652 if (StatsVector)
1654 HeapFree(GetProcessHeap(), 0, *StatsVector);
1655 *StatsVector = NULL;
1657 return RPC_S_OK;
1660 /***********************************************************************
1661 * RpcMgmtEpEltInqBegin (RPCRT4.@)
1663 RPC_STATUS WINAPI RpcMgmtEpEltInqBegin(RPC_BINDING_HANDLE Binding, ULONG InquiryType,
1664 RPC_IF_ID *IfId, ULONG VersOption, UUID *ObjectUuid, RPC_EP_INQ_HANDLE* InquiryContext)
1666 FIXME("(%p,%u,%p,%u,%p,%p): stub\n",
1667 Binding, InquiryType, IfId, VersOption, ObjectUuid, InquiryContext);
1668 return RPC_S_INVALID_BINDING;
1671 /***********************************************************************
1672 * RpcMgmtIsServerListening (RPCRT4.@)
1674 RPC_STATUS WINAPI RpcMgmtIsServerListening(RPC_BINDING_HANDLE Binding)
1676 RPC_STATUS status = RPC_S_NOT_LISTENING;
1678 TRACE("(%p)\n", Binding);
1680 if (Binding) {
1681 RpcBinding *rpc_binding = (RpcBinding*)Binding;
1682 status = RPCRT4_IsServerListening(rpc_binding->Protseq, rpc_binding->Endpoint);
1683 }else {
1684 EnterCriticalSection(&listen_cs);
1685 if (manual_listen_count > 0) status = RPC_S_OK;
1686 LeaveCriticalSection(&listen_cs);
1689 return status;
1692 /***********************************************************************
1693 * RpcMgmtSetAuthorizationFn (RPCRT4.@)
1695 RPC_STATUS WINAPI RpcMgmtSetAuthorizationFn(RPC_MGMT_AUTHORIZATION_FN fn)
1697 FIXME("(%p): stub\n", fn);
1698 return RPC_S_OK;
1701 /***********************************************************************
1702 * RpcMgmtSetServerStackSize (RPCRT4.@)
1704 RPC_STATUS WINAPI RpcMgmtSetServerStackSize(ULONG ThreadStackSize)
1706 FIXME("(0x%x): stub\n", ThreadStackSize);
1707 return RPC_S_OK;
1710 /***********************************************************************
1711 * I_RpcGetCurrentCallHandle (RPCRT4.@)
1713 RPC_BINDING_HANDLE WINAPI I_RpcGetCurrentCallHandle(void)
1715 TRACE("\n");
1716 return RPCRT4_GetThreadCurrentCallHandle();