mshtml: Implement HTMLElement_insertAdjacentHTML and HTMLElement_insertAdjacentText.
[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_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
58
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"
65
66 #include "rpc.h"
67 #include "rpcndr.h"
68
69 #include "wine/debug.h"
70
71 #include "rpc_binding.h"
72 #include "rpc_message.h"
73 #include "rpc_server.h"
74 #include "epm_towers.h"
75
76 #ifndef SOL_TCP
77 # define SOL_TCP IPPROTO_TCP
78 #endif
79
80 WINE_DEFAULT_DEBUG_CHANNEL(rpc);
81
82 static CRITICAL_SECTION assoc_list_cs;
83 static CRITICAL_SECTION_DEBUG assoc_list_cs_debug =
84 {
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") }
88 };
89 static CRITICAL_SECTION assoc_list_cs = { &assoc_list_cs_debug, -1, 0, 0, 0, 0 };
90
91 static struct list assoc_list = LIST_INIT(assoc_list);
92
93 /**** ncacn_np support ****/
94
95 typedef struct _RpcConnection_np
96 {
97   RpcConnection common;
98   HANDLE pipe;
99   OVERLAPPED ovl;
100   BOOL listening;
101 } RpcConnection_np;
102
103 static RpcConnection *rpcrt4_conn_np_alloc(void)
104 {
105   RpcConnection_np *npc = HeapAlloc(GetProcessHeap(), 0, sizeof(RpcConnection_np));
106   if (npc)
107   {
108     npc->pipe = NULL;
109     memset(&npc->ovl, 0, sizeof(npc->ovl));
110     npc->listening = FALSE;
111   }
112   return &npc->common;
113 }
114
115 static RPC_STATUS rpcrt4_conn_listen_pipe(RpcConnection_np *npc)
116 {
117   if (npc->listening)
118     return RPC_S_OK;
119
120   npc->listening = TRUE;
121   if (ConnectNamedPipe(npc->pipe, &npc->ovl))
122     return RPC_S_OK;
123
124   if (GetLastError() == ERROR_PIPE_CONNECTED) {
125     SetEvent(npc->ovl.hEvent);
126     return RPC_S_OK;
127   }
128   if (GetLastError() == ERROR_IO_PENDING) {
129     /* will be completed in rpcrt4_protseq_np_wait_for_new_connection */
130     return RPC_S_OK;
131   }
132   npc->listening = FALSE;
133   WARN("Couldn't ConnectNamedPipe (error was %d)\n", GetLastError());
134   return RPC_S_OUT_OF_RESOURCES;
135 }
136
137 static RPC_STATUS rpcrt4_conn_create_pipe(RpcConnection *Connection, LPCSTR pname)
138 {
139   RpcConnection_np *npc = (RpcConnection_np *) Connection;
140   TRACE("listening on %s\n", pname);
141
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;
152   }
153
154   memset(&npc->ovl, 0, sizeof(npc->ovl));
155   npc->ovl.hEvent = CreateEventW(NULL, TRUE, FALSE, NULL);
156
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;
160 }
161
162 static RPC_STATUS rpcrt4_conn_open_pipe(RpcConnection *Connection, LPCSTR pname, BOOL wait)
163 {
164   RpcConnection_np *npc = (RpcConnection_np *) Connection;
165   HANDLE pipe;
166   DWORD err, dwMode;
167
168   TRACE("connecting to %s\n", pname);
169
170   while (TRUE) {
171     DWORD dwFlags = 0;
172     if (Connection->QOS)
173     {
174         dwFlags = SECURITY_SQOS_PRESENT;
175         switch (Connection->QOS->qos->ImpersonationType)
176         {
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;
192         }
193         if (Connection->QOS->qos->IdentityTracking == RPC_C_QOS_IDENTIFY_DYNAMIC)
194             dwFlags |= SECURITY_CONTEXT_TRACKING;
195     }
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;
203     }
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;
210     }
211   }
212
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;
220
221   return RPC_S_OK;
222 }
223
224 static RPC_STATUS rpcrt4_ncalrpc_open(RpcConnection* Connection)
225 {
226   RpcConnection_np *npc = (RpcConnection_np *) Connection;
227   static const char prefix[] = "\\\\.\\pipe\\lrpc\\";
228   RPC_STATUS r;
229   LPSTR pname;
230
231   /* already connected? */
232   if (npc->pipe)
233     return RPC_S_OK;
234
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);
241
242   return r;
243 }
244
245 static RPC_STATUS rpcrt4_protseq_ncalrpc_open_endpoint(RpcServerProtseq* protseq, LPSTR endpoint)
246 {
247   static const char prefix[] = "\\\\.\\pipe\\lrpc\\";
248   RPC_STATUS r;
249   LPSTR pname;
250   RpcConnection *Connection;
251
252   r = RPCRT4_CreateConnection(&Connection, TRUE, protseq->Protseq, NULL,
253                               endpoint, NULL, NULL, NULL);
254   if (r != RPC_S_OK)
255       return r;
256
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);
263
264   EnterCriticalSection(&protseq->cs);
265   Connection->Next = protseq->conn;
266   protseq->conn = Connection;
267   LeaveCriticalSection(&protseq->cs);
268
269   return r;
270 }
271
272 static RPC_STATUS rpcrt4_ncacn_np_open(RpcConnection* Connection)
273 {
274   RpcConnection_np *npc = (RpcConnection_np *) Connection;
275   static const char prefix[] = "\\\\.";
276   RPC_STATUS r;
277   LPSTR pname;
278
279   /* already connected? */
280   if (npc->pipe)
281     return RPC_S_OK;
282
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);
288
289   return r;
290 }
291
292 static RPC_STATUS rpcrt4_protseq_ncacn_np_open_endpoint(RpcServerProtseq *protseq, LPSTR endpoint)
293 {
294   static const char prefix[] = "\\\\.";
295   RPC_STATUS r;
296   LPSTR pname;
297   RpcConnection *Connection;
298
299   r = RPCRT4_CreateConnection(&Connection, TRUE, protseq->Protseq, NULL,
300                               endpoint, NULL, NULL, NULL);
301   if (r != RPC_S_OK)
302     return r;
303
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);
309
310   EnterCriticalSection(&protseq->cs);
311   Connection->Next = protseq->conn;
312   protseq->conn = Connection;
313   LeaveCriticalSection(&protseq->cs);
314
315   return r;
316 }
317
318 static void rpcrt4_conn_np_handoff(RpcConnection_np *old_npc, RpcConnection_np *new_npc)
319 {    
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 */
322
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;
328 }
329
330 static RPC_STATUS rpcrt4_ncacn_np_handoff(RpcConnection *old_conn, RpcConnection *new_conn)
331 {
332   RPC_STATUS status;
333   LPSTR pname;
334   static const char prefix[] = "\\\\.";
335
336   rpcrt4_conn_np_handoff((RpcConnection_np *)old_conn, (RpcConnection_np *)new_conn);
337
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);
342
343   return status;
344 }
345
346 static RPC_STATUS rpcrt4_ncalrpc_handoff(RpcConnection *old_conn, RpcConnection *new_conn)
347 {
348   RPC_STATUS status;
349   LPSTR pname;
350   static const char prefix[] = "\\\\.\\pipe\\lrpc\\";
351
352   TRACE("%s\n", old_conn->Endpoint);
353
354   rpcrt4_conn_np_handoff((RpcConnection_np *)old_conn, (RpcConnection_np *)new_conn);
355
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);
360     
361   return status;
362 }
363
364 static int rpcrt4_conn_np_read(RpcConnection *Connection,
365                         void *buffer, unsigned int count)
366 {
367   RpcConnection_np *npc = (RpcConnection_np *) Connection;
368   char *buf = buffer;
369   BOOL ret = TRUE;
370   unsigned int bytes_left = count;
371
372   while (bytes_left)
373   {
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;
380   }
381   return ret ? count : -1;
382 }
383
384 static int rpcrt4_conn_np_write(RpcConnection *Connection,
385                              const void *buffer, unsigned int count)
386 {
387   RpcConnection_np *npc = (RpcConnection_np *) Connection;
388   const char *buf = buffer;
389   BOOL ret = TRUE;
390   unsigned int bytes_left = count;
391
392   while (bytes_left)
393   {
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;
400   }
401   return ret ? count : -1;
402 }
403
404 static int rpcrt4_conn_np_close(RpcConnection *Connection)
405 {
406   RpcConnection_np *npc = (RpcConnection_np *) Connection;
407   if (npc->pipe) {
408     FlushFileBuffers(npc->pipe);
409     CloseHandle(npc->pipe);
410     npc->pipe = 0;
411   }
412   if (npc->ovl.hEvent) {
413     CloseHandle(npc->ovl.hEvent);
414     npc->ovl.hEvent = 0;
415   }
416   return 0;
417 }
418
419 static size_t rpcrt4_ncacn_np_get_top_of_tower(unsigned char *tower_data,
420                                                const char *networkaddr,
421                                                const char *endpoint)
422 {
423     twr_empty_floor_t *smb_floor;
424     twr_empty_floor_t *nb_floor;
425     size_t size;
426     size_t networkaddr_size;
427     size_t endpoint_size;
428
429     TRACE("(%p, %s, %s)\n", tower_data, networkaddr, endpoint);
430
431     networkaddr_size = strlen(networkaddr) + 1;
432     endpoint_size = strlen(endpoint) + 1;
433     size = sizeof(*smb_floor) + endpoint_size + sizeof(*nb_floor) + networkaddr_size;
434
435     if (!tower_data)
436         return size;
437
438     smb_floor = (twr_empty_floor_t *)tower_data;
439
440     tower_data += sizeof(*smb_floor);
441
442     smb_floor->count_lhs = sizeof(smb_floor->protid);
443     smb_floor->protid = EPM_PROTOCOL_SMB;
444     smb_floor->count_rhs = endpoint_size;
445
446     memcpy(tower_data, endpoint, endpoint_size);
447     tower_data += endpoint_size;
448
449     nb_floor = (twr_empty_floor_t *)tower_data;
450
451     tower_data += sizeof(*nb_floor);
452
453     nb_floor->count_lhs = sizeof(nb_floor->protid);
454     nb_floor->protid = EPM_PROTOCOL_NETBIOS;
455     nb_floor->count_rhs = networkaddr_size;
456
457     memcpy(tower_data, networkaddr, networkaddr_size);
458     tower_data += networkaddr_size;
459
460     return size;
461 }
462
463 static RPC_STATUS rpcrt4_ncacn_np_parse_top_of_tower(const unsigned char *tower_data,
464                                                      size_t tower_size,
465                                                      char **networkaddr,
466                                                      char **endpoint)
467 {
468     const twr_empty_floor_t *smb_floor = (const twr_empty_floor_t *)tower_data;
469     const twr_empty_floor_t *nb_floor;
470
471     TRACE("(%p, %d, %p, %p)\n", tower_data, (int)tower_size, networkaddr, endpoint);
472
473     if (tower_size < sizeof(*smb_floor))
474         return EPT_S_NOT_REGISTERED;
475
476     tower_data += sizeof(*smb_floor);
477     tower_size -= sizeof(*smb_floor);
478
479     if ((smb_floor->count_lhs != sizeof(smb_floor->protid)) ||
480         (smb_floor->protid != EPM_PROTOCOL_SMB) ||
481         (smb_floor->count_rhs > tower_size))
482         return EPT_S_NOT_REGISTERED;
483
484     if (endpoint)
485     {
486         *endpoint = I_RpcAllocate(smb_floor->count_rhs);
487         if (!*endpoint)
488             return RPC_S_OUT_OF_RESOURCES;
489         memcpy(*endpoint, tower_data, smb_floor->count_rhs);
490     }
491     tower_data += smb_floor->count_rhs;
492     tower_size -= smb_floor->count_rhs;
493
494     if (tower_size < sizeof(*nb_floor))
495         return EPT_S_NOT_REGISTERED;
496
497     nb_floor = (const twr_empty_floor_t *)tower_data;
498
499     tower_data += sizeof(*nb_floor);
500     tower_size -= sizeof(*nb_floor);
501
502     if ((nb_floor->count_lhs != sizeof(nb_floor->protid)) ||
503         (nb_floor->protid != EPM_PROTOCOL_NETBIOS) ||
504         (nb_floor->count_rhs > tower_size))
505         return EPT_S_NOT_REGISTERED;
506
507     if (networkaddr)
508     {
509         *networkaddr = I_RpcAllocate(nb_floor->count_rhs);
510         if (!*networkaddr)
511         {
512             if (endpoint)
513             {
514                 I_RpcFree(*endpoint);
515                 *endpoint = NULL;
516             }
517             return RPC_S_OUT_OF_RESOURCES;
518         }
519         memcpy(*networkaddr, tower_data, nb_floor->count_rhs);
520     }
521
522     return RPC_S_OK;
523 }
524
525 typedef struct _RpcServerProtseq_np
526 {
527     RpcServerProtseq common;
528     HANDLE mgr_event;
529 } RpcServerProtseq_np;
530
531 static RpcServerProtseq *rpcrt4_protseq_np_alloc(void)
532 {
533     RpcServerProtseq_np *ps = HeapAlloc(GetProcessHeap(), 0, sizeof(*ps));
534     if (ps)
535         ps->mgr_event = CreateEventW(NULL, FALSE, FALSE, NULL);
536     return &ps->common;
537 }
538
539 static void rpcrt4_protseq_np_signal_state_changed(RpcServerProtseq *protseq)
540 {
541     RpcServerProtseq_np *npps = CONTAINING_RECORD(protseq, RpcServerProtseq_np, common);
542     SetEvent(npps->mgr_event);
543 }
544
545 static void *rpcrt4_protseq_np_get_wait_array(RpcServerProtseq *protseq, void *prev_array, unsigned int *count)
546 {
547     HANDLE *objs = prev_array;
548     RpcConnection_np *conn;
549     RpcServerProtseq_np *npps = CONTAINING_RECORD(protseq, RpcServerProtseq_np, common);
550     
551     EnterCriticalSection(&protseq->cs);
552     
553     /* open and count connections */
554     *count = 1;
555     conn = CONTAINING_RECORD(protseq->conn, RpcConnection_np, common);
556     while (conn) {
557         rpcrt4_conn_listen_pipe(conn);
558         if (conn->ovl.hEvent)
559             (*count)++;
560         conn = CONTAINING_RECORD(conn->common.Next, RpcConnection_np, common);
561     }
562     
563     /* make array of connections */
564     if (objs)
565         objs = HeapReAlloc(GetProcessHeap(), 0, objs, *count*sizeof(HANDLE));
566     else
567         objs = HeapAlloc(GetProcessHeap(), 0, *count*sizeof(HANDLE));
568     if (!objs)
569     {
570         ERR("couldn't allocate objs\n");
571         LeaveCriticalSection(&protseq->cs);
572         return NULL;
573     }
574     
575     objs[0] = npps->mgr_event;
576     *count = 1;
577     conn = CONTAINING_RECORD(protseq->conn, RpcConnection_np, common);
578     while (conn) {
579         if ((objs[*count] = conn->ovl.hEvent))
580             (*count)++;
581         conn = CONTAINING_RECORD(conn->common.Next, RpcConnection_np, common);
582     }
583     LeaveCriticalSection(&protseq->cs);
584     return objs;
585 }
586
587 static void rpcrt4_protseq_np_free_wait_array(RpcServerProtseq *protseq, void *array)
588 {
589     HeapFree(GetProcessHeap(), 0, array);
590 }
591
592 static int rpcrt4_protseq_np_wait_for_new_connection(RpcServerProtseq *protseq, unsigned int count, void *wait_array)
593 {
594     HANDLE b_handle;
595     HANDLE *objs = wait_array;
596     DWORD res;
597     RpcConnection *cconn;
598     RpcConnection_np *conn;
599     
600     if (!objs)
601         return -1;
602     
603     res = WaitForMultipleObjects(count, objs, FALSE, INFINITE);
604     if (res == WAIT_OBJECT_0)
605         return 0;
606     else if (res == WAIT_FAILED)
607     {
608         ERR("wait failed with error %d\n", GetLastError());
609         return -1;
610     }
611     else
612     {
613         b_handle = objs[res - WAIT_OBJECT_0];
614         /* find which connection got a RPC */
615         EnterCriticalSection(&protseq->cs);
616         conn = CONTAINING_RECORD(protseq->conn, RpcConnection_np, common);
617         while (conn) {
618             if (b_handle == conn->ovl.hEvent) break;
619             conn = CONTAINING_RECORD(conn->common.Next, RpcConnection_np, common);
620         }
621         cconn = NULL;
622         if (conn)
623             RPCRT4_SpawnConnection(&cconn, &conn->common);
624         else
625             ERR("failed to locate connection for handle %p\n", b_handle);
626         LeaveCriticalSection(&protseq->cs);
627         if (cconn)
628         {
629             RPCRT4_new_client(cconn);
630             return 1;
631         }
632         else return -1;
633     }
634 }
635
636 static size_t rpcrt4_ncalrpc_get_top_of_tower(unsigned char *tower_data,
637                                               const char *networkaddr,
638                                               const char *endpoint)
639 {
640     twr_empty_floor_t *pipe_floor;
641     size_t size;
642     size_t endpoint_size;
643
644     TRACE("(%p, %s, %s)\n", tower_data, networkaddr, endpoint);
645
646     endpoint_size = strlen(networkaddr) + 1;
647     size = sizeof(*pipe_floor) + endpoint_size;
648
649     if (!tower_data)
650         return size;
651
652     pipe_floor = (twr_empty_floor_t *)tower_data;
653
654     tower_data += sizeof(*pipe_floor);
655
656     pipe_floor->count_lhs = sizeof(pipe_floor->protid);
657     pipe_floor->protid = EPM_PROTOCOL_SMB;
658     pipe_floor->count_rhs = endpoint_size;
659
660     memcpy(tower_data, endpoint, endpoint_size);
661     tower_data += endpoint_size;
662
663     return size;
664 }
665
666 static RPC_STATUS rpcrt4_ncalrpc_parse_top_of_tower(const unsigned char *tower_data,
667                                                     size_t tower_size,
668                                                     char **networkaddr,
669                                                     char **endpoint)
670 {
671     const twr_empty_floor_t *pipe_floor = (const twr_empty_floor_t *)tower_data;
672
673     TRACE("(%p, %d, %p, %p)\n", tower_data, (int)tower_size, networkaddr, endpoint);
674
675     *networkaddr = NULL;
676     *endpoint = NULL;
677
678     if (tower_size < sizeof(*pipe_floor))
679         return EPT_S_NOT_REGISTERED;
680
681     tower_data += sizeof(*pipe_floor);
682     tower_size -= sizeof(*pipe_floor);
683
684     if ((pipe_floor->count_lhs != sizeof(pipe_floor->protid)) ||
685         (pipe_floor->protid != EPM_PROTOCOL_SMB) ||
686         (pipe_floor->count_rhs > tower_size))
687         return EPT_S_NOT_REGISTERED;
688
689     if (endpoint)
690     {
691         *endpoint = I_RpcAllocate(pipe_floor->count_rhs);
692         if (!*endpoint)
693             return RPC_S_OUT_OF_RESOURCES;
694         memcpy(*endpoint, tower_data, pipe_floor->count_rhs);
695     }
696
697     return RPC_S_OK;
698 }
699
700 /**** ncacn_ip_tcp support ****/
701
702 typedef struct _RpcConnection_tcp
703 {
704   RpcConnection common;
705   int sock;
706 } RpcConnection_tcp;
707
708 static RpcConnection *rpcrt4_conn_tcp_alloc(void)
709 {
710   RpcConnection_tcp *tcpc;
711   tcpc = HeapAlloc(GetProcessHeap(), 0, sizeof(RpcConnection_tcp));
712   if (tcpc == NULL)
713     return NULL;
714   tcpc->sock = -1;
715   return &tcpc->common;
716 }
717
718 static RPC_STATUS rpcrt4_ncacn_ip_tcp_open(RpcConnection* Connection)
719 {
720   RpcConnection_tcp *tcpc = (RpcConnection_tcp *) Connection;
721   int sock;
722   int ret;
723   struct addrinfo *ai;
724   struct addrinfo *ai_cur;
725   struct addrinfo hints;
726
727   TRACE("(%s, %s)\n", Connection->NetworkAddr, Connection->Endpoint);
728
729   if (tcpc->sock != -1)
730     return RPC_S_OK;
731
732   hints.ai_flags          = 0;
733   hints.ai_family         = PF_UNSPEC;
734   hints.ai_socktype       = SOCK_STREAM;
735   hints.ai_protocol       = IPPROTO_TCP;
736   hints.ai_addrlen        = 0;
737   hints.ai_addr           = NULL;
738   hints.ai_canonname      = NULL;
739   hints.ai_next           = NULL;
740
741   ret = getaddrinfo(Connection->NetworkAddr, Connection->Endpoint, &hints, &ai);
742   if (ret)
743   {
744     ERR("getaddrinfo for %s:%s failed: %s\n", Connection->NetworkAddr,
745       Connection->Endpoint, gai_strerror(ret));
746     return RPC_S_SERVER_UNAVAILABLE;
747   }
748
749   for (ai_cur = ai; ai_cur; ai_cur = ai_cur->ai_next)
750   {
751     int val;
752
753     if (TRACE_ON(rpc))
754     {
755       char host[256];
756       char service[256];
757       getnameinfo(ai_cur->ai_addr, ai_cur->ai_addrlen,
758         host, sizeof(host), service, sizeof(service),
759         NI_NUMERICHOST | NI_NUMERICSERV);
760       TRACE("trying %s:%s\n", host, service);
761     }
762
763     sock = socket(ai_cur->ai_family, ai_cur->ai_socktype, ai_cur->ai_protocol);
764     if (sock < 0)
765     {
766       WARN("socket() failed: %s\n", strerror(errno));
767       continue;
768     }
769
770     if (0>connect(sock, ai_cur->ai_addr, ai_cur->ai_addrlen))
771     {
772       WARN("connect() failed: %s\n", strerror(errno));
773       close(sock);
774       continue;
775     }
776
777     /* RPC depends on having minimal latency so disable the Nagle algorithm */
778     val = 1;
779     setsockopt(sock, SOL_TCP, TCP_NODELAY, &val, sizeof(val));
780
781     tcpc->sock = sock;
782
783     freeaddrinfo(ai);
784     TRACE("connected\n");
785     return RPC_S_OK;
786   }
787
788   freeaddrinfo(ai);
789   ERR("couldn't connect to %s:%s\n", Connection->NetworkAddr, Connection->Endpoint);
790   return RPC_S_SERVER_UNAVAILABLE;
791 }
792
793 static RPC_STATUS rpcrt4_protseq_ncacn_ip_tcp_open_endpoint(RpcServerProtseq *protseq, LPSTR endpoint)
794 {
795     RPC_STATUS status = RPC_S_CANT_CREATE_ENDPOINT;
796     int sock;
797     int ret;
798     struct addrinfo *ai;
799     struct addrinfo *ai_cur;
800     struct addrinfo hints;
801     RpcConnection *first_connection = NULL;
802
803     TRACE("(%p, %s)\n", protseq, endpoint);
804
805     hints.ai_flags          = AI_PASSIVE /* for non-localhost addresses */;
806     hints.ai_family         = PF_UNSPEC;
807     hints.ai_socktype       = SOCK_STREAM;
808     hints.ai_protocol       = IPPROTO_TCP;
809     hints.ai_addrlen        = 0;
810     hints.ai_addr           = NULL;
811     hints.ai_canonname      = NULL;
812     hints.ai_next           = NULL;
813
814     ret = getaddrinfo(NULL, endpoint, &hints, &ai);
815     if (ret)
816     {
817         ERR("getaddrinfo for port %s failed: %s\n", endpoint,
818             gai_strerror(ret));
819         if ((ret == EAI_SERVICE) || (ret == EAI_NONAME))
820             return RPC_S_INVALID_ENDPOINT_FORMAT;
821         return RPC_S_CANT_CREATE_ENDPOINT;
822     }
823
824     for (ai_cur = ai; ai_cur; ai_cur = ai_cur->ai_next)
825     {
826         RpcConnection_tcp *tcpc;
827         RPC_STATUS create_status;
828
829         if (TRACE_ON(rpc))
830         {
831             char host[256];
832             char service[256];
833             getnameinfo(ai_cur->ai_addr, ai_cur->ai_addrlen,
834                         host, sizeof(host), service, sizeof(service),
835                         NI_NUMERICHOST | NI_NUMERICSERV);
836             TRACE("trying %s:%s\n", host, service);
837         }
838
839         sock = socket(ai_cur->ai_family, ai_cur->ai_socktype, ai_cur->ai_protocol);
840         if (sock < 0)
841         {
842             WARN("socket() failed: %s\n", strerror(errno));
843             status = RPC_S_CANT_CREATE_ENDPOINT;
844             continue;
845         }
846
847         ret = bind(sock, ai_cur->ai_addr, ai_cur->ai_addrlen);
848         if (ret < 0)
849         {
850             WARN("bind failed: %s\n", strerror(errno));
851             close(sock);
852             if (errno == EADDRINUSE)
853               status = RPC_S_DUPLICATE_ENDPOINT;
854             else
855               status = RPC_S_CANT_CREATE_ENDPOINT;
856             continue;
857         }
858         create_status = RPCRT4_CreateConnection((RpcConnection **)&tcpc, TRUE,
859                                                 protseq->Protseq, NULL,
860                                                 endpoint, NULL, NULL, NULL);
861         if (create_status != RPC_S_OK)
862         {
863             close(sock);
864             status = create_status;
865             continue;
866         }
867
868         tcpc->sock = sock;
869         ret = listen(sock, protseq->MaxCalls);
870         if (ret < 0)
871         {
872             WARN("listen failed: %s\n", strerror(errno));
873             RPCRT4_DestroyConnection(&tcpc->common);
874             status = RPC_S_OUT_OF_RESOURCES;
875             continue;
876         }
877         /* need a non-blocking socket, otherwise accept() has a potential
878          * race-condition (poll() says it is readable, connection drops,
879          * and accept() blocks until the next connection comes...)
880          */
881         ret = fcntl(sock, F_SETFL, O_NONBLOCK);
882         if (ret < 0)
883         {
884             WARN("couldn't make socket non-blocking, error %d\n", ret);
885             RPCRT4_DestroyConnection(&tcpc->common);
886             status = RPC_S_OUT_OF_RESOURCES;
887             continue;
888         }
889
890         tcpc->common.Next = first_connection;
891         first_connection = &tcpc->common;
892     }
893
894     freeaddrinfo(ai);
895
896     /* if at least one connection was created for an endpoint then
897      * return success */
898     if (first_connection)
899     {
900         RpcConnection *conn;
901
902         /* find last element in list */
903         for (conn = first_connection; conn->Next; conn = conn->Next)
904             ;
905
906         EnterCriticalSection(&protseq->cs);
907         conn->Next = protseq->conn;
908         protseq->conn = first_connection;
909         LeaveCriticalSection(&protseq->cs);
910         
911         TRACE("listening on %s\n", endpoint);
912         return RPC_S_OK;
913     }
914
915     ERR("couldn't listen on port %s\n", endpoint);
916     return status;
917 }
918
919 static RPC_STATUS rpcrt4_conn_tcp_handoff(RpcConnection *old_conn, RpcConnection *new_conn)
920 {
921   int ret;
922   struct sockaddr_in address;
923   socklen_t addrsize;
924   RpcConnection_tcp *server = (RpcConnection_tcp*) old_conn;
925   RpcConnection_tcp *client = (RpcConnection_tcp*) new_conn;
926
927   addrsize = sizeof(address);
928   ret = accept(server->sock, (struct sockaddr*) &address, &addrsize);
929   if (ret < 0)
930   {
931     ERR("Failed to accept a TCP connection: error %d\n", ret);
932     return RPC_S_OUT_OF_RESOURCES;
933   }
934   /* reset to blocking behaviour */
935   fcntl(ret, F_SETFL, 0);
936   client->sock = ret;
937   TRACE("Accepted a new TCP connection\n");
938   return RPC_S_OK;
939 }
940
941 static int rpcrt4_conn_tcp_read(RpcConnection *Connection,
942                                 void *buffer, unsigned int count)
943 {
944   RpcConnection_tcp *tcpc = (RpcConnection_tcp *) Connection;
945   int r = recv(tcpc->sock, buffer, count, MSG_WAITALL);
946   TRACE("%d %p %u -> %d\n", tcpc->sock, buffer, count, r);
947   return r;
948 }
949
950 static int rpcrt4_conn_tcp_write(RpcConnection *Connection,
951                                  const void *buffer, unsigned int count)
952 {
953   RpcConnection_tcp *tcpc = (RpcConnection_tcp *) Connection;
954   int r = write(tcpc->sock, buffer, count);
955   TRACE("%d %p %u -> %d\n", tcpc->sock, buffer, count, r);
956   return r;
957 }
958
959 static int rpcrt4_conn_tcp_close(RpcConnection *Connection)
960 {
961   RpcConnection_tcp *tcpc = (RpcConnection_tcp *) Connection;
962
963   TRACE("%d\n", tcpc->sock);
964
965   if (tcpc->sock != -1)
966     close(tcpc->sock);
967   tcpc->sock = -1;
968   return 0;
969 }
970
971 static size_t rpcrt4_ncacn_ip_tcp_get_top_of_tower(unsigned char *tower_data,
972                                                    const char *networkaddr,
973                                                    const char *endpoint)
974 {
975     twr_tcp_floor_t *tcp_floor;
976     twr_ipv4_floor_t *ipv4_floor;
977     struct addrinfo *ai;
978     struct addrinfo hints;
979     int ret;
980     size_t size = sizeof(*tcp_floor) + sizeof(*ipv4_floor);
981
982     TRACE("(%p, %s, %s)\n", tower_data, networkaddr, endpoint);
983
984     if (!tower_data)
985         return size;
986
987     tcp_floor = (twr_tcp_floor_t *)tower_data;
988     tower_data += sizeof(*tcp_floor);
989
990     ipv4_floor = (twr_ipv4_floor_t *)tower_data;
991
992     tcp_floor->count_lhs = sizeof(tcp_floor->protid);
993     tcp_floor->protid = EPM_PROTOCOL_TCP;
994     tcp_floor->count_rhs = sizeof(tcp_floor->port);
995
996     ipv4_floor->count_lhs = sizeof(ipv4_floor->protid);
997     ipv4_floor->protid = EPM_PROTOCOL_IP;
998     ipv4_floor->count_rhs = sizeof(ipv4_floor->ipv4addr);
999
1000     hints.ai_flags          = AI_NUMERICHOST;
1001     /* FIXME: only support IPv4 at the moment. how is IPv6 represented by the EPM? */
1002     hints.ai_family         = PF_INET;
1003     hints.ai_socktype       = SOCK_STREAM;
1004     hints.ai_protocol       = IPPROTO_TCP;
1005     hints.ai_addrlen        = 0;
1006     hints.ai_addr           = NULL;
1007     hints.ai_canonname      = NULL;
1008     hints.ai_next           = NULL;
1009
1010     ret = getaddrinfo(networkaddr, endpoint, &hints, &ai);
1011     if (ret)
1012     {
1013         ret = getaddrinfo("0.0.0.0", endpoint, &hints, &ai);
1014         if (ret)
1015         {
1016             ERR("getaddrinfo failed: %s\n", gai_strerror(ret));
1017             return 0;
1018         }
1019     }
1020
1021     if (ai->ai_family == PF_INET)
1022     {
1023         const struct sockaddr_in *sin = (const struct sockaddr_in *)ai->ai_addr;
1024         tcp_floor->port = sin->sin_port;
1025         ipv4_floor->ipv4addr = sin->sin_addr.s_addr;
1026     }
1027     else
1028     {
1029         ERR("unexpected protocol family %d\n", ai->ai_family);
1030         return 0;
1031     }
1032
1033     freeaddrinfo(ai);
1034
1035     return size;
1036 }
1037
1038 static RPC_STATUS rpcrt4_ncacn_ip_tcp_parse_top_of_tower(const unsigned char *tower_data,
1039                                                          size_t tower_size,
1040                                                          char **networkaddr,
1041                                                          char **endpoint)
1042 {
1043     const twr_tcp_floor_t *tcp_floor = (const twr_tcp_floor_t *)tower_data;
1044     const twr_ipv4_floor_t *ipv4_floor;
1045     struct in_addr in_addr;
1046
1047     TRACE("(%p, %d, %p, %p)\n", tower_data, (int)tower_size, networkaddr, endpoint);
1048
1049     if (tower_size < sizeof(*tcp_floor))
1050         return EPT_S_NOT_REGISTERED;
1051
1052     tower_data += sizeof(*tcp_floor);
1053     tower_size -= sizeof(*tcp_floor);
1054
1055     if (tower_size < sizeof(*ipv4_floor))
1056         return EPT_S_NOT_REGISTERED;
1057
1058     ipv4_floor = (const twr_ipv4_floor_t *)tower_data;
1059
1060     if ((tcp_floor->count_lhs != sizeof(tcp_floor->protid)) ||
1061         (tcp_floor->protid != EPM_PROTOCOL_TCP) ||
1062         (tcp_floor->count_rhs != sizeof(tcp_floor->port)) ||
1063         (ipv4_floor->count_lhs != sizeof(ipv4_floor->protid)) ||
1064         (ipv4_floor->protid != EPM_PROTOCOL_IP) ||
1065         (ipv4_floor->count_rhs != sizeof(ipv4_floor->ipv4addr)))
1066         return EPT_S_NOT_REGISTERED;
1067
1068     if (endpoint)
1069     {
1070         *endpoint = I_RpcAllocate(6 /* sizeof("65535") + 1 */);
1071         if (!*endpoint)
1072             return RPC_S_OUT_OF_RESOURCES;
1073         sprintf(*endpoint, "%u", ntohs(tcp_floor->port));
1074     }
1075
1076     if (networkaddr)
1077     {
1078         *networkaddr = I_RpcAllocate(INET_ADDRSTRLEN);
1079         if (!*networkaddr)
1080         {
1081             if (endpoint)
1082             {
1083                 I_RpcFree(*endpoint);
1084                 *endpoint = NULL;
1085             }
1086             return RPC_S_OUT_OF_RESOURCES;
1087         }
1088         in_addr.s_addr = ipv4_floor->ipv4addr;
1089         if (!inet_ntop(AF_INET, &in_addr, *networkaddr, INET_ADDRSTRLEN))
1090         {
1091             ERR("inet_ntop: %s\n", strerror(errno));
1092             I_RpcFree(*networkaddr);
1093             *networkaddr = NULL;
1094             if (endpoint)
1095             {
1096                 I_RpcFree(*endpoint);
1097                 *endpoint = NULL;
1098             }
1099             return EPT_S_NOT_REGISTERED;
1100         }
1101     }
1102
1103     return RPC_S_OK;
1104 }
1105
1106 typedef struct _RpcServerProtseq_sock
1107 {
1108     RpcServerProtseq common;
1109     int mgr_event_rcv;
1110     int mgr_event_snd;
1111 } RpcServerProtseq_sock;
1112
1113 static RpcServerProtseq *rpcrt4_protseq_sock_alloc(void)
1114 {
1115     RpcServerProtseq_sock *ps = HeapAlloc(GetProcessHeap(), 0, sizeof(*ps));
1116     if (ps)
1117     {
1118         int fds[2];
1119         if (!socketpair(PF_UNIX, SOCK_DGRAM, 0, fds))
1120         {
1121             fcntl(fds[0], F_SETFL, O_NONBLOCK);
1122             fcntl(fds[1], F_SETFL, O_NONBLOCK);
1123             ps->mgr_event_rcv = fds[0];
1124             ps->mgr_event_snd = fds[1];
1125         }
1126         else
1127         {
1128             ERR("socketpair failed with error %s\n", strerror(errno));
1129             HeapFree(GetProcessHeap(), 0, ps);
1130             return NULL;
1131         }
1132     }
1133     return &ps->common;
1134 }
1135
1136 static void rpcrt4_protseq_sock_signal_state_changed(RpcServerProtseq *protseq)
1137 {
1138     RpcServerProtseq_sock *sockps = CONTAINING_RECORD(protseq, RpcServerProtseq_sock, common);
1139     char dummy = 1;
1140     write(sockps->mgr_event_snd, &dummy, sizeof(dummy));
1141 }
1142
1143 static void *rpcrt4_protseq_sock_get_wait_array(RpcServerProtseq *protseq, void *prev_array, unsigned int *count)
1144 {
1145     struct pollfd *poll_info = prev_array;
1146     RpcConnection_tcp *conn;
1147     RpcServerProtseq_sock *sockps = CONTAINING_RECORD(protseq, RpcServerProtseq_sock, common);
1148
1149     EnterCriticalSection(&protseq->cs);
1150     
1151     /* open and count connections */
1152     *count = 1;
1153     conn = (RpcConnection_tcp *)protseq->conn;
1154     while (conn) {
1155         if (conn->sock != -1)
1156             (*count)++;
1157         conn = (RpcConnection_tcp *)conn->common.Next;
1158     }
1159     
1160     /* make array of connections */
1161     if (poll_info)
1162         poll_info = HeapReAlloc(GetProcessHeap(), 0, poll_info, *count*sizeof(*poll_info));
1163     else
1164         poll_info = HeapAlloc(GetProcessHeap(), 0, *count*sizeof(*poll_info));
1165     if (!poll_info)
1166     {
1167         ERR("couldn't allocate poll_info\n");
1168         LeaveCriticalSection(&protseq->cs);
1169         return NULL;
1170     }
1171
1172     poll_info[0].fd = sockps->mgr_event_rcv;
1173     poll_info[0].events = POLLIN;
1174     *count = 1;
1175     conn =  CONTAINING_RECORD(protseq->conn, RpcConnection_tcp, common);
1176     while (conn) {
1177         if (conn->sock != -1)
1178         {
1179             poll_info[*count].fd = conn->sock;
1180             poll_info[*count].events = POLLIN;
1181             (*count)++;
1182         }
1183         conn = CONTAINING_RECORD(conn->common.Next, RpcConnection_tcp, common);
1184     }
1185     LeaveCriticalSection(&protseq->cs);
1186     return poll_info;
1187 }
1188
1189 static void rpcrt4_protseq_sock_free_wait_array(RpcServerProtseq *protseq, void *array)
1190 {
1191     HeapFree(GetProcessHeap(), 0, array);
1192 }
1193
1194 static int rpcrt4_protseq_sock_wait_for_new_connection(RpcServerProtseq *protseq, unsigned int count, void *wait_array)
1195 {
1196     struct pollfd *poll_info = wait_array;
1197     int ret, i;
1198     RpcConnection *cconn;
1199     RpcConnection_tcp *conn;
1200     
1201     if (!poll_info)
1202         return -1;
1203     
1204     ret = poll(poll_info, count, -1);
1205     if (ret < 0)
1206     {
1207         ERR("poll failed with error %d\n", ret);
1208         return -1;
1209     }
1210
1211     for (i = 0; i < count; i++)
1212         if (poll_info[i].revents & POLLIN)
1213         {
1214             /* RPC server event */
1215             if (i == 0)
1216             {
1217                 char dummy;
1218                 read(poll_info[0].fd, &dummy, sizeof(dummy));
1219                 return 0;
1220             }
1221
1222             /* find which connection got a RPC */
1223             EnterCriticalSection(&protseq->cs);
1224             conn = CONTAINING_RECORD(protseq->conn, RpcConnection_tcp, common);
1225             while (conn) {
1226                 if (poll_info[i].fd == conn->sock) break;
1227                 conn = CONTAINING_RECORD(conn->common.Next, RpcConnection_tcp, common);
1228             }
1229             cconn = NULL;
1230             if (conn)
1231                 RPCRT4_SpawnConnection(&cconn, &conn->common);
1232             else
1233                 ERR("failed to locate connection for fd %d\n", poll_info[i].fd);
1234             LeaveCriticalSection(&protseq->cs);
1235             if (cconn)
1236                 RPCRT4_new_client(cconn);
1237             else
1238                 return -1;
1239         }
1240
1241     return 1;
1242 }
1243
1244 static const struct connection_ops conn_protseq_list[] = {
1245   { "ncacn_np",
1246     { EPM_PROTOCOL_NCACN, EPM_PROTOCOL_SMB },
1247     rpcrt4_conn_np_alloc,
1248     rpcrt4_ncacn_np_open,
1249     rpcrt4_ncacn_np_handoff,
1250     rpcrt4_conn_np_read,
1251     rpcrt4_conn_np_write,
1252     rpcrt4_conn_np_close,
1253     rpcrt4_ncacn_np_get_top_of_tower,
1254     rpcrt4_ncacn_np_parse_top_of_tower,
1255   },
1256   { "ncalrpc",
1257     { EPM_PROTOCOL_NCALRPC, EPM_PROTOCOL_PIPE },
1258     rpcrt4_conn_np_alloc,
1259     rpcrt4_ncalrpc_open,
1260     rpcrt4_ncalrpc_handoff,
1261     rpcrt4_conn_np_read,
1262     rpcrt4_conn_np_write,
1263     rpcrt4_conn_np_close,
1264     rpcrt4_ncalrpc_get_top_of_tower,
1265     rpcrt4_ncalrpc_parse_top_of_tower,
1266   },
1267   { "ncacn_ip_tcp",
1268     { EPM_PROTOCOL_NCACN, EPM_PROTOCOL_TCP },
1269     rpcrt4_conn_tcp_alloc,
1270     rpcrt4_ncacn_ip_tcp_open,
1271     rpcrt4_conn_tcp_handoff,
1272     rpcrt4_conn_tcp_read,
1273     rpcrt4_conn_tcp_write,
1274     rpcrt4_conn_tcp_close,
1275     rpcrt4_ncacn_ip_tcp_get_top_of_tower,
1276     rpcrt4_ncacn_ip_tcp_parse_top_of_tower,
1277   }
1278 };
1279
1280
1281 static const struct protseq_ops protseq_list[] =
1282 {
1283     {
1284         "ncacn_np",
1285         rpcrt4_protseq_np_alloc,
1286         rpcrt4_protseq_np_signal_state_changed,
1287         rpcrt4_protseq_np_get_wait_array,
1288         rpcrt4_protseq_np_free_wait_array,
1289         rpcrt4_protseq_np_wait_for_new_connection,
1290         rpcrt4_protseq_ncacn_np_open_endpoint,
1291     },
1292     {
1293         "ncalrpc",
1294         rpcrt4_protseq_np_alloc,
1295         rpcrt4_protseq_np_signal_state_changed,
1296         rpcrt4_protseq_np_get_wait_array,
1297         rpcrt4_protseq_np_free_wait_array,
1298         rpcrt4_protseq_np_wait_for_new_connection,
1299         rpcrt4_protseq_ncalrpc_open_endpoint,
1300     },
1301     {
1302         "ncacn_ip_tcp",
1303         rpcrt4_protseq_sock_alloc,
1304         rpcrt4_protseq_sock_signal_state_changed,
1305         rpcrt4_protseq_sock_get_wait_array,
1306         rpcrt4_protseq_sock_free_wait_array,
1307         rpcrt4_protseq_sock_wait_for_new_connection,
1308         rpcrt4_protseq_ncacn_ip_tcp_open_endpoint,
1309     },
1310 };
1311
1312 #define ARRAYSIZE(a) (sizeof((a)) / sizeof((a)[0]))
1313
1314 const struct protseq_ops *rpcrt4_get_protseq_ops(const char *protseq)
1315 {
1316   int i;
1317   for(i=0; i<ARRAYSIZE(protseq_list); i++)
1318     if (!strcmp(protseq_list[i].name, protseq))
1319       return &protseq_list[i];
1320   return NULL;
1321 }
1322
1323 static const struct connection_ops *rpcrt4_get_conn_protseq_ops(const char *protseq)
1324 {
1325     int i;
1326     for(i=0; i<ARRAYSIZE(conn_protseq_list); i++)
1327         if (!strcmp(conn_protseq_list[i].name, protseq))
1328             return &conn_protseq_list[i];
1329     return NULL;
1330 }
1331
1332 /**** interface to rest of code ****/
1333
1334 RPC_STATUS RPCRT4_OpenClientConnection(RpcConnection* Connection)
1335 {
1336   TRACE("(Connection == ^%p)\n", Connection);
1337
1338   assert(!Connection->server);
1339   return Connection->ops->open_connection_client(Connection);
1340 }
1341
1342 RPC_STATUS RPCRT4_CloseConnection(RpcConnection* Connection)
1343 {
1344   TRACE("(Connection == ^%p)\n", Connection);
1345   if (SecIsValidHandle(&Connection->ctx))
1346   {
1347     DeleteSecurityContext(&Connection->ctx);
1348     SecInvalidateHandle(&Connection->ctx);
1349   }
1350   rpcrt4_conn_close(Connection);
1351   return RPC_S_OK;
1352 }
1353
1354 RPC_STATUS RPCRT4_CreateConnection(RpcConnection** Connection, BOOL server,
1355     LPCSTR Protseq, LPCSTR NetworkAddr, LPCSTR Endpoint,
1356     LPCWSTR NetworkOptions, RpcAuthInfo* AuthInfo, RpcQualityOfService *QOS)
1357 {
1358   const struct connection_ops *ops;
1359   RpcConnection* NewConnection;
1360
1361   ops = rpcrt4_get_conn_protseq_ops(Protseq);
1362   if (!ops)
1363   {
1364     FIXME("not supported for protseq %s\n", Protseq);
1365     return RPC_S_PROTSEQ_NOT_SUPPORTED;
1366   }
1367
1368   NewConnection = ops->alloc();
1369   NewConnection->Next = NULL;
1370   NewConnection->server = server;
1371   NewConnection->ops = ops;
1372   NewConnection->NetworkAddr = RPCRT4_strdupA(NetworkAddr);
1373   NewConnection->Endpoint = RPCRT4_strdupA(Endpoint);
1374   NewConnection->NetworkOptions = RPCRT4_strdupW(NetworkOptions);
1375   NewConnection->MaxTransmissionSize = RPC_MAX_PACKET_SIZE;
1376   memset(&NewConnection->ActiveInterface, 0, sizeof(NewConnection->ActiveInterface));
1377   NewConnection->NextCallId = 1;
1378
1379   SecInvalidateHandle(&NewConnection->ctx);
1380   memset(&NewConnection->exp, 0, sizeof(NewConnection->exp));
1381   NewConnection->attr = 0;
1382   if (AuthInfo) RpcAuthInfo_AddRef(AuthInfo);
1383   NewConnection->AuthInfo = AuthInfo;
1384   NewConnection->encryption_auth_len = 0;
1385   NewConnection->signature_auth_len = 0;
1386   if (QOS) RpcQualityOfService_AddRef(QOS);
1387   NewConnection->QOS = QOS;
1388
1389   list_init(&NewConnection->conn_pool_entry);
1390
1391   TRACE("connection: %p\n", NewConnection);
1392   *Connection = NewConnection;
1393
1394   return RPC_S_OK;
1395 }
1396
1397 RPC_STATUS RPCRT4_GetAssociation(LPCSTR Protseq, LPCSTR NetworkAddr,
1398                                  LPCSTR Endpoint, LPCWSTR NetworkOptions,
1399                                  RpcAssoc **assoc_out)
1400 {
1401   RpcAssoc *assoc;
1402
1403   EnterCriticalSection(&assoc_list_cs);
1404   LIST_FOR_EACH_ENTRY(assoc, &assoc_list, RpcAssoc, entry)
1405   {
1406     if (!strcmp(Protseq, assoc->Protseq) &&
1407         !strcmp(NetworkAddr, assoc->NetworkAddr) &&
1408         !strcmp(Endpoint, assoc->Endpoint) &&
1409         ((!assoc->NetworkOptions && !NetworkOptions) || !strcmpW(NetworkOptions, assoc->NetworkOptions)))
1410     {
1411       assoc->refs++;
1412       *assoc_out = assoc;
1413       LeaveCriticalSection(&assoc_list_cs);
1414       TRACE("using existing assoc %p\n", assoc);
1415       return RPC_S_OK;
1416     }
1417   }
1418
1419   assoc = HeapAlloc(GetProcessHeap(), 0, sizeof(*assoc));
1420   if (!assoc)
1421   {
1422     LeaveCriticalSection(&assoc_list_cs);
1423     return RPC_S_OUT_OF_RESOURCES;
1424   }
1425   assoc->refs = 1;
1426   list_init(&assoc->connection_pool);
1427   InitializeCriticalSection(&assoc->cs);
1428   assoc->Protseq = RPCRT4_strdupA(Protseq);
1429   assoc->NetworkAddr = RPCRT4_strdupA(NetworkAddr);
1430   assoc->Endpoint = RPCRT4_strdupA(Endpoint);
1431   assoc->NetworkOptions = NetworkOptions ? RPCRT4_strdupW(NetworkOptions) : NULL;
1432   assoc->assoc_group_id = 0;
1433   list_add_head(&assoc_list, &assoc->entry);
1434   *assoc_out = assoc;
1435
1436   LeaveCriticalSection(&assoc_list_cs);
1437
1438   TRACE("new assoc %p\n", assoc);
1439
1440   return RPC_S_OK;
1441 }
1442
1443 ULONG RpcAssoc_Release(RpcAssoc *assoc)
1444 {
1445   ULONG refs;
1446
1447   EnterCriticalSection(&assoc_list_cs);
1448   refs = --assoc->refs;
1449   if (!refs)
1450     list_remove(&assoc->entry);
1451   LeaveCriticalSection(&assoc_list_cs);
1452
1453   if (!refs)
1454   {
1455     RpcConnection *Connection, *cursor2;
1456
1457     TRACE("destroying assoc %p\n", assoc);
1458
1459     LIST_FOR_EACH_ENTRY_SAFE(Connection, cursor2, &assoc->connection_pool, RpcConnection, conn_pool_entry)
1460     {
1461       list_remove(&Connection->conn_pool_entry);
1462       RPCRT4_DestroyConnection(Connection);
1463     }
1464
1465     HeapFree(GetProcessHeap(), 0, assoc->NetworkOptions);
1466     HeapFree(GetProcessHeap(), 0, assoc->Endpoint);
1467     HeapFree(GetProcessHeap(), 0, assoc->NetworkAddr);
1468     HeapFree(GetProcessHeap(), 0, assoc->Protseq);
1469
1470     HeapFree(GetProcessHeap(), 0, assoc);
1471   }
1472
1473   return refs;
1474 }
1475
1476 static RPC_STATUS RpcAssoc_BindConnection(RpcAssoc *assoc, RpcConnection *conn,
1477                                           const RPC_SYNTAX_IDENTIFIER *InterfaceId,
1478                                           const RPC_SYNTAX_IDENTIFIER *TransferSyntax)
1479 {
1480   RpcPktHdr *hdr;
1481   RpcPktHdr *response_hdr;
1482   RPC_MESSAGE msg;
1483   RPC_STATUS status;
1484
1485   TRACE("sending bind request to server\n");
1486
1487   hdr = RPCRT4_BuildBindHeader(NDR_LOCAL_DATA_REPRESENTATION,
1488                                RPC_MAX_PACKET_SIZE, RPC_MAX_PACKET_SIZE,
1489                                assoc->assoc_group_id,
1490                                InterfaceId, TransferSyntax);
1491
1492   status = RPCRT4_Send(conn, hdr, NULL, 0);
1493   RPCRT4_FreeHeader(hdr);
1494   if (status != RPC_S_OK)
1495     return status;
1496
1497   status = RPCRT4_Receive(conn, &response_hdr, &msg);
1498   if (status != RPC_S_OK)
1499   {
1500     ERR("receive failed\n");
1501     return status;
1502   }
1503
1504   if (response_hdr->common.ptype != PKT_BIND_ACK)
1505   {
1506     ERR("failed to bind for interface %s, %d.%d\n",
1507       debugstr_guid(&InterfaceId->SyntaxGUID),
1508       InterfaceId->SyntaxVersion.MajorVersion,
1509       InterfaceId->SyntaxVersion.MinorVersion);
1510     RPCRT4_FreeHeader(response_hdr);
1511     return RPC_S_PROTOCOL_ERROR;
1512   }
1513
1514   /* FIXME: do more checks? */
1515
1516   conn->assoc_group_id = response_hdr->bind_ack.assoc_gid;
1517   conn->MaxTransmissionSize = response_hdr->bind_ack.max_tsize;
1518   conn->ActiveInterface = *InterfaceId;
1519   RPCRT4_FreeHeader(response_hdr);
1520   return RPC_S_OK;
1521 }
1522
1523 static RpcConnection *RpcAssoc_GetIdleConnection(RpcAssoc *assoc,
1524     const RPC_SYNTAX_IDENTIFIER *InterfaceId,
1525     const RPC_SYNTAX_IDENTIFIER *TransferSyntax, const RpcAuthInfo *AuthInfo,
1526     const RpcQualityOfService *QOS)
1527 {
1528   RpcConnection *Connection;
1529   EnterCriticalSection(&assoc->cs);
1530   /* try to find a compatible connection from the connection pool */
1531   LIST_FOR_EACH_ENTRY(Connection, &assoc->connection_pool, RpcConnection, conn_pool_entry)
1532   {
1533     if (!memcmp(&Connection->ActiveInterface, InterfaceId,
1534                 sizeof(RPC_SYNTAX_IDENTIFIER)) &&
1535         RpcAuthInfo_IsEqual(Connection->AuthInfo, AuthInfo) &&
1536         RpcQualityOfService_IsEqual(Connection->QOS, QOS))
1537     {
1538       list_remove(&Connection->conn_pool_entry);
1539       LeaveCriticalSection(&assoc->cs);
1540       TRACE("got connection from pool %p\n", Connection);
1541       return Connection;
1542     }
1543   }
1544
1545   LeaveCriticalSection(&assoc->cs);
1546   return NULL;
1547 }
1548
1549 RPC_STATUS RpcAssoc_GetClientConnection(RpcAssoc *assoc,
1550     const RPC_SYNTAX_IDENTIFIER *InterfaceId,
1551     const RPC_SYNTAX_IDENTIFIER *TransferSyntax, RpcAuthInfo *AuthInfo,
1552     RpcQualityOfService *QOS, RpcConnection **Connection)
1553 {
1554   RpcConnection *NewConnection;
1555   RPC_STATUS status;
1556
1557   *Connection = RpcAssoc_GetIdleConnection(assoc, InterfaceId, TransferSyntax, AuthInfo, QOS);
1558   if (*Connection)
1559     return RPC_S_OK;
1560
1561   /* create a new connection */
1562   status = RPCRT4_CreateConnection(&NewConnection, FALSE /* is this a server connection? */,
1563                                    assoc->Protseq, assoc->NetworkAddr,
1564                                    assoc->Endpoint, assoc->NetworkOptions,
1565                                    AuthInfo, QOS);
1566   if (status != RPC_S_OK)
1567     return status;
1568
1569   status = RPCRT4_OpenClientConnection(NewConnection);
1570   if (status != RPC_S_OK)
1571   {
1572     RPCRT4_DestroyConnection(NewConnection);
1573     return status;
1574   }
1575
1576   status = RpcAssoc_BindConnection(assoc, NewConnection, InterfaceId, TransferSyntax);
1577   if (status != RPC_S_OK)
1578   {
1579     RPCRT4_DestroyConnection(NewConnection);
1580     return status;
1581   }
1582
1583   *Connection = NewConnection;
1584
1585   return RPC_S_OK;
1586 }
1587
1588 void RpcAssoc_ReleaseIdleConnection(RpcAssoc *assoc, RpcConnection *Connection)
1589 {
1590   assert(!Connection->server);
1591   EnterCriticalSection(&assoc->cs);
1592   if (!assoc->assoc_group_id) assoc->assoc_group_id = Connection->assoc_group_id;
1593   list_add_head(&assoc->connection_pool, &Connection->conn_pool_entry);
1594   LeaveCriticalSection(&assoc->cs);
1595 }
1596
1597
1598 RPC_STATUS RPCRT4_SpawnConnection(RpcConnection** Connection, RpcConnection* OldConnection)
1599 {
1600   RPC_STATUS err;
1601
1602   err = RPCRT4_CreateConnection(Connection, OldConnection->server,
1603                                 rpcrt4_conn_get_name(OldConnection),
1604                                 OldConnection->NetworkAddr,
1605                                 OldConnection->Endpoint, NULL,
1606                                 OldConnection->AuthInfo, OldConnection->QOS);
1607   if (err == RPC_S_OK)
1608     rpcrt4_conn_handoff(OldConnection, *Connection);
1609   return err;
1610 }
1611
1612 RPC_STATUS RPCRT4_DestroyConnection(RpcConnection* Connection)
1613 {
1614   TRACE("connection: %p\n", Connection);
1615
1616   RPCRT4_CloseConnection(Connection);
1617   RPCRT4_strfree(Connection->Endpoint);
1618   RPCRT4_strfree(Connection->NetworkAddr);
1619   HeapFree(GetProcessHeap(), 0, Connection->NetworkOptions);
1620   if (Connection->AuthInfo) RpcAuthInfo_Release(Connection->AuthInfo);
1621   if (Connection->QOS) RpcQualityOfService_Release(Connection->QOS);
1622   HeapFree(GetProcessHeap(), 0, Connection);
1623   return RPC_S_OK;
1624 }
1625
1626 RPC_STATUS RpcTransport_GetTopOfTower(unsigned char *tower_data,
1627                                       size_t *tower_size,
1628                                       const char *protseq,
1629                                       const char *networkaddr,
1630                                       const char *endpoint)
1631 {
1632     twr_empty_floor_t *protocol_floor;
1633     const struct connection_ops *protseq_ops = rpcrt4_get_conn_protseq_ops(protseq);
1634
1635     *tower_size = 0;
1636
1637     if (!protseq_ops)
1638         return RPC_S_INVALID_RPC_PROTSEQ;
1639
1640     if (!tower_data)
1641     {
1642         *tower_size = sizeof(*protocol_floor);
1643         *tower_size += protseq_ops->get_top_of_tower(NULL, networkaddr, endpoint);
1644         return RPC_S_OK;
1645     }
1646
1647     protocol_floor = (twr_empty_floor_t *)tower_data;
1648     protocol_floor->count_lhs = sizeof(protocol_floor->protid);
1649     protocol_floor->protid = protseq_ops->epm_protocols[0];
1650     protocol_floor->count_rhs = 0;
1651
1652     tower_data += sizeof(*protocol_floor);
1653
1654     *tower_size = protseq_ops->get_top_of_tower(tower_data, networkaddr, endpoint);
1655     if (!*tower_size)
1656         return EPT_S_NOT_REGISTERED;
1657
1658     *tower_size += sizeof(*protocol_floor);
1659
1660     return RPC_S_OK;
1661 }
1662
1663 RPC_STATUS RpcTransport_ParseTopOfTower(const unsigned char *tower_data,
1664                                         size_t tower_size,
1665                                         char **protseq,
1666                                         char **networkaddr,
1667                                         char **endpoint)
1668 {
1669     const twr_empty_floor_t *protocol_floor;
1670     const twr_empty_floor_t *floor4;
1671     const struct connection_ops *protseq_ops = NULL;
1672     RPC_STATUS status;
1673     int i;
1674
1675     if (tower_size < sizeof(*protocol_floor))
1676         return EPT_S_NOT_REGISTERED;
1677
1678     protocol_floor = (const twr_empty_floor_t *)tower_data;
1679     tower_data += sizeof(*protocol_floor);
1680     tower_size -= sizeof(*protocol_floor);
1681     if ((protocol_floor->count_lhs != sizeof(protocol_floor->protid)) ||
1682         (protocol_floor->count_rhs > tower_size))
1683         return EPT_S_NOT_REGISTERED;
1684     tower_data += protocol_floor->count_rhs;
1685     tower_size -= protocol_floor->count_rhs;
1686
1687     floor4 = (const twr_empty_floor_t *)tower_data;
1688     if ((tower_size < sizeof(*floor4)) ||
1689         (floor4->count_lhs != sizeof(floor4->protid)))
1690         return EPT_S_NOT_REGISTERED;
1691
1692     for(i = 0; i < ARRAYSIZE(conn_protseq_list); i++)
1693         if ((protocol_floor->protid == conn_protseq_list[i].epm_protocols[0]) &&
1694             (floor4->protid == conn_protseq_list[i].epm_protocols[1]))
1695         {
1696             protseq_ops = &conn_protseq_list[i];
1697             break;
1698         }
1699
1700     if (!protseq_ops)
1701         return EPT_S_NOT_REGISTERED;
1702
1703     status = protseq_ops->parse_top_of_tower(tower_data, tower_size, networkaddr, endpoint);
1704
1705     if ((status == RPC_S_OK) && protseq)
1706     {
1707         *protseq = I_RpcAllocate(strlen(protseq_ops->name) + 1);
1708         strcpy(*protseq, protseq_ops->name);
1709     }
1710
1711     return status;
1712 }
1713
1714 /***********************************************************************
1715  *             RpcNetworkIsProtseqValidW (RPCRT4.@)
1716  *
1717  * Checks if the given protocol sequence is known by the RPC system.
1718  * If it is, returns RPC_S_OK, otherwise RPC_S_PROTSEQ_NOT_SUPPORTED.
1719  *
1720  */
1721 RPC_STATUS WINAPI RpcNetworkIsProtseqValidW(RPC_WSTR protseq)
1722 {
1723   char ps[0x10];
1724
1725   WideCharToMultiByte(CP_ACP, 0, protseq, -1,
1726                       ps, sizeof ps, NULL, NULL);
1727   if (rpcrt4_get_conn_protseq_ops(ps))
1728     return RPC_S_OK;
1729
1730   FIXME("Unknown protseq %s\n", debugstr_w(protseq));
1731
1732   return RPC_S_INVALID_RPC_PROTSEQ;
1733 }
1734
1735 /***********************************************************************
1736  *             RpcNetworkIsProtseqValidA (RPCRT4.@)
1737  */
1738 RPC_STATUS WINAPI RpcNetworkIsProtseqValidA(RPC_CSTR protseq)
1739 {
1740   UNICODE_STRING protseqW;
1741
1742   if (RtlCreateUnicodeStringFromAsciiz(&protseqW, (char*)protseq))
1743   {
1744     RPC_STATUS ret = RpcNetworkIsProtseqValidW(protseqW.Buffer);
1745     RtlFreeUnicodeString(&protseqW);
1746     return ret;
1747   }
1748   return RPC_S_OUT_OF_MEMORY;
1749 }