rpcrt4: EmbeddedPointerUnmarshall doesn't need to change the address of the allocated...
[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 void rpcrt4_conn_np_cancel_call(RpcConnection *Connection)
420 {
421     /* FIXME: implement when named pipe writes use overlapped I/O */
422 }
423
424 static size_t rpcrt4_ncacn_np_get_top_of_tower(unsigned char *tower_data,
425                                                const char *networkaddr,
426                                                const char *endpoint)
427 {
428     twr_empty_floor_t *smb_floor;
429     twr_empty_floor_t *nb_floor;
430     size_t size;
431     size_t networkaddr_size;
432     size_t endpoint_size;
433
434     TRACE("(%p, %s, %s)\n", tower_data, networkaddr, endpoint);
435
436     networkaddr_size = strlen(networkaddr) + 1;
437     endpoint_size = strlen(endpoint) + 1;
438     size = sizeof(*smb_floor) + endpoint_size + sizeof(*nb_floor) + networkaddr_size;
439
440     if (!tower_data)
441         return size;
442
443     smb_floor = (twr_empty_floor_t *)tower_data;
444
445     tower_data += sizeof(*smb_floor);
446
447     smb_floor->count_lhs = sizeof(smb_floor->protid);
448     smb_floor->protid = EPM_PROTOCOL_SMB;
449     smb_floor->count_rhs = endpoint_size;
450
451     memcpy(tower_data, endpoint, endpoint_size);
452     tower_data += endpoint_size;
453
454     nb_floor = (twr_empty_floor_t *)tower_data;
455
456     tower_data += sizeof(*nb_floor);
457
458     nb_floor->count_lhs = sizeof(nb_floor->protid);
459     nb_floor->protid = EPM_PROTOCOL_NETBIOS;
460     nb_floor->count_rhs = networkaddr_size;
461
462     memcpy(tower_data, networkaddr, networkaddr_size);
463     tower_data += networkaddr_size;
464
465     return size;
466 }
467
468 static RPC_STATUS rpcrt4_ncacn_np_parse_top_of_tower(const unsigned char *tower_data,
469                                                      size_t tower_size,
470                                                      char **networkaddr,
471                                                      char **endpoint)
472 {
473     const twr_empty_floor_t *smb_floor = (const twr_empty_floor_t *)tower_data;
474     const twr_empty_floor_t *nb_floor;
475
476     TRACE("(%p, %d, %p, %p)\n", tower_data, (int)tower_size, networkaddr, endpoint);
477
478     if (tower_size < sizeof(*smb_floor))
479         return EPT_S_NOT_REGISTERED;
480
481     tower_data += sizeof(*smb_floor);
482     tower_size -= sizeof(*smb_floor);
483
484     if ((smb_floor->count_lhs != sizeof(smb_floor->protid)) ||
485         (smb_floor->protid != EPM_PROTOCOL_SMB) ||
486         (smb_floor->count_rhs > tower_size))
487         return EPT_S_NOT_REGISTERED;
488
489     if (endpoint)
490     {
491         *endpoint = I_RpcAllocate(smb_floor->count_rhs);
492         if (!*endpoint)
493             return RPC_S_OUT_OF_RESOURCES;
494         memcpy(*endpoint, tower_data, smb_floor->count_rhs);
495     }
496     tower_data += smb_floor->count_rhs;
497     tower_size -= smb_floor->count_rhs;
498
499     if (tower_size < sizeof(*nb_floor))
500         return EPT_S_NOT_REGISTERED;
501
502     nb_floor = (const twr_empty_floor_t *)tower_data;
503
504     tower_data += sizeof(*nb_floor);
505     tower_size -= sizeof(*nb_floor);
506
507     if ((nb_floor->count_lhs != sizeof(nb_floor->protid)) ||
508         (nb_floor->protid != EPM_PROTOCOL_NETBIOS) ||
509         (nb_floor->count_rhs > tower_size))
510         return EPT_S_NOT_REGISTERED;
511
512     if (networkaddr)
513     {
514         *networkaddr = I_RpcAllocate(nb_floor->count_rhs);
515         if (!*networkaddr)
516         {
517             if (endpoint)
518             {
519                 I_RpcFree(*endpoint);
520                 *endpoint = NULL;
521             }
522             return RPC_S_OUT_OF_RESOURCES;
523         }
524         memcpy(*networkaddr, tower_data, nb_floor->count_rhs);
525     }
526
527     return RPC_S_OK;
528 }
529
530 typedef struct _RpcServerProtseq_np
531 {
532     RpcServerProtseq common;
533     HANDLE mgr_event;
534 } RpcServerProtseq_np;
535
536 static RpcServerProtseq *rpcrt4_protseq_np_alloc(void)
537 {
538     RpcServerProtseq_np *ps = HeapAlloc(GetProcessHeap(), 0, sizeof(*ps));
539     if (ps)
540         ps->mgr_event = CreateEventW(NULL, FALSE, FALSE, NULL);
541     return &ps->common;
542 }
543
544 static void rpcrt4_protseq_np_signal_state_changed(RpcServerProtseq *protseq)
545 {
546     RpcServerProtseq_np *npps = CONTAINING_RECORD(protseq, RpcServerProtseq_np, common);
547     SetEvent(npps->mgr_event);
548 }
549
550 static void *rpcrt4_protseq_np_get_wait_array(RpcServerProtseq *protseq, void *prev_array, unsigned int *count)
551 {
552     HANDLE *objs = prev_array;
553     RpcConnection_np *conn;
554     RpcServerProtseq_np *npps = CONTAINING_RECORD(protseq, RpcServerProtseq_np, common);
555     
556     EnterCriticalSection(&protseq->cs);
557     
558     /* open and count connections */
559     *count = 1;
560     conn = CONTAINING_RECORD(protseq->conn, RpcConnection_np, common);
561     while (conn) {
562         rpcrt4_conn_listen_pipe(conn);
563         if (conn->ovl.hEvent)
564             (*count)++;
565         conn = CONTAINING_RECORD(conn->common.Next, RpcConnection_np, common);
566     }
567     
568     /* make array of connections */
569     if (objs)
570         objs = HeapReAlloc(GetProcessHeap(), 0, objs, *count*sizeof(HANDLE));
571     else
572         objs = HeapAlloc(GetProcessHeap(), 0, *count*sizeof(HANDLE));
573     if (!objs)
574     {
575         ERR("couldn't allocate objs\n");
576         LeaveCriticalSection(&protseq->cs);
577         return NULL;
578     }
579     
580     objs[0] = npps->mgr_event;
581     *count = 1;
582     conn = CONTAINING_RECORD(protseq->conn, RpcConnection_np, common);
583     while (conn) {
584         if ((objs[*count] = conn->ovl.hEvent))
585             (*count)++;
586         conn = CONTAINING_RECORD(conn->common.Next, RpcConnection_np, common);
587     }
588     LeaveCriticalSection(&protseq->cs);
589     return objs;
590 }
591
592 static void rpcrt4_protseq_np_free_wait_array(RpcServerProtseq *protseq, void *array)
593 {
594     HeapFree(GetProcessHeap(), 0, array);
595 }
596
597 static int rpcrt4_protseq_np_wait_for_new_connection(RpcServerProtseq *protseq, unsigned int count, void *wait_array)
598 {
599     HANDLE b_handle;
600     HANDLE *objs = wait_array;
601     DWORD res;
602     RpcConnection *cconn;
603     RpcConnection_np *conn;
604     
605     if (!objs)
606         return -1;
607     
608     res = WaitForMultipleObjects(count, objs, FALSE, INFINITE);
609     if (res == WAIT_OBJECT_0)
610         return 0;
611     else if (res == WAIT_FAILED)
612     {
613         ERR("wait failed with error %d\n", GetLastError());
614         return -1;
615     }
616     else
617     {
618         b_handle = objs[res - WAIT_OBJECT_0];
619         /* find which connection got a RPC */
620         EnterCriticalSection(&protseq->cs);
621         conn = CONTAINING_RECORD(protseq->conn, RpcConnection_np, common);
622         while (conn) {
623             if (b_handle == conn->ovl.hEvent) break;
624             conn = CONTAINING_RECORD(conn->common.Next, RpcConnection_np, common);
625         }
626         cconn = NULL;
627         if (conn)
628             RPCRT4_SpawnConnection(&cconn, &conn->common);
629         else
630             ERR("failed to locate connection for handle %p\n", b_handle);
631         LeaveCriticalSection(&protseq->cs);
632         if (cconn)
633         {
634             RPCRT4_new_client(cconn);
635             return 1;
636         }
637         else return -1;
638     }
639 }
640
641 static size_t rpcrt4_ncalrpc_get_top_of_tower(unsigned char *tower_data,
642                                               const char *networkaddr,
643                                               const char *endpoint)
644 {
645     twr_empty_floor_t *pipe_floor;
646     size_t size;
647     size_t endpoint_size;
648
649     TRACE("(%p, %s, %s)\n", tower_data, networkaddr, endpoint);
650
651     endpoint_size = strlen(networkaddr) + 1;
652     size = sizeof(*pipe_floor) + endpoint_size;
653
654     if (!tower_data)
655         return size;
656
657     pipe_floor = (twr_empty_floor_t *)tower_data;
658
659     tower_data += sizeof(*pipe_floor);
660
661     pipe_floor->count_lhs = sizeof(pipe_floor->protid);
662     pipe_floor->protid = EPM_PROTOCOL_SMB;
663     pipe_floor->count_rhs = endpoint_size;
664
665     memcpy(tower_data, endpoint, endpoint_size);
666     tower_data += endpoint_size;
667
668     return size;
669 }
670
671 static RPC_STATUS rpcrt4_ncalrpc_parse_top_of_tower(const unsigned char *tower_data,
672                                                     size_t tower_size,
673                                                     char **networkaddr,
674                                                     char **endpoint)
675 {
676     const twr_empty_floor_t *pipe_floor = (const twr_empty_floor_t *)tower_data;
677
678     TRACE("(%p, %d, %p, %p)\n", tower_data, (int)tower_size, networkaddr, endpoint);
679
680     *networkaddr = NULL;
681     *endpoint = NULL;
682
683     if (tower_size < sizeof(*pipe_floor))
684         return EPT_S_NOT_REGISTERED;
685
686     tower_data += sizeof(*pipe_floor);
687     tower_size -= sizeof(*pipe_floor);
688
689     if ((pipe_floor->count_lhs != sizeof(pipe_floor->protid)) ||
690         (pipe_floor->protid != EPM_PROTOCOL_SMB) ||
691         (pipe_floor->count_rhs > tower_size))
692         return EPT_S_NOT_REGISTERED;
693
694     if (endpoint)
695     {
696         *endpoint = I_RpcAllocate(pipe_floor->count_rhs);
697         if (!*endpoint)
698             return RPC_S_OUT_OF_RESOURCES;
699         memcpy(*endpoint, tower_data, pipe_floor->count_rhs);
700     }
701
702     return RPC_S_OK;
703 }
704
705 /**** ncacn_ip_tcp support ****/
706
707 typedef struct _RpcConnection_tcp
708 {
709   RpcConnection common;
710   int sock;
711   int cancel_fds[2];
712 } RpcConnection_tcp;
713
714 static RpcConnection *rpcrt4_conn_tcp_alloc(void)
715 {
716   RpcConnection_tcp *tcpc;
717   tcpc = HeapAlloc(GetProcessHeap(), 0, sizeof(RpcConnection_tcp));
718   if (tcpc == NULL)
719     return NULL;
720   tcpc->sock = -1;
721   if (socketpair(PF_UNIX, SOCK_STREAM, 0, tcpc->cancel_fds) < 0)
722   {
723     ERR("socketpair() failed: %s\n", strerror(errno));
724     HeapFree(GetProcessHeap(), 0, tcpc);
725     return NULL;
726   }
727   return &tcpc->common;
728 }
729
730 static RPC_STATUS rpcrt4_ncacn_ip_tcp_open(RpcConnection* Connection)
731 {
732   RpcConnection_tcp *tcpc = (RpcConnection_tcp *) Connection;
733   int sock;
734   int ret;
735   struct addrinfo *ai;
736   struct addrinfo *ai_cur;
737   struct addrinfo hints;
738
739   TRACE("(%s, %s)\n", Connection->NetworkAddr, Connection->Endpoint);
740
741   if (tcpc->sock != -1)
742     return RPC_S_OK;
743
744   hints.ai_flags          = 0;
745   hints.ai_family         = PF_UNSPEC;
746   hints.ai_socktype       = SOCK_STREAM;
747   hints.ai_protocol       = IPPROTO_TCP;
748   hints.ai_addrlen        = 0;
749   hints.ai_addr           = NULL;
750   hints.ai_canonname      = NULL;
751   hints.ai_next           = NULL;
752
753   ret = getaddrinfo(Connection->NetworkAddr, Connection->Endpoint, &hints, &ai);
754   if (ret)
755   {
756     ERR("getaddrinfo for %s:%s failed: %s\n", Connection->NetworkAddr,
757       Connection->Endpoint, gai_strerror(ret));
758     return RPC_S_SERVER_UNAVAILABLE;
759   }
760
761   for (ai_cur = ai; ai_cur; ai_cur = ai_cur->ai_next)
762   {
763     int val;
764
765     if (TRACE_ON(rpc))
766     {
767       char host[256];
768       char service[256];
769       getnameinfo(ai_cur->ai_addr, ai_cur->ai_addrlen,
770         host, sizeof(host), service, sizeof(service),
771         NI_NUMERICHOST | NI_NUMERICSERV);
772       TRACE("trying %s:%s\n", host, service);
773     }
774
775     sock = socket(ai_cur->ai_family, ai_cur->ai_socktype, ai_cur->ai_protocol);
776     if (sock == -1)
777     {
778       WARN("socket() failed: %s\n", strerror(errno));
779       continue;
780     }
781
782     if (0>connect(sock, ai_cur->ai_addr, ai_cur->ai_addrlen))
783     {
784       WARN("connect() failed: %s\n", strerror(errno));
785       close(sock);
786       continue;
787     }
788
789     /* RPC depends on having minimal latency so disable the Nagle algorithm */
790     val = 1;
791     setsockopt(sock, SOL_TCP, TCP_NODELAY, &val, sizeof(val));
792     fcntl(sock, F_SETFL, O_NONBLOCK); /* make socket nonblocking */
793
794     tcpc->sock = sock;
795
796     freeaddrinfo(ai);
797     TRACE("connected\n");
798     return RPC_S_OK;
799   }
800
801   freeaddrinfo(ai);
802   ERR("couldn't connect to %s:%s\n", Connection->NetworkAddr, Connection->Endpoint);
803   return RPC_S_SERVER_UNAVAILABLE;
804 }
805
806 static RPC_STATUS rpcrt4_protseq_ncacn_ip_tcp_open_endpoint(RpcServerProtseq *protseq, LPSTR endpoint)
807 {
808     RPC_STATUS status = RPC_S_CANT_CREATE_ENDPOINT;
809     int sock;
810     int ret;
811     struct addrinfo *ai;
812     struct addrinfo *ai_cur;
813     struct addrinfo hints;
814     RpcConnection *first_connection = NULL;
815
816     TRACE("(%p, %s)\n", protseq, endpoint);
817
818     hints.ai_flags          = AI_PASSIVE /* for non-localhost addresses */;
819     hints.ai_family         = PF_UNSPEC;
820     hints.ai_socktype       = SOCK_STREAM;
821     hints.ai_protocol       = IPPROTO_TCP;
822     hints.ai_addrlen        = 0;
823     hints.ai_addr           = NULL;
824     hints.ai_canonname      = NULL;
825     hints.ai_next           = NULL;
826
827     ret = getaddrinfo(NULL, endpoint, &hints, &ai);
828     if (ret)
829     {
830         ERR("getaddrinfo for port %s failed: %s\n", endpoint,
831             gai_strerror(ret));
832         if ((ret == EAI_SERVICE) || (ret == EAI_NONAME))
833             return RPC_S_INVALID_ENDPOINT_FORMAT;
834         return RPC_S_CANT_CREATE_ENDPOINT;
835     }
836
837     for (ai_cur = ai; ai_cur; ai_cur = ai_cur->ai_next)
838     {
839         RpcConnection_tcp *tcpc;
840         RPC_STATUS create_status;
841
842         if (TRACE_ON(rpc))
843         {
844             char host[256];
845             char service[256];
846             getnameinfo(ai_cur->ai_addr, ai_cur->ai_addrlen,
847                         host, sizeof(host), service, sizeof(service),
848                         NI_NUMERICHOST | NI_NUMERICSERV);
849             TRACE("trying %s:%s\n", host, service);
850         }
851
852         sock = socket(ai_cur->ai_family, ai_cur->ai_socktype, ai_cur->ai_protocol);
853         if (sock == -1)
854         {
855             WARN("socket() failed: %s\n", strerror(errno));
856             status = RPC_S_CANT_CREATE_ENDPOINT;
857             continue;
858         }
859
860         ret = bind(sock, ai_cur->ai_addr, ai_cur->ai_addrlen);
861         if (ret < 0)
862         {
863             WARN("bind failed: %s\n", strerror(errno));
864             close(sock);
865             if (errno == EADDRINUSE)
866               status = RPC_S_DUPLICATE_ENDPOINT;
867             else
868               status = RPC_S_CANT_CREATE_ENDPOINT;
869             continue;
870         }
871         create_status = RPCRT4_CreateConnection((RpcConnection **)&tcpc, TRUE,
872                                                 protseq->Protseq, NULL,
873                                                 endpoint, NULL, NULL, NULL);
874         if (create_status != RPC_S_OK)
875         {
876             close(sock);
877             status = create_status;
878             continue;
879         }
880
881         tcpc->sock = sock;
882         ret = listen(sock, protseq->MaxCalls);
883         if (ret < 0)
884         {
885             WARN("listen failed: %s\n", strerror(errno));
886             RPCRT4_DestroyConnection(&tcpc->common);
887             status = RPC_S_OUT_OF_RESOURCES;
888             continue;
889         }
890         /* need a non-blocking socket, otherwise accept() has a potential
891          * race-condition (poll() says it is readable, connection drops,
892          * and accept() blocks until the next connection comes...)
893          */
894         ret = fcntl(sock, F_SETFL, O_NONBLOCK);
895         if (ret < 0)
896         {
897             WARN("couldn't make socket non-blocking, error %d\n", ret);
898             RPCRT4_DestroyConnection(&tcpc->common);
899             status = RPC_S_OUT_OF_RESOURCES;
900             continue;
901         }
902
903         tcpc->common.Next = first_connection;
904         first_connection = &tcpc->common;
905     }
906
907     freeaddrinfo(ai);
908
909     /* if at least one connection was created for an endpoint then
910      * return success */
911     if (first_connection)
912     {
913         RpcConnection *conn;
914
915         /* find last element in list */
916         for (conn = first_connection; conn->Next; conn = conn->Next)
917             ;
918
919         EnterCriticalSection(&protseq->cs);
920         conn->Next = protseq->conn;
921         protseq->conn = first_connection;
922         LeaveCriticalSection(&protseq->cs);
923         
924         TRACE("listening on %s\n", endpoint);
925         return RPC_S_OK;
926     }
927
928     ERR("couldn't listen on port %s\n", endpoint);
929     return status;
930 }
931
932 static RPC_STATUS rpcrt4_conn_tcp_handoff(RpcConnection *old_conn, RpcConnection *new_conn)
933 {
934   int ret;
935   struct sockaddr_in address;
936   socklen_t addrsize;
937   RpcConnection_tcp *server = (RpcConnection_tcp*) old_conn;
938   RpcConnection_tcp *client = (RpcConnection_tcp*) new_conn;
939
940   addrsize = sizeof(address);
941   ret = accept(server->sock, (struct sockaddr*) &address, &addrsize);
942   if (ret < 0)
943   {
944     ERR("Failed to accept a TCP connection: error %d\n", ret);
945     return RPC_S_OUT_OF_RESOURCES;
946   }
947   /* reset to blocking behaviour */
948   fcntl(ret, F_SETFL, 0);
949   client->sock = ret;
950   TRACE("Accepted a new TCP connection\n");
951   return RPC_S_OK;
952 }
953
954 static int rpcrt4_conn_tcp_read(RpcConnection *Connection,
955                                 void *buffer, unsigned int count)
956 {
957   RpcConnection_tcp *tcpc = (RpcConnection_tcp *) Connection;
958   int bytes_read = 0;
959   do
960   {
961     int r = recv(tcpc->sock, (char *)buffer + bytes_read, count - bytes_read, 0);
962     if (r >= 0)
963       bytes_read += r;
964     else if (errno != EAGAIN)
965       return -1;
966     else
967     {
968       struct pollfd pfds[2];
969       pfds[0].fd = tcpc->sock;
970       pfds[0].events = POLLIN;
971       pfds[1].fd = tcpc->cancel_fds[0];
972       pfds[1].fd = POLLIN;
973       if (poll(pfds, 2, -1 /* infinite */) == -1 && errno != EINTR)
974       {
975         ERR("poll() failed: %s\n", strerror(errno));
976         return -1;
977       }
978       if (pfds[1].revents & POLLIN) /* canceled */
979       {
980         char dummy;
981         read(pfds[1].fd, &dummy, sizeof(dummy));
982         return -1;
983       }
984     }
985   } while (bytes_read != count);
986   TRACE("%d %p %u -> %d\n", tcpc->sock, buffer, count, bytes_read);
987   return bytes_read;
988 }
989
990 static int rpcrt4_conn_tcp_write(RpcConnection *Connection,
991                                  const void *buffer, unsigned int count)
992 {
993   RpcConnection_tcp *tcpc = (RpcConnection_tcp *) Connection;
994   int bytes_written = 0;
995   do
996   {
997     int r = write(tcpc->sock, (const char *)buffer + bytes_written, count - bytes_written);
998     if (r >= 0)
999       bytes_written += r;
1000     else if (errno != EAGAIN)
1001       return -1;
1002     else
1003     {
1004       struct pollfd pfd;
1005       pfd.fd = tcpc->sock;
1006       pfd.events = POLLOUT;
1007       if (poll(&pfd, 1, -1 /* infinite */) == -1 && errno != EINTR)
1008       {
1009         ERR("poll() failed: %s\n", strerror(errno));
1010         return -1;
1011       }
1012     }
1013   } while (bytes_written != count);
1014   TRACE("%d %p %u -> %d\n", tcpc->sock, buffer, count, bytes_written);
1015   return bytes_written;
1016 }
1017
1018 static int rpcrt4_conn_tcp_close(RpcConnection *Connection)
1019 {
1020   RpcConnection_tcp *tcpc = (RpcConnection_tcp *) Connection;
1021
1022   TRACE("%d\n", tcpc->sock);
1023
1024   if (tcpc->sock != -1)
1025     close(tcpc->sock);
1026   tcpc->sock = -1;
1027   close(tcpc->cancel_fds[0]);
1028   close(tcpc->cancel_fds[1]);
1029   return 0;
1030 }
1031
1032 static void rpcrt4_conn_tcp_cancel_call(RpcConnection *Connection)
1033 {
1034     RpcConnection_tcp *tcpc = (RpcConnection_tcp *) Connection;
1035     char dummy = 1;
1036
1037     TRACE("%p\n", Connection);
1038
1039     write(tcpc->cancel_fds[1], &dummy, 1);
1040 }
1041
1042 static size_t rpcrt4_ncacn_ip_tcp_get_top_of_tower(unsigned char *tower_data,
1043                                                    const char *networkaddr,
1044                                                    const char *endpoint)
1045 {
1046     twr_tcp_floor_t *tcp_floor;
1047     twr_ipv4_floor_t *ipv4_floor;
1048     struct addrinfo *ai;
1049     struct addrinfo hints;
1050     int ret;
1051     size_t size = sizeof(*tcp_floor) + sizeof(*ipv4_floor);
1052
1053     TRACE("(%p, %s, %s)\n", tower_data, networkaddr, endpoint);
1054
1055     if (!tower_data)
1056         return size;
1057
1058     tcp_floor = (twr_tcp_floor_t *)tower_data;
1059     tower_data += sizeof(*tcp_floor);
1060
1061     ipv4_floor = (twr_ipv4_floor_t *)tower_data;
1062
1063     tcp_floor->count_lhs = sizeof(tcp_floor->protid);
1064     tcp_floor->protid = EPM_PROTOCOL_TCP;
1065     tcp_floor->count_rhs = sizeof(tcp_floor->port);
1066
1067     ipv4_floor->count_lhs = sizeof(ipv4_floor->protid);
1068     ipv4_floor->protid = EPM_PROTOCOL_IP;
1069     ipv4_floor->count_rhs = sizeof(ipv4_floor->ipv4addr);
1070
1071     hints.ai_flags          = AI_NUMERICHOST;
1072     /* FIXME: only support IPv4 at the moment. how is IPv6 represented by the EPM? */
1073     hints.ai_family         = PF_INET;
1074     hints.ai_socktype       = SOCK_STREAM;
1075     hints.ai_protocol       = IPPROTO_TCP;
1076     hints.ai_addrlen        = 0;
1077     hints.ai_addr           = NULL;
1078     hints.ai_canonname      = NULL;
1079     hints.ai_next           = NULL;
1080
1081     ret = getaddrinfo(networkaddr, endpoint, &hints, &ai);
1082     if (ret)
1083     {
1084         ret = getaddrinfo("0.0.0.0", endpoint, &hints, &ai);
1085         if (ret)
1086         {
1087             ERR("getaddrinfo failed: %s\n", gai_strerror(ret));
1088             return 0;
1089         }
1090     }
1091
1092     if (ai->ai_family == PF_INET)
1093     {
1094         const struct sockaddr_in *sin = (const struct sockaddr_in *)ai->ai_addr;
1095         tcp_floor->port = sin->sin_port;
1096         ipv4_floor->ipv4addr = sin->sin_addr.s_addr;
1097     }
1098     else
1099     {
1100         ERR("unexpected protocol family %d\n", ai->ai_family);
1101         return 0;
1102     }
1103
1104     freeaddrinfo(ai);
1105
1106     return size;
1107 }
1108
1109 static RPC_STATUS rpcrt4_ncacn_ip_tcp_parse_top_of_tower(const unsigned char *tower_data,
1110                                                          size_t tower_size,
1111                                                          char **networkaddr,
1112                                                          char **endpoint)
1113 {
1114     const twr_tcp_floor_t *tcp_floor = (const twr_tcp_floor_t *)tower_data;
1115     const twr_ipv4_floor_t *ipv4_floor;
1116     struct in_addr in_addr;
1117
1118     TRACE("(%p, %d, %p, %p)\n", tower_data, (int)tower_size, networkaddr, endpoint);
1119
1120     if (tower_size < sizeof(*tcp_floor))
1121         return EPT_S_NOT_REGISTERED;
1122
1123     tower_data += sizeof(*tcp_floor);
1124     tower_size -= sizeof(*tcp_floor);
1125
1126     if (tower_size < sizeof(*ipv4_floor))
1127         return EPT_S_NOT_REGISTERED;
1128
1129     ipv4_floor = (const twr_ipv4_floor_t *)tower_data;
1130
1131     if ((tcp_floor->count_lhs != sizeof(tcp_floor->protid)) ||
1132         (tcp_floor->protid != EPM_PROTOCOL_TCP) ||
1133         (tcp_floor->count_rhs != sizeof(tcp_floor->port)) ||
1134         (ipv4_floor->count_lhs != sizeof(ipv4_floor->protid)) ||
1135         (ipv4_floor->protid != EPM_PROTOCOL_IP) ||
1136         (ipv4_floor->count_rhs != sizeof(ipv4_floor->ipv4addr)))
1137         return EPT_S_NOT_REGISTERED;
1138
1139     if (endpoint)
1140     {
1141         *endpoint = I_RpcAllocate(6 /* sizeof("65535") + 1 */);
1142         if (!*endpoint)
1143             return RPC_S_OUT_OF_RESOURCES;
1144         sprintf(*endpoint, "%u", ntohs(tcp_floor->port));
1145     }
1146
1147     if (networkaddr)
1148     {
1149         *networkaddr = I_RpcAllocate(INET_ADDRSTRLEN);
1150         if (!*networkaddr)
1151         {
1152             if (endpoint)
1153             {
1154                 I_RpcFree(*endpoint);
1155                 *endpoint = NULL;
1156             }
1157             return RPC_S_OUT_OF_RESOURCES;
1158         }
1159         in_addr.s_addr = ipv4_floor->ipv4addr;
1160         if (!inet_ntop(AF_INET, &in_addr, *networkaddr, INET_ADDRSTRLEN))
1161         {
1162             ERR("inet_ntop: %s\n", strerror(errno));
1163             I_RpcFree(*networkaddr);
1164             *networkaddr = NULL;
1165             if (endpoint)
1166             {
1167                 I_RpcFree(*endpoint);
1168                 *endpoint = NULL;
1169             }
1170             return EPT_S_NOT_REGISTERED;
1171         }
1172     }
1173
1174     return RPC_S_OK;
1175 }
1176
1177 typedef struct _RpcServerProtseq_sock
1178 {
1179     RpcServerProtseq common;
1180     int mgr_event_rcv;
1181     int mgr_event_snd;
1182 } RpcServerProtseq_sock;
1183
1184 static RpcServerProtseq *rpcrt4_protseq_sock_alloc(void)
1185 {
1186     RpcServerProtseq_sock *ps = HeapAlloc(GetProcessHeap(), 0, sizeof(*ps));
1187     if (ps)
1188     {
1189         int fds[2];
1190         if (!socketpair(PF_UNIX, SOCK_DGRAM, 0, fds))
1191         {
1192             fcntl(fds[0], F_SETFL, O_NONBLOCK);
1193             fcntl(fds[1], F_SETFL, O_NONBLOCK);
1194             ps->mgr_event_rcv = fds[0];
1195             ps->mgr_event_snd = fds[1];
1196         }
1197         else
1198         {
1199             ERR("socketpair failed with error %s\n", strerror(errno));
1200             HeapFree(GetProcessHeap(), 0, ps);
1201             return NULL;
1202         }
1203     }
1204     return &ps->common;
1205 }
1206
1207 static void rpcrt4_protseq_sock_signal_state_changed(RpcServerProtseq *protseq)
1208 {
1209     RpcServerProtseq_sock *sockps = CONTAINING_RECORD(protseq, RpcServerProtseq_sock, common);
1210     char dummy = 1;
1211     write(sockps->mgr_event_snd, &dummy, sizeof(dummy));
1212 }
1213
1214 static void *rpcrt4_protseq_sock_get_wait_array(RpcServerProtseq *protseq, void *prev_array, unsigned int *count)
1215 {
1216     struct pollfd *poll_info = prev_array;
1217     RpcConnection_tcp *conn;
1218     RpcServerProtseq_sock *sockps = CONTAINING_RECORD(protseq, RpcServerProtseq_sock, common);
1219
1220     EnterCriticalSection(&protseq->cs);
1221     
1222     /* open and count connections */
1223     *count = 1;
1224     conn = (RpcConnection_tcp *)protseq->conn;
1225     while (conn) {
1226         if (conn->sock != -1)
1227             (*count)++;
1228         conn = (RpcConnection_tcp *)conn->common.Next;
1229     }
1230     
1231     /* make array of connections */
1232     if (poll_info)
1233         poll_info = HeapReAlloc(GetProcessHeap(), 0, poll_info, *count*sizeof(*poll_info));
1234     else
1235         poll_info = HeapAlloc(GetProcessHeap(), 0, *count*sizeof(*poll_info));
1236     if (!poll_info)
1237     {
1238         ERR("couldn't allocate poll_info\n");
1239         LeaveCriticalSection(&protseq->cs);
1240         return NULL;
1241     }
1242
1243     poll_info[0].fd = sockps->mgr_event_rcv;
1244     poll_info[0].events = POLLIN;
1245     *count = 1;
1246     conn =  CONTAINING_RECORD(protseq->conn, RpcConnection_tcp, common);
1247     while (conn) {
1248         if (conn->sock != -1)
1249         {
1250             poll_info[*count].fd = conn->sock;
1251             poll_info[*count].events = POLLIN;
1252             (*count)++;
1253         }
1254         conn = CONTAINING_RECORD(conn->common.Next, RpcConnection_tcp, common);
1255     }
1256     LeaveCriticalSection(&protseq->cs);
1257     return poll_info;
1258 }
1259
1260 static void rpcrt4_protseq_sock_free_wait_array(RpcServerProtseq *protseq, void *array)
1261 {
1262     HeapFree(GetProcessHeap(), 0, array);
1263 }
1264
1265 static int rpcrt4_protseq_sock_wait_for_new_connection(RpcServerProtseq *protseq, unsigned int count, void *wait_array)
1266 {
1267     struct pollfd *poll_info = wait_array;
1268     int ret, i;
1269     RpcConnection *cconn;
1270     RpcConnection_tcp *conn;
1271     
1272     if (!poll_info)
1273         return -1;
1274     
1275     ret = poll(poll_info, count, -1);
1276     if (ret < 0)
1277     {
1278         ERR("poll failed with error %d\n", ret);
1279         return -1;
1280     }
1281
1282     for (i = 0; i < count; i++)
1283         if (poll_info[i].revents & POLLIN)
1284         {
1285             /* RPC server event */
1286             if (i == 0)
1287             {
1288                 char dummy;
1289                 read(poll_info[0].fd, &dummy, sizeof(dummy));
1290                 return 0;
1291             }
1292
1293             /* find which connection got a RPC */
1294             EnterCriticalSection(&protseq->cs);
1295             conn = CONTAINING_RECORD(protseq->conn, RpcConnection_tcp, common);
1296             while (conn) {
1297                 if (poll_info[i].fd == conn->sock) break;
1298                 conn = CONTAINING_RECORD(conn->common.Next, RpcConnection_tcp, common);
1299             }
1300             cconn = NULL;
1301             if (conn)
1302                 RPCRT4_SpawnConnection(&cconn, &conn->common);
1303             else
1304                 ERR("failed to locate connection for fd %d\n", poll_info[i].fd);
1305             LeaveCriticalSection(&protseq->cs);
1306             if (cconn)
1307                 RPCRT4_new_client(cconn);
1308             else
1309                 return -1;
1310         }
1311
1312     return 1;
1313 }
1314
1315 static const struct connection_ops conn_protseq_list[] = {
1316   { "ncacn_np",
1317     { EPM_PROTOCOL_NCACN, EPM_PROTOCOL_SMB },
1318     rpcrt4_conn_np_alloc,
1319     rpcrt4_ncacn_np_open,
1320     rpcrt4_ncacn_np_handoff,
1321     rpcrt4_conn_np_read,
1322     rpcrt4_conn_np_write,
1323     rpcrt4_conn_np_close,
1324     rpcrt4_conn_np_cancel_call,
1325     rpcrt4_ncacn_np_get_top_of_tower,
1326     rpcrt4_ncacn_np_parse_top_of_tower,
1327   },
1328   { "ncalrpc",
1329     { EPM_PROTOCOL_NCALRPC, EPM_PROTOCOL_PIPE },
1330     rpcrt4_conn_np_alloc,
1331     rpcrt4_ncalrpc_open,
1332     rpcrt4_ncalrpc_handoff,
1333     rpcrt4_conn_np_read,
1334     rpcrt4_conn_np_write,
1335     rpcrt4_conn_np_close,
1336     rpcrt4_conn_np_cancel_call,
1337     rpcrt4_ncalrpc_get_top_of_tower,
1338     rpcrt4_ncalrpc_parse_top_of_tower,
1339   },
1340   { "ncacn_ip_tcp",
1341     { EPM_PROTOCOL_NCACN, EPM_PROTOCOL_TCP },
1342     rpcrt4_conn_tcp_alloc,
1343     rpcrt4_ncacn_ip_tcp_open,
1344     rpcrt4_conn_tcp_handoff,
1345     rpcrt4_conn_tcp_read,
1346     rpcrt4_conn_tcp_write,
1347     rpcrt4_conn_tcp_close,
1348     rpcrt4_conn_tcp_cancel_call,
1349     rpcrt4_ncacn_ip_tcp_get_top_of_tower,
1350     rpcrt4_ncacn_ip_tcp_parse_top_of_tower,
1351   }
1352 };
1353
1354
1355 static const struct protseq_ops protseq_list[] =
1356 {
1357     {
1358         "ncacn_np",
1359         rpcrt4_protseq_np_alloc,
1360         rpcrt4_protseq_np_signal_state_changed,
1361         rpcrt4_protseq_np_get_wait_array,
1362         rpcrt4_protseq_np_free_wait_array,
1363         rpcrt4_protseq_np_wait_for_new_connection,
1364         rpcrt4_protseq_ncacn_np_open_endpoint,
1365     },
1366     {
1367         "ncalrpc",
1368         rpcrt4_protseq_np_alloc,
1369         rpcrt4_protseq_np_signal_state_changed,
1370         rpcrt4_protseq_np_get_wait_array,
1371         rpcrt4_protseq_np_free_wait_array,
1372         rpcrt4_protseq_np_wait_for_new_connection,
1373         rpcrt4_protseq_ncalrpc_open_endpoint,
1374     },
1375     {
1376         "ncacn_ip_tcp",
1377         rpcrt4_protseq_sock_alloc,
1378         rpcrt4_protseq_sock_signal_state_changed,
1379         rpcrt4_protseq_sock_get_wait_array,
1380         rpcrt4_protseq_sock_free_wait_array,
1381         rpcrt4_protseq_sock_wait_for_new_connection,
1382         rpcrt4_protseq_ncacn_ip_tcp_open_endpoint,
1383     },
1384 };
1385
1386 #define ARRAYSIZE(a) (sizeof((a)) / sizeof((a)[0]))
1387
1388 const struct protseq_ops *rpcrt4_get_protseq_ops(const char *protseq)
1389 {
1390   int i;
1391   for(i=0; i<ARRAYSIZE(protseq_list); i++)
1392     if (!strcmp(protseq_list[i].name, protseq))
1393       return &protseq_list[i];
1394   return NULL;
1395 }
1396
1397 static const struct connection_ops *rpcrt4_get_conn_protseq_ops(const char *protseq)
1398 {
1399     int i;
1400     for(i=0; i<ARRAYSIZE(conn_protseq_list); i++)
1401         if (!strcmp(conn_protseq_list[i].name, protseq))
1402             return &conn_protseq_list[i];
1403     return NULL;
1404 }
1405
1406 /**** interface to rest of code ****/
1407
1408 RPC_STATUS RPCRT4_OpenClientConnection(RpcConnection* Connection)
1409 {
1410   TRACE("(Connection == ^%p)\n", Connection);
1411
1412   assert(!Connection->server);
1413   return Connection->ops->open_connection_client(Connection);
1414 }
1415
1416 RPC_STATUS RPCRT4_CloseConnection(RpcConnection* Connection)
1417 {
1418   TRACE("(Connection == ^%p)\n", Connection);
1419   if (SecIsValidHandle(&Connection->ctx))
1420   {
1421     DeleteSecurityContext(&Connection->ctx);
1422     SecInvalidateHandle(&Connection->ctx);
1423   }
1424   rpcrt4_conn_close(Connection);
1425   return RPC_S_OK;
1426 }
1427
1428 RPC_STATUS RPCRT4_CreateConnection(RpcConnection** Connection, BOOL server,
1429     LPCSTR Protseq, LPCSTR NetworkAddr, LPCSTR Endpoint,
1430     LPCWSTR NetworkOptions, RpcAuthInfo* AuthInfo, RpcQualityOfService *QOS)
1431 {
1432   const struct connection_ops *ops;
1433   RpcConnection* NewConnection;
1434
1435   ops = rpcrt4_get_conn_protseq_ops(Protseq);
1436   if (!ops)
1437   {
1438     FIXME("not supported for protseq %s\n", Protseq);
1439     return RPC_S_PROTSEQ_NOT_SUPPORTED;
1440   }
1441
1442   NewConnection = ops->alloc();
1443   NewConnection->Next = NULL;
1444   NewConnection->server = server;
1445   NewConnection->ops = ops;
1446   NewConnection->NetworkAddr = RPCRT4_strdupA(NetworkAddr);
1447   NewConnection->Endpoint = RPCRT4_strdupA(Endpoint);
1448   NewConnection->NetworkOptions = RPCRT4_strdupW(NetworkOptions);
1449   NewConnection->MaxTransmissionSize = RPC_MAX_PACKET_SIZE;
1450   memset(&NewConnection->ActiveInterface, 0, sizeof(NewConnection->ActiveInterface));
1451   NewConnection->NextCallId = 1;
1452
1453   SecInvalidateHandle(&NewConnection->ctx);
1454   memset(&NewConnection->exp, 0, sizeof(NewConnection->exp));
1455   NewConnection->attr = 0;
1456   if (AuthInfo) RpcAuthInfo_AddRef(AuthInfo);
1457   NewConnection->AuthInfo = AuthInfo;
1458   NewConnection->encryption_auth_len = 0;
1459   NewConnection->signature_auth_len = 0;
1460   if (QOS) RpcQualityOfService_AddRef(QOS);
1461   NewConnection->QOS = QOS;
1462
1463   list_init(&NewConnection->conn_pool_entry);
1464
1465   TRACE("connection: %p\n", NewConnection);
1466   *Connection = NewConnection;
1467
1468   return RPC_S_OK;
1469 }
1470
1471 RPC_STATUS RPCRT4_GetAssociation(LPCSTR Protseq, LPCSTR NetworkAddr,
1472                                  LPCSTR Endpoint, LPCWSTR NetworkOptions,
1473                                  RpcAssoc **assoc_out)
1474 {
1475   RpcAssoc *assoc;
1476
1477   EnterCriticalSection(&assoc_list_cs);
1478   LIST_FOR_EACH_ENTRY(assoc, &assoc_list, RpcAssoc, entry)
1479   {
1480     if (!strcmp(Protseq, assoc->Protseq) &&
1481         !strcmp(NetworkAddr, assoc->NetworkAddr) &&
1482         !strcmp(Endpoint, assoc->Endpoint) &&
1483         ((!assoc->NetworkOptions && !NetworkOptions) || !strcmpW(NetworkOptions, assoc->NetworkOptions)))
1484     {
1485       assoc->refs++;
1486       *assoc_out = assoc;
1487       LeaveCriticalSection(&assoc_list_cs);
1488       TRACE("using existing assoc %p\n", assoc);
1489       return RPC_S_OK;
1490     }
1491   }
1492
1493   assoc = HeapAlloc(GetProcessHeap(), 0, sizeof(*assoc));
1494   if (!assoc)
1495   {
1496     LeaveCriticalSection(&assoc_list_cs);
1497     return RPC_S_OUT_OF_RESOURCES;
1498   }
1499   assoc->refs = 1;
1500   list_init(&assoc->connection_pool);
1501   InitializeCriticalSection(&assoc->cs);
1502   assoc->Protseq = RPCRT4_strdupA(Protseq);
1503   assoc->NetworkAddr = RPCRT4_strdupA(NetworkAddr);
1504   assoc->Endpoint = RPCRT4_strdupA(Endpoint);
1505   assoc->NetworkOptions = NetworkOptions ? RPCRT4_strdupW(NetworkOptions) : NULL;
1506   assoc->assoc_group_id = 0;
1507   list_add_head(&assoc_list, &assoc->entry);
1508   *assoc_out = assoc;
1509
1510   LeaveCriticalSection(&assoc_list_cs);
1511
1512   TRACE("new assoc %p\n", assoc);
1513
1514   return RPC_S_OK;
1515 }
1516
1517 ULONG RpcAssoc_Release(RpcAssoc *assoc)
1518 {
1519   ULONG refs;
1520
1521   EnterCriticalSection(&assoc_list_cs);
1522   refs = --assoc->refs;
1523   if (!refs)
1524     list_remove(&assoc->entry);
1525   LeaveCriticalSection(&assoc_list_cs);
1526
1527   if (!refs)
1528   {
1529     RpcConnection *Connection, *cursor2;
1530
1531     TRACE("destroying assoc %p\n", assoc);
1532
1533     LIST_FOR_EACH_ENTRY_SAFE(Connection, cursor2, &assoc->connection_pool, RpcConnection, conn_pool_entry)
1534     {
1535       list_remove(&Connection->conn_pool_entry);
1536       RPCRT4_DestroyConnection(Connection);
1537     }
1538
1539     HeapFree(GetProcessHeap(), 0, assoc->NetworkOptions);
1540     HeapFree(GetProcessHeap(), 0, assoc->Endpoint);
1541     HeapFree(GetProcessHeap(), 0, assoc->NetworkAddr);
1542     HeapFree(GetProcessHeap(), 0, assoc->Protseq);
1543
1544     HeapFree(GetProcessHeap(), 0, assoc);
1545   }
1546
1547   return refs;
1548 }
1549
1550 #define ROUND_UP(value, alignment) (((value) + ((alignment) - 1)) & ~((alignment)-1))
1551
1552 static RPC_STATUS RpcAssoc_BindConnection(const RpcAssoc *assoc, RpcConnection *conn,
1553                                           const RPC_SYNTAX_IDENTIFIER *InterfaceId,
1554                                           const RPC_SYNTAX_IDENTIFIER *TransferSyntax)
1555 {
1556   RpcPktHdr *hdr;
1557   RpcPktHdr *response_hdr;
1558   RPC_MESSAGE msg;
1559   RPC_STATUS status;
1560
1561   TRACE("sending bind request to server\n");
1562
1563   hdr = RPCRT4_BuildBindHeader(NDR_LOCAL_DATA_REPRESENTATION,
1564                                RPC_MAX_PACKET_SIZE, RPC_MAX_PACKET_SIZE,
1565                                assoc->assoc_group_id,
1566                                InterfaceId, TransferSyntax);
1567
1568   status = RPCRT4_Send(conn, hdr, NULL, 0);
1569   RPCRT4_FreeHeader(hdr);
1570   if (status != RPC_S_OK)
1571     return status;
1572
1573   status = RPCRT4_Receive(conn, &response_hdr, &msg);
1574   if (status != RPC_S_OK)
1575   {
1576     ERR("receive failed\n");
1577     return status;
1578   }
1579
1580   switch (response_hdr->common.ptype)
1581   {
1582   case PKT_BIND_ACK:
1583   {
1584     RpcAddressString *server_address = msg.Buffer;
1585     if ((msg.BufferLength >= FIELD_OFFSET(RpcAddressString, string[0])) ||
1586         (msg.BufferLength >= ROUND_UP(FIELD_OFFSET(RpcAddressString, string[server_address->length]), 4)))
1587     {
1588         unsigned short remaining = msg.BufferLength -
1589             ROUND_UP(FIELD_OFFSET(RpcAddressString, string[server_address->length]), 4);
1590         RpcResults *results = (RpcResults*)((ULONG_PTR)server_address +
1591             ROUND_UP(FIELD_OFFSET(RpcAddressString, string[server_address->length]), 4));
1592         if ((results->num_results == 1) && (remaining >= sizeof(*results)))
1593         {
1594             switch (results->results[0].result)
1595             {
1596             case RESULT_ACCEPT:
1597                 conn->assoc_group_id = response_hdr->bind_ack.assoc_gid;
1598                 conn->MaxTransmissionSize = response_hdr->bind_ack.max_tsize;
1599                 conn->ActiveInterface = *InterfaceId;
1600                 break;
1601             case RESULT_PROVIDER_REJECTION:
1602                 switch (results->results[0].reason)
1603                 {
1604                 case REASON_ABSTRACT_SYNTAX_NOT_SUPPORTED:
1605                     ERR("syntax %s, %d.%d not supported\n",
1606                         debugstr_guid(&InterfaceId->SyntaxGUID),
1607                         InterfaceId->SyntaxVersion.MajorVersion,
1608                         InterfaceId->SyntaxVersion.MinorVersion);
1609                     status = RPC_S_UNKNOWN_IF;
1610                     break;
1611                 case REASON_TRANSFER_SYNTAXES_NOT_SUPPORTED:
1612                     ERR("transfer syntax not supported\n");
1613                     status = RPC_S_SERVER_UNAVAILABLE;
1614                     break;
1615                 case REASON_NONE:
1616                 default:
1617                     status = RPC_S_CALL_FAILED_DNE;
1618                 }
1619                 break;
1620             case RESULT_USER_REJECTION:
1621             default:
1622                 ERR("rejection result %d\n", results->results[0].result);
1623                 status = RPC_S_CALL_FAILED_DNE;
1624             }
1625         }
1626         else
1627         {
1628             ERR("incorrect results size\n");
1629             status = RPC_S_CALL_FAILED_DNE;
1630         }
1631     }
1632     else
1633     {
1634         ERR("bind ack packet too small (%d)\n", msg.BufferLength);
1635         status = RPC_S_PROTOCOL_ERROR;
1636     }
1637     break;
1638   }
1639   case PKT_BIND_NACK:
1640     switch (response_hdr->bind_nack.reject_reason)
1641     {
1642     case REJECT_LOCAL_LIMIT_EXCEEDED:
1643     case REJECT_TEMPORARY_CONGESTION:
1644         ERR("server too busy\n");
1645         status = RPC_S_SERVER_TOO_BUSY;
1646         break;
1647     case REJECT_PROTOCOL_VERSION_NOT_SUPPORTED:
1648         ERR("protocol version not supported\n");
1649         status = RPC_S_PROTOCOL_ERROR;
1650         break;
1651     case REJECT_UNKNOWN_AUTHN_SERVICE:
1652         ERR("unknown authentication service\n");
1653         status = RPC_S_UNKNOWN_AUTHN_SERVICE;
1654         break;
1655     case REJECT_INVALID_CHECKSUM:
1656         ERR("invalid checksum\n");
1657         status = ERROR_ACCESS_DENIED;
1658         break;
1659     default:
1660         ERR("rejected bind for reason %d\n", response_hdr->bind_nack.reject_reason);
1661         status = RPC_S_CALL_FAILED_DNE;
1662     }
1663     break;
1664   default:
1665     ERR("wrong packet type received %d\n", response_hdr->common.ptype);
1666     status = RPC_S_PROTOCOL_ERROR;
1667     break;
1668   }
1669
1670   RPCRT4_FreeHeader(response_hdr);
1671   return status;
1672 }
1673
1674 static RpcConnection *RpcAssoc_GetIdleConnection(RpcAssoc *assoc,
1675     const RPC_SYNTAX_IDENTIFIER *InterfaceId,
1676     const RPC_SYNTAX_IDENTIFIER *TransferSyntax, const RpcAuthInfo *AuthInfo,
1677     const RpcQualityOfService *QOS)
1678 {
1679   RpcConnection *Connection;
1680   EnterCriticalSection(&assoc->cs);
1681   /* try to find a compatible connection from the connection pool */
1682   LIST_FOR_EACH_ENTRY(Connection, &assoc->connection_pool, RpcConnection, conn_pool_entry)
1683   {
1684     if (!memcmp(&Connection->ActiveInterface, InterfaceId,
1685                 sizeof(RPC_SYNTAX_IDENTIFIER)) &&
1686         RpcAuthInfo_IsEqual(Connection->AuthInfo, AuthInfo) &&
1687         RpcQualityOfService_IsEqual(Connection->QOS, QOS))
1688     {
1689       list_remove(&Connection->conn_pool_entry);
1690       LeaveCriticalSection(&assoc->cs);
1691       TRACE("got connection from pool %p\n", Connection);
1692       return Connection;
1693     }
1694   }
1695
1696   LeaveCriticalSection(&assoc->cs);
1697   return NULL;
1698 }
1699
1700 RPC_STATUS RpcAssoc_GetClientConnection(RpcAssoc *assoc,
1701     const RPC_SYNTAX_IDENTIFIER *InterfaceId,
1702     const RPC_SYNTAX_IDENTIFIER *TransferSyntax, RpcAuthInfo *AuthInfo,
1703     RpcQualityOfService *QOS, RpcConnection **Connection)
1704 {
1705   RpcConnection *NewConnection;
1706   RPC_STATUS status;
1707
1708   *Connection = RpcAssoc_GetIdleConnection(assoc, InterfaceId, TransferSyntax, AuthInfo, QOS);
1709   if (*Connection)
1710     return RPC_S_OK;
1711
1712   /* create a new connection */
1713   status = RPCRT4_CreateConnection(&NewConnection, FALSE /* is this a server connection? */,
1714                                    assoc->Protseq, assoc->NetworkAddr,
1715                                    assoc->Endpoint, assoc->NetworkOptions,
1716                                    AuthInfo, QOS);
1717   if (status != RPC_S_OK)
1718     return status;
1719
1720   status = RPCRT4_OpenClientConnection(NewConnection);
1721   if (status != RPC_S_OK)
1722   {
1723     RPCRT4_DestroyConnection(NewConnection);
1724     return status;
1725   }
1726
1727   status = RpcAssoc_BindConnection(assoc, NewConnection, InterfaceId, TransferSyntax);
1728   if (status != RPC_S_OK)
1729   {
1730     RPCRT4_DestroyConnection(NewConnection);
1731     return status;
1732   }
1733
1734   *Connection = NewConnection;
1735
1736   return RPC_S_OK;
1737 }
1738
1739 void RpcAssoc_ReleaseIdleConnection(RpcAssoc *assoc, RpcConnection *Connection)
1740 {
1741   assert(!Connection->server);
1742   EnterCriticalSection(&assoc->cs);
1743   if (!assoc->assoc_group_id) assoc->assoc_group_id = Connection->assoc_group_id;
1744   list_add_head(&assoc->connection_pool, &Connection->conn_pool_entry);
1745   LeaveCriticalSection(&assoc->cs);
1746 }
1747
1748
1749 RPC_STATUS RPCRT4_SpawnConnection(RpcConnection** Connection, RpcConnection* OldConnection)
1750 {
1751   RPC_STATUS err;
1752
1753   err = RPCRT4_CreateConnection(Connection, OldConnection->server,
1754                                 rpcrt4_conn_get_name(OldConnection),
1755                                 OldConnection->NetworkAddr,
1756                                 OldConnection->Endpoint, NULL,
1757                                 OldConnection->AuthInfo, OldConnection->QOS);
1758   if (err == RPC_S_OK)
1759     rpcrt4_conn_handoff(OldConnection, *Connection);
1760   return err;
1761 }
1762
1763 RPC_STATUS RPCRT4_DestroyConnection(RpcConnection* Connection)
1764 {
1765   TRACE("connection: %p\n", Connection);
1766
1767   RPCRT4_CloseConnection(Connection);
1768   RPCRT4_strfree(Connection->Endpoint);
1769   RPCRT4_strfree(Connection->NetworkAddr);
1770   HeapFree(GetProcessHeap(), 0, Connection->NetworkOptions);
1771   if (Connection->AuthInfo) RpcAuthInfo_Release(Connection->AuthInfo);
1772   if (Connection->QOS) RpcQualityOfService_Release(Connection->QOS);
1773   HeapFree(GetProcessHeap(), 0, Connection);
1774   return RPC_S_OK;
1775 }
1776
1777 RPC_STATUS RpcTransport_GetTopOfTower(unsigned char *tower_data,
1778                                       size_t *tower_size,
1779                                       const char *protseq,
1780                                       const char *networkaddr,
1781                                       const char *endpoint)
1782 {
1783     twr_empty_floor_t *protocol_floor;
1784     const struct connection_ops *protseq_ops = rpcrt4_get_conn_protseq_ops(protseq);
1785
1786     *tower_size = 0;
1787
1788     if (!protseq_ops)
1789         return RPC_S_INVALID_RPC_PROTSEQ;
1790
1791     if (!tower_data)
1792     {
1793         *tower_size = sizeof(*protocol_floor);
1794         *tower_size += protseq_ops->get_top_of_tower(NULL, networkaddr, endpoint);
1795         return RPC_S_OK;
1796     }
1797
1798     protocol_floor = (twr_empty_floor_t *)tower_data;
1799     protocol_floor->count_lhs = sizeof(protocol_floor->protid);
1800     protocol_floor->protid = protseq_ops->epm_protocols[0];
1801     protocol_floor->count_rhs = 0;
1802
1803     tower_data += sizeof(*protocol_floor);
1804
1805     *tower_size = protseq_ops->get_top_of_tower(tower_data, networkaddr, endpoint);
1806     if (!*tower_size)
1807         return EPT_S_NOT_REGISTERED;
1808
1809     *tower_size += sizeof(*protocol_floor);
1810
1811     return RPC_S_OK;
1812 }
1813
1814 RPC_STATUS RpcTransport_ParseTopOfTower(const unsigned char *tower_data,
1815                                         size_t tower_size,
1816                                         char **protseq,
1817                                         char **networkaddr,
1818                                         char **endpoint)
1819 {
1820     const twr_empty_floor_t *protocol_floor;
1821     const twr_empty_floor_t *floor4;
1822     const struct connection_ops *protseq_ops = NULL;
1823     RPC_STATUS status;
1824     int i;
1825
1826     if (tower_size < sizeof(*protocol_floor))
1827         return EPT_S_NOT_REGISTERED;
1828
1829     protocol_floor = (const twr_empty_floor_t *)tower_data;
1830     tower_data += sizeof(*protocol_floor);
1831     tower_size -= sizeof(*protocol_floor);
1832     if ((protocol_floor->count_lhs != sizeof(protocol_floor->protid)) ||
1833         (protocol_floor->count_rhs > tower_size))
1834         return EPT_S_NOT_REGISTERED;
1835     tower_data += protocol_floor->count_rhs;
1836     tower_size -= protocol_floor->count_rhs;
1837
1838     floor4 = (const twr_empty_floor_t *)tower_data;
1839     if ((tower_size < sizeof(*floor4)) ||
1840         (floor4->count_lhs != sizeof(floor4->protid)))
1841         return EPT_S_NOT_REGISTERED;
1842
1843     for(i = 0; i < ARRAYSIZE(conn_protseq_list); i++)
1844         if ((protocol_floor->protid == conn_protseq_list[i].epm_protocols[0]) &&
1845             (floor4->protid == conn_protseq_list[i].epm_protocols[1]))
1846         {
1847             protseq_ops = &conn_protseq_list[i];
1848             break;
1849         }
1850
1851     if (!protseq_ops)
1852         return EPT_S_NOT_REGISTERED;
1853
1854     status = protseq_ops->parse_top_of_tower(tower_data, tower_size, networkaddr, endpoint);
1855
1856     if ((status == RPC_S_OK) && protseq)
1857     {
1858         *protseq = I_RpcAllocate(strlen(protseq_ops->name) + 1);
1859         strcpy(*protseq, protseq_ops->name);
1860     }
1861
1862     return status;
1863 }
1864
1865 /***********************************************************************
1866  *             RpcNetworkIsProtseqValidW (RPCRT4.@)
1867  *
1868  * Checks if the given protocol sequence is known by the RPC system.
1869  * If it is, returns RPC_S_OK, otherwise RPC_S_PROTSEQ_NOT_SUPPORTED.
1870  *
1871  */
1872 RPC_STATUS WINAPI RpcNetworkIsProtseqValidW(RPC_WSTR protseq)
1873 {
1874   char ps[0x10];
1875
1876   WideCharToMultiByte(CP_ACP, 0, protseq, -1,
1877                       ps, sizeof ps, NULL, NULL);
1878   if (rpcrt4_get_conn_protseq_ops(ps))
1879     return RPC_S_OK;
1880
1881   FIXME("Unknown protseq %s\n", debugstr_w(protseq));
1882
1883   return RPC_S_INVALID_RPC_PROTSEQ;
1884 }
1885
1886 /***********************************************************************
1887  *             RpcNetworkIsProtseqValidA (RPCRT4.@)
1888  */
1889 RPC_STATUS WINAPI RpcNetworkIsProtseqValidA(RPC_CSTR protseq)
1890 {
1891   UNICODE_STRING protseqW;
1892
1893   if (RtlCreateUnicodeStringFromAsciiz(&protseqW, (char*)protseq))
1894   {
1895     RPC_STATUS ret = RpcNetworkIsProtseqValidW(protseqW.Buffer);
1896     RtlFreeUnicodeString(&protseqW);
1897     return ret;
1898   }
1899   return RPC_S_OUT_OF_MEMORY;
1900 }