iphlpapi: Correct copy/paste error in GetTcpTable.
[wine/wine-kai.git] / dlls / rpcrt4 / rpc_transport.c
blobdfb7eceebe40d7a7e2d12e6585e8a55afc92475a
1 /*
2 * RPC transport layer
4 * Copyright 2001 Ove Kåven, TransGaming Technologies
5 * Copyright 2003 Mike Hearn
6 * Copyright 2004 Filip Navara
7 * Copyright 2006 Mike McCormack
8 * Copyright 2006 Damjan Jovanovic
10 * This library is free software; you can redistribute it and/or
11 * modify it under the terms of the GNU Lesser General Public
12 * License as published by the Free Software Foundation; either
13 * version 2.1 of the License, or (at your option) any later version.
15 * This library is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
18 * Lesser General Public License for more details.
20 * You should have received a copy of the GNU Lesser General Public
21 * License along with this library; if not, write to the Free Software
22 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
26 #include "config.h"
28 #include <stdarg.h>
29 #include <stdio.h>
30 #include <string.h>
31 #include <assert.h>
32 #include <errno.h>
34 #ifdef HAVE_UNISTD_H
35 # include <unistd.h>
36 #endif
37 #include <fcntl.h>
38 #include <stdlib.h>
39 #include <sys/types.h>
40 #ifdef HAVE_SYS_SOCKET_H
41 # include <sys/socket.h>
42 #endif
43 #ifdef HAVE_NETINET_IN_H
44 # include <netinet/in.h>
45 #endif
46 #ifdef HAVE_NETINET_TCP_H
47 # include <netinet/tcp.h>
48 #endif
49 #ifdef HAVE_ARPA_INET_H
50 # include <arpa/inet.h>
51 #endif
52 #ifdef HAVE_NETDB_H
53 #include <netdb.h>
54 #endif
55 #ifdef HAVE_SYS_POLL_H
56 #include <sys/poll.h>
57 #endif
59 #include "windef.h"
60 #include "winbase.h"
61 #include "winnls.h"
62 #include "winerror.h"
63 #include "winternl.h"
64 #include "wine/unicode.h"
66 #include "rpc.h"
67 #include "rpcndr.h"
69 #include "wine/debug.h"
71 #include "rpc_binding.h"
72 #include "rpc_message.h"
73 #include "rpc_server.h"
74 #include "epm_towers.h"
76 #ifndef SOL_TCP
77 # define SOL_TCP IPPROTO_TCP
78 #endif
80 WINE_DEFAULT_DEBUG_CHANNEL(rpc);
82 static CRITICAL_SECTION assoc_list_cs;
83 static CRITICAL_SECTION_DEBUG assoc_list_cs_debug =
85 0, 0, &assoc_list_cs,
86 { &assoc_list_cs_debug.ProcessLocksList, &assoc_list_cs_debug.ProcessLocksList },
87 0, 0, { (DWORD_PTR)(__FILE__ ": assoc_list_cs") }
89 static CRITICAL_SECTION assoc_list_cs = { &assoc_list_cs_debug, -1, 0, 0, 0, 0 };
91 static struct list assoc_list = LIST_INIT(assoc_list);
93 /**** ncacn_np support ****/
95 typedef struct _RpcConnection_np
97 RpcConnection common;
98 HANDLE pipe;
99 OVERLAPPED ovl;
100 BOOL listening;
101 } RpcConnection_np;
103 static RpcConnection *rpcrt4_conn_np_alloc(void)
105 RpcConnection_np *npc = HeapAlloc(GetProcessHeap(), 0, sizeof(RpcConnection_np));
106 if (npc)
108 npc->pipe = NULL;
109 memset(&npc->ovl, 0, sizeof(npc->ovl));
110 npc->listening = FALSE;
112 return &npc->common;
115 static RPC_STATUS rpcrt4_conn_listen_pipe(RpcConnection_np *npc)
117 if (npc->listening)
118 return RPC_S_OK;
120 npc->listening = TRUE;
121 if (ConnectNamedPipe(npc->pipe, &npc->ovl))
122 return RPC_S_OK;
124 if (GetLastError() == ERROR_PIPE_CONNECTED) {
125 SetEvent(npc->ovl.hEvent);
126 return RPC_S_OK;
128 if (GetLastError() == ERROR_IO_PENDING) {
129 /* will be completed in rpcrt4_protseq_np_wait_for_new_connection */
130 return RPC_S_OK;
132 npc->listening = FALSE;
133 WARN("Couldn't ConnectNamedPipe (error was %d)\n", GetLastError());
134 return RPC_S_OUT_OF_RESOURCES;
137 static RPC_STATUS rpcrt4_conn_create_pipe(RpcConnection *Connection, LPCSTR pname)
139 RpcConnection_np *npc = (RpcConnection_np *) Connection;
140 TRACE("listening on %s\n", pname);
142 npc->pipe = CreateNamedPipeA(pname, PIPE_ACCESS_DUPLEX,
143 PIPE_TYPE_MESSAGE | PIPE_READMODE_MESSAGE,
144 PIPE_UNLIMITED_INSTANCES,
145 RPC_MAX_PACKET_SIZE, RPC_MAX_PACKET_SIZE, 5000, NULL);
146 if (npc->pipe == INVALID_HANDLE_VALUE) {
147 WARN("CreateNamedPipe failed with error %d\n", GetLastError());
148 if (GetLastError() == ERROR_FILE_EXISTS)
149 return RPC_S_DUPLICATE_ENDPOINT;
150 else
151 return RPC_S_CANT_CREATE_ENDPOINT;
154 memset(&npc->ovl, 0, sizeof(npc->ovl));
155 npc->ovl.hEvent = CreateEventW(NULL, TRUE, FALSE, NULL);
157 /* Note: we don't call ConnectNamedPipe here because it must be done in the
158 * server thread as the thread must be alertable */
159 return RPC_S_OK;
162 static RPC_STATUS rpcrt4_conn_open_pipe(RpcConnection *Connection, LPCSTR pname, BOOL wait)
164 RpcConnection_np *npc = (RpcConnection_np *) Connection;
165 HANDLE pipe;
166 DWORD err, dwMode;
168 TRACE("connecting to %s\n", pname);
170 while (TRUE) {
171 DWORD dwFlags = 0;
172 if (Connection->QOS)
174 dwFlags = SECURITY_SQOS_PRESENT;
175 switch (Connection->QOS->qos->ImpersonationType)
177 case RPC_C_IMP_LEVEL_DEFAULT:
178 /* FIXME: what to do here? */
179 break;
180 case RPC_C_IMP_LEVEL_ANONYMOUS:
181 dwFlags |= SECURITY_ANONYMOUS;
182 break;
183 case RPC_C_IMP_LEVEL_IDENTIFY:
184 dwFlags |= SECURITY_IDENTIFICATION;
185 break;
186 case RPC_C_IMP_LEVEL_IMPERSONATE:
187 dwFlags |= SECURITY_IMPERSONATION;
188 break;
189 case RPC_C_IMP_LEVEL_DELEGATE:
190 dwFlags |= SECURITY_DELEGATION;
191 break;
193 if (Connection->QOS->qos->IdentityTracking == RPC_C_QOS_IDENTIFY_DYNAMIC)
194 dwFlags |= SECURITY_CONTEXT_TRACKING;
196 pipe = CreateFileA(pname, GENERIC_READ|GENERIC_WRITE, 0, NULL,
197 OPEN_EXISTING, dwFlags, 0);
198 if (pipe != INVALID_HANDLE_VALUE) break;
199 err = GetLastError();
200 if (err == ERROR_PIPE_BUSY) {
201 TRACE("connection failed, error=%x\n", err);
202 return RPC_S_SERVER_TOO_BUSY;
204 if (!wait)
205 return RPC_S_SERVER_UNAVAILABLE;
206 if (!WaitNamedPipeA(pname, NMPWAIT_WAIT_FOREVER)) {
207 err = GetLastError();
208 WARN("connection failed, error=%x\n", err);
209 return RPC_S_SERVER_UNAVAILABLE;
213 /* success */
214 memset(&npc->ovl, 0, sizeof(npc->ovl));
215 /* pipe is connected; change to message-read mode. */
216 dwMode = PIPE_READMODE_MESSAGE;
217 SetNamedPipeHandleState(pipe, &dwMode, NULL, NULL);
218 npc->ovl.hEvent = CreateEventW(NULL, TRUE, FALSE, NULL);
219 npc->pipe = pipe;
221 return RPC_S_OK;
224 static RPC_STATUS rpcrt4_ncalrpc_open(RpcConnection* Connection)
226 RpcConnection_np *npc = (RpcConnection_np *) Connection;
227 static const char prefix[] = "\\\\.\\pipe\\lrpc\\";
228 RPC_STATUS r;
229 LPSTR pname;
231 /* already connected? */
232 if (npc->pipe)
233 return RPC_S_OK;
235 /* protseq=ncalrpc: supposed to use NT LPC ports,
236 * but we'll implement it with named pipes for now */
237 pname = I_RpcAllocate(strlen(prefix) + strlen(Connection->Endpoint) + 1);
238 strcat(strcpy(pname, prefix), Connection->Endpoint);
239 r = rpcrt4_conn_open_pipe(Connection, pname, TRUE);
240 I_RpcFree(pname);
242 return r;
245 static RPC_STATUS rpcrt4_protseq_ncalrpc_open_endpoint(RpcServerProtseq* protseq, LPSTR endpoint)
247 static const char prefix[] = "\\\\.\\pipe\\lrpc\\";
248 RPC_STATUS r;
249 LPSTR pname;
250 RpcConnection *Connection;
252 r = RPCRT4_CreateConnection(&Connection, TRUE, protseq->Protseq, NULL,
253 endpoint, NULL, NULL, NULL);
254 if (r != RPC_S_OK)
255 return r;
257 /* protseq=ncalrpc: supposed to use NT LPC ports,
258 * but we'll implement it with named pipes for now */
259 pname = I_RpcAllocate(strlen(prefix) + strlen(Connection->Endpoint) + 1);
260 strcat(strcpy(pname, prefix), Connection->Endpoint);
261 r = rpcrt4_conn_create_pipe(Connection, pname);
262 I_RpcFree(pname);
264 EnterCriticalSection(&protseq->cs);
265 Connection->Next = protseq->conn;
266 protseq->conn = Connection;
267 LeaveCriticalSection(&protseq->cs);
269 return r;
272 static RPC_STATUS rpcrt4_ncacn_np_open(RpcConnection* Connection)
274 RpcConnection_np *npc = (RpcConnection_np *) Connection;
275 static const char prefix[] = "\\\\.";
276 RPC_STATUS r;
277 LPSTR pname;
279 /* already connected? */
280 if (npc->pipe)
281 return RPC_S_OK;
283 /* protseq=ncacn_np: named pipes */
284 pname = I_RpcAllocate(strlen(prefix) + strlen(Connection->Endpoint) + 1);
285 strcat(strcpy(pname, prefix), Connection->Endpoint);
286 r = rpcrt4_conn_open_pipe(Connection, pname, FALSE);
287 I_RpcFree(pname);
289 return r;
292 static RPC_STATUS rpcrt4_protseq_ncacn_np_open_endpoint(RpcServerProtseq *protseq, LPSTR endpoint)
294 static const char prefix[] = "\\\\.";
295 RPC_STATUS r;
296 LPSTR pname;
297 RpcConnection *Connection;
299 r = RPCRT4_CreateConnection(&Connection, TRUE, protseq->Protseq, NULL,
300 endpoint, NULL, NULL, NULL);
301 if (r != RPC_S_OK)
302 return r;
304 /* protseq=ncacn_np: named pipes */
305 pname = I_RpcAllocate(strlen(prefix) + strlen(Connection->Endpoint) + 1);
306 strcat(strcpy(pname, prefix), Connection->Endpoint);
307 r = rpcrt4_conn_create_pipe(Connection, pname);
308 I_RpcFree(pname);
310 EnterCriticalSection(&protseq->cs);
311 Connection->Next = protseq->conn;
312 protseq->conn = Connection;
313 LeaveCriticalSection(&protseq->cs);
315 return r;
318 static void rpcrt4_conn_np_handoff(RpcConnection_np *old_npc, RpcConnection_np *new_npc)
320 /* because of the way named pipes work, we'll transfer the connected pipe
321 * to the child, then reopen the server binding to continue listening */
323 new_npc->pipe = old_npc->pipe;
324 new_npc->ovl = old_npc->ovl;
325 old_npc->pipe = 0;
326 memset(&old_npc->ovl, 0, sizeof(old_npc->ovl));
327 old_npc->listening = FALSE;
330 static RPC_STATUS rpcrt4_ncacn_np_handoff(RpcConnection *old_conn, RpcConnection *new_conn)
332 RPC_STATUS status;
333 LPSTR pname;
334 static const char prefix[] = "\\\\.";
336 rpcrt4_conn_np_handoff((RpcConnection_np *)old_conn, (RpcConnection_np *)new_conn);
338 pname = I_RpcAllocate(strlen(prefix) + strlen(old_conn->Endpoint) + 1);
339 strcat(strcpy(pname, prefix), old_conn->Endpoint);
340 status = rpcrt4_conn_create_pipe(old_conn, pname);
341 I_RpcFree(pname);
343 return status;
346 static RPC_STATUS rpcrt4_ncalrpc_handoff(RpcConnection *old_conn, RpcConnection *new_conn)
348 RPC_STATUS status;
349 LPSTR pname;
350 static const char prefix[] = "\\\\.\\pipe\\lrpc\\";
352 TRACE("%s\n", old_conn->Endpoint);
354 rpcrt4_conn_np_handoff((RpcConnection_np *)old_conn, (RpcConnection_np *)new_conn);
356 pname = I_RpcAllocate(strlen(prefix) + strlen(old_conn->Endpoint) + 1);
357 strcat(strcpy(pname, prefix), old_conn->Endpoint);
358 status = rpcrt4_conn_create_pipe(old_conn, pname);
359 I_RpcFree(pname);
361 return status;
364 static int rpcrt4_conn_np_read(RpcConnection *Connection,
365 void *buffer, unsigned int count)
367 RpcConnection_np *npc = (RpcConnection_np *) Connection;
368 char *buf = buffer;
369 BOOL ret = TRUE;
370 unsigned int bytes_left = count;
372 while (bytes_left)
374 DWORD bytes_read;
375 ret = ReadFile(npc->pipe, buf, bytes_left, &bytes_read, NULL);
376 if (!ret || !bytes_read)
377 break;
378 bytes_left -= bytes_read;
379 buf += bytes_read;
381 return ret ? count : -1;
384 static int rpcrt4_conn_np_write(RpcConnection *Connection,
385 const void *buffer, unsigned int count)
387 RpcConnection_np *npc = (RpcConnection_np *) Connection;
388 const char *buf = buffer;
389 BOOL ret = TRUE;
390 unsigned int bytes_left = count;
392 while (bytes_left)
394 DWORD bytes_written;
395 ret = WriteFile(npc->pipe, buf, count, &bytes_written, NULL);
396 if (!ret || !bytes_written)
397 break;
398 bytes_left -= bytes_written;
399 buf += bytes_written;
401 return ret ? count : -1;
404 static int rpcrt4_conn_np_close(RpcConnection *Connection)
406 RpcConnection_np *npc = (RpcConnection_np *) Connection;
407 if (npc->pipe) {
408 FlushFileBuffers(npc->pipe);
409 CloseHandle(npc->pipe);
410 npc->pipe = 0;
412 if (npc->ovl.hEvent) {
413 CloseHandle(npc->ovl.hEvent);
414 npc->ovl.hEvent = 0;
416 return 0;
419 static void rpcrt4_conn_np_cancel_call(RpcConnection *Connection)
421 /* FIXME: implement when named pipe writes use overlapped I/O */
424 static size_t rpcrt4_ncacn_np_get_top_of_tower(unsigned char *tower_data,
425 const char *networkaddr,
426 const char *endpoint)
428 twr_empty_floor_t *smb_floor;
429 twr_empty_floor_t *nb_floor;
430 size_t size;
431 size_t networkaddr_size;
432 size_t endpoint_size;
434 TRACE("(%p, %s, %s)\n", tower_data, networkaddr, endpoint);
436 networkaddr_size = strlen(networkaddr) + 1;
437 endpoint_size = strlen(endpoint) + 1;
438 size = sizeof(*smb_floor) + endpoint_size + sizeof(*nb_floor) + networkaddr_size;
440 if (!tower_data)
441 return size;
443 smb_floor = (twr_empty_floor_t *)tower_data;
445 tower_data += sizeof(*smb_floor);
447 smb_floor->count_lhs = sizeof(smb_floor->protid);
448 smb_floor->protid = EPM_PROTOCOL_SMB;
449 smb_floor->count_rhs = endpoint_size;
451 memcpy(tower_data, endpoint, endpoint_size);
452 tower_data += endpoint_size;
454 nb_floor = (twr_empty_floor_t *)tower_data;
456 tower_data += sizeof(*nb_floor);
458 nb_floor->count_lhs = sizeof(nb_floor->protid);
459 nb_floor->protid = EPM_PROTOCOL_NETBIOS;
460 nb_floor->count_rhs = networkaddr_size;
462 memcpy(tower_data, networkaddr, networkaddr_size);
463 tower_data += networkaddr_size;
465 return size;
468 static RPC_STATUS rpcrt4_ncacn_np_parse_top_of_tower(const unsigned char *tower_data,
469 size_t tower_size,
470 char **networkaddr,
471 char **endpoint)
473 const twr_empty_floor_t *smb_floor = (const twr_empty_floor_t *)tower_data;
474 const twr_empty_floor_t *nb_floor;
476 TRACE("(%p, %d, %p, %p)\n", tower_data, (int)tower_size, networkaddr, endpoint);
478 if (tower_size < sizeof(*smb_floor))
479 return EPT_S_NOT_REGISTERED;
481 tower_data += sizeof(*smb_floor);
482 tower_size -= sizeof(*smb_floor);
484 if ((smb_floor->count_lhs != sizeof(smb_floor->protid)) ||
485 (smb_floor->protid != EPM_PROTOCOL_SMB) ||
486 (smb_floor->count_rhs > tower_size))
487 return EPT_S_NOT_REGISTERED;
489 if (endpoint)
491 *endpoint = I_RpcAllocate(smb_floor->count_rhs);
492 if (!*endpoint)
493 return RPC_S_OUT_OF_RESOURCES;
494 memcpy(*endpoint, tower_data, smb_floor->count_rhs);
496 tower_data += smb_floor->count_rhs;
497 tower_size -= smb_floor->count_rhs;
499 if (tower_size < sizeof(*nb_floor))
500 return EPT_S_NOT_REGISTERED;
502 nb_floor = (const twr_empty_floor_t *)tower_data;
504 tower_data += sizeof(*nb_floor);
505 tower_size -= sizeof(*nb_floor);
507 if ((nb_floor->count_lhs != sizeof(nb_floor->protid)) ||
508 (nb_floor->protid != EPM_PROTOCOL_NETBIOS) ||
509 (nb_floor->count_rhs > tower_size))
510 return EPT_S_NOT_REGISTERED;
512 if (networkaddr)
514 *networkaddr = I_RpcAllocate(nb_floor->count_rhs);
515 if (!*networkaddr)
517 if (endpoint)
519 I_RpcFree(*endpoint);
520 *endpoint = NULL;
522 return RPC_S_OUT_OF_RESOURCES;
524 memcpy(*networkaddr, tower_data, nb_floor->count_rhs);
527 return RPC_S_OK;
530 typedef struct _RpcServerProtseq_np
532 RpcServerProtseq common;
533 HANDLE mgr_event;
534 } RpcServerProtseq_np;
536 static RpcServerProtseq *rpcrt4_protseq_np_alloc(void)
538 RpcServerProtseq_np *ps = HeapAlloc(GetProcessHeap(), 0, sizeof(*ps));
539 if (ps)
540 ps->mgr_event = CreateEventW(NULL, FALSE, FALSE, NULL);
541 return &ps->common;
544 static void rpcrt4_protseq_np_signal_state_changed(RpcServerProtseq *protseq)
546 RpcServerProtseq_np *npps = CONTAINING_RECORD(protseq, RpcServerProtseq_np, common);
547 SetEvent(npps->mgr_event);
550 static void *rpcrt4_protseq_np_get_wait_array(RpcServerProtseq *protseq, void *prev_array, unsigned int *count)
552 HANDLE *objs = prev_array;
553 RpcConnection_np *conn;
554 RpcServerProtseq_np *npps = CONTAINING_RECORD(protseq, RpcServerProtseq_np, common);
556 EnterCriticalSection(&protseq->cs);
558 /* open and count connections */
559 *count = 1;
560 conn = CONTAINING_RECORD(protseq->conn, RpcConnection_np, common);
561 while (conn) {
562 rpcrt4_conn_listen_pipe(conn);
563 if (conn->ovl.hEvent)
564 (*count)++;
565 conn = CONTAINING_RECORD(conn->common.Next, RpcConnection_np, common);
568 /* make array of connections */
569 if (objs)
570 objs = HeapReAlloc(GetProcessHeap(), 0, objs, *count*sizeof(HANDLE));
571 else
572 objs = HeapAlloc(GetProcessHeap(), 0, *count*sizeof(HANDLE));
573 if (!objs)
575 ERR("couldn't allocate objs\n");
576 LeaveCriticalSection(&protseq->cs);
577 return NULL;
580 objs[0] = npps->mgr_event;
581 *count = 1;
582 conn = CONTAINING_RECORD(protseq->conn, RpcConnection_np, common);
583 while (conn) {
584 if ((objs[*count] = conn->ovl.hEvent))
585 (*count)++;
586 conn = CONTAINING_RECORD(conn->common.Next, RpcConnection_np, common);
588 LeaveCriticalSection(&protseq->cs);
589 return objs;
592 static void rpcrt4_protseq_np_free_wait_array(RpcServerProtseq *protseq, void *array)
594 HeapFree(GetProcessHeap(), 0, array);
597 static int rpcrt4_protseq_np_wait_for_new_connection(RpcServerProtseq *protseq, unsigned int count, void *wait_array)
599 HANDLE b_handle;
600 HANDLE *objs = wait_array;
601 DWORD res;
602 RpcConnection *cconn;
603 RpcConnection_np *conn;
605 if (!objs)
606 return -1;
608 res = WaitForMultipleObjects(count, objs, FALSE, INFINITE);
609 if (res == WAIT_OBJECT_0)
610 return 0;
611 else if (res == WAIT_FAILED)
613 ERR("wait failed with error %d\n", GetLastError());
614 return -1;
616 else
618 b_handle = objs[res - WAIT_OBJECT_0];
619 /* find which connection got a RPC */
620 EnterCriticalSection(&protseq->cs);
621 conn = CONTAINING_RECORD(protseq->conn, RpcConnection_np, common);
622 while (conn) {
623 if (b_handle == conn->ovl.hEvent) break;
624 conn = CONTAINING_RECORD(conn->common.Next, RpcConnection_np, common);
626 cconn = NULL;
627 if (conn)
628 RPCRT4_SpawnConnection(&cconn, &conn->common);
629 else
630 ERR("failed to locate connection for handle %p\n", b_handle);
631 LeaveCriticalSection(&protseq->cs);
632 if (cconn)
634 RPCRT4_new_client(cconn);
635 return 1;
637 else return -1;
641 static size_t rpcrt4_ncalrpc_get_top_of_tower(unsigned char *tower_data,
642 const char *networkaddr,
643 const char *endpoint)
645 twr_empty_floor_t *pipe_floor;
646 size_t size;
647 size_t endpoint_size;
649 TRACE("(%p, %s, %s)\n", tower_data, networkaddr, endpoint);
651 endpoint_size = strlen(networkaddr) + 1;
652 size = sizeof(*pipe_floor) + endpoint_size;
654 if (!tower_data)
655 return size;
657 pipe_floor = (twr_empty_floor_t *)tower_data;
659 tower_data += sizeof(*pipe_floor);
661 pipe_floor->count_lhs = sizeof(pipe_floor->protid);
662 pipe_floor->protid = EPM_PROTOCOL_SMB;
663 pipe_floor->count_rhs = endpoint_size;
665 memcpy(tower_data, endpoint, endpoint_size);
666 tower_data += endpoint_size;
668 return size;
671 static RPC_STATUS rpcrt4_ncalrpc_parse_top_of_tower(const unsigned char *tower_data,
672 size_t tower_size,
673 char **networkaddr,
674 char **endpoint)
676 const twr_empty_floor_t *pipe_floor = (const twr_empty_floor_t *)tower_data;
678 TRACE("(%p, %d, %p, %p)\n", tower_data, (int)tower_size, networkaddr, endpoint);
680 *networkaddr = NULL;
681 *endpoint = NULL;
683 if (tower_size < sizeof(*pipe_floor))
684 return EPT_S_NOT_REGISTERED;
686 tower_data += sizeof(*pipe_floor);
687 tower_size -= sizeof(*pipe_floor);
689 if ((pipe_floor->count_lhs != sizeof(pipe_floor->protid)) ||
690 (pipe_floor->protid != EPM_PROTOCOL_SMB) ||
691 (pipe_floor->count_rhs > tower_size))
692 return EPT_S_NOT_REGISTERED;
694 if (endpoint)
696 *endpoint = I_RpcAllocate(pipe_floor->count_rhs);
697 if (!*endpoint)
698 return RPC_S_OUT_OF_RESOURCES;
699 memcpy(*endpoint, tower_data, pipe_floor->count_rhs);
702 return RPC_S_OK;
705 /**** ncacn_ip_tcp support ****/
707 typedef struct _RpcConnection_tcp
709 RpcConnection common;
710 int sock;
711 int cancel_fds[2];
712 } RpcConnection_tcp;
714 static RpcConnection *rpcrt4_conn_tcp_alloc(void)
716 RpcConnection_tcp *tcpc;
717 tcpc = HeapAlloc(GetProcessHeap(), 0, sizeof(RpcConnection_tcp));
718 if (tcpc == NULL)
719 return NULL;
720 tcpc->sock = -1;
721 if (socketpair(PF_UNIX, SOCK_STREAM, 0, tcpc->cancel_fds) < 0)
723 ERR("socketpair() failed: %s\n", strerror(errno));
724 HeapFree(GetProcessHeap(), 0, tcpc);
725 return NULL;
727 return &tcpc->common;
730 static RPC_STATUS rpcrt4_ncacn_ip_tcp_open(RpcConnection* Connection)
732 RpcConnection_tcp *tcpc = (RpcConnection_tcp *) Connection;
733 int sock;
734 int ret;
735 struct addrinfo *ai;
736 struct addrinfo *ai_cur;
737 struct addrinfo hints;
739 TRACE("(%s, %s)\n", Connection->NetworkAddr, Connection->Endpoint);
741 if (tcpc->sock != -1)
742 return RPC_S_OK;
744 hints.ai_flags = 0;
745 hints.ai_family = PF_UNSPEC;
746 hints.ai_socktype = SOCK_STREAM;
747 hints.ai_protocol = IPPROTO_TCP;
748 hints.ai_addrlen = 0;
749 hints.ai_addr = NULL;
750 hints.ai_canonname = NULL;
751 hints.ai_next = NULL;
753 ret = getaddrinfo(Connection->NetworkAddr, Connection->Endpoint, &hints, &ai);
754 if (ret)
756 ERR("getaddrinfo for %s:%s failed: %s\n", Connection->NetworkAddr,
757 Connection->Endpoint, gai_strerror(ret));
758 return RPC_S_SERVER_UNAVAILABLE;
761 for (ai_cur = ai; ai_cur; ai_cur = ai_cur->ai_next)
763 int val;
765 if (TRACE_ON(rpc))
767 char host[256];
768 char service[256];
769 getnameinfo(ai_cur->ai_addr, ai_cur->ai_addrlen,
770 host, sizeof(host), service, sizeof(service),
771 NI_NUMERICHOST | NI_NUMERICSERV);
772 TRACE("trying %s:%s\n", host, service);
775 sock = socket(ai_cur->ai_family, ai_cur->ai_socktype, ai_cur->ai_protocol);
776 if (sock < 0)
778 WARN("socket() failed: %s\n", strerror(errno));
779 continue;
782 if (0>connect(sock, ai_cur->ai_addr, ai_cur->ai_addrlen))
784 WARN("connect() failed: %s\n", strerror(errno));
785 close(sock);
786 continue;
789 /* RPC depends on having minimal latency so disable the Nagle algorithm */
790 val = 1;
791 setsockopt(sock, SOL_TCP, TCP_NODELAY, &val, sizeof(val));
792 fcntl(sock, F_SETFL, O_NONBLOCK); /* make socket nonblocking */
794 tcpc->sock = sock;
796 freeaddrinfo(ai);
797 TRACE("connected\n");
798 return RPC_S_OK;
801 freeaddrinfo(ai);
802 ERR("couldn't connect to %s:%s\n", Connection->NetworkAddr, Connection->Endpoint);
803 return RPC_S_SERVER_UNAVAILABLE;
806 static RPC_STATUS rpcrt4_protseq_ncacn_ip_tcp_open_endpoint(RpcServerProtseq *protseq, LPSTR endpoint)
808 RPC_STATUS status = RPC_S_CANT_CREATE_ENDPOINT;
809 int sock;
810 int ret;
811 struct addrinfo *ai;
812 struct addrinfo *ai_cur;
813 struct addrinfo hints;
814 RpcConnection *first_connection = NULL;
816 TRACE("(%p, %s)\n", protseq, endpoint);
818 hints.ai_flags = AI_PASSIVE /* for non-localhost addresses */;
819 hints.ai_family = PF_UNSPEC;
820 hints.ai_socktype = SOCK_STREAM;
821 hints.ai_protocol = IPPROTO_TCP;
822 hints.ai_addrlen = 0;
823 hints.ai_addr = NULL;
824 hints.ai_canonname = NULL;
825 hints.ai_next = NULL;
827 ret = getaddrinfo(NULL, endpoint, &hints, &ai);
828 if (ret)
830 ERR("getaddrinfo for port %s failed: %s\n", endpoint,
831 gai_strerror(ret));
832 if ((ret == EAI_SERVICE) || (ret == EAI_NONAME))
833 return RPC_S_INVALID_ENDPOINT_FORMAT;
834 return RPC_S_CANT_CREATE_ENDPOINT;
837 for (ai_cur = ai; ai_cur; ai_cur = ai_cur->ai_next)
839 RpcConnection_tcp *tcpc;
840 RPC_STATUS create_status;
842 if (TRACE_ON(rpc))
844 char host[256];
845 char service[256];
846 getnameinfo(ai_cur->ai_addr, ai_cur->ai_addrlen,
847 host, sizeof(host), service, sizeof(service),
848 NI_NUMERICHOST | NI_NUMERICSERV);
849 TRACE("trying %s:%s\n", host, service);
852 sock = socket(ai_cur->ai_family, ai_cur->ai_socktype, ai_cur->ai_protocol);
853 if (sock < 0)
855 WARN("socket() failed: %s\n", strerror(errno));
856 status = RPC_S_CANT_CREATE_ENDPOINT;
857 continue;
860 ret = bind(sock, ai_cur->ai_addr, ai_cur->ai_addrlen);
861 if (ret < 0)
863 WARN("bind failed: %s\n", strerror(errno));
864 close(sock);
865 if (errno == EADDRINUSE)
866 status = RPC_S_DUPLICATE_ENDPOINT;
867 else
868 status = RPC_S_CANT_CREATE_ENDPOINT;
869 continue;
871 create_status = RPCRT4_CreateConnection((RpcConnection **)&tcpc, TRUE,
872 protseq->Protseq, NULL,
873 endpoint, NULL, NULL, NULL);
874 if (create_status != RPC_S_OK)
876 close(sock);
877 status = create_status;
878 continue;
881 tcpc->sock = sock;
882 ret = listen(sock, protseq->MaxCalls);
883 if (ret < 0)
885 WARN("listen failed: %s\n", strerror(errno));
886 RPCRT4_DestroyConnection(&tcpc->common);
887 status = RPC_S_OUT_OF_RESOURCES;
888 continue;
890 /* need a non-blocking socket, otherwise accept() has a potential
891 * race-condition (poll() says it is readable, connection drops,
892 * and accept() blocks until the next connection comes...)
894 ret = fcntl(sock, F_SETFL, O_NONBLOCK);
895 if (ret < 0)
897 WARN("couldn't make socket non-blocking, error %d\n", ret);
898 RPCRT4_DestroyConnection(&tcpc->common);
899 status = RPC_S_OUT_OF_RESOURCES;
900 continue;
903 tcpc->common.Next = first_connection;
904 first_connection = &tcpc->common;
907 freeaddrinfo(ai);
909 /* if at least one connection was created for an endpoint then
910 * return success */
911 if (first_connection)
913 RpcConnection *conn;
915 /* find last element in list */
916 for (conn = first_connection; conn->Next; conn = conn->Next)
919 EnterCriticalSection(&protseq->cs);
920 conn->Next = protseq->conn;
921 protseq->conn = first_connection;
922 LeaveCriticalSection(&protseq->cs);
924 TRACE("listening on %s\n", endpoint);
925 return RPC_S_OK;
928 ERR("couldn't listen on port %s\n", endpoint);
929 return status;
932 static RPC_STATUS rpcrt4_conn_tcp_handoff(RpcConnection *old_conn, RpcConnection *new_conn)
934 int ret;
935 struct sockaddr_in address;
936 socklen_t addrsize;
937 RpcConnection_tcp *server = (RpcConnection_tcp*) old_conn;
938 RpcConnection_tcp *client = (RpcConnection_tcp*) new_conn;
940 addrsize = sizeof(address);
941 ret = accept(server->sock, (struct sockaddr*) &address, &addrsize);
942 if (ret < 0)
944 ERR("Failed to accept a TCP connection: error %d\n", ret);
945 return RPC_S_OUT_OF_RESOURCES;
947 /* reset to blocking behaviour */
948 fcntl(ret, F_SETFL, 0);
949 client->sock = ret;
950 TRACE("Accepted a new TCP connection\n");
951 return RPC_S_OK;
954 static int rpcrt4_conn_tcp_read(RpcConnection *Connection,
955 void *buffer, unsigned int count)
957 RpcConnection_tcp *tcpc = (RpcConnection_tcp *) Connection;
958 int bytes_read = 0;
961 int r = recv(tcpc->sock, (char *)buffer + bytes_read, count - bytes_read, 0);
962 if (r >= 0)
963 bytes_read += r;
964 else if (errno != EAGAIN)
965 return -1;
966 else
968 struct pollfd pfds[2];
969 pfds[0].fd = tcpc->sock;
970 pfds[0].events = POLLIN;
971 pfds[1].fd = tcpc->cancel_fds[0];
972 pfds[1].fd = POLLIN;
973 if (poll(pfds, 2, -1 /* infinite */) == -1 && errno != EINTR)
975 ERR("poll() failed: %s\n", strerror(errno));
976 return -1;
978 if (pfds[1].revents & POLLIN) /* canceled */
980 char dummy;
981 read(pfds[1].fd, &dummy, sizeof(dummy));
982 return -1;
985 } while (bytes_read != count);
986 TRACE("%d %p %u -> %d\n", tcpc->sock, buffer, count, bytes_read);
987 return bytes_read;
990 static int rpcrt4_conn_tcp_write(RpcConnection *Connection,
991 const void *buffer, unsigned int count)
993 RpcConnection_tcp *tcpc = (RpcConnection_tcp *) Connection;
994 int bytes_written = 0;
997 int r = write(tcpc->sock, (const char *)buffer + bytes_written, count - bytes_written);
998 if (r >= 0)
999 bytes_written += r;
1000 else if (errno != EAGAIN)
1001 return -1;
1002 else
1004 struct pollfd pfd;
1005 pfd.fd = tcpc->sock;
1006 pfd.events = POLLOUT;
1007 if (poll(&pfd, 1, -1 /* infinite */) == -1 && errno != EINTR)
1009 ERR("poll() failed: %s\n", strerror(errno));
1010 return -1;
1013 } while (bytes_written != count);
1014 TRACE("%d %p %u -> %d\n", tcpc->sock, buffer, count, bytes_written);
1015 return bytes_written;
1018 static int rpcrt4_conn_tcp_close(RpcConnection *Connection)
1020 RpcConnection_tcp *tcpc = (RpcConnection_tcp *) Connection;
1022 TRACE("%d\n", tcpc->sock);
1024 if (tcpc->sock != -1)
1025 close(tcpc->sock);
1026 tcpc->sock = -1;
1027 close(tcpc->cancel_fds[0]);
1028 close(tcpc->cancel_fds[1]);
1029 return 0;
1032 static void rpcrt4_conn_tcp_cancel_call(RpcConnection *Connection)
1034 RpcConnection_tcp *tcpc = (RpcConnection_tcp *) Connection;
1035 char dummy = 1;
1037 TRACE("%p\n", Connection);
1039 write(tcpc->cancel_fds[1], &dummy, 1);
1042 static size_t rpcrt4_ncacn_ip_tcp_get_top_of_tower(unsigned char *tower_data,
1043 const char *networkaddr,
1044 const char *endpoint)
1046 twr_tcp_floor_t *tcp_floor;
1047 twr_ipv4_floor_t *ipv4_floor;
1048 struct addrinfo *ai;
1049 struct addrinfo hints;
1050 int ret;
1051 size_t size = sizeof(*tcp_floor) + sizeof(*ipv4_floor);
1053 TRACE("(%p, %s, %s)\n", tower_data, networkaddr, endpoint);
1055 if (!tower_data)
1056 return size;
1058 tcp_floor = (twr_tcp_floor_t *)tower_data;
1059 tower_data += sizeof(*tcp_floor);
1061 ipv4_floor = (twr_ipv4_floor_t *)tower_data;
1063 tcp_floor->count_lhs = sizeof(tcp_floor->protid);
1064 tcp_floor->protid = EPM_PROTOCOL_TCP;
1065 tcp_floor->count_rhs = sizeof(tcp_floor->port);
1067 ipv4_floor->count_lhs = sizeof(ipv4_floor->protid);
1068 ipv4_floor->protid = EPM_PROTOCOL_IP;
1069 ipv4_floor->count_rhs = sizeof(ipv4_floor->ipv4addr);
1071 hints.ai_flags = AI_NUMERICHOST;
1072 /* FIXME: only support IPv4 at the moment. how is IPv6 represented by the EPM? */
1073 hints.ai_family = PF_INET;
1074 hints.ai_socktype = SOCK_STREAM;
1075 hints.ai_protocol = IPPROTO_TCP;
1076 hints.ai_addrlen = 0;
1077 hints.ai_addr = NULL;
1078 hints.ai_canonname = NULL;
1079 hints.ai_next = NULL;
1081 ret = getaddrinfo(networkaddr, endpoint, &hints, &ai);
1082 if (ret)
1084 ret = getaddrinfo("0.0.0.0", endpoint, &hints, &ai);
1085 if (ret)
1087 ERR("getaddrinfo failed: %s\n", gai_strerror(ret));
1088 return 0;
1092 if (ai->ai_family == PF_INET)
1094 const struct sockaddr_in *sin = (const struct sockaddr_in *)ai->ai_addr;
1095 tcp_floor->port = sin->sin_port;
1096 ipv4_floor->ipv4addr = sin->sin_addr.s_addr;
1098 else
1100 ERR("unexpected protocol family %d\n", ai->ai_family);
1101 return 0;
1104 freeaddrinfo(ai);
1106 return size;
1109 static RPC_STATUS rpcrt4_ncacn_ip_tcp_parse_top_of_tower(const unsigned char *tower_data,
1110 size_t tower_size,
1111 char **networkaddr,
1112 char **endpoint)
1114 const twr_tcp_floor_t *tcp_floor = (const twr_tcp_floor_t *)tower_data;
1115 const twr_ipv4_floor_t *ipv4_floor;
1116 struct in_addr in_addr;
1118 TRACE("(%p, %d, %p, %p)\n", tower_data, (int)tower_size, networkaddr, endpoint);
1120 if (tower_size < sizeof(*tcp_floor))
1121 return EPT_S_NOT_REGISTERED;
1123 tower_data += sizeof(*tcp_floor);
1124 tower_size -= sizeof(*tcp_floor);
1126 if (tower_size < sizeof(*ipv4_floor))
1127 return EPT_S_NOT_REGISTERED;
1129 ipv4_floor = (const twr_ipv4_floor_t *)tower_data;
1131 if ((tcp_floor->count_lhs != sizeof(tcp_floor->protid)) ||
1132 (tcp_floor->protid != EPM_PROTOCOL_TCP) ||
1133 (tcp_floor->count_rhs != sizeof(tcp_floor->port)) ||
1134 (ipv4_floor->count_lhs != sizeof(ipv4_floor->protid)) ||
1135 (ipv4_floor->protid != EPM_PROTOCOL_IP) ||
1136 (ipv4_floor->count_rhs != sizeof(ipv4_floor->ipv4addr)))
1137 return EPT_S_NOT_REGISTERED;
1139 if (endpoint)
1141 *endpoint = I_RpcAllocate(6 /* sizeof("65535") + 1 */);
1142 if (!*endpoint)
1143 return RPC_S_OUT_OF_RESOURCES;
1144 sprintf(*endpoint, "%u", ntohs(tcp_floor->port));
1147 if (networkaddr)
1149 *networkaddr = I_RpcAllocate(INET_ADDRSTRLEN);
1150 if (!*networkaddr)
1152 if (endpoint)
1154 I_RpcFree(*endpoint);
1155 *endpoint = NULL;
1157 return RPC_S_OUT_OF_RESOURCES;
1159 in_addr.s_addr = ipv4_floor->ipv4addr;
1160 if (!inet_ntop(AF_INET, &in_addr, *networkaddr, INET_ADDRSTRLEN))
1162 ERR("inet_ntop: %s\n", strerror(errno));
1163 I_RpcFree(*networkaddr);
1164 *networkaddr = NULL;
1165 if (endpoint)
1167 I_RpcFree(*endpoint);
1168 *endpoint = NULL;
1170 return EPT_S_NOT_REGISTERED;
1174 return RPC_S_OK;
1177 typedef struct _RpcServerProtseq_sock
1179 RpcServerProtseq common;
1180 int mgr_event_rcv;
1181 int mgr_event_snd;
1182 } RpcServerProtseq_sock;
1184 static RpcServerProtseq *rpcrt4_protseq_sock_alloc(void)
1186 RpcServerProtseq_sock *ps = HeapAlloc(GetProcessHeap(), 0, sizeof(*ps));
1187 if (ps)
1189 int fds[2];
1190 if (!socketpair(PF_UNIX, SOCK_DGRAM, 0, fds))
1192 fcntl(fds[0], F_SETFL, O_NONBLOCK);
1193 fcntl(fds[1], F_SETFL, O_NONBLOCK);
1194 ps->mgr_event_rcv = fds[0];
1195 ps->mgr_event_snd = fds[1];
1197 else
1199 ERR("socketpair failed with error %s\n", strerror(errno));
1200 HeapFree(GetProcessHeap(), 0, ps);
1201 return NULL;
1204 return &ps->common;
1207 static void rpcrt4_protseq_sock_signal_state_changed(RpcServerProtseq *protseq)
1209 RpcServerProtseq_sock *sockps = CONTAINING_RECORD(protseq, RpcServerProtseq_sock, common);
1210 char dummy = 1;
1211 write(sockps->mgr_event_snd, &dummy, sizeof(dummy));
1214 static void *rpcrt4_protseq_sock_get_wait_array(RpcServerProtseq *protseq, void *prev_array, unsigned int *count)
1216 struct pollfd *poll_info = prev_array;
1217 RpcConnection_tcp *conn;
1218 RpcServerProtseq_sock *sockps = CONTAINING_RECORD(protseq, RpcServerProtseq_sock, common);
1220 EnterCriticalSection(&protseq->cs);
1222 /* open and count connections */
1223 *count = 1;
1224 conn = (RpcConnection_tcp *)protseq->conn;
1225 while (conn) {
1226 if (conn->sock != -1)
1227 (*count)++;
1228 conn = (RpcConnection_tcp *)conn->common.Next;
1231 /* make array of connections */
1232 if (poll_info)
1233 poll_info = HeapReAlloc(GetProcessHeap(), 0, poll_info, *count*sizeof(*poll_info));
1234 else
1235 poll_info = HeapAlloc(GetProcessHeap(), 0, *count*sizeof(*poll_info));
1236 if (!poll_info)
1238 ERR("couldn't allocate poll_info\n");
1239 LeaveCriticalSection(&protseq->cs);
1240 return NULL;
1243 poll_info[0].fd = sockps->mgr_event_rcv;
1244 poll_info[0].events = POLLIN;
1245 *count = 1;
1246 conn = CONTAINING_RECORD(protseq->conn, RpcConnection_tcp, common);
1247 while (conn) {
1248 if (conn->sock != -1)
1250 poll_info[*count].fd = conn->sock;
1251 poll_info[*count].events = POLLIN;
1252 (*count)++;
1254 conn = CONTAINING_RECORD(conn->common.Next, RpcConnection_tcp, common);
1256 LeaveCriticalSection(&protseq->cs);
1257 return poll_info;
1260 static void rpcrt4_protseq_sock_free_wait_array(RpcServerProtseq *protseq, void *array)
1262 HeapFree(GetProcessHeap(), 0, array);
1265 static int rpcrt4_protseq_sock_wait_for_new_connection(RpcServerProtseq *protseq, unsigned int count, void *wait_array)
1267 struct pollfd *poll_info = wait_array;
1268 int ret, i;
1269 RpcConnection *cconn;
1270 RpcConnection_tcp *conn;
1272 if (!poll_info)
1273 return -1;
1275 ret = poll(poll_info, count, -1);
1276 if (ret < 0)
1278 ERR("poll failed with error %d\n", ret);
1279 return -1;
1282 for (i = 0; i < count; i++)
1283 if (poll_info[i].revents & POLLIN)
1285 /* RPC server event */
1286 if (i == 0)
1288 char dummy;
1289 read(poll_info[0].fd, &dummy, sizeof(dummy));
1290 return 0;
1293 /* find which connection got a RPC */
1294 EnterCriticalSection(&protseq->cs);
1295 conn = CONTAINING_RECORD(protseq->conn, RpcConnection_tcp, common);
1296 while (conn) {
1297 if (poll_info[i].fd == conn->sock) break;
1298 conn = CONTAINING_RECORD(conn->common.Next, RpcConnection_tcp, common);
1300 cconn = NULL;
1301 if (conn)
1302 RPCRT4_SpawnConnection(&cconn, &conn->common);
1303 else
1304 ERR("failed to locate connection for fd %d\n", poll_info[i].fd);
1305 LeaveCriticalSection(&protseq->cs);
1306 if (cconn)
1307 RPCRT4_new_client(cconn);
1308 else
1309 return -1;
1312 return 1;
1315 static const struct connection_ops conn_protseq_list[] = {
1316 { "ncacn_np",
1317 { EPM_PROTOCOL_NCACN, EPM_PROTOCOL_SMB },
1318 rpcrt4_conn_np_alloc,
1319 rpcrt4_ncacn_np_open,
1320 rpcrt4_ncacn_np_handoff,
1321 rpcrt4_conn_np_read,
1322 rpcrt4_conn_np_write,
1323 rpcrt4_conn_np_close,
1324 rpcrt4_conn_np_cancel_call,
1325 rpcrt4_ncacn_np_get_top_of_tower,
1326 rpcrt4_ncacn_np_parse_top_of_tower,
1328 { "ncalrpc",
1329 { EPM_PROTOCOL_NCALRPC, EPM_PROTOCOL_PIPE },
1330 rpcrt4_conn_np_alloc,
1331 rpcrt4_ncalrpc_open,
1332 rpcrt4_ncalrpc_handoff,
1333 rpcrt4_conn_np_read,
1334 rpcrt4_conn_np_write,
1335 rpcrt4_conn_np_close,
1336 rpcrt4_conn_np_cancel_call,
1337 rpcrt4_ncalrpc_get_top_of_tower,
1338 rpcrt4_ncalrpc_parse_top_of_tower,
1340 { "ncacn_ip_tcp",
1341 { EPM_PROTOCOL_NCACN, EPM_PROTOCOL_TCP },
1342 rpcrt4_conn_tcp_alloc,
1343 rpcrt4_ncacn_ip_tcp_open,
1344 rpcrt4_conn_tcp_handoff,
1345 rpcrt4_conn_tcp_read,
1346 rpcrt4_conn_tcp_write,
1347 rpcrt4_conn_tcp_close,
1348 rpcrt4_conn_tcp_cancel_call,
1349 rpcrt4_ncacn_ip_tcp_get_top_of_tower,
1350 rpcrt4_ncacn_ip_tcp_parse_top_of_tower,
1355 static const struct protseq_ops protseq_list[] =
1358 "ncacn_np",
1359 rpcrt4_protseq_np_alloc,
1360 rpcrt4_protseq_np_signal_state_changed,
1361 rpcrt4_protseq_np_get_wait_array,
1362 rpcrt4_protseq_np_free_wait_array,
1363 rpcrt4_protseq_np_wait_for_new_connection,
1364 rpcrt4_protseq_ncacn_np_open_endpoint,
1367 "ncalrpc",
1368 rpcrt4_protseq_np_alloc,
1369 rpcrt4_protseq_np_signal_state_changed,
1370 rpcrt4_protseq_np_get_wait_array,
1371 rpcrt4_protseq_np_free_wait_array,
1372 rpcrt4_protseq_np_wait_for_new_connection,
1373 rpcrt4_protseq_ncalrpc_open_endpoint,
1376 "ncacn_ip_tcp",
1377 rpcrt4_protseq_sock_alloc,
1378 rpcrt4_protseq_sock_signal_state_changed,
1379 rpcrt4_protseq_sock_get_wait_array,
1380 rpcrt4_protseq_sock_free_wait_array,
1381 rpcrt4_protseq_sock_wait_for_new_connection,
1382 rpcrt4_protseq_ncacn_ip_tcp_open_endpoint,
1386 #define ARRAYSIZE(a) (sizeof((a)) / sizeof((a)[0]))
1388 const struct protseq_ops *rpcrt4_get_protseq_ops(const char *protseq)
1390 int i;
1391 for(i=0; i<ARRAYSIZE(protseq_list); i++)
1392 if (!strcmp(protseq_list[i].name, protseq))
1393 return &protseq_list[i];
1394 return NULL;
1397 static const struct connection_ops *rpcrt4_get_conn_protseq_ops(const char *protseq)
1399 int i;
1400 for(i=0; i<ARRAYSIZE(conn_protseq_list); i++)
1401 if (!strcmp(conn_protseq_list[i].name, protseq))
1402 return &conn_protseq_list[i];
1403 return NULL;
1406 /**** interface to rest of code ****/
1408 RPC_STATUS RPCRT4_OpenClientConnection(RpcConnection* Connection)
1410 TRACE("(Connection == ^%p)\n", Connection);
1412 assert(!Connection->server);
1413 return Connection->ops->open_connection_client(Connection);
1416 RPC_STATUS RPCRT4_CloseConnection(RpcConnection* Connection)
1418 TRACE("(Connection == ^%p)\n", Connection);
1419 if (SecIsValidHandle(&Connection->ctx))
1421 DeleteSecurityContext(&Connection->ctx);
1422 SecInvalidateHandle(&Connection->ctx);
1424 rpcrt4_conn_close(Connection);
1425 return RPC_S_OK;
1428 RPC_STATUS RPCRT4_CreateConnection(RpcConnection** Connection, BOOL server,
1429 LPCSTR Protseq, LPCSTR NetworkAddr, LPCSTR Endpoint,
1430 LPCWSTR NetworkOptions, RpcAuthInfo* AuthInfo, RpcQualityOfService *QOS)
1432 const struct connection_ops *ops;
1433 RpcConnection* NewConnection;
1435 ops = rpcrt4_get_conn_protseq_ops(Protseq);
1436 if (!ops)
1438 FIXME("not supported for protseq %s\n", Protseq);
1439 return RPC_S_PROTSEQ_NOT_SUPPORTED;
1442 NewConnection = ops->alloc();
1443 NewConnection->Next = NULL;
1444 NewConnection->server = server;
1445 NewConnection->ops = ops;
1446 NewConnection->NetworkAddr = RPCRT4_strdupA(NetworkAddr);
1447 NewConnection->Endpoint = RPCRT4_strdupA(Endpoint);
1448 NewConnection->NetworkOptions = RPCRT4_strdupW(NetworkOptions);
1449 NewConnection->MaxTransmissionSize = RPC_MAX_PACKET_SIZE;
1450 memset(&NewConnection->ActiveInterface, 0, sizeof(NewConnection->ActiveInterface));
1451 NewConnection->NextCallId = 1;
1453 SecInvalidateHandle(&NewConnection->ctx);
1454 memset(&NewConnection->exp, 0, sizeof(NewConnection->exp));
1455 NewConnection->attr = 0;
1456 if (AuthInfo) RpcAuthInfo_AddRef(AuthInfo);
1457 NewConnection->AuthInfo = AuthInfo;
1458 NewConnection->encryption_auth_len = 0;
1459 NewConnection->signature_auth_len = 0;
1460 if (QOS) RpcQualityOfService_AddRef(QOS);
1461 NewConnection->QOS = QOS;
1463 list_init(&NewConnection->conn_pool_entry);
1465 TRACE("connection: %p\n", NewConnection);
1466 *Connection = NewConnection;
1468 return RPC_S_OK;
1471 RPC_STATUS RPCRT4_GetAssociation(LPCSTR Protseq, LPCSTR NetworkAddr,
1472 LPCSTR Endpoint, LPCWSTR NetworkOptions,
1473 RpcAssoc **assoc_out)
1475 RpcAssoc *assoc;
1477 EnterCriticalSection(&assoc_list_cs);
1478 LIST_FOR_EACH_ENTRY(assoc, &assoc_list, RpcAssoc, entry)
1480 if (!strcmp(Protseq, assoc->Protseq) &&
1481 !strcmp(NetworkAddr, assoc->NetworkAddr) &&
1482 !strcmp(Endpoint, assoc->Endpoint) &&
1483 ((!assoc->NetworkOptions && !NetworkOptions) || !strcmpW(NetworkOptions, assoc->NetworkOptions)))
1485 assoc->refs++;
1486 *assoc_out = assoc;
1487 LeaveCriticalSection(&assoc_list_cs);
1488 TRACE("using existing assoc %p\n", assoc);
1489 return RPC_S_OK;
1493 assoc = HeapAlloc(GetProcessHeap(), 0, sizeof(*assoc));
1494 if (!assoc)
1496 LeaveCriticalSection(&assoc_list_cs);
1497 return RPC_S_OUT_OF_RESOURCES;
1499 assoc->refs = 1;
1500 list_init(&assoc->connection_pool);
1501 InitializeCriticalSection(&assoc->cs);
1502 assoc->Protseq = RPCRT4_strdupA(Protseq);
1503 assoc->NetworkAddr = RPCRT4_strdupA(NetworkAddr);
1504 assoc->Endpoint = RPCRT4_strdupA(Endpoint);
1505 assoc->NetworkOptions = NetworkOptions ? RPCRT4_strdupW(NetworkOptions) : NULL;
1506 assoc->assoc_group_id = 0;
1507 list_add_head(&assoc_list, &assoc->entry);
1508 *assoc_out = assoc;
1510 LeaveCriticalSection(&assoc_list_cs);
1512 TRACE("new assoc %p\n", assoc);
1514 return RPC_S_OK;
1517 ULONG RpcAssoc_Release(RpcAssoc *assoc)
1519 ULONG refs;
1521 EnterCriticalSection(&assoc_list_cs);
1522 refs = --assoc->refs;
1523 if (!refs)
1524 list_remove(&assoc->entry);
1525 LeaveCriticalSection(&assoc_list_cs);
1527 if (!refs)
1529 RpcConnection *Connection, *cursor2;
1531 TRACE("destroying assoc %p\n", assoc);
1533 LIST_FOR_EACH_ENTRY_SAFE(Connection, cursor2, &assoc->connection_pool, RpcConnection, conn_pool_entry)
1535 list_remove(&Connection->conn_pool_entry);
1536 RPCRT4_DestroyConnection(Connection);
1539 HeapFree(GetProcessHeap(), 0, assoc->NetworkOptions);
1540 HeapFree(GetProcessHeap(), 0, assoc->Endpoint);
1541 HeapFree(GetProcessHeap(), 0, assoc->NetworkAddr);
1542 HeapFree(GetProcessHeap(), 0, assoc->Protseq);
1544 HeapFree(GetProcessHeap(), 0, assoc);
1547 return refs;
1550 #define ROUND_UP(value, alignment) (((value) + ((alignment) - 1)) & ~((alignment)-1))
1552 static RPC_STATUS RpcAssoc_BindConnection(const RpcAssoc *assoc, RpcConnection *conn,
1553 const RPC_SYNTAX_IDENTIFIER *InterfaceId,
1554 const RPC_SYNTAX_IDENTIFIER *TransferSyntax)
1556 RpcPktHdr *hdr;
1557 RpcPktHdr *response_hdr;
1558 RPC_MESSAGE msg;
1559 RPC_STATUS status;
1561 TRACE("sending bind request to server\n");
1563 hdr = RPCRT4_BuildBindHeader(NDR_LOCAL_DATA_REPRESENTATION,
1564 RPC_MAX_PACKET_SIZE, RPC_MAX_PACKET_SIZE,
1565 assoc->assoc_group_id,
1566 InterfaceId, TransferSyntax);
1568 status = RPCRT4_Send(conn, hdr, NULL, 0);
1569 RPCRT4_FreeHeader(hdr);
1570 if (status != RPC_S_OK)
1571 return status;
1573 status = RPCRT4_Receive(conn, &response_hdr, &msg);
1574 if (status != RPC_S_OK)
1576 ERR("receive failed\n");
1577 return status;
1580 switch (response_hdr->common.ptype)
1582 case PKT_BIND_ACK:
1584 RpcAddressString *server_address = msg.Buffer;
1585 if ((msg.BufferLength >= FIELD_OFFSET(RpcAddressString, string[0])) ||
1586 (msg.BufferLength >= ROUND_UP(FIELD_OFFSET(RpcAddressString, string[server_address->length]), 4)))
1588 unsigned short remaining = msg.BufferLength -
1589 ROUND_UP(FIELD_OFFSET(RpcAddressString, string[server_address->length]), 4);
1590 RpcResults *results = (RpcResults*)((ULONG_PTR)server_address +
1591 ROUND_UP(FIELD_OFFSET(RpcAddressString, string[server_address->length]), 4));
1592 if ((results->num_results == 1) && (remaining >= sizeof(*results)))
1594 switch (results->results[0].result)
1596 case RESULT_ACCEPT:
1597 conn->assoc_group_id = response_hdr->bind_ack.assoc_gid;
1598 conn->MaxTransmissionSize = response_hdr->bind_ack.max_tsize;
1599 conn->ActiveInterface = *InterfaceId;
1600 break;
1601 case RESULT_PROVIDER_REJECTION:
1602 switch (results->results[0].reason)
1604 case REASON_ABSTRACT_SYNTAX_NOT_SUPPORTED:
1605 ERR("syntax %s, %d.%d not supported\n",
1606 debugstr_guid(&InterfaceId->SyntaxGUID),
1607 InterfaceId->SyntaxVersion.MajorVersion,
1608 InterfaceId->SyntaxVersion.MinorVersion);
1609 status = RPC_S_UNKNOWN_IF;
1610 break;
1611 case REASON_TRANSFER_SYNTAXES_NOT_SUPPORTED:
1612 ERR("transfer syntax not supported\n");
1613 status = RPC_S_SERVER_UNAVAILABLE;
1614 break;
1615 case REASON_NONE:
1616 default:
1617 status = RPC_S_CALL_FAILED_DNE;
1619 break;
1620 case RESULT_USER_REJECTION:
1621 default:
1622 ERR("rejection result %d\n", results->results[0].result);
1623 status = RPC_S_CALL_FAILED_DNE;
1626 else
1628 ERR("incorrect results size\n");
1629 status = RPC_S_CALL_FAILED_DNE;
1632 else
1634 ERR("bind ack packet too small (%d)\n", msg.BufferLength);
1635 status = RPC_S_PROTOCOL_ERROR;
1637 break;
1639 case PKT_BIND_NACK:
1640 switch (response_hdr->bind_nack.reject_reason)
1642 case REJECT_LOCAL_LIMIT_EXCEEDED:
1643 case REJECT_TEMPORARY_CONGESTION:
1644 ERR("server too busy\n");
1645 status = RPC_S_SERVER_TOO_BUSY;
1646 break;
1647 case REJECT_PROTOCOL_VERSION_NOT_SUPPORTED:
1648 ERR("protocol version not supported\n");
1649 status = RPC_S_PROTOCOL_ERROR;
1650 break;
1651 case REJECT_UNKNOWN_AUTHN_SERVICE:
1652 ERR("unknown authentication service\n");
1653 status = RPC_S_UNKNOWN_AUTHN_SERVICE;
1654 break;
1655 case REJECT_INVALID_CHECKSUM:
1656 ERR("invalid checksum\n");
1657 status = ERROR_ACCESS_DENIED;
1658 break;
1659 default:
1660 ERR("rejected bind for reason %d\n", response_hdr->bind_nack.reject_reason);
1661 status = RPC_S_CALL_FAILED_DNE;
1663 break;
1664 default:
1665 ERR("wrong packet type received %d\n", response_hdr->common.ptype);
1666 status = RPC_S_PROTOCOL_ERROR;
1667 break;
1670 RPCRT4_FreeHeader(response_hdr);
1671 return status;
1674 static RpcConnection *RpcAssoc_GetIdleConnection(RpcAssoc *assoc,
1675 const RPC_SYNTAX_IDENTIFIER *InterfaceId,
1676 const RPC_SYNTAX_IDENTIFIER *TransferSyntax, const RpcAuthInfo *AuthInfo,
1677 const RpcQualityOfService *QOS)
1679 RpcConnection *Connection;
1680 EnterCriticalSection(&assoc->cs);
1681 /* try to find a compatible connection from the connection pool */
1682 LIST_FOR_EACH_ENTRY(Connection, &assoc->connection_pool, RpcConnection, conn_pool_entry)
1684 if (!memcmp(&Connection->ActiveInterface, InterfaceId,
1685 sizeof(RPC_SYNTAX_IDENTIFIER)) &&
1686 RpcAuthInfo_IsEqual(Connection->AuthInfo, AuthInfo) &&
1687 RpcQualityOfService_IsEqual(Connection->QOS, QOS))
1689 list_remove(&Connection->conn_pool_entry);
1690 LeaveCriticalSection(&assoc->cs);
1691 TRACE("got connection from pool %p\n", Connection);
1692 return Connection;
1696 LeaveCriticalSection(&assoc->cs);
1697 return NULL;
1700 RPC_STATUS RpcAssoc_GetClientConnection(RpcAssoc *assoc,
1701 const RPC_SYNTAX_IDENTIFIER *InterfaceId,
1702 const RPC_SYNTAX_IDENTIFIER *TransferSyntax, RpcAuthInfo *AuthInfo,
1703 RpcQualityOfService *QOS, RpcConnection **Connection)
1705 RpcConnection *NewConnection;
1706 RPC_STATUS status;
1708 *Connection = RpcAssoc_GetIdleConnection(assoc, InterfaceId, TransferSyntax, AuthInfo, QOS);
1709 if (*Connection)
1710 return RPC_S_OK;
1712 /* create a new connection */
1713 status = RPCRT4_CreateConnection(&NewConnection, FALSE /* is this a server connection? */,
1714 assoc->Protseq, assoc->NetworkAddr,
1715 assoc->Endpoint, assoc->NetworkOptions,
1716 AuthInfo, QOS);
1717 if (status != RPC_S_OK)
1718 return status;
1720 status = RPCRT4_OpenClientConnection(NewConnection);
1721 if (status != RPC_S_OK)
1723 RPCRT4_DestroyConnection(NewConnection);
1724 return status;
1727 status = RpcAssoc_BindConnection(assoc, NewConnection, InterfaceId, TransferSyntax);
1728 if (status != RPC_S_OK)
1730 RPCRT4_DestroyConnection(NewConnection);
1731 return status;
1734 *Connection = NewConnection;
1736 return RPC_S_OK;
1739 void RpcAssoc_ReleaseIdleConnection(RpcAssoc *assoc, RpcConnection *Connection)
1741 assert(!Connection->server);
1742 EnterCriticalSection(&assoc->cs);
1743 if (!assoc->assoc_group_id) assoc->assoc_group_id = Connection->assoc_group_id;
1744 list_add_head(&assoc->connection_pool, &Connection->conn_pool_entry);
1745 LeaveCriticalSection(&assoc->cs);
1749 RPC_STATUS RPCRT4_SpawnConnection(RpcConnection** Connection, RpcConnection* OldConnection)
1751 RPC_STATUS err;
1753 err = RPCRT4_CreateConnection(Connection, OldConnection->server,
1754 rpcrt4_conn_get_name(OldConnection),
1755 OldConnection->NetworkAddr,
1756 OldConnection->Endpoint, NULL,
1757 OldConnection->AuthInfo, OldConnection->QOS);
1758 if (err == RPC_S_OK)
1759 rpcrt4_conn_handoff(OldConnection, *Connection);
1760 return err;
1763 RPC_STATUS RPCRT4_DestroyConnection(RpcConnection* Connection)
1765 TRACE("connection: %p\n", Connection);
1767 RPCRT4_CloseConnection(Connection);
1768 RPCRT4_strfree(Connection->Endpoint);
1769 RPCRT4_strfree(Connection->NetworkAddr);
1770 HeapFree(GetProcessHeap(), 0, Connection->NetworkOptions);
1771 if (Connection->AuthInfo) RpcAuthInfo_Release(Connection->AuthInfo);
1772 if (Connection->QOS) RpcQualityOfService_Release(Connection->QOS);
1773 HeapFree(GetProcessHeap(), 0, Connection);
1774 return RPC_S_OK;
1777 RPC_STATUS RpcTransport_GetTopOfTower(unsigned char *tower_data,
1778 size_t *tower_size,
1779 const char *protseq,
1780 const char *networkaddr,
1781 const char *endpoint)
1783 twr_empty_floor_t *protocol_floor;
1784 const struct connection_ops *protseq_ops = rpcrt4_get_conn_protseq_ops(protseq);
1786 *tower_size = 0;
1788 if (!protseq_ops)
1789 return RPC_S_INVALID_RPC_PROTSEQ;
1791 if (!tower_data)
1793 *tower_size = sizeof(*protocol_floor);
1794 *tower_size += protseq_ops->get_top_of_tower(NULL, networkaddr, endpoint);
1795 return RPC_S_OK;
1798 protocol_floor = (twr_empty_floor_t *)tower_data;
1799 protocol_floor->count_lhs = sizeof(protocol_floor->protid);
1800 protocol_floor->protid = protseq_ops->epm_protocols[0];
1801 protocol_floor->count_rhs = 0;
1803 tower_data += sizeof(*protocol_floor);
1805 *tower_size = protseq_ops->get_top_of_tower(tower_data, networkaddr, endpoint);
1806 if (!*tower_size)
1807 return EPT_S_NOT_REGISTERED;
1809 *tower_size += sizeof(*protocol_floor);
1811 return RPC_S_OK;
1814 RPC_STATUS RpcTransport_ParseTopOfTower(const unsigned char *tower_data,
1815 size_t tower_size,
1816 char **protseq,
1817 char **networkaddr,
1818 char **endpoint)
1820 const twr_empty_floor_t *protocol_floor;
1821 const twr_empty_floor_t *floor4;
1822 const struct connection_ops *protseq_ops = NULL;
1823 RPC_STATUS status;
1824 int i;
1826 if (tower_size < sizeof(*protocol_floor))
1827 return EPT_S_NOT_REGISTERED;
1829 protocol_floor = (const twr_empty_floor_t *)tower_data;
1830 tower_data += sizeof(*protocol_floor);
1831 tower_size -= sizeof(*protocol_floor);
1832 if ((protocol_floor->count_lhs != sizeof(protocol_floor->protid)) ||
1833 (protocol_floor->count_rhs > tower_size))
1834 return EPT_S_NOT_REGISTERED;
1835 tower_data += protocol_floor->count_rhs;
1836 tower_size -= protocol_floor->count_rhs;
1838 floor4 = (const twr_empty_floor_t *)tower_data;
1839 if ((tower_size < sizeof(*floor4)) ||
1840 (floor4->count_lhs != sizeof(floor4->protid)))
1841 return EPT_S_NOT_REGISTERED;
1843 for(i = 0; i < ARRAYSIZE(conn_protseq_list); i++)
1844 if ((protocol_floor->protid == conn_protseq_list[i].epm_protocols[0]) &&
1845 (floor4->protid == conn_protseq_list[i].epm_protocols[1]))
1847 protseq_ops = &conn_protseq_list[i];
1848 break;
1851 if (!protseq_ops)
1852 return EPT_S_NOT_REGISTERED;
1854 status = protseq_ops->parse_top_of_tower(tower_data, tower_size, networkaddr, endpoint);
1856 if ((status == RPC_S_OK) && protseq)
1858 *protseq = I_RpcAllocate(strlen(protseq_ops->name) + 1);
1859 strcpy(*protseq, protseq_ops->name);
1862 return status;
1865 /***********************************************************************
1866 * RpcNetworkIsProtseqValidW (RPCRT4.@)
1868 * Checks if the given protocol sequence is known by the RPC system.
1869 * If it is, returns RPC_S_OK, otherwise RPC_S_PROTSEQ_NOT_SUPPORTED.
1872 RPC_STATUS WINAPI RpcNetworkIsProtseqValidW(RPC_WSTR protseq)
1874 char ps[0x10];
1876 WideCharToMultiByte(CP_ACP, 0, protseq, -1,
1877 ps, sizeof ps, NULL, NULL);
1878 if (rpcrt4_get_conn_protseq_ops(ps))
1879 return RPC_S_OK;
1881 FIXME("Unknown protseq %s\n", debugstr_w(protseq));
1883 return RPC_S_INVALID_RPC_PROTSEQ;
1886 /***********************************************************************
1887 * RpcNetworkIsProtseqValidA (RPCRT4.@)
1889 RPC_STATUS WINAPI RpcNetworkIsProtseqValidA(RPC_CSTR protseq)
1891 UNICODE_STRING protseqW;
1893 if (RtlCreateUnicodeStringFromAsciiz(&protseqW, (char*)protseq))
1895 RPC_STATUS ret = RpcNetworkIsProtseqValidW(protseqW.Buffer);
1896 RtlFreeUnicodeString(&protseqW);
1897 return ret;
1899 return RPC_S_OUT_OF_MEMORY;