rpcrt4: Use MaxCalls from the protseq when determining the backlog length to pass...
[wine] / dlls / rpcrt4 / rpc_transport.c
1 /*
2  * RPC transport layer
3  *
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
9  *
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.
14  *
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.
19  *
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
23  *
24  */
25
26 #include "config.h"
27
28 #include <stdarg.h>
29 #include <stdio.h>
30 #include <string.h>
31 #include <assert.h>
32 #include <errno.h>
33
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_ARPA_INET_H
47 # include <arpa/inet.h>
48 #endif
49 #ifdef HAVE_NETDB_H
50 #include <netdb.h>
51 #endif
52 #ifdef HAVE_SYS_POLL_H
53 #include <sys/poll.h>
54 #endif
55
56 #include "windef.h"
57 #include "winbase.h"
58 #include "winnls.h"
59 #include "winerror.h"
60 #include "winreg.h"
61 #include "winternl.h"
62 #include "wine/unicode.h"
63
64 #include "rpc.h"
65 #include "rpcndr.h"
66
67 #include "wine/debug.h"
68
69 #include "rpc_binding.h"
70 #include "rpc_message.h"
71 #include "rpc_server.h"
72 #include "epm_towers.h"
73
74 WINE_DEFAULT_DEBUG_CHANNEL(rpc);
75
76 static CRITICAL_SECTION connection_pool_cs;
77 static CRITICAL_SECTION_DEBUG connection_pool_cs_debug =
78 {
79     0, 0, &connection_pool_cs,
80     { &connection_pool_cs_debug.ProcessLocksList, &connection_pool_cs_debug.ProcessLocksList },
81       0, 0, { (DWORD_PTR)(__FILE__ ": connection_pool") }
82 };
83 static CRITICAL_SECTION connection_pool_cs = { &connection_pool_cs_debug, -1, 0, 0, 0, 0 };
84
85 static struct list connection_pool = LIST_INIT(connection_pool);
86
87 /**** ncacn_np support ****/
88
89 typedef struct _RpcConnection_np
90 {
91   RpcConnection common;
92   HANDLE pipe;
93   OVERLAPPED ovl;
94   BOOL listening;
95 } RpcConnection_np;
96
97 static RpcConnection *rpcrt4_conn_np_alloc(void)
98 {
99   RpcConnection_np *npc = HeapAlloc(GetProcessHeap(), 0, sizeof(RpcConnection_np));
100   if (npc)
101   {
102     npc->pipe = NULL;
103     memset(&npc->ovl, 0, sizeof(npc->ovl));
104     npc->listening = FALSE;
105   }
106   return &npc->common;
107 }
108
109 static RPC_STATUS rpcrt4_conn_listen_pipe(RpcConnection_np *npc)
110 {
111   if (npc->listening)
112     return RPC_S_OK;
113
114   npc->listening = TRUE;
115   if (ConnectNamedPipe(npc->pipe, &npc->ovl))
116     return RPC_S_OK;
117
118   WARN("Couldn't ConnectNamedPipe (error was %ld)\n", GetLastError());
119   if (GetLastError() == ERROR_PIPE_CONNECTED) {
120     SetEvent(npc->ovl.hEvent);
121     return RPC_S_OK;
122   }
123   if (GetLastError() == ERROR_IO_PENDING) {
124     /* FIXME: looks like we need to GetOverlappedResult here? */
125     return RPC_S_OK;
126   }
127   npc->listening = FALSE;
128   return RPC_S_OUT_OF_RESOURCES;
129 }
130
131 static RPC_STATUS rpcrt4_conn_create_pipe(RpcConnection *Connection, LPCSTR pname)
132 {
133   RpcConnection_np *npc = (RpcConnection_np *) Connection;
134   TRACE("listening on %s\n", pname);
135
136   npc->pipe = CreateNamedPipeA(pname, PIPE_ACCESS_DUPLEX,
137                                PIPE_TYPE_MESSAGE | PIPE_READMODE_MESSAGE,
138                                PIPE_UNLIMITED_INSTANCES,
139                                RPC_MAX_PACKET_SIZE, RPC_MAX_PACKET_SIZE, 5000, NULL);
140   if (npc->pipe == INVALID_HANDLE_VALUE) {
141     WARN("CreateNamedPipe failed with error %ld\n", GetLastError());
142     if (GetLastError() == ERROR_FILE_EXISTS)
143       return RPC_S_DUPLICATE_ENDPOINT;
144     else
145       return RPC_S_CANT_CREATE_ENDPOINT;
146   }
147
148   memset(&npc->ovl, 0, sizeof(npc->ovl));
149   npc->ovl.hEvent = CreateEventW(NULL, TRUE, FALSE, NULL);
150
151   /* Note: we don't call ConnectNamedPipe here because it must be done in the
152    * server thread as the thread must be alertable */
153   return RPC_S_OK;
154 }
155
156 static RPC_STATUS rpcrt4_conn_open_pipe(RpcConnection *Connection, LPCSTR pname, BOOL wait)
157 {
158   RpcConnection_np *npc = (RpcConnection_np *) Connection;
159   HANDLE pipe;
160   DWORD err, dwMode;
161
162   TRACE("connecting to %s\n", pname);
163
164   while (TRUE) {
165     pipe = CreateFileA(pname, GENERIC_READ|GENERIC_WRITE, 0, NULL,
166                        OPEN_EXISTING, 0, 0);
167     if (pipe != INVALID_HANDLE_VALUE) break;
168     err = GetLastError();
169     if (err == ERROR_PIPE_BUSY) {
170       TRACE("connection failed, error=%lx\n", err);
171       return RPC_S_SERVER_TOO_BUSY;
172     }
173     if (!wait)
174       return RPC_S_SERVER_UNAVAILABLE;
175     if (!WaitNamedPipeA(pname, NMPWAIT_WAIT_FOREVER)) {
176       err = GetLastError();
177       WARN("connection failed, error=%lx\n", err);
178       return RPC_S_SERVER_UNAVAILABLE;
179     }
180   }
181
182   /* success */
183   memset(&npc->ovl, 0, sizeof(npc->ovl));
184   /* pipe is connected; change to message-read mode. */
185   dwMode = PIPE_READMODE_MESSAGE;
186   SetNamedPipeHandleState(pipe, &dwMode, NULL, NULL);
187   npc->ovl.hEvent = CreateEventW(NULL, TRUE, FALSE, NULL);
188   npc->pipe = pipe;
189
190   return RPC_S_OK;
191 }
192
193 static RPC_STATUS rpcrt4_ncalrpc_open(RpcConnection* Connection)
194 {
195   RpcConnection_np *npc = (RpcConnection_np *) Connection;
196   static LPCSTR prefix = "\\\\.\\pipe\\lrpc\\";
197   RPC_STATUS r;
198   LPSTR pname;
199
200   /* already connected? */
201   if (npc->pipe)
202     return RPC_S_OK;
203
204   /* protseq=ncalrpc: supposed to use NT LPC ports,
205    * but we'll implement it with named pipes for now */
206   pname = I_RpcAllocate(strlen(prefix) + strlen(Connection->Endpoint) + 1);
207   strcat(strcpy(pname, prefix), Connection->Endpoint);
208   r = rpcrt4_conn_open_pipe(Connection, pname, TRUE);
209   I_RpcFree(pname);
210
211   return r;
212 }
213
214 static RPC_STATUS rpcrt4_protseq_ncalrpc_open_endpoint(RpcServerProtseq* protseq, LPSTR endpoint)
215 {
216   static LPCSTR prefix = "\\\\.\\pipe\\lrpc\\";
217   RPC_STATUS r;
218   LPSTR pname;
219   RpcConnection *Connection;
220
221   r = RPCRT4_CreateConnection(&Connection, TRUE, protseq->Protseq, NULL,
222                               endpoint, NULL, NULL, NULL);
223   if (r != RPC_S_OK)
224       return r;
225
226   /* protseq=ncalrpc: supposed to use NT LPC ports,
227    * but we'll implement it with named pipes for now */
228   pname = I_RpcAllocate(strlen(prefix) + strlen(Connection->Endpoint) + 1);
229   strcat(strcpy(pname, prefix), Connection->Endpoint);
230   r = rpcrt4_conn_create_pipe(Connection, pname);
231   I_RpcFree(pname);
232
233   EnterCriticalSection(&protseq->cs);
234   Connection->Next = protseq->conn;
235   protseq->conn = Connection;
236   LeaveCriticalSection(&protseq->cs);
237
238   return r;
239 }
240
241 static RPC_STATUS rpcrt4_ncacn_np_open(RpcConnection* Connection)
242 {
243   RpcConnection_np *npc = (RpcConnection_np *) Connection;
244   static LPCSTR prefix = "\\\\.";
245   RPC_STATUS r;
246   LPSTR pname;
247
248   /* already connected? */
249   if (npc->pipe)
250     return RPC_S_OK;
251
252   /* protseq=ncacn_np: named pipes */
253   pname = I_RpcAllocate(strlen(prefix) + strlen(Connection->Endpoint) + 1);
254   strcat(strcpy(pname, prefix), Connection->Endpoint);
255   r = rpcrt4_conn_open_pipe(Connection, pname, FALSE);
256   I_RpcFree(pname);
257
258   return r;
259 }
260
261 static RPC_STATUS rpcrt4_protseq_ncacn_np_open_endpoint(RpcServerProtseq *protseq, LPSTR endpoint)
262 {
263   static LPCSTR prefix = "\\\\.";
264   RPC_STATUS r;
265   LPSTR pname;
266   RpcConnection *Connection;
267
268   r = RPCRT4_CreateConnection(&Connection, TRUE, protseq->Protseq, NULL,
269                               endpoint, NULL, NULL, NULL);
270   if (r != RPC_S_OK)
271     return r;
272
273   /* protseq=ncacn_np: named pipes */
274   pname = I_RpcAllocate(strlen(prefix) + strlen(Connection->Endpoint) + 1);
275   strcat(strcpy(pname, prefix), Connection->Endpoint);
276   r = rpcrt4_conn_create_pipe(Connection, pname);
277   I_RpcFree(pname);
278     
279   return r;
280 }
281
282 static void rpcrt4_conn_np_handoff(RpcConnection_np *old_npc, RpcConnection_np *new_npc)
283 {    
284   /* because of the way named pipes work, we'll transfer the connected pipe
285    * to the child, then reopen the server binding to continue listening */
286
287   new_npc->pipe = old_npc->pipe;
288   new_npc->ovl = old_npc->ovl;
289   old_npc->pipe = 0;
290   memset(&old_npc->ovl, 0, sizeof(old_npc->ovl));
291   old_npc->listening = FALSE;
292 }
293
294 static RPC_STATUS rpcrt4_ncacn_np_handoff(RpcConnection *old_conn, RpcConnection *new_conn)
295 {
296   RPC_STATUS status;
297   LPSTR pname;
298   static LPCSTR prefix = "\\\\.";
299
300   rpcrt4_conn_np_handoff((RpcConnection_np *)old_conn, (RpcConnection_np *)new_conn);
301
302   pname = I_RpcAllocate(strlen(prefix) + strlen(old_conn->Endpoint) + 1);
303   strcat(strcpy(pname, prefix), old_conn->Endpoint);
304   status = rpcrt4_conn_create_pipe(old_conn, pname);
305   I_RpcFree(pname);
306
307   return status;
308 }
309
310 static RPC_STATUS rpcrt4_ncalrpc_handoff(RpcConnection *old_conn, RpcConnection *new_conn)
311 {
312   RPC_STATUS status;
313   LPSTR pname;
314   static LPCSTR prefix = "\\\\.\\pipe\\lrpc\\";
315
316   TRACE("%s\n", old_conn->Endpoint);
317
318   rpcrt4_conn_np_handoff((RpcConnection_np *)old_conn, (RpcConnection_np *)new_conn);
319
320   pname = I_RpcAllocate(strlen(prefix) + strlen(old_conn->Endpoint) + 1);
321   strcat(strcpy(pname, prefix), old_conn->Endpoint);
322   status = rpcrt4_conn_create_pipe(old_conn, pname);
323   I_RpcFree(pname);
324     
325   return status;
326 }
327
328 static int rpcrt4_conn_np_read(RpcConnection *Connection,
329                         void *buffer, unsigned int count)
330 {
331   RpcConnection_np *npc = (RpcConnection_np *) Connection;
332   DWORD dwRead = 0;
333   if (!ReadFile(npc->pipe, buffer, count, &dwRead, NULL) &&
334       (GetLastError() != ERROR_MORE_DATA))
335     return -1;
336   return dwRead;
337 }
338
339 static int rpcrt4_conn_np_write(RpcConnection *Connection,
340                              const void *buffer, unsigned int count)
341 {
342   RpcConnection_np *npc = (RpcConnection_np *) Connection;
343   DWORD dwWritten = 0;
344   if (!WriteFile(npc->pipe, buffer, count, &dwWritten, NULL))
345     return -1;
346   return dwWritten;
347 }
348
349 static int rpcrt4_conn_np_close(RpcConnection *Connection)
350 {
351   RpcConnection_np *npc = (RpcConnection_np *) Connection;
352   if (npc->pipe) {
353     FlushFileBuffers(npc->pipe);
354     CloseHandle(npc->pipe);
355     npc->pipe = 0;
356   }
357   if (npc->ovl.hEvent) {
358     CloseHandle(npc->ovl.hEvent);
359     npc->ovl.hEvent = 0;
360   }
361   return 0;
362 }
363
364 static size_t rpcrt4_ncacn_np_get_top_of_tower(unsigned char *tower_data,
365                                                const char *networkaddr,
366                                                const char *endpoint)
367 {
368     twr_empty_floor_t *smb_floor;
369     twr_empty_floor_t *nb_floor;
370     size_t size;
371     size_t networkaddr_size;
372     size_t endpoint_size;
373
374     TRACE("(%p, %s, %s)\n", tower_data, networkaddr, endpoint);
375
376     networkaddr_size = strlen(networkaddr) + 1;
377     endpoint_size = strlen(endpoint) + 1;
378     size = sizeof(*smb_floor) + endpoint_size + sizeof(*nb_floor) + networkaddr_size;
379
380     if (!tower_data)
381         return size;
382
383     smb_floor = (twr_empty_floor_t *)tower_data;
384
385     tower_data += sizeof(*smb_floor);
386
387     smb_floor->count_lhs = sizeof(smb_floor->protid);
388     smb_floor->protid = EPM_PROTOCOL_SMB;
389     smb_floor->count_rhs = endpoint_size;
390
391     memcpy(tower_data, endpoint, endpoint_size);
392     tower_data += endpoint_size;
393
394     nb_floor = (twr_empty_floor_t *)tower_data;
395
396     tower_data += sizeof(*nb_floor);
397
398     nb_floor->count_lhs = sizeof(nb_floor->protid);
399     nb_floor->protid = EPM_PROTOCOL_NETBIOS;
400     nb_floor->count_rhs = networkaddr_size;
401
402     memcpy(tower_data, networkaddr, networkaddr_size);
403     tower_data += networkaddr_size;
404
405     return size;
406 }
407
408 static RPC_STATUS rpcrt4_ncacn_np_parse_top_of_tower(const unsigned char *tower_data,
409                                                      size_t tower_size,
410                                                      char **networkaddr,
411                                                      char **endpoint)
412 {
413     const twr_empty_floor_t *smb_floor = (const twr_empty_floor_t *)tower_data;
414     const twr_empty_floor_t *nb_floor;
415
416     TRACE("(%p, %d, %p, %p)\n", tower_data, (int)tower_size, networkaddr, endpoint);
417
418     if (tower_size < sizeof(*smb_floor))
419         return EPT_S_NOT_REGISTERED;
420
421     tower_data += sizeof(*smb_floor);
422     tower_size -= sizeof(*smb_floor);
423
424     if ((smb_floor->count_lhs != sizeof(smb_floor->protid)) ||
425         (smb_floor->protid != EPM_PROTOCOL_SMB) ||
426         (smb_floor->count_rhs > tower_size))
427         return EPT_S_NOT_REGISTERED;
428
429     if (endpoint)
430     {
431         *endpoint = I_RpcAllocate(smb_floor->count_rhs);
432         if (!*endpoint)
433             return RPC_S_OUT_OF_RESOURCES;
434         memcpy(*endpoint, tower_data, smb_floor->count_rhs);
435     }
436     tower_data += smb_floor->count_rhs;
437     tower_size -= smb_floor->count_rhs;
438
439     if (tower_size < sizeof(*nb_floor))
440         return EPT_S_NOT_REGISTERED;
441
442     nb_floor = (const twr_empty_floor_t *)tower_data;
443
444     tower_data += sizeof(*nb_floor);
445     tower_size -= sizeof(*nb_floor);
446
447     if ((nb_floor->count_lhs != sizeof(nb_floor->protid)) ||
448         (nb_floor->protid != EPM_PROTOCOL_NETBIOS) ||
449         (nb_floor->count_rhs > tower_size))
450         return EPT_S_NOT_REGISTERED;
451
452     if (networkaddr)
453     {
454         *networkaddr = I_RpcAllocate(nb_floor->count_rhs);
455         if (!*networkaddr)
456         {
457             if (endpoint)
458             {
459                 I_RpcFree(*endpoint);
460                 *endpoint = NULL;
461             }
462             return RPC_S_OUT_OF_RESOURCES;
463         }
464         memcpy(*networkaddr, tower_data, nb_floor->count_rhs);
465     }
466
467     return RPC_S_OK;
468 }
469
470 typedef struct _RpcServerProtseq_np
471 {
472     RpcServerProtseq common;
473     HANDLE mgr_event;
474 } RpcServerProtseq_np;
475
476 static RpcServerProtseq *rpcrt4_protseq_np_alloc(void)
477 {
478     RpcServerProtseq_np *ps = HeapAlloc(GetProcessHeap(), 0, sizeof(*ps));
479     if (ps)
480         ps->mgr_event = CreateEventW(NULL, FALSE, FALSE, NULL);
481     return &ps->common;
482 }
483
484 static void rpcrt4_protseq_np_signal_state_changed(RpcServerProtseq *protseq)
485 {
486     RpcServerProtseq_np *npps = CONTAINING_RECORD(protseq, RpcServerProtseq_np, common);
487     SetEvent(npps->mgr_event);
488 }
489
490 static void *rpcrt4_protseq_np_get_wait_array(RpcServerProtseq *protseq, void *prev_array, unsigned int *count)
491 {
492     HANDLE *objs = prev_array;
493     RpcConnection_np *conn;
494     RpcServerProtseq_np *npps = CONTAINING_RECORD(protseq, RpcServerProtseq_np, common);
495     
496     EnterCriticalSection(&protseq->cs);
497     
498     /* open and count connections */
499     *count = 1;
500     conn = CONTAINING_RECORD(protseq->conn, RpcConnection_np, common);
501     while (conn) {
502         rpcrt4_conn_listen_pipe(conn);
503         if (conn->ovl.hEvent)
504             (*count)++;
505         conn = CONTAINING_RECORD(conn->common.Next, RpcConnection_np, common);
506     }
507     
508     /* make array of connections */
509     if (objs)
510         objs = HeapReAlloc(GetProcessHeap(), 0, objs, *count*sizeof(HANDLE));
511     else
512         objs = HeapAlloc(GetProcessHeap(), 0, *count*sizeof(HANDLE));
513     if (!objs)
514     {
515         ERR("couldn't allocate objs\n");
516         LeaveCriticalSection(&protseq->cs);
517         return NULL;
518     }
519     
520     objs[0] = npps->mgr_event;
521     *count = 1;
522     conn = CONTAINING_RECORD(protseq->conn, RpcConnection_np, common);
523     while (conn) {
524         if ((objs[*count] = conn->ovl.hEvent))
525             (*count)++;
526         conn = CONTAINING_RECORD(conn->common.Next, RpcConnection_np, common);
527     }
528     LeaveCriticalSection(&protseq->cs);
529     return objs;
530 }
531
532 static void rpcrt4_protseq_np_free_wait_array(RpcServerProtseq *protseq, void *array)
533 {
534     HeapFree(GetProcessHeap(), 0, array);
535 }
536
537 static int rpcrt4_protseq_np_wait_for_new_connection(RpcServerProtseq *protseq, unsigned int count, void *wait_array)
538 {
539     HANDLE b_handle;
540     HANDLE *objs = wait_array;
541     DWORD res;
542     RpcConnection *cconn;
543     RpcConnection_np *conn;
544     
545     if (!objs)
546         return -1;
547     
548     res = WaitForMultipleObjects(count, objs, FALSE, INFINITE);
549     if (res == WAIT_OBJECT_0)
550         return 0;
551     else if (res == WAIT_FAILED)
552     {
553         ERR("wait failed with error %ld\n", GetLastError());
554         return -1;
555     }
556     else
557     {
558         b_handle = objs[res - WAIT_OBJECT_0];
559         /* find which connection got a RPC */
560         EnterCriticalSection(&protseq->cs);
561         conn = CONTAINING_RECORD(protseq->conn, RpcConnection_np, common);
562         while (conn) {
563             if (b_handle == conn->ovl.hEvent) break;
564             conn = CONTAINING_RECORD(conn->common.Next, RpcConnection_np, common);
565         }
566         cconn = NULL;
567         if (conn)
568             RPCRT4_SpawnConnection(&cconn, &conn->common);
569         else
570             ERR("failed to locate connection for handle %p\n", b_handle);
571         LeaveCriticalSection(&protseq->cs);
572         if (cconn)
573         {
574             RPCRT4_new_client(cconn);
575             return 1;
576         }
577         else return -1;
578     }
579 }
580
581 static size_t rpcrt4_ncalrpc_get_top_of_tower(unsigned char *tower_data,
582                                               const char *networkaddr,
583                                               const char *endpoint)
584 {
585     twr_empty_floor_t *pipe_floor;
586     size_t size;
587     size_t endpoint_size;
588
589     TRACE("(%p, %s, %s)\n", tower_data, networkaddr, endpoint);
590
591     endpoint_size = strlen(networkaddr) + 1;
592     size = sizeof(*pipe_floor) + endpoint_size;
593
594     if (!tower_data)
595         return size;
596
597     pipe_floor = (twr_empty_floor_t *)tower_data;
598
599     tower_data += sizeof(*pipe_floor);
600
601     pipe_floor->count_lhs = sizeof(pipe_floor->protid);
602     pipe_floor->protid = EPM_PROTOCOL_SMB;
603     pipe_floor->count_rhs = endpoint_size;
604
605     memcpy(tower_data, endpoint, endpoint_size);
606     tower_data += endpoint_size;
607
608     return size;
609 }
610
611 static RPC_STATUS rpcrt4_ncalrpc_parse_top_of_tower(const unsigned char *tower_data,
612                                                     size_t tower_size,
613                                                     char **networkaddr,
614                                                     char **endpoint)
615 {
616     const twr_empty_floor_t *pipe_floor = (const twr_empty_floor_t *)tower_data;
617
618     TRACE("(%p, %d, %p, %p)\n", tower_data, (int)tower_size, networkaddr, endpoint);
619
620     *networkaddr = NULL;
621     *endpoint = NULL;
622
623     if (tower_size < sizeof(*pipe_floor))
624         return EPT_S_NOT_REGISTERED;
625
626     tower_data += sizeof(*pipe_floor);
627     tower_size -= sizeof(*pipe_floor);
628
629     if ((pipe_floor->count_lhs != sizeof(pipe_floor->protid)) ||
630         (pipe_floor->protid != EPM_PROTOCOL_SMB) ||
631         (pipe_floor->count_rhs > tower_size))
632         return EPT_S_NOT_REGISTERED;
633
634     if (endpoint)
635     {
636         *endpoint = I_RpcAllocate(pipe_floor->count_rhs);
637         if (!*endpoint)
638             return RPC_S_OUT_OF_RESOURCES;
639         memcpy(*endpoint, tower_data, pipe_floor->count_rhs);
640     }
641
642     return RPC_S_OK;
643 }
644
645 /**** ncacn_ip_tcp support ****/
646
647 typedef struct _RpcConnection_tcp
648 {
649   RpcConnection common;
650   int sock;
651 } RpcConnection_tcp;
652
653 static RpcConnection *rpcrt4_conn_tcp_alloc(void)
654 {
655   RpcConnection_tcp *tcpc;
656   tcpc = HeapAlloc(GetProcessHeap(), 0, sizeof(RpcConnection_tcp));
657   if (tcpc == NULL)
658     return NULL;
659   tcpc->sock = -1;
660   return &tcpc->common;
661 }
662
663 static RPC_STATUS rpcrt4_ncacn_ip_tcp_open(RpcConnection* Connection)
664 {
665   RpcConnection_tcp *tcpc = (RpcConnection_tcp *) Connection;
666   int sock;
667   int ret;
668   struct addrinfo *ai;
669   struct addrinfo *ai_cur;
670   struct addrinfo hints;
671
672   TRACE("(%s, %s)\n", Connection->NetworkAddr, Connection->Endpoint);
673
674   if (tcpc->sock != -1)
675     return RPC_S_OK;
676
677   hints.ai_flags          = 0;
678   hints.ai_family         = PF_UNSPEC;
679   hints.ai_socktype       = SOCK_STREAM;
680   hints.ai_protocol       = IPPROTO_TCP;
681   hints.ai_addrlen        = 0;
682   hints.ai_addr           = NULL;
683   hints.ai_canonname      = NULL;
684   hints.ai_next           = NULL;
685
686   ret = getaddrinfo(Connection->NetworkAddr, Connection->Endpoint, &hints, &ai);
687   if (ret)
688   {
689     ERR("getaddrinfo for %s:%s failed: %s\n", Connection->NetworkAddr,
690       Connection->Endpoint, gai_strerror(ret));
691     return RPC_S_SERVER_UNAVAILABLE;
692   }
693
694   for (ai_cur = ai; ai_cur; ai_cur = ai_cur->ai_next)
695   {
696     if (TRACE_ON(rpc))
697     {
698       char host[256];
699       char service[256];
700       getnameinfo(ai_cur->ai_addr, ai_cur->ai_addrlen,
701         host, sizeof(host), service, sizeof(service),
702         NI_NUMERICHOST | NI_NUMERICSERV);
703       TRACE("trying %s:%s\n", host, service);
704     }
705
706     sock = socket(ai_cur->ai_family, ai_cur->ai_socktype, ai_cur->ai_protocol);
707     if (sock < 0)
708     {
709       WARN("socket() failed: %s\n", strerror(errno));
710       continue;
711     }
712
713     if (0>connect(sock, ai_cur->ai_addr, ai_cur->ai_addrlen))
714     {
715       WARN("connect() failed: %s\n", strerror(errno));
716       close(sock);
717       continue;
718     }
719     tcpc->sock = sock;
720
721     freeaddrinfo(ai);
722     TRACE("connected\n");
723     return RPC_S_OK;
724   }
725
726   freeaddrinfo(ai);
727   ERR("couldn't connect to %s:%s\n", Connection->NetworkAddr, Connection->Endpoint);
728   return RPC_S_SERVER_UNAVAILABLE;
729 }
730
731 static RPC_STATUS rpcrt4_protseq_ncacn_ip_tcp_open_endpoint(RpcServerProtseq *protseq, LPSTR endpoint)
732 {
733     RPC_STATUS status = RPC_S_CANT_CREATE_ENDPOINT;
734     int sock;
735     int ret;
736     struct addrinfo *ai;
737     struct addrinfo *ai_cur;
738     struct addrinfo hints;
739
740     TRACE("(%p, %s)\n", protseq, endpoint);
741
742     hints.ai_flags          = AI_PASSIVE /* for non-localhost addresses */;
743     hints.ai_family         = PF_UNSPEC;
744     hints.ai_socktype       = SOCK_STREAM;
745     hints.ai_protocol       = IPPROTO_TCP;
746     hints.ai_addrlen        = 0;
747     hints.ai_addr           = NULL;
748     hints.ai_canonname      = NULL;
749     hints.ai_next           = NULL;
750
751     ret = getaddrinfo(NULL, endpoint, &hints, &ai);
752     if (ret)
753     {
754         ERR("getaddrinfo for port %s failed: %s\n", endpoint,
755             gai_strerror(ret));
756         if ((ret == EAI_SERVICE) || (ret == EAI_NONAME))
757             return RPC_S_INVALID_ENDPOINT_FORMAT;
758         return RPC_S_CANT_CREATE_ENDPOINT;
759     }
760
761     for (ai_cur = ai; ai_cur; ai_cur = ai_cur->ai_next)
762     {
763         RpcConnection_tcp *tcpc;
764         if (TRACE_ON(rpc))
765         {
766             char host[256];
767             char service[256];
768             getnameinfo(ai_cur->ai_addr, ai_cur->ai_addrlen,
769                         host, sizeof(host), service, sizeof(service),
770                         NI_NUMERICHOST | NI_NUMERICSERV);
771             TRACE("trying %s:%s\n", host, service);
772         }
773
774         sock = socket(ai_cur->ai_family, ai_cur->ai_socktype, ai_cur->ai_protocol);
775         if (sock < 0)
776         {
777             WARN("socket() failed: %s\n", strerror(errno));
778             status = RPC_S_CANT_CREATE_ENDPOINT;
779             continue;
780         }
781
782         ret = bind(sock, ai_cur->ai_addr, ai_cur->ai_addrlen);
783         if (ret < 0)
784         {
785             WARN("bind failed: %s\n", strerror(errno));
786             close(sock);
787             if (errno == EADDRINUSE)
788               status = RPC_S_DUPLICATE_ENDPOINT;
789             else
790               status = RPC_S_CANT_CREATE_ENDPOINT;
791             continue;
792         }
793         status = RPCRT4_CreateConnection((RpcConnection **)&tcpc, TRUE,
794                                          protseq->Protseq, NULL, endpoint, NULL,
795                                          NULL, NULL);
796         if (status != RPC_S_OK)
797         {
798             close(sock);
799             continue;
800         }
801
802         ret = listen(sock, protseq->MaxCalls);
803         if (ret < 0)
804         {
805             WARN("listen failed: %s\n", strerror(errno));
806             close(sock);
807             status = RPC_S_OUT_OF_RESOURCES;
808             continue;
809         }
810         /* need a non-blocking socket, otherwise accept() has a potential
811          * race-condition (poll() says it is readable, connection drops,
812          * and accept() blocks until the next connection comes...)
813          */
814         ret = fcntl(sock, F_SETFL, O_NONBLOCK);
815         if (ret < 0)
816         {
817             WARN("couldn't make socket non-blocking, error %d\n", ret);
818             close(sock);
819             status = RPC_S_OUT_OF_RESOURCES;
820             continue;
821         }
822         tcpc->sock = sock;
823
824         freeaddrinfo(ai);
825
826         EnterCriticalSection(&protseq->cs);
827         tcpc->common.Next = protseq->conn;
828         protseq->conn = &tcpc->common;
829         LeaveCriticalSection(&protseq->cs);
830
831         TRACE("listening on %s\n", endpoint);
832         return RPC_S_OK;
833     }
834
835     freeaddrinfo(ai);
836     ERR("couldn't listen on port %s\n", endpoint);
837     return status;
838 }
839
840 static RPC_STATUS rpcrt4_conn_tcp_handoff(RpcConnection *old_conn, RpcConnection *new_conn)
841 {
842   int ret;
843   struct sockaddr_in address;
844   socklen_t addrsize;
845   RpcConnection_tcp *server = (RpcConnection_tcp*) old_conn;
846   RpcConnection_tcp *client = (RpcConnection_tcp*) new_conn;
847
848   addrsize = sizeof(address);
849   ret = accept(server->sock, (struct sockaddr*) &address, &addrsize);
850   if (ret < 0)
851   {
852     ERR("Failed to accept a TCP connection: error %d\n", ret);
853     return RPC_S_OUT_OF_RESOURCES;
854   }
855   /* reset to blocking behaviour */
856   fcntl(ret, F_SETFL, 0);
857   client->sock = ret;
858   TRACE("Accepted a new TCP connection\n");
859   return RPC_S_OK;
860 }
861
862 static int rpcrt4_conn_tcp_read(RpcConnection *Connection,
863                                 void *buffer, unsigned int count)
864 {
865   RpcConnection_tcp *tcpc = (RpcConnection_tcp *) Connection;
866   int r = recv(tcpc->sock, buffer, count, MSG_WAITALL);
867   TRACE("%d %p %u -> %d\n", tcpc->sock, buffer, count, r);
868   return r;
869 }
870
871 static int rpcrt4_conn_tcp_write(RpcConnection *Connection,
872                                  const void *buffer, unsigned int count)
873 {
874   RpcConnection_tcp *tcpc = (RpcConnection_tcp *) Connection;
875   int r = write(tcpc->sock, buffer, count);
876   TRACE("%d %p %u -> %d\n", tcpc->sock, buffer, count, r);
877   return r;
878 }
879
880 static int rpcrt4_conn_tcp_close(RpcConnection *Connection)
881 {
882   RpcConnection_tcp *tcpc = (RpcConnection_tcp *) Connection;
883
884   TRACE("%d\n", tcpc->sock);
885
886   if (tcpc->sock != -1)
887     close(tcpc->sock);
888   tcpc->sock = -1;
889   return 0;
890 }
891
892 static size_t rpcrt4_ncacn_ip_tcp_get_top_of_tower(unsigned char *tower_data,
893                                                    const char *networkaddr,
894                                                    const char *endpoint)
895 {
896     twr_tcp_floor_t *tcp_floor;
897     twr_ipv4_floor_t *ipv4_floor;
898     struct addrinfo *ai;
899     struct addrinfo hints;
900     int ret;
901     size_t size = sizeof(*tcp_floor) + sizeof(*ipv4_floor);
902
903     TRACE("(%p, %s, %s)\n", tower_data, networkaddr, endpoint);
904
905     if (!tower_data)
906         return size;
907
908     tcp_floor = (twr_tcp_floor_t *)tower_data;
909     tower_data += sizeof(*tcp_floor);
910
911     ipv4_floor = (twr_ipv4_floor_t *)tower_data;
912
913     tcp_floor->count_lhs = sizeof(tcp_floor->protid);
914     tcp_floor->protid = EPM_PROTOCOL_TCP;
915     tcp_floor->count_rhs = sizeof(tcp_floor->port);
916
917     ipv4_floor->count_lhs = sizeof(ipv4_floor->protid);
918     ipv4_floor->protid = EPM_PROTOCOL_IP;
919     ipv4_floor->count_rhs = sizeof(ipv4_floor->ipv4addr);
920
921     hints.ai_flags          = AI_NUMERICHOST;
922     /* FIXME: only support IPv4 at the moment. how is IPv6 represented by the EPM? */
923     hints.ai_family         = PF_INET;
924     hints.ai_socktype       = SOCK_STREAM;
925     hints.ai_protocol       = IPPROTO_TCP;
926     hints.ai_addrlen        = 0;
927     hints.ai_addr           = NULL;
928     hints.ai_canonname      = NULL;
929     hints.ai_next           = NULL;
930
931     ret = getaddrinfo(networkaddr, endpoint, &hints, &ai);
932     if (ret)
933     {
934         ret = getaddrinfo("0.0.0.0", endpoint, &hints, &ai);
935         if (ret)
936         {
937             ERR("getaddrinfo failed: %s\n", gai_strerror(ret));
938             return 0;
939         }
940     }
941
942     if (ai->ai_family == PF_INET)
943     {
944         const struct sockaddr_in *sin = (const struct sockaddr_in *)ai->ai_addr;
945         tcp_floor->port = sin->sin_port;
946         ipv4_floor->ipv4addr = sin->sin_addr.s_addr;
947     }
948     else
949     {
950         ERR("unexpected protocol family %d\n", ai->ai_family);
951         return 0;
952     }
953
954     freeaddrinfo(ai);
955
956     return size;
957 }
958
959 static RPC_STATUS rpcrt4_ncacn_ip_tcp_parse_top_of_tower(const unsigned char *tower_data,
960                                                          size_t tower_size,
961                                                          char **networkaddr,
962                                                          char **endpoint)
963 {
964     const twr_tcp_floor_t *tcp_floor = (const twr_tcp_floor_t *)tower_data;
965     const twr_ipv4_floor_t *ipv4_floor;
966     struct in_addr in_addr;
967
968     TRACE("(%p, %d, %p, %p)\n", tower_data, (int)tower_size, networkaddr, endpoint);
969
970     if (tower_size < sizeof(*tcp_floor))
971         return EPT_S_NOT_REGISTERED;
972
973     tower_data += sizeof(*tcp_floor);
974     tower_size -= sizeof(*tcp_floor);
975
976     if (tower_size < sizeof(*ipv4_floor))
977         return EPT_S_NOT_REGISTERED;
978
979     ipv4_floor = (const twr_ipv4_floor_t *)tower_data;
980
981     if ((tcp_floor->count_lhs != sizeof(tcp_floor->protid)) ||
982         (tcp_floor->protid != EPM_PROTOCOL_TCP) ||
983         (tcp_floor->count_rhs != sizeof(tcp_floor->port)) ||
984         (ipv4_floor->count_lhs != sizeof(ipv4_floor->protid)) ||
985         (ipv4_floor->protid != EPM_PROTOCOL_IP) ||
986         (ipv4_floor->count_rhs != sizeof(ipv4_floor->ipv4addr)))
987         return EPT_S_NOT_REGISTERED;
988
989     if (endpoint)
990     {
991         *endpoint = I_RpcAllocate(6 /* sizeof("65535") + 1 */);
992         if (!*endpoint)
993             return RPC_S_OUT_OF_RESOURCES;
994         sprintf(*endpoint, "%u", ntohs(tcp_floor->port));
995     }
996
997     if (networkaddr)
998     {
999         *networkaddr = I_RpcAllocate(INET_ADDRSTRLEN);
1000         if (!*networkaddr)
1001         {
1002             if (endpoint)
1003             {
1004                 I_RpcFree(*endpoint);
1005                 *endpoint = NULL;
1006             }
1007             return RPC_S_OUT_OF_RESOURCES;
1008         }
1009         in_addr.s_addr = ipv4_floor->ipv4addr;
1010         if (!inet_ntop(AF_INET, &in_addr, *networkaddr, INET_ADDRSTRLEN))
1011         {
1012             ERR("inet_ntop: %s\n", strerror(errno));
1013             I_RpcFree(*networkaddr);
1014             *networkaddr = NULL;
1015             if (endpoint)
1016             {
1017                 I_RpcFree(*endpoint);
1018                 *endpoint = NULL;
1019             }
1020             return EPT_S_NOT_REGISTERED;
1021         }
1022     }
1023
1024     return RPC_S_OK;
1025 }
1026
1027 typedef struct _RpcServerProtseq_sock
1028 {
1029     RpcServerProtseq common;
1030     int mgr_event_rcv;
1031     int mgr_event_snd;
1032 } RpcServerProtseq_sock;
1033
1034 static RpcServerProtseq *rpcrt4_protseq_sock_alloc(void)
1035 {
1036     RpcServerProtseq_sock *ps = HeapAlloc(GetProcessHeap(), 0, sizeof(*ps));
1037     if (ps)
1038     {
1039         int fds[2];
1040         if (!socketpair(PF_UNIX, SOCK_DGRAM, 0, fds))
1041         {
1042             fcntl(fds[0], F_SETFL, O_NONBLOCK);
1043             fcntl(fds[1], F_SETFL, O_NONBLOCK);
1044             ps->mgr_event_rcv = fds[0];
1045             ps->mgr_event_snd = fds[1];
1046         }
1047         else
1048         {
1049             ERR("socketpair failed with error %s\n", strerror(errno));
1050             HeapFree(GetProcessHeap(), 0, ps);
1051             return NULL;
1052         }
1053     }
1054     return &ps->common;
1055 }
1056
1057 static void rpcrt4_protseq_sock_signal_state_changed(RpcServerProtseq *protseq)
1058 {
1059     RpcServerProtseq_sock *sockps = CONTAINING_RECORD(protseq, RpcServerProtseq_sock, common);
1060     char dummy = 1;
1061     write(sockps->mgr_event_snd, &dummy, sizeof(dummy));
1062 }
1063
1064 static void *rpcrt4_protseq_sock_get_wait_array(RpcServerProtseq *protseq, void *prev_array, unsigned int *count)
1065 {
1066     struct pollfd *poll_info = prev_array;
1067     RpcConnection_tcp *conn;
1068     RpcServerProtseq_sock *sockps = CONTAINING_RECORD(protseq, RpcServerProtseq_sock, common);
1069
1070     EnterCriticalSection(&protseq->cs);
1071     
1072     /* open and count connections */
1073     *count = 1;
1074     conn = (RpcConnection_tcp *)protseq->conn;
1075     while (conn) {
1076         if (conn->sock != -1)
1077             (*count)++;
1078         conn = (RpcConnection_tcp *)conn->common.Next;
1079     }
1080     
1081     /* make array of connections */
1082     if (poll_info)
1083         poll_info = HeapReAlloc(GetProcessHeap(), 0, poll_info, *count*sizeof(*poll_info));
1084     else
1085         poll_info = HeapAlloc(GetProcessHeap(), 0, *count*sizeof(*poll_info));
1086     if (!poll_info)
1087     {
1088         ERR("couldn't allocate poll_info\n");
1089         LeaveCriticalSection(&protseq->cs);
1090         return NULL;
1091     }
1092
1093     poll_info[0].fd = sockps->mgr_event_rcv;
1094     poll_info[0].events = POLLIN;
1095     *count = 1;
1096     conn =  CONTAINING_RECORD(protseq->conn, RpcConnection_tcp, common);
1097     while (conn) {
1098         if (conn->sock != -1)
1099         {
1100             poll_info[*count].fd = conn->sock;
1101             poll_info[*count].events = POLLIN;
1102             (*count)++;
1103         }
1104         conn = CONTAINING_RECORD(conn->common.Next, RpcConnection_tcp, common);
1105     }
1106     LeaveCriticalSection(&protseq->cs);
1107     return poll_info;
1108 }
1109
1110 static void rpcrt4_protseq_sock_free_wait_array(RpcServerProtseq *protseq, void *array)
1111 {
1112     HeapFree(GetProcessHeap(), 0, array);
1113 }
1114
1115 static int rpcrt4_protseq_sock_wait_for_new_connection(RpcServerProtseq *protseq, unsigned int count, void *wait_array)
1116 {
1117     struct pollfd *poll_info = wait_array;
1118     int ret, i;
1119     RpcConnection *cconn;
1120     RpcConnection_tcp *conn;
1121     
1122     if (!poll_info)
1123         return -1;
1124     
1125     ret = poll(poll_info, count, -1);
1126     if (ret < 0)
1127     {
1128         ERR("poll failed with error %d\n", ret);
1129         return -1;
1130     }
1131
1132     for (i = 0; i < count; i++)
1133         if (poll_info[i].revents & POLLIN)
1134         {
1135             /* RPC server event */
1136             if (i == 0)
1137             {
1138                 char dummy;
1139                 read(poll_info[0].fd, &dummy, sizeof(dummy));
1140                 return 0;
1141             }
1142
1143             /* find which connection got a RPC */
1144             EnterCriticalSection(&protseq->cs);
1145             conn = CONTAINING_RECORD(protseq->conn, RpcConnection_tcp, common);
1146             while (conn) {
1147                 if (poll_info[i].fd == conn->sock) break;
1148                 conn = CONTAINING_RECORD(conn->common.Next, RpcConnection_tcp, common);
1149             }
1150             cconn = NULL;
1151             if (conn)
1152                 RPCRT4_SpawnConnection(&cconn, &conn->common);
1153             else
1154                 ERR("failed to locate connection for fd %d\n", poll_info[i].fd);
1155             LeaveCriticalSection(&protseq->cs);
1156             if (cconn)
1157                 RPCRT4_new_client(cconn);
1158             else
1159                 return -1;
1160         }
1161
1162     return 1;
1163 }
1164
1165 static const struct connection_ops conn_protseq_list[] = {
1166   { "ncacn_np",
1167     { EPM_PROTOCOL_NCACN, EPM_PROTOCOL_SMB },
1168     rpcrt4_conn_np_alloc,
1169     rpcrt4_ncacn_np_open,
1170     rpcrt4_ncacn_np_handoff,
1171     rpcrt4_conn_np_read,
1172     rpcrt4_conn_np_write,
1173     rpcrt4_conn_np_close,
1174     rpcrt4_ncacn_np_get_top_of_tower,
1175     rpcrt4_ncacn_np_parse_top_of_tower,
1176   },
1177   { "ncalrpc",
1178     { EPM_PROTOCOL_NCALRPC, EPM_PROTOCOL_PIPE },
1179     rpcrt4_conn_np_alloc,
1180     rpcrt4_ncalrpc_open,
1181     rpcrt4_ncalrpc_handoff,
1182     rpcrt4_conn_np_read,
1183     rpcrt4_conn_np_write,
1184     rpcrt4_conn_np_close,
1185     rpcrt4_ncalrpc_get_top_of_tower,
1186     rpcrt4_ncalrpc_parse_top_of_tower,
1187   },
1188   { "ncacn_ip_tcp",
1189     { EPM_PROTOCOL_NCACN, EPM_PROTOCOL_TCP },
1190     rpcrt4_conn_tcp_alloc,
1191     rpcrt4_ncacn_ip_tcp_open,
1192     rpcrt4_conn_tcp_handoff,
1193     rpcrt4_conn_tcp_read,
1194     rpcrt4_conn_tcp_write,
1195     rpcrt4_conn_tcp_close,
1196     rpcrt4_ncacn_ip_tcp_get_top_of_tower,
1197     rpcrt4_ncacn_ip_tcp_parse_top_of_tower,
1198   }
1199 };
1200
1201
1202 static const struct protseq_ops protseq_list[] =
1203 {
1204     {
1205         "ncacn_np",
1206         rpcrt4_protseq_np_alloc,
1207         rpcrt4_protseq_np_signal_state_changed,
1208         rpcrt4_protseq_np_get_wait_array,
1209         rpcrt4_protseq_np_free_wait_array,
1210         rpcrt4_protseq_np_wait_for_new_connection,
1211         rpcrt4_protseq_ncacn_np_open_endpoint,
1212     },
1213     {
1214         "ncalrpc",
1215         rpcrt4_protseq_np_alloc,
1216         rpcrt4_protseq_np_signal_state_changed,
1217         rpcrt4_protseq_np_get_wait_array,
1218         rpcrt4_protseq_np_free_wait_array,
1219         rpcrt4_protseq_np_wait_for_new_connection,
1220         rpcrt4_protseq_ncalrpc_open_endpoint,
1221     },
1222     {
1223         "ncacn_ip_tcp",
1224         rpcrt4_protseq_sock_alloc,
1225         rpcrt4_protseq_sock_signal_state_changed,
1226         rpcrt4_protseq_sock_get_wait_array,
1227         rpcrt4_protseq_sock_free_wait_array,
1228         rpcrt4_protseq_sock_wait_for_new_connection,
1229         rpcrt4_protseq_ncacn_ip_tcp_open_endpoint,
1230     },
1231 };
1232
1233 #define ARRAYSIZE(a) (sizeof((a)) / sizeof((a)[0]))
1234
1235 const struct protseq_ops *rpcrt4_get_protseq_ops(const char *protseq)
1236 {
1237   int i;
1238   for(i=0; i<ARRAYSIZE(protseq_list); i++)
1239     if (!strcmp(protseq_list[i].name, protseq))
1240       return &protseq_list[i];
1241   return NULL;
1242 }
1243
1244 static const struct connection_ops *rpcrt4_get_conn_protseq_ops(const char *protseq)
1245 {
1246     int i;
1247     for(i=0; i<ARRAYSIZE(conn_protseq_list); i++)
1248         if (!strcmp(conn_protseq_list[i].name, protseq))
1249             return &conn_protseq_list[i];
1250     return NULL;
1251 }
1252
1253 /**** interface to rest of code ****/
1254
1255 RPC_STATUS RPCRT4_OpenClientConnection(RpcConnection* Connection)
1256 {
1257   TRACE("(Connection == ^%p)\n", Connection);
1258
1259   assert(!Connection->server);
1260   return Connection->ops->open_connection_client(Connection);
1261 }
1262
1263 RPC_STATUS RPCRT4_CloseConnection(RpcConnection* Connection)
1264 {
1265   TRACE("(Connection == ^%p)\n", Connection);
1266   rpcrt4_conn_close(Connection);
1267   return RPC_S_OK;
1268 }
1269
1270 RPC_STATUS RPCRT4_CreateConnection(RpcConnection** Connection, BOOL server,
1271     LPCSTR Protseq, LPCSTR NetworkAddr, LPCSTR Endpoint,
1272     LPCSTR NetworkOptions, RpcAuthInfo* AuthInfo, RpcBinding* Binding)
1273 {
1274   const struct connection_ops *ops;
1275   RpcConnection* NewConnection;
1276
1277   ops = rpcrt4_get_conn_protseq_ops(Protseq);
1278   if (!ops)
1279     return RPC_S_PROTSEQ_NOT_SUPPORTED;
1280
1281   NewConnection = ops->alloc();
1282   NewConnection->Next = NULL;
1283   NewConnection->server = server;
1284   NewConnection->ops = ops;
1285   NewConnection->NetworkAddr = RPCRT4_strdupA(NetworkAddr);
1286   NewConnection->Endpoint = RPCRT4_strdupA(Endpoint);
1287   NewConnection->Used = Binding;
1288   NewConnection->MaxTransmissionSize = RPC_MAX_PACKET_SIZE;
1289   memset(&NewConnection->ActiveInterface, 0, sizeof(NewConnection->ActiveInterface));
1290   NewConnection->NextCallId = 1;
1291
1292   memset(&NewConnection->ctx, 0, sizeof(NewConnection->ctx));
1293   if (AuthInfo) RpcAuthInfo_AddRef(AuthInfo);
1294   NewConnection->AuthInfo = AuthInfo;
1295   list_init(&NewConnection->conn_pool_entry);
1296
1297   TRACE("connection: %p\n", NewConnection);
1298   *Connection = NewConnection;
1299
1300   return RPC_S_OK;
1301 }
1302
1303 RpcConnection *RPCRT4_GetIdleConnection(const RPC_SYNTAX_IDENTIFIER *InterfaceId,
1304     const RPC_SYNTAX_IDENTIFIER *TransferSyntax, LPCSTR Protseq, LPCSTR NetworkAddr,
1305     LPCSTR Endpoint, RpcAuthInfo* AuthInfo)
1306 {
1307   RpcConnection *Connection;
1308   /* try to find a compatible connection from the connection pool */
1309   EnterCriticalSection(&connection_pool_cs);
1310   LIST_FOR_EACH_ENTRY(Connection, &connection_pool, RpcConnection, conn_pool_entry)
1311     if ((Connection->AuthInfo == AuthInfo) &&
1312         !memcmp(&Connection->ActiveInterface, InterfaceId,
1313            sizeof(RPC_SYNTAX_IDENTIFIER)) &&
1314         !strcmp(rpcrt4_conn_get_name(Connection), Protseq) &&
1315         !strcmp(Connection->NetworkAddr, NetworkAddr) &&
1316         !strcmp(Connection->Endpoint, Endpoint))
1317     {
1318       list_remove(&Connection->conn_pool_entry);
1319       LeaveCriticalSection(&connection_pool_cs);
1320       TRACE("got connection from pool %p\n", Connection);
1321       return Connection;
1322     }
1323
1324   LeaveCriticalSection(&connection_pool_cs);
1325   return NULL;
1326 }
1327
1328 void RPCRT4_ReleaseIdleConnection(RpcConnection *Connection)
1329 {
1330   assert(!Connection->server);
1331   EnterCriticalSection(&connection_pool_cs);
1332   list_add_head(&connection_pool, &Connection->conn_pool_entry);
1333   LeaveCriticalSection(&connection_pool_cs);
1334 }
1335
1336
1337 RPC_STATUS RPCRT4_SpawnConnection(RpcConnection** Connection, RpcConnection* OldConnection)
1338 {
1339   RPC_STATUS err;
1340
1341   err = RPCRT4_CreateConnection(Connection, OldConnection->server,
1342                                 rpcrt4_conn_get_name(OldConnection),
1343                                 OldConnection->NetworkAddr,
1344                                 OldConnection->Endpoint, NULL,
1345                                 OldConnection->AuthInfo, NULL);
1346   if (err == RPC_S_OK)
1347     rpcrt4_conn_handoff(OldConnection, *Connection);
1348   return err;
1349 }
1350
1351 RPC_STATUS RPCRT4_DestroyConnection(RpcConnection* Connection)
1352 {
1353   TRACE("connection: %p\n", Connection);
1354
1355   RPCRT4_CloseConnection(Connection);
1356   RPCRT4_strfree(Connection->Endpoint);
1357   RPCRT4_strfree(Connection->NetworkAddr);
1358   if (Connection->AuthInfo) RpcAuthInfo_Release(Connection->AuthInfo);
1359   HeapFree(GetProcessHeap(), 0, Connection);
1360   return RPC_S_OK;
1361 }
1362
1363 RPC_STATUS RpcTransport_GetTopOfTower(unsigned char *tower_data,
1364                                       size_t *tower_size,
1365                                       const char *protseq,
1366                                       const char *networkaddr,
1367                                       const char *endpoint)
1368 {
1369     twr_empty_floor_t *protocol_floor;
1370     const struct connection_ops *protseq_ops = rpcrt4_get_conn_protseq_ops(protseq);
1371
1372     *tower_size = 0;
1373
1374     if (!protseq_ops)
1375         return RPC_S_INVALID_RPC_PROTSEQ;
1376
1377     if (!tower_data)
1378     {
1379         *tower_size = sizeof(*protocol_floor);
1380         *tower_size += protseq_ops->get_top_of_tower(NULL, networkaddr, endpoint);
1381         return RPC_S_OK;
1382     }
1383
1384     protocol_floor = (twr_empty_floor_t *)tower_data;
1385     protocol_floor->count_lhs = sizeof(protocol_floor->protid);
1386     protocol_floor->protid = protseq_ops->epm_protocols[0];
1387     protocol_floor->count_rhs = 0;
1388
1389     tower_data += sizeof(*protocol_floor);
1390
1391     *tower_size = protseq_ops->get_top_of_tower(tower_data, networkaddr, endpoint);
1392     if (!*tower_size)
1393         return EPT_S_NOT_REGISTERED;
1394
1395     *tower_size += sizeof(*protocol_floor);
1396
1397     return RPC_S_OK;
1398 }
1399
1400 RPC_STATUS RpcTransport_ParseTopOfTower(const unsigned char *tower_data,
1401                                         size_t tower_size,
1402                                         char **protseq,
1403                                         char **networkaddr,
1404                                         char **endpoint)
1405 {
1406     const twr_empty_floor_t *protocol_floor;
1407     const twr_empty_floor_t *floor4;
1408     const struct connection_ops *protseq_ops = NULL;
1409     RPC_STATUS status;
1410     int i;
1411
1412     if (tower_size < sizeof(*protocol_floor))
1413         return EPT_S_NOT_REGISTERED;
1414
1415     protocol_floor = (const twr_empty_floor_t *)tower_data;
1416     tower_data += sizeof(*protocol_floor);
1417     tower_size -= sizeof(*protocol_floor);
1418     if ((protocol_floor->count_lhs != sizeof(protocol_floor->protid)) ||
1419         (protocol_floor->count_rhs > tower_size))
1420         return EPT_S_NOT_REGISTERED;
1421     tower_data += protocol_floor->count_rhs;
1422     tower_size -= protocol_floor->count_rhs;
1423
1424     floor4 = (const twr_empty_floor_t *)tower_data;
1425     if ((tower_size < sizeof(*floor4)) ||
1426         (floor4->count_lhs != sizeof(floor4->protid)))
1427         return EPT_S_NOT_REGISTERED;
1428
1429     for(i = 0; i < ARRAYSIZE(conn_protseq_list); i++)
1430         if ((protocol_floor->protid == conn_protseq_list[i].epm_protocols[0]) &&
1431             (floor4->protid == conn_protseq_list[i].epm_protocols[1]))
1432         {
1433             protseq_ops = &conn_protseq_list[i];
1434             break;
1435         }
1436
1437     if (!protseq_ops)
1438         return EPT_S_NOT_REGISTERED;
1439
1440     status = protseq_ops->parse_top_of_tower(tower_data, tower_size, networkaddr, endpoint);
1441
1442     if ((status == RPC_S_OK) && protseq)
1443     {
1444         *protseq = I_RpcAllocate(strlen(protseq_ops->name) + 1);
1445         strcpy(*protseq, protseq_ops->name);
1446     }
1447
1448     return status;
1449 }
1450
1451 /***********************************************************************
1452  *             RpcNetworkIsProtseqValidW (RPCRT4.@)
1453  *
1454  * Checks if the given protocol sequence is known by the RPC system.
1455  * If it is, returns RPC_S_OK, otherwise RPC_S_PROTSEQ_NOT_SUPPORTED.
1456  *
1457  */
1458 RPC_STATUS WINAPI RpcNetworkIsProtseqValidW(RPC_WSTR protseq)
1459 {
1460   char ps[0x10];
1461
1462   WideCharToMultiByte(CP_ACP, 0, protseq, -1,
1463                       ps, sizeof ps, NULL, NULL);
1464   if (rpcrt4_get_conn_protseq_ops(ps))
1465     return RPC_S_OK;
1466
1467   FIXME("Unknown protseq %s\n", debugstr_w(protseq));
1468
1469   return RPC_S_INVALID_RPC_PROTSEQ;
1470 }
1471
1472 /***********************************************************************
1473  *             RpcNetworkIsProtseqValidA (RPCRT4.@)
1474  */
1475 RPC_STATUS WINAPI RpcNetworkIsProtseqValidA(RPC_CSTR protseq)
1476 {
1477   UNICODE_STRING protseqW;
1478
1479   if (RtlCreateUnicodeStringFromAsciiz(&protseqW, (char*)protseq))
1480   {
1481     RPC_STATUS ret = RpcNetworkIsProtseqValidW(protseqW.Buffer);
1482     RtlFreeUnicodeString(&protseqW);
1483     return ret;
1484   }
1485   return RPC_S_OUT_OF_MEMORY;
1486 }