cmd: DIR command outputs free space for the path.
[wine.git] / dlls / rpcrt4 / rpc_server.c
blob41431ebca0289a9980cb9fb8f64417bc31a6661b
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 <stdarg.h>
24 #include <stdio.h>
25 #include <stdlib.h>
26 #include <string.h>
27 #include <assert.h>
29 #include "windef.h"
30 #include "winbase.h"
31 #include "winerror.h"
33 #include "rpc.h"
34 #include "rpcndr.h"
35 #include "excpt.h"
37 #include "wine/debug.h"
38 #include "wine/exception.h"
40 #include "rpc_server.h"
41 #include "rpc_assoc.h"
42 #include "rpc_message.h"
43 #include "rpc_defs.h"
44 #include "ncastatus.h"
45 #include "secext.h"
47 WINE_DEFAULT_DEBUG_CHANNEL(rpc);
49 typedef struct _RpcPacket
51 struct _RpcConnection* conn;
52 RpcPktHdr* hdr;
53 RPC_MESSAGE* msg;
54 unsigned char *auth_data;
55 ULONG auth_length;
56 } RpcPacket;
58 typedef struct _RpcObjTypeMap
60 /* FIXME: a hash table would be better. */
61 struct _RpcObjTypeMap *next;
62 UUID Object;
63 UUID Type;
64 } RpcObjTypeMap;
66 static RpcObjTypeMap *RpcObjTypeMaps;
68 /* list of type RpcServerProtseq */
69 static struct list protseqs = LIST_INIT(protseqs);
70 static struct list server_interfaces = LIST_INIT(server_interfaces);
71 static struct list server_registered_auth_info = LIST_INIT(server_registered_auth_info);
73 static CRITICAL_SECTION server_cs;
74 static CRITICAL_SECTION_DEBUG server_cs_debug =
76 0, 0, &server_cs,
77 { &server_cs_debug.ProcessLocksList, &server_cs_debug.ProcessLocksList },
78 0, 0, { (DWORD_PTR)(__FILE__ ": server_cs") }
80 static CRITICAL_SECTION server_cs = { &server_cs_debug, -1, 0, 0, 0, 0 };
82 static CRITICAL_SECTION listen_cs;
83 static CRITICAL_SECTION_DEBUG listen_cs_debug =
85 0, 0, &listen_cs,
86 { &listen_cs_debug.ProcessLocksList, &listen_cs_debug.ProcessLocksList },
87 0, 0, { (DWORD_PTR)(__FILE__ ": listen_cs") }
89 static CRITICAL_SECTION listen_cs = { &listen_cs_debug, -1, 0, 0, 0, 0 };
91 static CRITICAL_SECTION server_auth_info_cs;
92 static CRITICAL_SECTION_DEBUG server_auth_info_cs_debug =
94 0, 0, &server_auth_info_cs,
95 { &server_auth_info_cs_debug.ProcessLocksList, &server_auth_info_cs_debug.ProcessLocksList },
96 0, 0, { (DWORD_PTR)(__FILE__ ": server_auth_info_cs") }
98 static CRITICAL_SECTION server_auth_info_cs = { &server_auth_info_cs_debug, -1, 0, 0, 0, 0 };
100 /* whether the server is currently listening */
101 static BOOL std_listen;
102 /* total listeners including auto listeners */
103 static LONG listen_count;
104 /* event set once all manual listening is finished */
105 static HANDLE listen_done_event;
107 static UUID uuid_nil;
109 static inline RpcObjTypeMap *LookupObjTypeMap(UUID *ObjUuid)
111 RpcObjTypeMap *rslt = RpcObjTypeMaps;
112 RPC_STATUS dummy;
114 while (rslt) {
115 if (! UuidCompare(ObjUuid, &rslt->Object, &dummy)) break;
116 rslt = rslt->next;
119 return rslt;
122 static inline UUID *LookupObjType(UUID *ObjUuid)
124 RpcObjTypeMap *map = LookupObjTypeMap(ObjUuid);
125 if (map)
126 return &map->Type;
127 else
128 return &uuid_nil;
131 static RpcServerInterface* RPCRT4_find_interface(UUID* object,
132 const RPC_SYNTAX_IDENTIFIER *if_id,
133 const RPC_SYNTAX_IDENTIFIER *transfer_syntax,
134 BOOL check_object)
136 UUID* MgrType = NULL;
137 RpcServerInterface* cif;
138 RPC_STATUS status;
140 if (check_object)
141 MgrType = LookupObjType(object);
142 EnterCriticalSection(&server_cs);
143 LIST_FOR_EACH_ENTRY(cif, &server_interfaces, RpcServerInterface, entry) {
144 if (!memcmp(if_id, &cif->If->InterfaceId, sizeof(RPC_SYNTAX_IDENTIFIER)) &&
145 (!transfer_syntax || !memcmp(transfer_syntax, &cif->If->TransferSyntax, sizeof(RPC_SYNTAX_IDENTIFIER))) &&
146 (check_object == FALSE || UuidEqual(MgrType, &cif->MgrTypeUuid, &status)) &&
147 std_listen) {
148 InterlockedIncrement(&cif->CurrentCalls);
149 break;
152 LeaveCriticalSection(&server_cs);
153 if (&cif->entry == &server_interfaces) cif = NULL;
154 TRACE("returning %p for object %s, if_id { %d.%d %s }\n", cif,
155 debugstr_guid(object), if_id->SyntaxVersion.MajorVersion,
156 if_id->SyntaxVersion.MinorVersion, debugstr_guid(&if_id->SyntaxGUID));
157 return cif;
160 static void RPCRT4_release_server_interface(RpcServerInterface *sif)
162 if (!InterlockedDecrement(&sif->CurrentCalls) &&
163 sif->Delete) {
164 /* sif must have been removed from server_interfaces before
165 * CallsCompletedEvent is set */
166 if (sif->CallsCompletedEvent)
167 SetEvent(sif->CallsCompletedEvent);
168 free(sif);
172 static RpcPktHdr *handle_bind_error(RpcConnection *conn, RPC_STATUS error)
174 unsigned int reject_reason;
175 switch (error)
177 case RPC_S_SERVER_TOO_BUSY:
178 reject_reason = REJECT_TEMPORARY_CONGESTION;
179 break;
180 case ERROR_OUTOFMEMORY:
181 case RPC_S_OUT_OF_RESOURCES:
182 reject_reason = REJECT_LOCAL_LIMIT_EXCEEDED;
183 break;
184 case RPC_S_PROTOCOL_ERROR:
185 reject_reason = REJECT_PROTOCOL_VERSION_NOT_SUPPORTED;
186 break;
187 case RPC_S_UNKNOWN_AUTHN_SERVICE:
188 reject_reason = REJECT_UNKNOWN_AUTHN_SERVICE;
189 break;
190 case ERROR_ACCESS_DENIED:
191 reject_reason = REJECT_INVALID_CHECKSUM;
192 break;
193 default:
194 FIXME("unexpected status value %ld\n", error);
195 /* fall through */
196 case RPC_S_INVALID_BOUND:
197 reject_reason = REJECT_REASON_NOT_SPECIFIED;
198 break;
200 return RPCRT4_BuildBindNackHeader(NDR_LOCAL_DATA_REPRESENTATION,
201 RPC_VER_MAJOR, RPC_VER_MINOR,
202 reject_reason);
205 static RPC_STATUS process_bind_packet_no_send(
206 RpcConnection *conn, RpcPktBindHdr *hdr, RPC_MESSAGE *msg,
207 unsigned char *auth_data, ULONG auth_length, RpcPktHdr **ack_response,
208 unsigned char **auth_data_out, ULONG *auth_length_out)
210 RPC_STATUS status;
211 RpcContextElement *ctxt_elem;
212 unsigned int i;
213 RpcResult *results;
215 /* validate data */
216 for (i = 0, ctxt_elem = msg->Buffer;
217 i < hdr->num_elements;
218 i++, ctxt_elem = (RpcContextElement *)&ctxt_elem->transfer_syntaxes[ctxt_elem->num_syntaxes])
220 if (((char *)ctxt_elem - (char *)msg->Buffer) > msg->BufferLength ||
221 ((char *)&ctxt_elem->transfer_syntaxes[ctxt_elem->num_syntaxes] - (char *)msg->Buffer) > msg->BufferLength)
223 ERR("inconsistent data in packet - packet length %d, num elements %d\n",
224 msg->BufferLength, hdr->num_elements);
225 return RPC_S_INVALID_BOUND;
229 if (hdr->max_tsize < RPC_MIN_PACKET_SIZE ||
230 !UuidIsNil(&conn->ActiveInterface.SyntaxGUID, &status) ||
231 conn->server_binding)
233 TRACE("packet size less than min size, or active interface syntax guid non-null\n");
235 return RPC_S_INVALID_BOUND;
238 results = malloc(hdr->num_elements * sizeof(*results));
239 if (!results)
240 return RPC_S_OUT_OF_RESOURCES;
242 for (i = 0, ctxt_elem = (RpcContextElement *)msg->Buffer;
243 i < hdr->num_elements;
244 i++, ctxt_elem = (RpcContextElement *)&ctxt_elem->transfer_syntaxes[ctxt_elem->num_syntaxes])
246 RpcServerInterface* sif = NULL;
247 unsigned int j;
249 for (j = 0; !sif && j < ctxt_elem->num_syntaxes; j++)
251 sif = RPCRT4_find_interface(NULL, &ctxt_elem->abstract_syntax,
252 &ctxt_elem->transfer_syntaxes[j], FALSE);
253 if (sif)
254 break;
256 if (sif)
258 RPCRT4_release_server_interface(sif);
259 TRACE("accepting bind request on connection %p for %s\n", conn,
260 debugstr_guid(&ctxt_elem->abstract_syntax.SyntaxGUID));
261 results[i].result = RESULT_ACCEPT;
262 results[i].reason = REASON_NONE;
263 results[i].transfer_syntax = ctxt_elem->transfer_syntaxes[j];
265 /* save the interface for later use */
266 /* FIXME: save linked list */
267 conn->ActiveInterface = ctxt_elem->abstract_syntax;
269 else if ((sif = RPCRT4_find_interface(NULL, &ctxt_elem->abstract_syntax,
270 NULL, FALSE)) != NULL)
272 RPCRT4_release_server_interface(sif);
273 TRACE("not accepting bind request on connection %p for %s - no transfer syntaxes supported\n",
274 conn, debugstr_guid(&ctxt_elem->abstract_syntax.SyntaxGUID));
275 results[i].result = RESULT_PROVIDER_REJECTION;
276 results[i].reason = REASON_TRANSFER_SYNTAXES_NOT_SUPPORTED;
277 memset(&results[i].transfer_syntax, 0, sizeof(results[i].transfer_syntax));
279 else
281 TRACE("not accepting bind request on connection %p for %s - abstract syntax not supported\n",
282 conn, debugstr_guid(&ctxt_elem->abstract_syntax.SyntaxGUID));
283 results[i].result = RESULT_PROVIDER_REJECTION;
284 results[i].reason = REASON_ABSTRACT_SYNTAX_NOT_SUPPORTED;
285 memset(&results[i].transfer_syntax, 0, sizeof(results[i].transfer_syntax));
289 /* create temporary binding */
290 status = RPCRT4_MakeBinding(&conn->server_binding, conn);
291 if (status != RPC_S_OK)
293 free(results);
294 return status;
297 status = RpcServerAssoc_GetAssociation(rpcrt4_conn_get_name(conn),
298 conn->NetworkAddr, conn->Endpoint,
299 conn->NetworkOptions,
300 hdr->assoc_gid,
301 &conn->server_binding->Assoc);
302 if (status != RPC_S_OK)
304 free(results);
305 return status;
308 if (auth_length)
310 status = RPCRT4_ServerConnectionAuth(conn, TRUE,
311 (RpcAuthVerifier *)auth_data,
312 auth_length, auth_data_out,
313 auth_length_out);
314 if (status != RPC_S_OK)
316 free(results);
317 return status;
321 *ack_response = RPCRT4_BuildBindAckHeader(NDR_LOCAL_DATA_REPRESENTATION,
322 RPC_MAX_PACKET_SIZE,
323 RPC_MAX_PACKET_SIZE,
324 conn->server_binding->Assoc->assoc_group_id,
325 conn->Endpoint, hdr->num_elements,
326 results);
327 free(results);
329 if (*ack_response)
330 conn->MaxTransmissionSize = hdr->max_tsize;
331 else
332 status = RPC_S_OUT_OF_RESOURCES;
334 return status;
337 static RPC_STATUS process_bind_packet(RpcConnection *conn, RpcPktBindHdr *hdr,
338 RPC_MESSAGE *msg,
339 unsigned char *auth_data,
340 ULONG auth_length)
342 RPC_STATUS status;
343 RpcPktHdr *response = NULL;
344 unsigned char *auth_data_out = NULL;
345 ULONG auth_length_out = 0;
347 status = process_bind_packet_no_send(conn, hdr, msg, auth_data, auth_length,
348 &response, &auth_data_out,
349 &auth_length_out);
350 if (status != RPC_S_OK)
351 response = handle_bind_error(conn, status);
352 if (response)
353 status = RPCRT4_SendWithAuth(conn, response, NULL, 0, auth_data_out, auth_length_out);
354 else
355 status = ERROR_OUTOFMEMORY;
356 free(response);
358 return status;
362 static RPC_STATUS process_request_packet(RpcConnection *conn, RpcPktRequestHdr *hdr, RPC_MESSAGE *msg)
364 RPC_STATUS status;
365 RpcPktHdr *response = NULL;
366 RpcServerInterface* sif;
367 RPC_DISPATCH_FUNCTION func;
368 BOOL exception;
369 UUID *object_uuid;
370 NDR_SCONTEXT context_handle;
371 void *buf = msg->Buffer;
373 /* fail if the connection isn't bound with an interface */
374 if (UuidIsNil(&conn->ActiveInterface.SyntaxGUID, &status)) {
375 /* FIXME: should send BindNack instead */
376 response = RPCRT4_BuildFaultHeader(NDR_LOCAL_DATA_REPRESENTATION,
377 status);
379 RPCRT4_Send(conn, response, NULL, 0);
380 free(response);
381 return RPC_S_OK;
384 if (hdr->common.flags & RPC_FLG_OBJECT_UUID) {
385 object_uuid = (UUID*)(hdr + 1);
386 } else {
387 object_uuid = NULL;
390 sif = RPCRT4_find_interface(object_uuid, &conn->ActiveInterface, NULL, TRUE);
391 if (!sif) {
392 WARN("interface %s no longer registered, returning fault packet\n", debugstr_guid(&conn->ActiveInterface.SyntaxGUID));
393 response = RPCRT4_BuildFaultHeader(NDR_LOCAL_DATA_REPRESENTATION,
394 NCA_S_UNK_IF);
396 RPCRT4_Send(conn, response, NULL, 0);
397 free(response);
398 return RPC_S_OK;
400 msg->RpcInterfaceInformation = sif->If;
401 /* copy the endpoint vector from sif to msg so that midl-generated code will use it */
402 msg->ManagerEpv = sif->MgrEpv;
403 if (object_uuid != NULL) {
404 RPCRT4_SetBindingObject(msg->Handle, object_uuid);
407 /* find dispatch function */
408 msg->ProcNum = hdr->opnum;
409 if (sif->Flags & RPC_IF_OLE) {
410 /* native ole32 always gives us a dispatch table with a single entry
411 * (I assume that's a wrapper for IRpcStubBuffer::Invoke) */
412 func = *sif->If->DispatchTable->DispatchTable;
413 } else {
414 if (msg->ProcNum >= sif->If->DispatchTable->DispatchTableCount) {
415 WARN("invalid procnum (%d/%d)\n", msg->ProcNum, sif->If->DispatchTable->DispatchTableCount);
416 response = RPCRT4_BuildFaultHeader(NDR_LOCAL_DATA_REPRESENTATION,
417 NCA_S_OP_RNG_ERROR);
419 RPCRT4_Send(conn, response, NULL, 0);
420 free(response);
422 func = sif->If->DispatchTable->DispatchTable[msg->ProcNum];
425 /* put in the drep. FIXME: is this more universally applicable?
426 perhaps we should move this outward... */
427 msg->DataRepresentation =
428 MAKELONG( MAKEWORD(hdr->common.drep[0], hdr->common.drep[1]),
429 MAKEWORD(hdr->common.drep[2], hdr->common.drep[3]));
431 exception = FALSE;
433 /* dispatch */
434 RPCRT4_SetThreadCurrentCallHandle(msg->Handle);
435 __TRY {
436 if (func) func(msg);
437 } __EXCEPT_ALL {
438 WARN("exception caught with code 0x%08lx = %ld\n", GetExceptionCode(), GetExceptionCode());
439 exception = TRUE;
440 if (GetExceptionCode() == STATUS_ACCESS_VIOLATION)
441 status = ERROR_NOACCESS;
442 else
443 status = GetExceptionCode();
444 response = RPCRT4_BuildFaultHeader(msg->DataRepresentation,
445 RPC2NCA_STATUS(status));
446 } __ENDTRY
447 RPCRT4_SetThreadCurrentCallHandle(NULL);
449 /* release any unmarshalled context handles */
450 while ((context_handle = RPCRT4_PopThreadContextHandle()) != NULL)
451 RpcServerAssoc_ReleaseContextHandle(conn->server_binding->Assoc, context_handle, TRUE);
453 if (!exception)
454 response = RPCRT4_BuildResponseHeader(msg->DataRepresentation,
455 msg->BufferLength);
457 /* send response packet */
458 if (response) {
459 status = RPCRT4_Send(conn, response, exception ? NULL : msg->Buffer,
460 exception ? 0 : msg->BufferLength);
461 free(response);
462 } else
463 ERR("out of memory\n");
465 msg->RpcInterfaceInformation = NULL;
466 RPCRT4_release_server_interface(sif);
468 if (msg->Buffer == buf) buf = NULL;
469 TRACE("freeing Buffer=%p\n", buf);
470 I_RpcFree(buf);
472 return status;
475 static RPC_STATUS process_auth3_packet(RpcConnection *conn,
476 RpcPktCommonHdr *hdr,
477 RPC_MESSAGE *msg,
478 unsigned char *auth_data,
479 ULONG auth_length)
481 RPC_STATUS status;
483 if (UuidIsNil(&conn->ActiveInterface.SyntaxGUID, &status) ||
484 !auth_length || msg->BufferLength != 0)
485 status = RPC_S_PROTOCOL_ERROR;
486 else
488 status = RPCRT4_ServerConnectionAuth(conn, FALSE,
489 (RpcAuthVerifier *)auth_data,
490 auth_length, NULL, NULL);
493 /* FIXME: client doesn't expect a response to this message so must store
494 * status in connection so that fault packet can be returned when next
495 * packet is received */
497 return RPC_S_OK;
500 static void RPCRT4_process_packet(RpcConnection* conn, RpcPktHdr* hdr,
501 RPC_MESSAGE* msg, unsigned char *auth_data,
502 ULONG auth_length)
504 msg->Handle = (RPC_BINDING_HANDLE)conn->server_binding;
506 switch (hdr->common.ptype) {
507 case PKT_BIND:
508 TRACE("got bind packet\n");
509 process_bind_packet(conn, &hdr->bind, msg, auth_data, auth_length);
510 break;
512 case PKT_REQUEST:
513 TRACE("got request packet\n");
514 process_request_packet(conn, &hdr->request, msg);
515 break;
517 case PKT_AUTH3:
518 TRACE("got auth3 packet\n");
519 process_auth3_packet(conn, &hdr->common, msg, auth_data, auth_length);
520 break;
521 default:
522 FIXME("unhandled packet type %u\n", hdr->common.ptype);
523 break;
526 /* clean up */
527 I_RpcFree(msg->Buffer);
528 free(hdr);
529 free(msg);
530 free(auth_data);
533 static DWORD CALLBACK RPCRT4_worker_thread(LPVOID the_arg)
535 RpcPacket *pkt = the_arg;
536 RPCRT4_process_packet(pkt->conn, pkt->hdr, pkt->msg, pkt->auth_data,
537 pkt->auth_length);
538 RPCRT4_ReleaseConnection(pkt->conn);
539 free(pkt);
540 return 0;
543 static DWORD CALLBACK RPCRT4_io_thread(LPVOID the_arg)
545 RpcConnection* conn = the_arg;
546 RpcPktHdr *hdr;
547 RPC_MESSAGE *msg;
548 RPC_STATUS status;
549 RpcPacket *packet;
550 unsigned char *auth_data;
551 ULONG auth_length;
553 TRACE("(%p)\n", conn);
554 SetThreadDescription(GetCurrentThread(), L"wine_rpcrt4_io");
556 for (;;) {
557 msg = calloc(1, sizeof(RPC_MESSAGE));
558 if (!msg) break;
560 status = RPCRT4_ReceiveWithAuth(conn, &hdr, msg, &auth_data, &auth_length);
561 if (status != RPC_S_OK) {
562 WARN("receive failed with error %lx\n", status);
563 free(msg);
564 break;
567 switch (hdr->common.ptype) {
568 case PKT_BIND:
569 TRACE("got bind packet\n");
571 status = process_bind_packet(conn, &hdr->bind, msg, auth_data,
572 auth_length);
573 break;
575 case PKT_REQUEST:
576 TRACE("got request packet\n");
578 packet = malloc(sizeof(RpcPacket));
579 if (!packet) {
580 I_RpcFree(msg->Buffer);
581 free(hdr);
582 free(msg);
583 free(auth_data);
584 goto exit;
586 packet->conn = RPCRT4_GrabConnection( conn );
587 packet->hdr = hdr;
588 packet->msg = msg;
589 packet->auth_data = auth_data;
590 packet->auth_length = auth_length;
591 if (!QueueUserWorkItem(RPCRT4_worker_thread, packet, WT_EXECUTELONGFUNCTION)) {
592 ERR("couldn't queue work item for worker thread, error was %ld\n", GetLastError());
593 free(packet);
594 status = RPC_S_OUT_OF_RESOURCES;
595 } else {
596 continue;
598 break;
600 case PKT_AUTH3:
601 TRACE("got auth3 packet\n");
603 status = process_auth3_packet(conn, &hdr->common, msg, auth_data,
604 auth_length);
605 break;
606 default:
607 FIXME("unhandled packet type %u\n", hdr->common.ptype);
608 break;
611 I_RpcFree(msg->Buffer);
612 free(hdr);
613 free(msg);
614 free(auth_data);
616 if (status != RPC_S_OK) {
617 WARN("processing packet failed with error %lu\n", status);
618 break;
621 exit:
622 RPCRT4_ReleaseConnection(conn);
623 return 0;
626 void RPCRT4_new_client(RpcConnection* conn)
628 HANDLE thread = CreateThread(NULL, 0, RPCRT4_io_thread, conn, 0, NULL);
629 if (!thread) {
630 DWORD err = GetLastError();
631 ERR("failed to create thread, error=%08lx\n", err);
632 RPCRT4_ReleaseConnection(conn);
634 /* we could set conn->thread, but then we'd have to make the io_thread wait
635 * for that, otherwise the thread might finish, destroy the connection, and
636 * free the memory we'd write to before we did, causing crashes and stuff -
637 * so let's implement that later, when we really need conn->thread */
639 CloseHandle( thread );
642 static DWORD CALLBACK RPCRT4_server_thread(LPVOID the_arg)
644 int res;
645 unsigned int count;
646 void *objs = NULL;
647 RpcServerProtseq* cps = the_arg;
648 RpcConnection* conn;
649 BOOL set_ready_event = FALSE;
651 TRACE("(the_arg == ^%p)\n", the_arg);
652 SetThreadDescription(GetCurrentThread(), L"wine_rpcrt4_server");
654 for (;;) {
655 objs = cps->ops->get_wait_array(cps, objs, &count);
657 if (set_ready_event)
659 /* signal to function that changed state that we are now sync'ed */
660 SetEvent(cps->server_ready_event);
661 set_ready_event = FALSE;
664 /* start waiting */
665 res = cps->ops->wait_for_new_connection(cps, count, objs);
667 if (res == -1 || (res == 0 && !std_listen))
669 /* cleanup */
670 cps->ops->free_wait_array(cps, objs);
671 break;
673 else if (res == 0)
674 set_ready_event = TRUE;
677 TRACE("closing connections\n");
679 EnterCriticalSection(&cps->cs);
680 LIST_FOR_EACH_ENTRY(conn, &cps->listeners, RpcConnection, protseq_entry)
681 RPCRT4_CloseConnection(conn);
682 LIST_FOR_EACH_ENTRY(conn, &cps->connections, RpcConnection, protseq_entry)
684 RPCRT4_GrabConnection(conn);
685 rpcrt4_conn_close_read(conn);
687 LeaveCriticalSection(&cps->cs);
689 if (res == 0 && !std_listen)
690 SetEvent(cps->server_ready_event);
692 TRACE("waiting for active connections to close\n");
694 EnterCriticalSection(&cps->cs);
695 while (!list_empty(&cps->connections))
697 conn = LIST_ENTRY(list_head(&cps->connections), RpcConnection, protseq_entry);
698 LeaveCriticalSection(&cps->cs);
699 rpcrt4_conn_release_and_wait(conn);
700 EnterCriticalSection(&cps->cs);
702 LeaveCriticalSection(&cps->cs);
704 EnterCriticalSection(&listen_cs);
705 CloseHandle(cps->server_thread);
706 cps->server_thread = NULL;
707 LeaveCriticalSection(&listen_cs);
708 TRACE("done\n");
709 return 0;
712 /* tells the server thread that the state has changed and waits for it to
713 * make the changes */
714 static void RPCRT4_sync_with_server_thread(RpcServerProtseq *ps)
716 /* make sure we are the only thread sync'ing the server state, otherwise
717 * there is a race with the server thread setting an older state and setting
718 * the server_ready_event when the new state hasn't yet been applied */
719 WaitForSingleObject(ps->mgr_mutex, INFINITE);
721 ps->ops->signal_state_changed(ps);
723 /* wait for server thread to make the requested changes before returning */
724 WaitForSingleObject(ps->server_ready_event, INFINITE);
726 ReleaseMutex(ps->mgr_mutex);
729 static RPC_STATUS RPCRT4_start_listen_protseq(RpcServerProtseq *ps, BOOL auto_listen)
731 RPC_STATUS status = RPC_S_OK;
733 EnterCriticalSection(&listen_cs);
734 if (ps->server_thread) goto done;
736 if (!ps->mgr_mutex) ps->mgr_mutex = CreateMutexW(NULL, FALSE, NULL);
737 if (!ps->server_ready_event) ps->server_ready_event = CreateEventW(NULL, FALSE, FALSE, NULL);
738 ps->server_thread = CreateThread(NULL, 0, RPCRT4_server_thread, ps, 0, NULL);
739 if (!ps->server_thread)
740 status = RPC_S_OUT_OF_RESOURCES;
742 done:
743 LeaveCriticalSection(&listen_cs);
744 return status;
747 static RPC_STATUS RPCRT4_start_listen(BOOL auto_listen)
749 RPC_STATUS status = RPC_S_ALREADY_LISTENING;
750 RpcServerProtseq *cps;
752 TRACE("\n");
754 EnterCriticalSection(&listen_cs);
755 if (auto_listen || !listen_done_event)
757 status = RPC_S_OK;
758 if(!auto_listen)
759 listen_done_event = CreateEventW(NULL, TRUE, FALSE, NULL);
760 if (++listen_count == 1)
761 std_listen = TRUE;
763 LeaveCriticalSection(&listen_cs);
764 if (status) return status;
766 if (std_listen)
768 EnterCriticalSection(&server_cs);
769 LIST_FOR_EACH_ENTRY(cps, &protseqs, RpcServerProtseq, entry)
771 status = RPCRT4_start_listen_protseq(cps, TRUE);
772 if (status != RPC_S_OK)
773 break;
775 /* make sure server is actually listening on the interface before
776 * returning */
777 RPCRT4_sync_with_server_thread(cps);
779 LeaveCriticalSection(&server_cs);
782 return status;
785 static RPC_STATUS RPCRT4_stop_listen(BOOL auto_listen)
787 BOOL stop_listen = FALSE;
788 RPC_STATUS status = RPC_S_OK;
790 EnterCriticalSection(&listen_cs);
791 if (!std_listen && (auto_listen || !listen_done_event))
793 status = RPC_S_NOT_LISTENING;
795 else
797 stop_listen = listen_count != 0 && --listen_count == 0;
798 assert(listen_count >= 0);
799 if (stop_listen)
800 std_listen = FALSE;
802 LeaveCriticalSection(&listen_cs);
804 if (status) return status;
806 if (stop_listen) {
807 RpcServerProtseq *cps;
808 EnterCriticalSection(&server_cs);
809 LIST_FOR_EACH_ENTRY(cps, &protseqs, RpcServerProtseq, entry)
810 RPCRT4_sync_with_server_thread(cps);
811 LeaveCriticalSection(&server_cs);
814 if (!auto_listen)
816 EnterCriticalSection(&listen_cs);
817 SetEvent( listen_done_event );
818 LeaveCriticalSection(&listen_cs);
820 return RPC_S_OK;
823 static BOOL RPCRT4_protseq_is_endpoint_registered(RpcServerProtseq *protseq, const char *endpoint)
825 RpcConnection *conn;
826 BOOL registered = FALSE;
827 EnterCriticalSection(&protseq->cs);
828 LIST_FOR_EACH_ENTRY(conn, &protseq->listeners, RpcConnection, protseq_entry) {
829 if (!endpoint || !strcmp(endpoint, conn->Endpoint)) {
830 registered = TRUE;
831 break;
834 LeaveCriticalSection(&protseq->cs);
835 return registered;
838 static RPC_STATUS RPCRT4_use_protseq(RpcServerProtseq* ps, const char *endpoint)
840 RPC_STATUS status;
842 EnterCriticalSection(&ps->cs);
844 if (RPCRT4_protseq_is_endpoint_registered(ps, endpoint))
845 status = RPC_S_OK;
846 else
847 status = ps->ops->open_endpoint(ps, endpoint);
849 LeaveCriticalSection(&ps->cs);
851 if (status != RPC_S_OK)
852 return status;
854 if (std_listen)
856 status = RPCRT4_start_listen_protseq(ps, FALSE);
857 if (status == RPC_S_OK)
858 RPCRT4_sync_with_server_thread(ps);
861 return status;
864 /***********************************************************************
865 * RpcServerInqBindings (RPCRT4.@)
867 RPC_STATUS WINAPI RpcServerInqBindings( RPC_BINDING_VECTOR** BindingVector )
869 RPC_STATUS status;
870 DWORD count;
871 RpcServerProtseq* ps;
872 RpcConnection* conn;
874 if (BindingVector)
875 TRACE("(*BindingVector == ^%p)\n", *BindingVector);
876 else
877 ERR("(BindingVector == NULL!!?)\n");
879 EnterCriticalSection(&server_cs);
880 /* count connections */
881 count = 0;
882 LIST_FOR_EACH_ENTRY(ps, &protseqs, RpcServerProtseq, entry) {
883 EnterCriticalSection(&ps->cs);
884 LIST_FOR_EACH_ENTRY(conn, &ps->listeners, RpcConnection, protseq_entry)
885 count++;
886 LeaveCriticalSection(&ps->cs);
888 if (count) {
889 /* export bindings */
890 *BindingVector = malloc(sizeof(RPC_BINDING_VECTOR) + sizeof(RPC_BINDING_HANDLE) * (count - 1));
891 (*BindingVector)->Count = count;
892 count = 0;
893 LIST_FOR_EACH_ENTRY(ps, &protseqs, RpcServerProtseq, entry) {
894 EnterCriticalSection(&ps->cs);
895 LIST_FOR_EACH_ENTRY(conn, &ps->listeners, RpcConnection, protseq_entry) {
896 RPCRT4_MakeBinding((RpcBinding**)&(*BindingVector)->BindingH[count],
897 conn);
898 count++;
900 LeaveCriticalSection(&ps->cs);
902 status = RPC_S_OK;
903 } else {
904 *BindingVector = NULL;
905 status = RPC_S_NO_BINDINGS;
907 LeaveCriticalSection(&server_cs);
908 return status;
911 /***********************************************************************
912 * RpcServerUseProtseqEpA (RPCRT4.@)
914 RPC_STATUS WINAPI RpcServerUseProtseqEpA( RPC_CSTR Protseq, UINT MaxCalls, RPC_CSTR Endpoint, LPVOID SecurityDescriptor )
916 RPC_POLICY policy;
918 TRACE( "(%s,%u,%s,%p)\n", Protseq, MaxCalls, Endpoint, SecurityDescriptor );
920 /* This should provide the default behaviour */
921 policy.Length = sizeof( policy );
922 policy.EndpointFlags = 0;
923 policy.NICFlags = 0;
925 return RpcServerUseProtseqEpExA( Protseq, MaxCalls, Endpoint, SecurityDescriptor, &policy );
928 /***********************************************************************
929 * RpcServerUseProtseqEpW (RPCRT4.@)
931 RPC_STATUS WINAPI RpcServerUseProtseqEpW( RPC_WSTR Protseq, UINT MaxCalls, RPC_WSTR Endpoint, LPVOID SecurityDescriptor )
933 RPC_POLICY policy;
935 TRACE( "(%s,%u,%s,%p)\n", debugstr_w( Protseq ), MaxCalls, debugstr_w( Endpoint ), SecurityDescriptor );
937 /* This should provide the default behaviour */
938 policy.Length = sizeof( policy );
939 policy.EndpointFlags = 0;
940 policy.NICFlags = 0;
942 return RpcServerUseProtseqEpExW( Protseq, MaxCalls, Endpoint, SecurityDescriptor, &policy );
945 /***********************************************************************
946 * alloc_serverprotoseq (internal)
948 * Must be called with server_cs held.
950 static RPC_STATUS alloc_serverprotoseq(UINT MaxCalls, const char *Protseq, RpcServerProtseq **ps)
952 const struct protseq_ops *ops = rpcrt4_get_protseq_ops(Protseq);
954 if (!ops)
956 FIXME("protseq %s not supported\n", debugstr_a(Protseq));
957 return RPC_S_PROTSEQ_NOT_SUPPORTED;
960 *ps = ops->alloc();
961 if (!*ps)
962 return RPC_S_OUT_OF_RESOURCES;
963 (*ps)->MaxCalls = MaxCalls;
964 (*ps)->Protseq = strdup(Protseq);
965 (*ps)->ops = ops;
966 list_init(&(*ps)->listeners);
967 list_init(&(*ps)->connections);
968 InitializeCriticalSection(&(*ps)->cs);
969 (*ps)->cs.DebugInfo->Spare[0] = (DWORD_PTR)(__FILE__ ": RpcServerProtseq.cs");
971 list_add_head(&protseqs, &(*ps)->entry);
973 TRACE("new protseq %p created for %s\n", *ps, Protseq);
975 return RPC_S_OK;
978 /* must be called with server_cs held */
979 static void destroy_serverprotoseq(RpcServerProtseq *ps)
981 free(ps->Protseq);
982 ps->cs.DebugInfo->Spare[0] = 0;
983 DeleteCriticalSection(&ps->cs);
984 CloseHandle(ps->mgr_mutex);
985 CloseHandle(ps->server_ready_event);
986 list_remove(&ps->entry);
987 free(ps);
990 /* Finds a given protseq or creates a new one if one doesn't already exist */
991 static RPC_STATUS RPCRT4_get_or_create_serverprotseq(UINT MaxCalls, const char *Protseq, RpcServerProtseq **ps)
993 RPC_STATUS status;
994 RpcServerProtseq *cps;
996 EnterCriticalSection(&server_cs);
998 LIST_FOR_EACH_ENTRY(cps, &protseqs, RpcServerProtseq, entry)
999 if (!strcmp(cps->Protseq, Protseq))
1001 TRACE("found existing protseq object for %s\n", Protseq);
1002 *ps = cps;
1003 LeaveCriticalSection(&server_cs);
1004 return S_OK;
1007 status = alloc_serverprotoseq(MaxCalls, Protseq, ps);
1009 LeaveCriticalSection(&server_cs);
1011 return status;
1014 /***********************************************************************
1015 * RpcServerUseProtseqEpExA (RPCRT4.@)
1017 RPC_STATUS WINAPI RpcServerUseProtseqEpExA( RPC_CSTR Protseq, UINT MaxCalls, RPC_CSTR Endpoint, LPVOID SecurityDescriptor,
1018 PRPC_POLICY lpPolicy )
1020 RpcServerProtseq* ps;
1021 RPC_STATUS status;
1023 TRACE("(%s,%u,%s,%p,{%u,%lu,%lu})\n", debugstr_a((const char *)Protseq),
1024 MaxCalls, debugstr_a((const char *)Endpoint), SecurityDescriptor,
1025 lpPolicy->Length, lpPolicy->EndpointFlags, lpPolicy->NICFlags );
1027 status = RPCRT4_get_or_create_serverprotseq(MaxCalls, (const char *)Protseq, &ps);
1028 if (status != RPC_S_OK)
1029 return status;
1031 return RPCRT4_use_protseq(ps, (const char *)Endpoint);
1034 /***********************************************************************
1035 * RpcServerUseProtseqEpExW (RPCRT4.@)
1037 RPC_STATUS WINAPI RpcServerUseProtseqEpExW( RPC_WSTR Protseq, UINT MaxCalls, RPC_WSTR Endpoint, LPVOID SecurityDescriptor,
1038 PRPC_POLICY lpPolicy )
1040 RpcServerProtseq* ps;
1041 RPC_STATUS status;
1042 LPSTR ProtseqA;
1043 LPSTR EndpointA;
1045 TRACE("(%s,%u,%s,%p,{%u,%lu,%lu})\n", debugstr_w( Protseq ), MaxCalls,
1046 debugstr_w( Endpoint ), SecurityDescriptor,
1047 lpPolicy->Length, lpPolicy->EndpointFlags, lpPolicy->NICFlags );
1049 ProtseqA = RPCRT4_strdupWtoA(Protseq);
1050 status = RPCRT4_get_or_create_serverprotseq(MaxCalls, ProtseqA, &ps);
1051 free(ProtseqA);
1052 if (status != RPC_S_OK)
1053 return status;
1055 EndpointA = RPCRT4_strdupWtoA(Endpoint);
1056 status = RPCRT4_use_protseq(ps, EndpointA);
1057 free(EndpointA);
1058 return status;
1061 /***********************************************************************
1062 * RpcServerUseProtseqA (RPCRT4.@)
1064 RPC_STATUS WINAPI RpcServerUseProtseqA(RPC_CSTR Protseq, unsigned int MaxCalls, void *SecurityDescriptor)
1066 RPC_STATUS status;
1067 RpcServerProtseq* ps;
1069 TRACE("(Protseq == %s, MaxCalls == %d, SecurityDescriptor == ^%p)\n", debugstr_a((char*)Protseq), MaxCalls, SecurityDescriptor);
1071 status = RPCRT4_get_or_create_serverprotseq(MaxCalls, (const char *)Protseq, &ps);
1072 if (status != RPC_S_OK)
1073 return status;
1075 return RPCRT4_use_protseq(ps, NULL);
1078 /***********************************************************************
1079 * RpcServerUseProtseqW (RPCRT4.@)
1081 RPC_STATUS WINAPI RpcServerUseProtseqW(RPC_WSTR Protseq, unsigned int MaxCalls, void *SecurityDescriptor)
1083 RPC_STATUS status;
1084 RpcServerProtseq* ps;
1085 LPSTR ProtseqA;
1087 TRACE("Protseq == %s, MaxCalls == %d, SecurityDescriptor == ^%p)\n", debugstr_w(Protseq), MaxCalls, SecurityDescriptor);
1089 ProtseqA = RPCRT4_strdupWtoA(Protseq);
1090 status = RPCRT4_get_or_create_serverprotseq(MaxCalls, ProtseqA, &ps);
1091 free(ProtseqA);
1092 if (status != RPC_S_OK)
1093 return status;
1095 return RPCRT4_use_protseq(ps, NULL);
1098 void RPCRT4_destroy_all_protseqs(void)
1100 RpcServerProtseq *cps, *cursor2;
1102 if (listen_count != 0)
1103 std_listen = FALSE;
1105 EnterCriticalSection(&server_cs);
1106 LIST_FOR_EACH_ENTRY_SAFE(cps, cursor2, &protseqs, RpcServerProtseq, entry)
1108 if (listen_count != 0)
1109 RPCRT4_sync_with_server_thread(cps);
1110 destroy_serverprotoseq(cps);
1112 LeaveCriticalSection(&server_cs);
1113 DeleteCriticalSection(&server_cs);
1114 DeleteCriticalSection(&listen_cs);
1117 /***********************************************************************
1118 * RpcServerRegisterIf (RPCRT4.@)
1120 RPC_STATUS WINAPI RpcServerRegisterIf( RPC_IF_HANDLE IfSpec, UUID* MgrTypeUuid, RPC_MGR_EPV* MgrEpv )
1122 TRACE("(%p,%s,%p)\n", IfSpec, debugstr_guid(MgrTypeUuid), MgrEpv);
1123 return RpcServerRegisterIf3( IfSpec, MgrTypeUuid, MgrEpv, 0, RPC_C_LISTEN_MAX_CALLS_DEFAULT, (UINT)-1, NULL, NULL );
1126 /***********************************************************************
1127 * RpcServerRegisterIfEx (RPCRT4.@)
1129 RPC_STATUS WINAPI RpcServerRegisterIfEx( RPC_IF_HANDLE IfSpec, UUID* MgrTypeUuid, RPC_MGR_EPV* MgrEpv,
1130 UINT Flags, UINT MaxCalls, RPC_IF_CALLBACK_FN* IfCallbackFn )
1132 TRACE("(%p,%s,%p,%u,%u,%p)\n", IfSpec, debugstr_guid(MgrTypeUuid), MgrEpv, Flags, MaxCalls, IfCallbackFn);
1133 return RpcServerRegisterIf3( IfSpec, MgrTypeUuid, MgrEpv, Flags, MaxCalls, (UINT)-1, IfCallbackFn, NULL );
1136 /***********************************************************************
1137 * RpcServerRegisterIf2 (RPCRT4.@)
1139 RPC_STATUS WINAPI RpcServerRegisterIf2( RPC_IF_HANDLE IfSpec, UUID* MgrTypeUuid, RPC_MGR_EPV* MgrEpv,
1140 UINT Flags, UINT MaxCalls, UINT MaxRpcSize, RPC_IF_CALLBACK_FN* IfCallbackFn )
1142 return RpcServerRegisterIf3( IfSpec, MgrTypeUuid, MgrEpv, Flags, MaxCalls, MaxRpcSize, IfCallbackFn, NULL );
1145 /***********************************************************************
1146 * RpcServerRegisterIf3 (RPCRT4.@)
1148 RPC_STATUS WINAPI RpcServerRegisterIf3( RPC_IF_HANDLE IfSpec, UUID* MgrTypeUuid, RPC_MGR_EPV* MgrEpv,
1149 UINT Flags, UINT MaxCalls, UINT MaxRpcSize, RPC_IF_CALLBACK_FN* IfCallbackFn, void* SecurityDescriptor)
1151 PRPC_SERVER_INTERFACE If = IfSpec;
1152 RpcServerInterface* sif;
1153 unsigned int i;
1155 TRACE("(%p,%s,%p,%u,%u,%u,%p,%p)\n", IfSpec, debugstr_guid(MgrTypeUuid), MgrEpv, Flags, MaxCalls,
1156 MaxRpcSize, IfCallbackFn, SecurityDescriptor);
1158 if (SecurityDescriptor)
1159 FIXME("Unsupported SecurityDescriptor argument.\n");
1161 TRACE(" interface id: %s %d.%d\n", debugstr_guid(&If->InterfaceId.SyntaxGUID),
1162 If->InterfaceId.SyntaxVersion.MajorVersion,
1163 If->InterfaceId.SyntaxVersion.MinorVersion);
1164 TRACE(" transfer syntax: %s %d.%d\n", debugstr_guid(&If->TransferSyntax.SyntaxGUID),
1165 If->TransferSyntax.SyntaxVersion.MajorVersion,
1166 If->TransferSyntax.SyntaxVersion.MinorVersion);
1167 TRACE(" dispatch table: %p\n", If->DispatchTable);
1168 if (If->DispatchTable) {
1169 TRACE(" dispatch table count: %d\n", If->DispatchTable->DispatchTableCount);
1170 for (i=0; i<If->DispatchTable->DispatchTableCount; i++) {
1171 TRACE(" entry %d: %p\n", i, If->DispatchTable->DispatchTable[i]);
1173 TRACE(" reserved: %Id\n", If->DispatchTable->Reserved);
1175 TRACE(" protseq endpoint count: %d\n", If->RpcProtseqEndpointCount);
1176 TRACE(" default manager epv: %p\n", If->DefaultManagerEpv);
1177 TRACE(" interpreter info: %p\n", If->InterpreterInfo);
1179 sif = calloc(1, sizeof(RpcServerInterface));
1180 sif->If = If;
1181 if (MgrTypeUuid) {
1182 sif->MgrTypeUuid = *MgrTypeUuid;
1183 sif->MgrEpv = MgrEpv;
1184 } else {
1185 memset(&sif->MgrTypeUuid, 0, sizeof(UUID));
1186 sif->MgrEpv = If->DefaultManagerEpv;
1188 sif->Flags = Flags;
1189 sif->MaxCalls = MaxCalls;
1190 sif->MaxRpcSize = MaxRpcSize;
1191 sif->IfCallbackFn = IfCallbackFn;
1193 EnterCriticalSection(&server_cs);
1194 list_add_head(&server_interfaces, &sif->entry);
1195 LeaveCriticalSection(&server_cs);
1197 if (sif->Flags & RPC_IF_AUTOLISTEN)
1198 RPCRT4_start_listen(TRUE);
1200 return RPC_S_OK;
1203 /***********************************************************************
1204 * RpcServerUnregisterIf (RPCRT4.@)
1206 RPC_STATUS WINAPI RpcServerUnregisterIf( RPC_IF_HANDLE IfSpec, UUID* MgrTypeUuid, UINT WaitForCallsToComplete )
1208 PRPC_SERVER_INTERFACE If = IfSpec;
1209 HANDLE event = NULL;
1210 BOOL found = FALSE;
1211 BOOL completed = TRUE;
1212 RpcServerInterface *cif;
1213 RPC_STATUS status;
1215 TRACE("(IfSpec == (RPC_IF_HANDLE)^%p (%s), MgrTypeUuid == %s, WaitForCallsToComplete == %u)\n",
1216 IfSpec, debugstr_guid(&If->InterfaceId.SyntaxGUID), debugstr_guid(MgrTypeUuid), WaitForCallsToComplete);
1218 EnterCriticalSection(&server_cs);
1219 LIST_FOR_EACH_ENTRY(cif, &server_interfaces, RpcServerInterface, entry) {
1220 if (((!IfSpec && !(cif->Flags & RPC_IF_AUTOLISTEN)) ||
1221 (IfSpec && !memcmp(&If->InterfaceId, &cif->If->InterfaceId, sizeof(RPC_SYNTAX_IDENTIFIER)))) &&
1222 UuidEqual(MgrTypeUuid, &cif->MgrTypeUuid, &status)) {
1223 list_remove(&cif->entry);
1224 TRACE("unregistering cif %p\n", cif);
1225 if (cif->CurrentCalls) {
1226 completed = FALSE;
1227 cif->Delete = TRUE;
1228 if (WaitForCallsToComplete)
1229 cif->CallsCompletedEvent = event = CreateEventW(NULL, FALSE, FALSE, NULL);
1231 found = TRUE;
1232 break;
1235 LeaveCriticalSection(&server_cs);
1237 if (!found) {
1238 ERR("not found for object %s\n", debugstr_guid(MgrTypeUuid));
1239 return RPC_S_UNKNOWN_IF;
1242 if (completed)
1243 free(cif);
1244 else if (event) {
1245 /* sif will be freed when the last call is completed, so be careful not to
1246 * touch that memory here as that could happen before we get here */
1247 WaitForSingleObject(event, INFINITE);
1248 CloseHandle(event);
1251 return RPC_S_OK;
1254 /***********************************************************************
1255 * RpcServerUnregisterIfEx (RPCRT4.@)
1257 RPC_STATUS WINAPI RpcServerUnregisterIfEx( RPC_IF_HANDLE IfSpec, UUID* MgrTypeUuid, int RundownContextHandles )
1259 FIXME("(IfSpec == (RPC_IF_HANDLE)^%p, MgrTypeUuid == %s, RundownContextHandles == %d): stub\n",
1260 IfSpec, debugstr_guid(MgrTypeUuid), RundownContextHandles);
1262 return RPC_S_OK;
1265 /***********************************************************************
1266 * RpcObjectSetType (RPCRT4.@)
1268 * PARAMS
1269 * ObjUuid [I] "Object" UUID
1270 * TypeUuid [I] "Type" UUID
1272 * RETURNS
1273 * RPC_S_OK The call succeeded
1274 * RPC_S_INVALID_OBJECT The provided object (nil) is not valid
1275 * RPC_S_ALREADY_REGISTERED The provided object is already registered
1277 * Maps "Object" UUIDs to "Type" UUIDs. Passing the nil UUID as the type
1278 * resets the mapping for the specified object UUID to nil (the default).
1279 * The nil object is always associated with the nil type and cannot be
1280 * reassigned. Servers can support multiple implementations on the same
1281 * interface by registering different end-point vectors for the different
1282 * types. There's no need to call this if a server only supports the nil
1283 * type, as is typical.
1285 RPC_STATUS WINAPI RpcObjectSetType( UUID* ObjUuid, UUID* TypeUuid )
1287 RpcObjTypeMap *map = RpcObjTypeMaps, *prev = NULL;
1288 RPC_STATUS dummy;
1290 TRACE("(ObjUUID == %s, TypeUuid == %s).\n", debugstr_guid(ObjUuid), debugstr_guid(TypeUuid));
1291 if ((! ObjUuid) || UuidIsNil(ObjUuid, &dummy)) {
1292 /* nil uuid cannot be remapped */
1293 return RPC_S_INVALID_OBJECT;
1296 /* find the mapping for this object if there is one ... */
1297 while (map) {
1298 if (! UuidCompare(ObjUuid, &map->Object, &dummy)) break;
1299 prev = map;
1300 map = map->next;
1302 if ((! TypeUuid) || UuidIsNil(TypeUuid, &dummy)) {
1303 /* ... and drop it from the list */
1304 if (map) {
1305 if (prev)
1306 prev->next = map->next;
1307 else
1308 RpcObjTypeMaps = map->next;
1309 free(map);
1311 } else {
1312 /* ... , fail if we found it ... */
1313 if (map)
1314 return RPC_S_ALREADY_REGISTERED;
1315 /* ... otherwise create a new one and add it in. */
1316 map = malloc(sizeof(RpcObjTypeMap));
1317 map->Object = *ObjUuid;
1318 map->Type = *TypeUuid;
1319 map->next = NULL;
1320 if (prev)
1321 prev->next = map; /* prev is the last map in the linklist */
1322 else
1323 RpcObjTypeMaps = map;
1326 return RPC_S_OK;
1329 struct rpc_server_registered_auth_info
1331 struct list entry;
1332 USHORT auth_type;
1333 WCHAR *package_name;
1334 WCHAR *principal;
1335 ULONG max_token;
1338 static RPC_STATUS find_security_package(ULONG auth_type, SecPkgInfoW **packages_buf, SecPkgInfoW **ret)
1340 SECURITY_STATUS sec_status;
1341 SecPkgInfoW *packages;
1342 ULONG package_count;
1343 ULONG i;
1345 sec_status = EnumerateSecurityPackagesW(&package_count, &packages);
1346 if (sec_status != SEC_E_OK)
1348 ERR("EnumerateSecurityPackagesW failed with error 0x%08lx\n", sec_status);
1349 return RPC_S_SEC_PKG_ERROR;
1352 for (i = 0; i < package_count; i++)
1353 if (packages[i].wRPCID == auth_type)
1354 break;
1356 if (i == package_count)
1358 WARN("unsupported AuthnSvc %lu\n", auth_type);
1359 FreeContextBuffer(packages);
1360 return RPC_S_UNKNOWN_AUTHN_SERVICE;
1363 TRACE("found package %s for service %lu\n", debugstr_w(packages[i].Name), auth_type);
1364 *packages_buf = packages;
1365 *ret = packages + i;
1366 return RPC_S_OK;
1369 RPC_STATUS RPCRT4_ServerGetRegisteredAuthInfo(
1370 USHORT auth_type, CredHandle *cred, TimeStamp *exp, ULONG *max_token)
1372 RPC_STATUS status = RPC_S_UNKNOWN_AUTHN_SERVICE;
1373 struct rpc_server_registered_auth_info *auth_info;
1374 SECURITY_STATUS sec_status;
1376 EnterCriticalSection(&server_auth_info_cs);
1377 LIST_FOR_EACH_ENTRY(auth_info, &server_registered_auth_info, struct rpc_server_registered_auth_info, entry)
1379 if (auth_info->auth_type == auth_type)
1381 sec_status = AcquireCredentialsHandleW((SEC_WCHAR *)auth_info->principal, auth_info->package_name,
1382 SECPKG_CRED_INBOUND, NULL, NULL, NULL, NULL,
1383 cred, exp);
1384 if (sec_status != SEC_E_OK)
1386 status = RPC_S_SEC_PKG_ERROR;
1387 break;
1390 *max_token = auth_info->max_token;
1391 status = RPC_S_OK;
1392 break;
1395 LeaveCriticalSection(&server_auth_info_cs);
1397 return status;
1400 void RPCRT4_ServerFreeAllRegisteredAuthInfo(void)
1402 struct rpc_server_registered_auth_info *auth_info, *cursor2;
1404 EnterCriticalSection(&server_auth_info_cs);
1405 LIST_FOR_EACH_ENTRY_SAFE(auth_info, cursor2, &server_registered_auth_info, struct rpc_server_registered_auth_info, entry)
1407 free(auth_info->package_name);
1408 free(auth_info->principal);
1409 free(auth_info);
1411 LeaveCriticalSection(&server_auth_info_cs);
1412 DeleteCriticalSection(&server_auth_info_cs);
1415 /***********************************************************************
1416 * RpcServerRegisterAuthInfoA (RPCRT4.@)
1418 RPC_STATUS WINAPI RpcServerRegisterAuthInfoA( RPC_CSTR ServerPrincName, ULONG AuthnSvc, RPC_AUTH_KEY_RETRIEVAL_FN GetKeyFn,
1419 LPVOID Arg )
1421 WCHAR *principal_name = NULL;
1422 RPC_STATUS status;
1424 TRACE("(%s,%lu,%p,%p)\n", ServerPrincName, AuthnSvc, GetKeyFn, Arg);
1426 if(ServerPrincName && !(principal_name = RPCRT4_strdupAtoW((const char*)ServerPrincName)))
1427 return RPC_S_OUT_OF_RESOURCES;
1429 status = RpcServerRegisterAuthInfoW(principal_name, AuthnSvc, GetKeyFn, Arg);
1431 free(principal_name);
1432 return status;
1435 /***********************************************************************
1436 * RpcServerRegisterAuthInfoW (RPCRT4.@)
1438 RPC_STATUS WINAPI RpcServerRegisterAuthInfoW( RPC_WSTR ServerPrincName, ULONG AuthnSvc, RPC_AUTH_KEY_RETRIEVAL_FN GetKeyFn,
1439 LPVOID Arg )
1441 struct rpc_server_registered_auth_info *auth_info;
1442 SecPkgInfoW *packages, *package;
1443 WCHAR *package_name;
1444 ULONG max_token;
1445 RPC_STATUS status;
1447 TRACE("(%s,%lu,%p,%p)\n", debugstr_w(ServerPrincName), AuthnSvc, GetKeyFn, Arg);
1449 status = find_security_package(AuthnSvc, &packages, &package);
1450 if (status != RPC_S_OK)
1451 return status;
1453 package_name = wcsdup(package->Name);
1454 max_token = package->cbMaxToken;
1455 FreeContextBuffer(packages);
1456 if (!package_name)
1457 return RPC_S_OUT_OF_RESOURCES;
1459 auth_info = calloc(1, sizeof(*auth_info));
1460 if (!auth_info) {
1461 free(package_name);
1462 return RPC_S_OUT_OF_RESOURCES;
1465 if (ServerPrincName && !(auth_info->principal = wcsdup(ServerPrincName))) {
1466 free(package_name);
1467 free(auth_info);
1468 return RPC_S_OUT_OF_RESOURCES;
1471 auth_info->auth_type = AuthnSvc;
1472 auth_info->package_name = package_name;
1473 auth_info->max_token = max_token;
1475 EnterCriticalSection(&server_auth_info_cs);
1476 list_add_tail(&server_registered_auth_info, &auth_info->entry);
1477 LeaveCriticalSection(&server_auth_info_cs);
1479 return RPC_S_OK;
1482 /******************************************************************************
1483 * RpcServerInqDefaultPrincNameA (rpcrt4.@)
1485 RPC_STATUS RPC_ENTRY RpcServerInqDefaultPrincNameA(ULONG AuthnSvc, RPC_CSTR *PrincName)
1487 RPC_STATUS ret;
1488 RPC_WSTR principalW;
1490 TRACE("%lu, %p\n", AuthnSvc, PrincName);
1492 if ((ret = RpcServerInqDefaultPrincNameW( AuthnSvc, &principalW )) == RPC_S_OK)
1494 if (!(*PrincName = (RPC_CSTR)RPCRT4_strdupWtoA( principalW ))) return RPC_S_OUT_OF_MEMORY;
1495 RpcStringFreeW( &principalW );
1497 return ret;
1500 /******************************************************************************
1501 * RpcServerInqDefaultPrincNameW (rpcrt4.@)
1503 RPC_STATUS RPC_ENTRY RpcServerInqDefaultPrincNameW(ULONG AuthnSvc, RPC_WSTR *PrincName)
1505 ULONG len = 0;
1507 FIXME("%lu, %p\n", AuthnSvc, PrincName);
1509 if (AuthnSvc != RPC_C_AUTHN_WINNT) return RPC_S_UNKNOWN_AUTHN_SERVICE;
1511 GetUserNameExW( NameSamCompatible, NULL, &len );
1512 if (GetLastError() != ERROR_MORE_DATA) return RPC_S_INTERNAL_ERROR;
1514 if (!(*PrincName = malloc(len * sizeof(WCHAR))))
1515 return RPC_S_OUT_OF_MEMORY;
1517 GetUserNameExW( NameSamCompatible, *PrincName, &len );
1518 return RPC_S_OK;
1521 /***********************************************************************
1522 * RpcServerListen (RPCRT4.@)
1524 RPC_STATUS WINAPI RpcServerListen( UINT MinimumCallThreads, UINT MaxCalls, UINT DontWait )
1526 RPC_STATUS status = RPC_S_OK;
1528 TRACE("(%u,%u,%u)\n", MinimumCallThreads, MaxCalls, DontWait);
1530 if (list_empty(&protseqs))
1531 return RPC_S_NO_PROTSEQS_REGISTERED;
1533 status = RPCRT4_start_listen(FALSE);
1535 if (DontWait || (status != RPC_S_OK)) return status;
1537 return RpcMgmtWaitServerListen();
1540 /***********************************************************************
1541 * RpcMgmtServerWaitListen (RPCRT4.@)
1543 RPC_STATUS WINAPI RpcMgmtWaitServerListen( void )
1545 RpcServerProtseq *protseq;
1546 HANDLE event, wait_thread;
1548 TRACE("()\n");
1550 EnterCriticalSection(&listen_cs);
1551 event = listen_done_event;
1552 LeaveCriticalSection(&listen_cs);
1554 if (!event)
1555 return RPC_S_NOT_LISTENING;
1557 TRACE( "waiting for server calls to finish\n" );
1558 WaitForSingleObject( event, INFINITE );
1559 TRACE( "done waiting\n" );
1561 EnterCriticalSection(&listen_cs);
1562 /* wait for server threads to finish */
1563 while(1)
1565 if (listen_count)
1566 break;
1568 wait_thread = NULL;
1569 EnterCriticalSection(&server_cs);
1570 LIST_FOR_EACH_ENTRY(protseq, &protseqs, RpcServerProtseq, entry)
1572 if ((wait_thread = protseq->server_thread))
1573 break;
1575 LeaveCriticalSection(&server_cs);
1576 if (!wait_thread)
1577 break;
1579 TRACE("waiting for thread %lu\n", GetThreadId(wait_thread));
1580 LeaveCriticalSection(&listen_cs);
1581 WaitForSingleObject(wait_thread, INFINITE);
1582 EnterCriticalSection(&listen_cs);
1584 if (listen_done_event == event)
1586 listen_done_event = NULL;
1587 CloseHandle( event );
1589 LeaveCriticalSection(&listen_cs);
1590 return RPC_S_OK;
1593 /***********************************************************************
1594 * RpcMgmtStopServerListening (RPCRT4.@)
1596 RPC_STATUS WINAPI RpcMgmtStopServerListening ( RPC_BINDING_HANDLE Binding )
1598 TRACE("(Binding == (RPC_BINDING_HANDLE)^%p)\n", Binding);
1600 if (Binding) {
1601 FIXME("client-side invocation not implemented.\n");
1602 return RPC_S_WRONG_KIND_OF_BINDING;
1605 return RPCRT4_stop_listen(FALSE);
1608 /***********************************************************************
1609 * RpcMgmtEnableIdleCleanup (RPCRT4.@)
1611 RPC_STATUS WINAPI RpcMgmtEnableIdleCleanup(void)
1613 FIXME("(): stub\n");
1614 return RPC_S_OK;
1617 /***********************************************************************
1618 * I_RpcServerStartListening (RPCRT4.@)
1620 RPC_STATUS WINAPI I_RpcServerStartListening( HWND hWnd )
1622 FIXME( "(%p): stub\n", hWnd );
1624 return RPC_S_OK;
1627 /***********************************************************************
1628 * I_RpcServerStopListening (RPCRT4.@)
1630 RPC_STATUS WINAPI I_RpcServerStopListening( void )
1632 FIXME( "(): stub\n" );
1634 return RPC_S_OK;
1637 /***********************************************************************
1638 * I_RpcWindowProc (RPCRT4.@)
1640 UINT WINAPI I_RpcWindowProc( void *hWnd, UINT Message, UINT wParam, ULONG lParam )
1642 FIXME( "(%p,%08x,%08x,%08lx): stub\n", hWnd, Message, wParam, lParam );
1644 return 0;
1647 /***********************************************************************
1648 * RpcMgmtInqIfIds (RPCRT4.@)
1650 RPC_STATUS WINAPI RpcMgmtInqIfIds(RPC_BINDING_HANDLE Binding, RPC_IF_ID_VECTOR **IfIdVector)
1652 FIXME("(%p,%p): stub\n", Binding, IfIdVector);
1653 return RPC_S_INVALID_BINDING;
1656 /***********************************************************************
1657 * RpcMgmtInqStats (RPCRT4.@)
1659 RPC_STATUS WINAPI RpcMgmtInqStats(RPC_BINDING_HANDLE Binding, RPC_STATS_VECTOR **Statistics)
1661 RPC_STATS_VECTOR *stats;
1663 FIXME("(%p,%p)\n", Binding, Statistics);
1665 if ((stats = malloc(sizeof(RPC_STATS_VECTOR))))
1667 stats->Count = 1;
1668 stats->Stats[0] = 0;
1669 *Statistics = stats;
1670 return RPC_S_OK;
1672 return RPC_S_OUT_OF_RESOURCES;
1675 /***********************************************************************
1676 * RpcMgmtStatsVectorFree (RPCRT4.@)
1678 RPC_STATUS WINAPI RpcMgmtStatsVectorFree(RPC_STATS_VECTOR **StatsVector)
1680 FIXME("(%p)\n", StatsVector);
1682 if (StatsVector)
1684 free(*StatsVector);
1685 *StatsVector = NULL;
1687 return RPC_S_OK;
1690 /***********************************************************************
1691 * RpcMgmtEpEltInqBegin (RPCRT4.@)
1693 RPC_STATUS WINAPI RpcMgmtEpEltInqBegin(RPC_BINDING_HANDLE Binding, ULONG InquiryType,
1694 RPC_IF_ID *IfId, ULONG VersOption, UUID *ObjectUuid, RPC_EP_INQ_HANDLE* InquiryContext)
1696 FIXME("(%p,%lu,%p,%lu,%p,%p): stub\n",
1697 Binding, InquiryType, IfId, VersOption, ObjectUuid, InquiryContext);
1698 return RPC_S_INVALID_BINDING;
1701 /***********************************************************************
1702 * RpcMgmtIsServerListening (RPCRT4.@)
1704 RPC_STATUS WINAPI RpcMgmtIsServerListening(RPC_BINDING_HANDLE Binding)
1706 RPC_STATUS status = RPC_S_NOT_LISTENING;
1708 TRACE("(%p)\n", Binding);
1710 if (Binding) {
1711 RpcBinding *rpc_binding = (RpcBinding*)Binding;
1712 status = RPCRT4_IsServerListening(rpc_binding->Protseq, rpc_binding->Endpoint);
1713 }else {
1714 EnterCriticalSection(&listen_cs);
1715 if (listen_done_event && std_listen) status = RPC_S_OK;
1716 LeaveCriticalSection(&listen_cs);
1719 return status;
1722 /***********************************************************************
1723 * RpcMgmtSetAuthorizationFn (RPCRT4.@)
1725 RPC_STATUS WINAPI RpcMgmtSetAuthorizationFn(RPC_MGMT_AUTHORIZATION_FN fn)
1727 FIXME("(%p): stub\n", fn);
1728 return RPC_S_OK;
1731 /***********************************************************************
1732 * RpcMgmtSetServerStackSize (RPCRT4.@)
1734 RPC_STATUS WINAPI RpcMgmtSetServerStackSize(ULONG ThreadStackSize)
1736 FIXME("(0x%lx): stub\n", ThreadStackSize);
1737 return RPC_S_OK;
1740 /***********************************************************************
1741 * I_RpcGetCurrentCallHandle (RPCRT4.@)
1743 RPC_BINDING_HANDLE WINAPI I_RpcGetCurrentCallHandle(void)
1745 TRACE("\n");
1746 return RPCRT4_GetThreadCurrentCallHandle();