mshtml: Store more info about properties in func_info_t.
[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 <stdlib.h>
33 #include <sys/types.h>
34
35 #if defined(__MINGW32__) || defined (_MSC_VER)
36 # include <ws2tcpip.h>
37 # ifndef EADDRINUSE
38 #  define EADDRINUSE WSAEADDRINUSE
39 # endif
40 # ifndef EAGAIN
41 #  define EAGAIN WSAEWOULDBLOCK
42 # endif
43 # undef errno
44 # define errno WSAGetLastError()
45 #else
46 # include <errno.h>
47 # ifdef HAVE_UNISTD_H
48 #  include <unistd.h>
49 # endif
50 # include <fcntl.h>
51 # ifdef HAVE_SYS_SOCKET_H
52 #  include <sys/socket.h>
53 # endif
54 # ifdef HAVE_NETINET_IN_H
55 #  include <netinet/in.h>
56 # endif
57 # ifdef HAVE_NETINET_TCP_H
58 #  include <netinet/tcp.h>
59 # endif
60 # ifdef HAVE_ARPA_INET_H
61 #  include <arpa/inet.h>
62 # endif
63 # ifdef HAVE_NETDB_H
64 #  include <netdb.h>
65 # endif
66 # ifdef HAVE_SYS_POLL_H
67 #  include <sys/poll.h>
68 # endif
69 # ifdef HAVE_SYS_FILIO_H
70 #  include <sys/filio.h>
71 # endif
72 # ifdef HAVE_SYS_IOCTL_H
73 #  include <sys/ioctl.h>
74 # endif
75 # define closesocket close
76 # define ioctlsocket ioctl
77 #endif /* defined(__MINGW32__) || defined (_MSC_VER) */
78
79 #include "windef.h"
80 #include "winbase.h"
81 #include "winnls.h"
82 #include "winerror.h"
83 #include "wininet.h"
84 #include "winternl.h"
85 #include "wine/unicode.h"
86
87 #include "rpc.h"
88 #include "rpcndr.h"
89
90 #include "wine/debug.h"
91
92 #include "rpc_binding.h"
93 #include "rpc_assoc.h"
94 #include "rpc_message.h"
95 #include "rpc_server.h"
96 #include "epm_towers.h"
97
98 #ifndef SOL_TCP
99 # define SOL_TCP IPPROTO_TCP
100 #endif
101
102 #define DEFAULT_NCACN_HTTP_TIMEOUT (60 * 1000)
103
104 WINE_DEFAULT_DEBUG_CHANNEL(rpc);
105
106 static RPC_STATUS RPCRT4_SpawnConnection(RpcConnection** Connection, RpcConnection* OldConnection);
107
108 /**** ncacn_np support ****/
109
110 typedef struct _RpcConnection_np
111 {
112   RpcConnection common;
113   HANDLE pipe;
114   HANDLE listen_thread;
115   BOOL listening;
116 } RpcConnection_np;
117
118 static RpcConnection *rpcrt4_conn_np_alloc(void)
119 {
120   RpcConnection_np *npc = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(RpcConnection_np));
121   return &npc->common;
122 }
123
124 static DWORD CALLBACK listen_thread(void *arg)
125 {
126   RpcConnection_np *npc = arg;
127   for (;;)
128   {
129       if (ConnectNamedPipe(npc->pipe, NULL))
130           return RPC_S_OK;
131
132       switch(GetLastError())
133       {
134       case ERROR_PIPE_CONNECTED:
135           return RPC_S_OK;
136       case ERROR_HANDLES_CLOSED:
137           /* connection closed during listen */
138           return RPC_S_NO_CONTEXT_AVAILABLE;
139       case ERROR_NO_DATA_DETECTED:
140           /* client has disconnected, retry */
141           DisconnectNamedPipe( npc->pipe );
142           break;
143       default:
144           npc->listening = FALSE;
145           WARN("Couldn't ConnectNamedPipe (error was %d)\n", GetLastError());
146           return RPC_S_OUT_OF_RESOURCES;
147       }
148   }
149 }
150
151 static RPC_STATUS rpcrt4_conn_listen_pipe(RpcConnection_np *npc)
152 {
153   if (npc->listening)
154     return RPC_S_OK;
155
156   npc->listening = TRUE;
157   npc->listen_thread = CreateThread(NULL, 0, listen_thread, npc, 0, NULL);
158   if (!npc->listen_thread)
159   {
160       npc->listening = FALSE;
161       ERR("Couldn't create listen thread (error was %d)\n", GetLastError());
162       return RPC_S_OUT_OF_RESOURCES;
163   }
164   return RPC_S_OK;
165 }
166
167 static RPC_STATUS rpcrt4_conn_create_pipe(RpcConnection *Connection, LPCSTR pname)
168 {
169   RpcConnection_np *npc = (RpcConnection_np *) Connection;
170   TRACE("listening on %s\n", pname);
171
172   npc->pipe = CreateNamedPipeA(pname, PIPE_ACCESS_DUPLEX,
173                                PIPE_TYPE_MESSAGE | PIPE_READMODE_MESSAGE,
174                                PIPE_UNLIMITED_INSTANCES,
175                                RPC_MAX_PACKET_SIZE, RPC_MAX_PACKET_SIZE, 5000, NULL);
176   if (npc->pipe == INVALID_HANDLE_VALUE) {
177     WARN("CreateNamedPipe failed with error %d\n", GetLastError());
178     if (GetLastError() == ERROR_FILE_EXISTS)
179       return RPC_S_DUPLICATE_ENDPOINT;
180     else
181       return RPC_S_CANT_CREATE_ENDPOINT;
182   }
183
184   /* Note: we don't call ConnectNamedPipe here because it must be done in the
185    * server thread as the thread must be alertable */
186   return RPC_S_OK;
187 }
188
189 static RPC_STATUS rpcrt4_conn_open_pipe(RpcConnection *Connection, LPCSTR pname, BOOL wait)
190 {
191   RpcConnection_np *npc = (RpcConnection_np *) Connection;
192   HANDLE pipe;
193   DWORD err, dwMode;
194
195   TRACE("connecting to %s\n", pname);
196
197   while (TRUE) {
198     DWORD dwFlags = 0;
199     if (Connection->QOS)
200     {
201         dwFlags = SECURITY_SQOS_PRESENT;
202         switch (Connection->QOS->qos->ImpersonationType)
203         {
204             case RPC_C_IMP_LEVEL_DEFAULT:
205                 /* FIXME: what to do here? */
206                 break;
207             case RPC_C_IMP_LEVEL_ANONYMOUS:
208                 dwFlags |= SECURITY_ANONYMOUS;
209                 break;
210             case RPC_C_IMP_LEVEL_IDENTIFY:
211                 dwFlags |= SECURITY_IDENTIFICATION;
212                 break;
213             case RPC_C_IMP_LEVEL_IMPERSONATE:
214                 dwFlags |= SECURITY_IMPERSONATION;
215                 break;
216             case RPC_C_IMP_LEVEL_DELEGATE:
217                 dwFlags |= SECURITY_DELEGATION;
218                 break;
219         }
220         if (Connection->QOS->qos->IdentityTracking == RPC_C_QOS_IDENTITY_DYNAMIC)
221             dwFlags |= SECURITY_CONTEXT_TRACKING;
222     }
223     pipe = CreateFileA(pname, GENERIC_READ|GENERIC_WRITE, 0, NULL,
224                        OPEN_EXISTING, dwFlags, 0);
225     if (pipe != INVALID_HANDLE_VALUE) break;
226     err = GetLastError();
227     if (err == ERROR_PIPE_BUSY) {
228       TRACE("connection failed, error=%x\n", err);
229       return RPC_S_SERVER_TOO_BUSY;
230     }
231     if (!wait || !WaitNamedPipeA(pname, NMPWAIT_WAIT_FOREVER)) {
232       err = GetLastError();
233       WARN("connection failed, error=%x\n", err);
234       return RPC_S_SERVER_UNAVAILABLE;
235     }
236   }
237
238   /* success */
239   /* pipe is connected; change to message-read mode. */
240   dwMode = PIPE_READMODE_MESSAGE;
241   SetNamedPipeHandleState(pipe, &dwMode, NULL, NULL);
242   npc->pipe = pipe;
243
244   return RPC_S_OK;
245 }
246
247 static RPC_STATUS rpcrt4_ncalrpc_open(RpcConnection* Connection)
248 {
249   RpcConnection_np *npc = (RpcConnection_np *) Connection;
250   static const char prefix[] = "\\\\.\\pipe\\lrpc\\";
251   RPC_STATUS r;
252   LPSTR pname;
253
254   /* already connected? */
255   if (npc->pipe)
256     return RPC_S_OK;
257
258   /* protseq=ncalrpc: supposed to use NT LPC ports,
259    * but we'll implement it with named pipes for now */
260   pname = I_RpcAllocate(strlen(prefix) + strlen(Connection->Endpoint) + 1);
261   strcat(strcpy(pname, prefix), Connection->Endpoint);
262   r = rpcrt4_conn_open_pipe(Connection, pname, TRUE);
263   I_RpcFree(pname);
264
265   return r;
266 }
267
268 static RPC_STATUS rpcrt4_protseq_ncalrpc_open_endpoint(RpcServerProtseq* protseq, const char *endpoint)
269 {
270   static const char prefix[] = "\\\\.\\pipe\\lrpc\\";
271   RPC_STATUS r;
272   LPSTR pname;
273   RpcConnection *Connection;
274   char generated_endpoint[22];
275
276   if (!endpoint)
277   {
278     static LONG lrpc_nameless_id;
279     DWORD process_id = GetCurrentProcessId();
280     ULONG id = InterlockedIncrement(&lrpc_nameless_id);
281     snprintf(generated_endpoint, sizeof(generated_endpoint),
282              "LRPC%08x.%08x", process_id, id);
283     endpoint = generated_endpoint;
284   }
285
286   r = RPCRT4_CreateConnection(&Connection, TRUE, protseq->Protseq, NULL,
287                               endpoint, NULL, NULL, NULL);
288   if (r != RPC_S_OK)
289       return r;
290
291   /* protseq=ncalrpc: supposed to use NT LPC ports,
292    * but we'll implement it with named pipes for now */
293   pname = I_RpcAllocate(strlen(prefix) + strlen(Connection->Endpoint) + 1);
294   strcat(strcpy(pname, prefix), Connection->Endpoint);
295   r = rpcrt4_conn_create_pipe(Connection, pname);
296   I_RpcFree(pname);
297
298   EnterCriticalSection(&protseq->cs);
299   Connection->Next = protseq->conn;
300   protseq->conn = Connection;
301   LeaveCriticalSection(&protseq->cs);
302
303   return r;
304 }
305
306 static RPC_STATUS rpcrt4_ncacn_np_open(RpcConnection* Connection)
307 {
308   RpcConnection_np *npc = (RpcConnection_np *) Connection;
309   static const char prefix[] = "\\\\.";
310   RPC_STATUS r;
311   LPSTR pname;
312
313   /* already connected? */
314   if (npc->pipe)
315     return RPC_S_OK;
316
317   /* protseq=ncacn_np: named pipes */
318   pname = I_RpcAllocate(strlen(prefix) + strlen(Connection->Endpoint) + 1);
319   strcat(strcpy(pname, prefix), Connection->Endpoint);
320   r = rpcrt4_conn_open_pipe(Connection, pname, FALSE);
321   I_RpcFree(pname);
322
323   return r;
324 }
325
326 static RPC_STATUS rpcrt4_protseq_ncacn_np_open_endpoint(RpcServerProtseq *protseq, const char *endpoint)
327 {
328   static const char prefix[] = "\\\\.";
329   RPC_STATUS r;
330   LPSTR pname;
331   RpcConnection *Connection;
332   char generated_endpoint[21];
333
334   if (!endpoint)
335   {
336     static LONG np_nameless_id;
337     DWORD process_id = GetCurrentProcessId();
338     ULONG id = InterlockedExchangeAdd(&np_nameless_id, 1 );
339     snprintf(generated_endpoint, sizeof(generated_endpoint),
340              "\\\\pipe\\\\%08x.%03x", process_id, id);
341     endpoint = generated_endpoint;
342   }
343
344   r = RPCRT4_CreateConnection(&Connection, TRUE, protseq->Protseq, NULL,
345                               endpoint, NULL, NULL, NULL);
346   if (r != RPC_S_OK)
347     return r;
348
349   /* protseq=ncacn_np: named pipes */
350   pname = I_RpcAllocate(strlen(prefix) + strlen(Connection->Endpoint) + 1);
351   strcat(strcpy(pname, prefix), Connection->Endpoint);
352   r = rpcrt4_conn_create_pipe(Connection, pname);
353   I_RpcFree(pname);
354
355   EnterCriticalSection(&protseq->cs);
356   Connection->Next = protseq->conn;
357   protseq->conn = Connection;
358   LeaveCriticalSection(&protseq->cs);
359
360   return r;
361 }
362
363 static void rpcrt4_conn_np_handoff(RpcConnection_np *old_npc, RpcConnection_np *new_npc)
364 {    
365   /* because of the way named pipes work, we'll transfer the connected pipe
366    * to the child, then reopen the server binding to continue listening */
367
368   new_npc->pipe = old_npc->pipe;
369   new_npc->listen_thread = old_npc->listen_thread;
370   old_npc->pipe = 0;
371   old_npc->listen_thread = 0;
372   old_npc->listening = FALSE;
373 }
374
375 static RPC_STATUS rpcrt4_ncacn_np_handoff(RpcConnection *old_conn, RpcConnection *new_conn)
376 {
377   RPC_STATUS status;
378   LPSTR pname;
379   static const char prefix[] = "\\\\.";
380
381   rpcrt4_conn_np_handoff((RpcConnection_np *)old_conn, (RpcConnection_np *)new_conn);
382
383   pname = I_RpcAllocate(strlen(prefix) + strlen(old_conn->Endpoint) + 1);
384   strcat(strcpy(pname, prefix), old_conn->Endpoint);
385   status = rpcrt4_conn_create_pipe(old_conn, pname);
386   I_RpcFree(pname);
387
388   return status;
389 }
390
391 static RPC_STATUS rpcrt4_ncalrpc_handoff(RpcConnection *old_conn, RpcConnection *new_conn)
392 {
393   RPC_STATUS status;
394   LPSTR pname;
395   static const char prefix[] = "\\\\.\\pipe\\lrpc\\";
396
397   TRACE("%s\n", old_conn->Endpoint);
398
399   rpcrt4_conn_np_handoff((RpcConnection_np *)old_conn, (RpcConnection_np *)new_conn);
400
401   pname = I_RpcAllocate(strlen(prefix) + strlen(old_conn->Endpoint) + 1);
402   strcat(strcpy(pname, prefix), old_conn->Endpoint);
403   status = rpcrt4_conn_create_pipe(old_conn, pname);
404   I_RpcFree(pname);
405     
406   return status;
407 }
408
409 static int rpcrt4_conn_np_read(RpcConnection *Connection,
410                         void *buffer, unsigned int count)
411 {
412   RpcConnection_np *npc = (RpcConnection_np *) Connection;
413   char *buf = buffer;
414   BOOL ret = TRUE;
415   unsigned int bytes_left = count;
416
417   while (bytes_left)
418   {
419     DWORD bytes_read;
420     ret = ReadFile(npc->pipe, buf, bytes_left, &bytes_read, NULL);
421     if (!ret && GetLastError() == ERROR_MORE_DATA)
422         ret = TRUE;
423     if (!ret || !bytes_read)
424         break;
425     bytes_left -= bytes_read;
426     buf += bytes_read;
427   }
428   return ret ? count : -1;
429 }
430
431 static int rpcrt4_conn_np_write(RpcConnection *Connection,
432                              const void *buffer, unsigned int count)
433 {
434   RpcConnection_np *npc = (RpcConnection_np *) Connection;
435   const char *buf = buffer;
436   BOOL ret = TRUE;
437   unsigned int bytes_left = count;
438
439   while (bytes_left)
440   {
441     DWORD bytes_written;
442     ret = WriteFile(npc->pipe, buf, bytes_left, &bytes_written, NULL);
443     if (!ret || !bytes_written)
444         break;
445     bytes_left -= bytes_written;
446     buf += bytes_written;
447   }
448   return ret ? count : -1;
449 }
450
451 static int rpcrt4_conn_np_close(RpcConnection *Connection)
452 {
453   RpcConnection_np *npc = (RpcConnection_np *) Connection;
454   if (npc->pipe) {
455     FlushFileBuffers(npc->pipe);
456     CloseHandle(npc->pipe);
457     npc->pipe = 0;
458   }
459   if (npc->listen_thread) {
460     CloseHandle(npc->listen_thread);
461     npc->listen_thread = 0;
462   }
463   return 0;
464 }
465
466 static void rpcrt4_conn_np_cancel_call(RpcConnection *Connection)
467 {
468     /* FIXME: implement when named pipe writes use overlapped I/O */
469 }
470
471 static int rpcrt4_conn_np_wait_for_incoming_data(RpcConnection *Connection)
472 {
473     /* FIXME: implement when named pipe writes use overlapped I/O */
474     return -1;
475 }
476
477 static size_t rpcrt4_ncacn_np_get_top_of_tower(unsigned char *tower_data,
478                                                const char *networkaddr,
479                                                const char *endpoint)
480 {
481     twr_empty_floor_t *smb_floor;
482     twr_empty_floor_t *nb_floor;
483     size_t size;
484     size_t networkaddr_size;
485     size_t endpoint_size;
486
487     TRACE("(%p, %s, %s)\n", tower_data, networkaddr, endpoint);
488
489     networkaddr_size = networkaddr ? strlen(networkaddr) + 1 : 1;
490     endpoint_size = endpoint ? strlen(endpoint) + 1 : 1;
491     size = sizeof(*smb_floor) + endpoint_size + sizeof(*nb_floor) + networkaddr_size;
492
493     if (!tower_data)
494         return size;
495
496     smb_floor = (twr_empty_floor_t *)tower_data;
497
498     tower_data += sizeof(*smb_floor);
499
500     smb_floor->count_lhs = sizeof(smb_floor->protid);
501     smb_floor->protid = EPM_PROTOCOL_SMB;
502     smb_floor->count_rhs = endpoint_size;
503
504     if (endpoint)
505         memcpy(tower_data, endpoint, endpoint_size);
506     else
507         tower_data[0] = 0;
508     tower_data += endpoint_size;
509
510     nb_floor = (twr_empty_floor_t *)tower_data;
511
512     tower_data += sizeof(*nb_floor);
513
514     nb_floor->count_lhs = sizeof(nb_floor->protid);
515     nb_floor->protid = EPM_PROTOCOL_NETBIOS;
516     nb_floor->count_rhs = networkaddr_size;
517
518     if (networkaddr)
519         memcpy(tower_data, networkaddr, networkaddr_size);
520     else
521         tower_data[0] = 0;
522
523     return size;
524 }
525
526 static RPC_STATUS rpcrt4_ncacn_np_parse_top_of_tower(const unsigned char *tower_data,
527                                                      size_t tower_size,
528                                                      char **networkaddr,
529                                                      char **endpoint)
530 {
531     const twr_empty_floor_t *smb_floor = (const twr_empty_floor_t *)tower_data;
532     const twr_empty_floor_t *nb_floor;
533
534     TRACE("(%p, %d, %p, %p)\n", tower_data, (int)tower_size, networkaddr, endpoint);
535
536     if (tower_size < sizeof(*smb_floor))
537         return EPT_S_NOT_REGISTERED;
538
539     tower_data += sizeof(*smb_floor);
540     tower_size -= sizeof(*smb_floor);
541
542     if ((smb_floor->count_lhs != sizeof(smb_floor->protid)) ||
543         (smb_floor->protid != EPM_PROTOCOL_SMB) ||
544         (smb_floor->count_rhs > tower_size) ||
545         (tower_data[smb_floor->count_rhs - 1] != '\0'))
546         return EPT_S_NOT_REGISTERED;
547
548     if (endpoint)
549     {
550         *endpoint = I_RpcAllocate(smb_floor->count_rhs);
551         if (!*endpoint)
552             return RPC_S_OUT_OF_RESOURCES;
553         memcpy(*endpoint, tower_data, smb_floor->count_rhs);
554     }
555     tower_data += smb_floor->count_rhs;
556     tower_size -= smb_floor->count_rhs;
557
558     if (tower_size < sizeof(*nb_floor))
559         return EPT_S_NOT_REGISTERED;
560
561     nb_floor = (const twr_empty_floor_t *)tower_data;
562
563     tower_data += sizeof(*nb_floor);
564     tower_size -= sizeof(*nb_floor);
565
566     if ((nb_floor->count_lhs != sizeof(nb_floor->protid)) ||
567         (nb_floor->protid != EPM_PROTOCOL_NETBIOS) ||
568         (nb_floor->count_rhs > tower_size) ||
569         (tower_data[nb_floor->count_rhs - 1] != '\0'))
570         return EPT_S_NOT_REGISTERED;
571
572     if (networkaddr)
573     {
574         *networkaddr = I_RpcAllocate(nb_floor->count_rhs);
575         if (!*networkaddr)
576         {
577             if (endpoint)
578             {
579                 I_RpcFree(*endpoint);
580                 *endpoint = NULL;
581             }
582             return RPC_S_OUT_OF_RESOURCES;
583         }
584         memcpy(*networkaddr, tower_data, nb_floor->count_rhs);
585     }
586
587     return RPC_S_OK;
588 }
589
590 static RPC_STATUS rpcrt4_conn_np_impersonate_client(RpcConnection *conn)
591 {
592     RpcConnection_np *npc = (RpcConnection_np *)conn;
593     BOOL ret;
594
595     TRACE("(%p)\n", conn);
596
597     if (conn->AuthInfo && SecIsValidHandle(&conn->ctx))
598         return RPCRT4_default_impersonate_client(conn);
599
600     ret = ImpersonateNamedPipeClient(npc->pipe);
601     if (!ret)
602     {
603         DWORD error = GetLastError();
604         WARN("ImpersonateNamedPipeClient failed with error %u\n", error);
605         switch (error)
606         {
607         case ERROR_CANNOT_IMPERSONATE:
608             return RPC_S_NO_CONTEXT_AVAILABLE;
609         }
610     }
611     return RPC_S_OK;
612 }
613
614 static RPC_STATUS rpcrt4_conn_np_revert_to_self(RpcConnection *conn)
615 {
616     BOOL ret;
617
618     TRACE("(%p)\n", conn);
619
620     if (conn->AuthInfo && SecIsValidHandle(&conn->ctx))
621         return RPCRT4_default_revert_to_self(conn);
622
623     ret = RevertToSelf();
624     if (!ret)
625     {
626         WARN("RevertToSelf failed with error %u\n", GetLastError());
627         return RPC_S_NO_CONTEXT_AVAILABLE;
628     }
629     return RPC_S_OK;
630 }
631
632 typedef struct _RpcServerProtseq_np
633 {
634     RpcServerProtseq common;
635     HANDLE mgr_event;
636 } RpcServerProtseq_np;
637
638 static RpcServerProtseq *rpcrt4_protseq_np_alloc(void)
639 {
640     RpcServerProtseq_np *ps = HeapAlloc(GetProcessHeap(), 0, sizeof(*ps));
641     if (ps)
642         ps->mgr_event = CreateEventW(NULL, FALSE, FALSE, NULL);
643     return &ps->common;
644 }
645
646 static void rpcrt4_protseq_np_signal_state_changed(RpcServerProtseq *protseq)
647 {
648     RpcServerProtseq_np *npps = CONTAINING_RECORD(protseq, RpcServerProtseq_np, common);
649     SetEvent(npps->mgr_event);
650 }
651
652 static void *rpcrt4_protseq_np_get_wait_array(RpcServerProtseq *protseq, void *prev_array, unsigned int *count)
653 {
654     HANDLE *objs = prev_array;
655     RpcConnection_np *conn;
656     RpcServerProtseq_np *npps = CONTAINING_RECORD(protseq, RpcServerProtseq_np, common);
657     
658     EnterCriticalSection(&protseq->cs);
659     
660     /* open and count connections */
661     *count = 1;
662     conn = CONTAINING_RECORD(protseq->conn, RpcConnection_np, common);
663     while (conn) {
664         rpcrt4_conn_listen_pipe(conn);
665         if (conn->listen_thread)
666             (*count)++;
667         conn = CONTAINING_RECORD(conn->common.Next, RpcConnection_np, common);
668     }
669     
670     /* make array of connections */
671     if (objs)
672         objs = HeapReAlloc(GetProcessHeap(), 0, objs, *count*sizeof(HANDLE));
673     else
674         objs = HeapAlloc(GetProcessHeap(), 0, *count*sizeof(HANDLE));
675     if (!objs)
676     {
677         ERR("couldn't allocate objs\n");
678         LeaveCriticalSection(&protseq->cs);
679         return NULL;
680     }
681     
682     objs[0] = npps->mgr_event;
683     *count = 1;
684     conn = CONTAINING_RECORD(protseq->conn, RpcConnection_np, common);
685     while (conn) {
686         if ((objs[*count] = conn->listen_thread))
687             (*count)++;
688         conn = CONTAINING_RECORD(conn->common.Next, RpcConnection_np, common);
689     }
690     LeaveCriticalSection(&protseq->cs);
691     return objs;
692 }
693
694 static void rpcrt4_protseq_np_free_wait_array(RpcServerProtseq *protseq, void *array)
695 {
696     HeapFree(GetProcessHeap(), 0, array);
697 }
698
699 static int rpcrt4_protseq_np_wait_for_new_connection(RpcServerProtseq *protseq, unsigned int count, void *wait_array)
700 {
701     HANDLE b_handle;
702     HANDLE *objs = wait_array;
703     DWORD res;
704     RpcConnection *cconn;
705     RpcConnection_np *conn;
706     
707     if (!objs)
708         return -1;
709
710     do
711     {
712         /* an alertable wait isn't strictly necessary, but due to our
713          * overlapped I/O implementation in Wine we need to free some memory
714          * by the file user APC being called, even if no completion routine was
715          * specified at the time of starting the async operation */
716         res = WaitForMultipleObjectsEx(count, objs, FALSE, INFINITE, TRUE);
717     } while (res == WAIT_IO_COMPLETION);
718
719     if (res == WAIT_OBJECT_0)
720         return 0;
721     else if (res == WAIT_FAILED)
722     {
723         ERR("wait failed with error %d\n", GetLastError());
724         return -1;
725     }
726     else
727     {
728         b_handle = objs[res - WAIT_OBJECT_0];
729         /* find which connection got a RPC */
730         EnterCriticalSection(&protseq->cs);
731         conn = CONTAINING_RECORD(protseq->conn, RpcConnection_np, common);
732         while (conn) {
733             if (b_handle == conn->listen_thread) break;
734             conn = CONTAINING_RECORD(conn->common.Next, RpcConnection_np, common);
735         }
736         cconn = NULL;
737         if (conn)
738         {
739             DWORD exit_code;
740             if (GetExitCodeThread(conn->listen_thread, &exit_code) && exit_code == RPC_S_OK)
741                 RPCRT4_SpawnConnection(&cconn, &conn->common);
742             CloseHandle(conn->listen_thread);
743             conn->listen_thread = 0;
744         }
745         else
746             ERR("failed to locate connection for handle %p\n", b_handle);
747         LeaveCriticalSection(&protseq->cs);
748         if (cconn)
749         {
750             RPCRT4_new_client(cconn);
751             return 1;
752         }
753         else return -1;
754     }
755 }
756
757 static size_t rpcrt4_ncalrpc_get_top_of_tower(unsigned char *tower_data,
758                                               const char *networkaddr,
759                                               const char *endpoint)
760 {
761     twr_empty_floor_t *pipe_floor;
762     size_t size;
763     size_t endpoint_size;
764
765     TRACE("(%p, %s, %s)\n", tower_data, networkaddr, endpoint);
766
767     endpoint_size = strlen(endpoint) + 1;
768     size = sizeof(*pipe_floor) + endpoint_size;
769
770     if (!tower_data)
771         return size;
772
773     pipe_floor = (twr_empty_floor_t *)tower_data;
774
775     tower_data += sizeof(*pipe_floor);
776
777     pipe_floor->count_lhs = sizeof(pipe_floor->protid);
778     pipe_floor->protid = EPM_PROTOCOL_PIPE;
779     pipe_floor->count_rhs = endpoint_size;
780
781     memcpy(tower_data, endpoint, endpoint_size);
782
783     return size;
784 }
785
786 static RPC_STATUS rpcrt4_ncalrpc_parse_top_of_tower(const unsigned char *tower_data,
787                                                     size_t tower_size,
788                                                     char **networkaddr,
789                                                     char **endpoint)
790 {
791     const twr_empty_floor_t *pipe_floor = (const twr_empty_floor_t *)tower_data;
792
793     TRACE("(%p, %d, %p, %p)\n", tower_data, (int)tower_size, networkaddr, endpoint);
794
795     if (tower_size < sizeof(*pipe_floor))
796         return EPT_S_NOT_REGISTERED;
797
798     tower_data += sizeof(*pipe_floor);
799     tower_size -= sizeof(*pipe_floor);
800
801     if ((pipe_floor->count_lhs != sizeof(pipe_floor->protid)) ||
802         (pipe_floor->protid != EPM_PROTOCOL_PIPE) ||
803         (pipe_floor->count_rhs > tower_size) ||
804         (tower_data[pipe_floor->count_rhs - 1] != '\0'))
805         return EPT_S_NOT_REGISTERED;
806
807     if (networkaddr)
808         *networkaddr = NULL;
809
810     if (endpoint)
811     {
812         *endpoint = I_RpcAllocate(pipe_floor->count_rhs);
813         if (!*endpoint)
814             return RPC_S_OUT_OF_RESOURCES;
815         memcpy(*endpoint, tower_data, pipe_floor->count_rhs);
816     }
817
818     return RPC_S_OK;
819 }
820
821 static BOOL rpcrt4_ncalrpc_is_authorized(RpcConnection *conn)
822 {
823     return FALSE;
824 }
825
826 static RPC_STATUS rpcrt4_ncalrpc_authorize(RpcConnection *conn, BOOL first_time,
827                                            unsigned char *in_buffer,
828                                            unsigned int in_size,
829                                            unsigned char *out_buffer,
830                                            unsigned int *out_size)
831 {
832     /* since this protocol is local to the machine there is no need to
833      * authenticate the caller */
834     *out_size = 0;
835     return RPC_S_OK;
836 }
837
838 static RPC_STATUS rpcrt4_ncalrpc_secure_packet(RpcConnection *conn,
839     enum secure_packet_direction dir,
840     RpcPktHdr *hdr, unsigned int hdr_size,
841     unsigned char *stub_data, unsigned int stub_data_size,
842     RpcAuthVerifier *auth_hdr,
843     unsigned char *auth_value, unsigned int auth_value_size)
844 {
845     /* since this protocol is local to the machine there is no need to secure
846      * the packet */
847     return RPC_S_OK;
848 }
849
850 static RPC_STATUS rpcrt4_ncalrpc_inquire_auth_client(
851     RpcConnection *conn, RPC_AUTHZ_HANDLE *privs, RPC_WSTR *server_princ_name,
852     ULONG *authn_level, ULONG *authn_svc, ULONG *authz_svc, ULONG flags)
853 {
854     TRACE("(%p, %p, %p, %p, %p, %p, 0x%x)\n", conn, privs,
855           server_princ_name, authn_level, authn_svc, authz_svc, flags);
856
857     if (privs)
858     {
859         FIXME("privs not implemented\n");
860         *privs = NULL;
861     }
862     if (server_princ_name)
863     {
864         FIXME("server_princ_name not implemented\n");
865         *server_princ_name = NULL;
866     }
867     if (authn_level) *authn_level = RPC_C_AUTHN_LEVEL_PKT_PRIVACY;
868     if (authn_svc) *authn_svc = RPC_C_AUTHN_WINNT;
869     if (authz_svc)
870     {
871         FIXME("authorization service not implemented\n");
872         *authz_svc = RPC_C_AUTHZ_NONE;
873     }
874     if (flags)
875         FIXME("flags 0x%x not implemented\n", flags);
876
877     return RPC_S_OK;
878 }
879
880 /**** ncacn_ip_tcp support ****/
881
882 static size_t rpcrt4_ip_tcp_get_top_of_tower(unsigned char *tower_data,
883                                              const char *networkaddr,
884                                              unsigned char tcp_protid,
885                                              const char *endpoint)
886 {
887     twr_tcp_floor_t *tcp_floor;
888     twr_ipv4_floor_t *ipv4_floor;
889     struct addrinfo *ai;
890     struct addrinfo hints;
891     int ret;
892     size_t size = sizeof(*tcp_floor) + sizeof(*ipv4_floor);
893
894     TRACE("(%p, %s, %s)\n", tower_data, networkaddr, endpoint);
895
896     if (!tower_data)
897         return size;
898
899     tcp_floor = (twr_tcp_floor_t *)tower_data;
900     tower_data += sizeof(*tcp_floor);
901
902     ipv4_floor = (twr_ipv4_floor_t *)tower_data;
903
904     tcp_floor->count_lhs = sizeof(tcp_floor->protid);
905     tcp_floor->protid = tcp_protid;
906     tcp_floor->count_rhs = sizeof(tcp_floor->port);
907
908     ipv4_floor->count_lhs = sizeof(ipv4_floor->protid);
909     ipv4_floor->protid = EPM_PROTOCOL_IP;
910     ipv4_floor->count_rhs = sizeof(ipv4_floor->ipv4addr);
911
912     hints.ai_flags          = AI_NUMERICHOST;
913     /* FIXME: only support IPv4 at the moment. how is IPv6 represented by the EPM? */
914     hints.ai_family         = PF_INET;
915     hints.ai_socktype       = SOCK_STREAM;
916     hints.ai_protocol       = IPPROTO_TCP;
917     hints.ai_addrlen        = 0;
918     hints.ai_addr           = NULL;
919     hints.ai_canonname      = NULL;
920     hints.ai_next           = NULL;
921
922     ret = getaddrinfo(networkaddr, endpoint, &hints, &ai);
923     if (ret)
924     {
925         ret = getaddrinfo("0.0.0.0", endpoint, &hints, &ai);
926         if (ret)
927         {
928             ERR("getaddrinfo failed: %s\n", gai_strerror(ret));
929             return 0;
930         }
931     }
932
933     if (ai->ai_family == PF_INET)
934     {
935         const struct sockaddr_in *sin = (const struct sockaddr_in *)ai->ai_addr;
936         tcp_floor->port = sin->sin_port;
937         ipv4_floor->ipv4addr = sin->sin_addr.s_addr;
938     }
939     else
940     {
941         ERR("unexpected protocol family %d\n", ai->ai_family);
942         return 0;
943     }
944
945     freeaddrinfo(ai);
946
947     return size;
948 }
949
950 static RPC_STATUS rpcrt4_ip_tcp_parse_top_of_tower(const unsigned char *tower_data,
951                                                    size_t tower_size,
952                                                    char **networkaddr,
953                                                    unsigned char tcp_protid,
954                                                    char **endpoint)
955 {
956     const twr_tcp_floor_t *tcp_floor = (const twr_tcp_floor_t *)tower_data;
957     const twr_ipv4_floor_t *ipv4_floor;
958     struct in_addr in_addr;
959
960     TRACE("(%p, %d, %p, %p)\n", tower_data, (int)tower_size, networkaddr, endpoint);
961
962     if (tower_size < sizeof(*tcp_floor))
963         return EPT_S_NOT_REGISTERED;
964
965     tower_data += sizeof(*tcp_floor);
966     tower_size -= sizeof(*tcp_floor);
967
968     if (tower_size < sizeof(*ipv4_floor))
969         return EPT_S_NOT_REGISTERED;
970
971     ipv4_floor = (const twr_ipv4_floor_t *)tower_data;
972
973     if ((tcp_floor->count_lhs != sizeof(tcp_floor->protid)) ||
974         (tcp_floor->protid != tcp_protid) ||
975         (tcp_floor->count_rhs != sizeof(tcp_floor->port)) ||
976         (ipv4_floor->count_lhs != sizeof(ipv4_floor->protid)) ||
977         (ipv4_floor->protid != EPM_PROTOCOL_IP) ||
978         (ipv4_floor->count_rhs != sizeof(ipv4_floor->ipv4addr)))
979         return EPT_S_NOT_REGISTERED;
980
981     if (endpoint)
982     {
983         *endpoint = I_RpcAllocate(6 /* sizeof("65535") + 1 */);
984         if (!*endpoint)
985             return RPC_S_OUT_OF_RESOURCES;
986         sprintf(*endpoint, "%u", ntohs(tcp_floor->port));
987     }
988
989     if (networkaddr)
990     {
991         *networkaddr = I_RpcAllocate(INET_ADDRSTRLEN);
992         if (!*networkaddr)
993         {
994             if (endpoint)
995             {
996                 I_RpcFree(*endpoint);
997                 *endpoint = NULL;
998             }
999             return RPC_S_OUT_OF_RESOURCES;
1000         }
1001         in_addr.s_addr = ipv4_floor->ipv4addr;
1002         if (!inet_ntop(AF_INET, &in_addr, *networkaddr, INET_ADDRSTRLEN))
1003         {
1004             ERR("inet_ntop: %s\n", strerror(errno));
1005             I_RpcFree(*networkaddr);
1006             *networkaddr = NULL;
1007             if (endpoint)
1008             {
1009                 I_RpcFree(*endpoint);
1010                 *endpoint = NULL;
1011             }
1012             return EPT_S_NOT_REGISTERED;
1013         }
1014     }
1015
1016     return RPC_S_OK;
1017 }
1018
1019 typedef struct _RpcConnection_tcp
1020 {
1021   RpcConnection common;
1022   int sock;
1023 #ifdef HAVE_SOCKETPAIR
1024   int cancel_fds[2];
1025 #else
1026   HANDLE sock_event;
1027   HANDLE cancel_event;
1028 #endif
1029 } RpcConnection_tcp;
1030
1031 #ifdef HAVE_SOCKETPAIR
1032
1033 static BOOL rpcrt4_sock_wait_init(RpcConnection_tcp *tcpc)
1034 {
1035   if (socketpair(PF_UNIX, SOCK_STREAM, 0, tcpc->cancel_fds) < 0)
1036   {
1037     ERR("socketpair() failed: %s\n", strerror(errno));
1038     return FALSE;
1039   }
1040   return TRUE;
1041 }
1042
1043 static BOOL rpcrt4_sock_wait_for_recv(RpcConnection_tcp *tcpc)
1044 {
1045   struct pollfd pfds[2];
1046   pfds[0].fd = tcpc->sock;
1047   pfds[0].events = POLLIN;
1048   pfds[1].fd = tcpc->cancel_fds[0];
1049   pfds[1].events = POLLIN;
1050   if (poll(pfds, 2, -1 /* infinite */) == -1 && errno != EINTR)
1051   {
1052     ERR("poll() failed: %s\n", strerror(errno));
1053     return FALSE;
1054   }
1055   if (pfds[1].revents & POLLIN) /* canceled */
1056   {
1057     char dummy;
1058     read(pfds[1].fd, &dummy, sizeof(dummy));
1059     return FALSE;
1060   }
1061   return TRUE;
1062 }
1063
1064 static BOOL rpcrt4_sock_wait_for_send(RpcConnection_tcp *tcpc)
1065 {
1066   struct pollfd pfd;
1067   pfd.fd = tcpc->sock;
1068   pfd.events = POLLOUT;
1069   if (poll(&pfd, 1, -1 /* infinite */) == -1 && errno != EINTR)
1070   {
1071     ERR("poll() failed: %s\n", strerror(errno));
1072     return FALSE;
1073   }
1074   return TRUE;
1075 }
1076
1077 static void rpcrt4_sock_wait_cancel(RpcConnection_tcp *tcpc)
1078 {
1079   char dummy = 1;
1080
1081   write(tcpc->cancel_fds[1], &dummy, 1);
1082 }
1083
1084 static void rpcrt4_sock_wait_destroy(RpcConnection_tcp *tcpc)
1085 {
1086   close(tcpc->cancel_fds[0]);
1087   close(tcpc->cancel_fds[1]);
1088 }
1089
1090 #else /* HAVE_SOCKETPAIR */
1091
1092 static BOOL rpcrt4_sock_wait_init(RpcConnection_tcp *tcpc)
1093 {
1094   static BOOL wsa_inited;
1095   if (!wsa_inited)
1096   {
1097     WSADATA wsadata;
1098     WSAStartup(MAKEWORD(2, 2), &wsadata);
1099     /* Note: WSAStartup can be called more than once so we don't bother with
1100      * making accesses to wsa_inited thread-safe */
1101     wsa_inited = TRUE;
1102   }
1103   tcpc->sock_event = CreateEventW(NULL, FALSE, FALSE, NULL);
1104   tcpc->cancel_event = CreateEventW(NULL, FALSE, FALSE, NULL);
1105   if (!tcpc->sock_event || !tcpc->cancel_event)
1106   {
1107     ERR("event creation failed\n");
1108     if (tcpc->sock_event) CloseHandle(tcpc->sock_event);
1109     return FALSE;
1110   }
1111   return TRUE;
1112 }
1113
1114 static BOOL rpcrt4_sock_wait_for_recv(RpcConnection_tcp *tcpc)
1115 {
1116   HANDLE wait_handles[2];
1117   DWORD res;
1118   if (WSAEventSelect(tcpc->sock, tcpc->sock_event, FD_READ | FD_CLOSE) == SOCKET_ERROR)
1119   {
1120     ERR("WSAEventSelect() failed with error %d\n", WSAGetLastError());
1121     return FALSE;
1122   }
1123   wait_handles[0] = tcpc->sock_event;
1124   wait_handles[1] = tcpc->cancel_event;
1125   res = WaitForMultipleObjects(2, wait_handles, FALSE, INFINITE);
1126   switch (res)
1127   {
1128   case WAIT_OBJECT_0:
1129     return TRUE;
1130   case WAIT_OBJECT_0 + 1:
1131     return FALSE;
1132   default:
1133     ERR("WaitForMultipleObjects() failed with error %d\n", GetLastError());
1134     return FALSE;
1135   }
1136 }
1137
1138 static BOOL rpcrt4_sock_wait_for_send(RpcConnection_tcp *tcpc)
1139 {
1140   DWORD res;
1141   if (WSAEventSelect(tcpc->sock, tcpc->sock_event, FD_WRITE | FD_CLOSE) == SOCKET_ERROR)
1142   {
1143     ERR("WSAEventSelect() failed with error %d\n", WSAGetLastError());
1144     return FALSE;
1145   }
1146   res = WaitForSingleObject(tcpc->sock_event, INFINITE);
1147   switch (res)
1148   {
1149   case WAIT_OBJECT_0:
1150     return TRUE;
1151   default:
1152     ERR("WaitForMultipleObjects() failed with error %d\n", GetLastError());
1153     return FALSE;
1154   }
1155 }
1156
1157 static void rpcrt4_sock_wait_cancel(RpcConnection_tcp *tcpc)
1158 {
1159   SetEvent(tcpc->cancel_event);
1160 }
1161
1162 static void rpcrt4_sock_wait_destroy(RpcConnection_tcp *tcpc)
1163 {
1164   CloseHandle(tcpc->sock_event);
1165   CloseHandle(tcpc->cancel_event);
1166 }
1167
1168 #endif
1169
1170 static RpcConnection *rpcrt4_conn_tcp_alloc(void)
1171 {
1172   RpcConnection_tcp *tcpc;
1173   tcpc = HeapAlloc(GetProcessHeap(), 0, sizeof(RpcConnection_tcp));
1174   if (tcpc == NULL)
1175     return NULL;
1176   tcpc->sock = -1;
1177   if (!rpcrt4_sock_wait_init(tcpc))
1178   {
1179     HeapFree(GetProcessHeap(), 0, tcpc);
1180     return NULL;
1181   }
1182   return &tcpc->common;
1183 }
1184
1185 static RPC_STATUS rpcrt4_ncacn_ip_tcp_open(RpcConnection* Connection)
1186 {
1187   RpcConnection_tcp *tcpc = (RpcConnection_tcp *) Connection;
1188   int sock;
1189   int ret;
1190   struct addrinfo *ai;
1191   struct addrinfo *ai_cur;
1192   struct addrinfo hints;
1193
1194   TRACE("(%s, %s)\n", Connection->NetworkAddr, Connection->Endpoint);
1195
1196   if (tcpc->sock != -1)
1197     return RPC_S_OK;
1198
1199   hints.ai_flags          = 0;
1200   hints.ai_family         = PF_UNSPEC;
1201   hints.ai_socktype       = SOCK_STREAM;
1202   hints.ai_protocol       = IPPROTO_TCP;
1203   hints.ai_addrlen        = 0;
1204   hints.ai_addr           = NULL;
1205   hints.ai_canonname      = NULL;
1206   hints.ai_next           = NULL;
1207
1208   ret = getaddrinfo(Connection->NetworkAddr, Connection->Endpoint, &hints, &ai);
1209   if (ret)
1210   {
1211     ERR("getaddrinfo for %s:%s failed: %s\n", Connection->NetworkAddr,
1212       Connection->Endpoint, gai_strerror(ret));
1213     return RPC_S_SERVER_UNAVAILABLE;
1214   }
1215
1216   for (ai_cur = ai; ai_cur; ai_cur = ai_cur->ai_next)
1217   {
1218     int val;
1219     u_long nonblocking;
1220
1221     if (ai_cur->ai_family != AF_INET && ai_cur->ai_family != AF_INET6)
1222     {
1223       TRACE("skipping non-IP/IPv6 address family\n");
1224       continue;
1225     }
1226
1227     if (TRACE_ON(rpc))
1228     {
1229       char host[256];
1230       char service[256];
1231       getnameinfo(ai_cur->ai_addr, ai_cur->ai_addrlen,
1232         host, sizeof(host), service, sizeof(service),
1233         NI_NUMERICHOST | NI_NUMERICSERV);
1234       TRACE("trying %s:%s\n", host, service);
1235     }
1236
1237     sock = socket(ai_cur->ai_family, ai_cur->ai_socktype, ai_cur->ai_protocol);
1238     if (sock == -1)
1239     {
1240       WARN("socket() failed: %s\n", strerror(errno));
1241       continue;
1242     }
1243
1244     if (0>connect(sock, ai_cur->ai_addr, ai_cur->ai_addrlen))
1245     {
1246       WARN("connect() failed: %s\n", strerror(errno));
1247       closesocket(sock);
1248       continue;
1249     }
1250
1251     /* RPC depends on having minimal latency so disable the Nagle algorithm */
1252     val = 1;
1253     setsockopt(sock, SOL_TCP, TCP_NODELAY, (char *)&val, sizeof(val));
1254     nonblocking = 1;
1255     ioctlsocket(sock, FIONBIO, &nonblocking);
1256
1257     tcpc->sock = sock;
1258
1259     freeaddrinfo(ai);
1260     TRACE("connected\n");
1261     return RPC_S_OK;
1262   }
1263
1264   freeaddrinfo(ai);
1265   ERR("couldn't connect to %s:%s\n", Connection->NetworkAddr, Connection->Endpoint);
1266   return RPC_S_SERVER_UNAVAILABLE;
1267 }
1268
1269 static RPC_STATUS rpcrt4_protseq_ncacn_ip_tcp_open_endpoint(RpcServerProtseq *protseq, const char *endpoint)
1270 {
1271     RPC_STATUS status = RPC_S_CANT_CREATE_ENDPOINT;
1272     int sock;
1273     int ret;
1274     struct addrinfo *ai;
1275     struct addrinfo *ai_cur;
1276     struct addrinfo hints;
1277     RpcConnection *first_connection = NULL;
1278
1279     TRACE("(%p, %s)\n", protseq, endpoint);
1280
1281     hints.ai_flags          = AI_PASSIVE /* for non-localhost addresses */;
1282     hints.ai_family         = PF_UNSPEC;
1283     hints.ai_socktype       = SOCK_STREAM;
1284     hints.ai_protocol       = IPPROTO_TCP;
1285     hints.ai_addrlen        = 0;
1286     hints.ai_addr           = NULL;
1287     hints.ai_canonname      = NULL;
1288     hints.ai_next           = NULL;
1289
1290     ret = getaddrinfo(NULL, endpoint ? endpoint : "0", &hints, &ai);
1291     if (ret)
1292     {
1293         ERR("getaddrinfo for port %s failed: %s\n", endpoint,
1294             gai_strerror(ret));
1295         if ((ret == EAI_SERVICE) || (ret == EAI_NONAME))
1296             return RPC_S_INVALID_ENDPOINT_FORMAT;
1297         return RPC_S_CANT_CREATE_ENDPOINT;
1298     }
1299
1300     for (ai_cur = ai; ai_cur; ai_cur = ai_cur->ai_next)
1301     {
1302         RpcConnection_tcp *tcpc;
1303         RPC_STATUS create_status;
1304         struct sockaddr_storage sa;
1305         socklen_t sa_len;
1306         char service[NI_MAXSERV];
1307         u_long nonblocking;
1308
1309         if (ai_cur->ai_family != AF_INET && ai_cur->ai_family != AF_INET6)
1310         {
1311             TRACE("skipping non-IP/IPv6 address family\n");
1312             continue;
1313         }
1314
1315         if (TRACE_ON(rpc))
1316         {
1317             char host[256];
1318             getnameinfo(ai_cur->ai_addr, ai_cur->ai_addrlen,
1319                         host, sizeof(host), service, sizeof(service),
1320                         NI_NUMERICHOST | NI_NUMERICSERV);
1321             TRACE("trying %s:%s\n", host, service);
1322         }
1323
1324         sock = socket(ai_cur->ai_family, ai_cur->ai_socktype, ai_cur->ai_protocol);
1325         if (sock == -1)
1326         {
1327             WARN("socket() failed: %s\n", strerror(errno));
1328             status = RPC_S_CANT_CREATE_ENDPOINT;
1329             continue;
1330         }
1331
1332         ret = bind(sock, ai_cur->ai_addr, ai_cur->ai_addrlen);
1333         if (ret < 0)
1334         {
1335             WARN("bind failed: %s\n", strerror(errno));
1336             closesocket(sock);
1337             if (errno == EADDRINUSE)
1338               status = RPC_S_DUPLICATE_ENDPOINT;
1339             else
1340               status = RPC_S_CANT_CREATE_ENDPOINT;
1341             continue;
1342         }
1343
1344         sa_len = sizeof(sa);
1345         if (getsockname(sock, (struct sockaddr *)&sa, &sa_len))
1346         {
1347             WARN("getsockname() failed: %s\n", strerror(errno));
1348             status = RPC_S_CANT_CREATE_ENDPOINT;
1349             continue;
1350         }
1351
1352         ret = getnameinfo((struct sockaddr *)&sa, sa_len,
1353                           NULL, 0, service, sizeof(service),
1354                           NI_NUMERICSERV);
1355         if (ret)
1356         {
1357             WARN("getnameinfo failed: %s\n", gai_strerror(ret));
1358             status = RPC_S_CANT_CREATE_ENDPOINT;
1359             continue;
1360         }
1361
1362         create_status = RPCRT4_CreateConnection((RpcConnection **)&tcpc, TRUE,
1363                                                 protseq->Protseq, NULL,
1364                                                 service, NULL, NULL, NULL);
1365         if (create_status != RPC_S_OK)
1366         {
1367             closesocket(sock);
1368             status = create_status;
1369             continue;
1370         }
1371
1372         tcpc->sock = sock;
1373         ret = listen(sock, protseq->MaxCalls);
1374         if (ret < 0)
1375         {
1376             WARN("listen failed: %s\n", strerror(errno));
1377             RPCRT4_ReleaseConnection(&tcpc->common);
1378             status = RPC_S_OUT_OF_RESOURCES;
1379             continue;
1380         }
1381         /* need a non-blocking socket, otherwise accept() has a potential
1382          * race-condition (poll() says it is readable, connection drops,
1383          * and accept() blocks until the next connection comes...)
1384          */
1385         nonblocking = 1;
1386         ret = ioctlsocket(sock, FIONBIO, &nonblocking);
1387         if (ret < 0)
1388         {
1389             WARN("couldn't make socket non-blocking, error %d\n", ret);
1390             RPCRT4_ReleaseConnection(&tcpc->common);
1391             status = RPC_S_OUT_OF_RESOURCES;
1392             continue;
1393         }
1394
1395         tcpc->common.Next = first_connection;
1396         first_connection = &tcpc->common;
1397
1398         /* since IPv4 and IPv6 share the same port space, we only need one
1399          * successful bind to listen for both */
1400         break;
1401     }
1402
1403     freeaddrinfo(ai);
1404
1405     /* if at least one connection was created for an endpoint then
1406      * return success */
1407     if (first_connection)
1408     {
1409         RpcConnection *conn;
1410
1411         /* find last element in list */
1412         for (conn = first_connection; conn->Next; conn = conn->Next)
1413             ;
1414
1415         EnterCriticalSection(&protseq->cs);
1416         conn->Next = protseq->conn;
1417         protseq->conn = first_connection;
1418         LeaveCriticalSection(&protseq->cs);
1419         
1420         TRACE("listening on %s\n", endpoint);
1421         return RPC_S_OK;
1422     }
1423
1424     ERR("couldn't listen on port %s\n", endpoint);
1425     return status;
1426 }
1427
1428 static RPC_STATUS rpcrt4_conn_tcp_handoff(RpcConnection *old_conn, RpcConnection *new_conn)
1429 {
1430   int ret;
1431   struct sockaddr_in address;
1432   socklen_t addrsize;
1433   RpcConnection_tcp *server = (RpcConnection_tcp*) old_conn;
1434   RpcConnection_tcp *client = (RpcConnection_tcp*) new_conn;
1435   u_long nonblocking;
1436
1437   addrsize = sizeof(address);
1438   ret = accept(server->sock, (struct sockaddr*) &address, &addrsize);
1439   if (ret < 0)
1440   {
1441     ERR("Failed to accept a TCP connection: error %d\n", ret);
1442     return RPC_S_OUT_OF_RESOURCES;
1443   }
1444   nonblocking = 1;
1445   ioctlsocket(ret, FIONBIO, &nonblocking);
1446   client->sock = ret;
1447   TRACE("Accepted a new TCP connection\n");
1448   return RPC_S_OK;
1449 }
1450
1451 static int rpcrt4_conn_tcp_read(RpcConnection *Connection,
1452                                 void *buffer, unsigned int count)
1453 {
1454   RpcConnection_tcp *tcpc = (RpcConnection_tcp *) Connection;
1455   int bytes_read = 0;
1456   while (bytes_read != count)
1457   {
1458     int r = recv(tcpc->sock, (char *)buffer + bytes_read, count - bytes_read, 0);
1459     if (!r)
1460       return -1;
1461     else if (r > 0)
1462       bytes_read += r;
1463     else if (errno != EAGAIN)
1464     {
1465       WARN("recv() failed: %s\n", strerror(errno));
1466       return -1;
1467     }
1468     else
1469     {
1470       if (!rpcrt4_sock_wait_for_recv(tcpc))
1471         return -1;
1472     }
1473   }
1474   TRACE("%d %p %u -> %d\n", tcpc->sock, buffer, count, bytes_read);
1475   return bytes_read;
1476 }
1477
1478 static int rpcrt4_conn_tcp_write(RpcConnection *Connection,
1479                                  const void *buffer, unsigned int count)
1480 {
1481   RpcConnection_tcp *tcpc = (RpcConnection_tcp *) Connection;
1482   int bytes_written = 0;
1483   while (bytes_written != count)
1484   {
1485     int r = send(tcpc->sock, (const char *)buffer + bytes_written, count - bytes_written, 0);
1486     if (r >= 0)
1487       bytes_written += r;
1488     else if (errno != EAGAIN)
1489       return -1;
1490     else
1491     {
1492       if (!rpcrt4_sock_wait_for_send(tcpc))
1493         return -1;
1494     }
1495   }
1496   TRACE("%d %p %u -> %d\n", tcpc->sock, buffer, count, bytes_written);
1497   return bytes_written;
1498 }
1499
1500 static int rpcrt4_conn_tcp_close(RpcConnection *Connection)
1501 {
1502   RpcConnection_tcp *tcpc = (RpcConnection_tcp *) Connection;
1503
1504   TRACE("%d\n", tcpc->sock);
1505
1506   if (tcpc->sock != -1)
1507     closesocket(tcpc->sock);
1508   tcpc->sock = -1;
1509   rpcrt4_sock_wait_destroy(tcpc);
1510   return 0;
1511 }
1512
1513 static void rpcrt4_conn_tcp_cancel_call(RpcConnection *Connection)
1514 {
1515     RpcConnection_tcp *tcpc = (RpcConnection_tcp *) Connection;
1516     TRACE("%p\n", Connection);
1517     rpcrt4_sock_wait_cancel(tcpc);
1518 }
1519
1520 static int rpcrt4_conn_tcp_wait_for_incoming_data(RpcConnection *Connection)
1521 {
1522     RpcConnection_tcp *tcpc = (RpcConnection_tcp *) Connection;
1523
1524     TRACE("%p\n", Connection);
1525
1526     if (!rpcrt4_sock_wait_for_recv(tcpc))
1527         return -1;
1528     return 0;
1529 }
1530
1531 static size_t rpcrt4_ncacn_ip_tcp_get_top_of_tower(unsigned char *tower_data,
1532                                                    const char *networkaddr,
1533                                                    const char *endpoint)
1534 {
1535     return rpcrt4_ip_tcp_get_top_of_tower(tower_data, networkaddr,
1536                                           EPM_PROTOCOL_TCP, endpoint);
1537 }
1538
1539 #ifdef HAVE_SOCKETPAIR
1540
1541 typedef struct _RpcServerProtseq_sock
1542 {
1543     RpcServerProtseq common;
1544     int mgr_event_rcv;
1545     int mgr_event_snd;
1546 } RpcServerProtseq_sock;
1547
1548 static RpcServerProtseq *rpcrt4_protseq_sock_alloc(void)
1549 {
1550     RpcServerProtseq_sock *ps = HeapAlloc(GetProcessHeap(), 0, sizeof(*ps));
1551     if (ps)
1552     {
1553         int fds[2];
1554         if (!socketpair(PF_UNIX, SOCK_DGRAM, 0, fds))
1555         {
1556             fcntl(fds[0], F_SETFL, O_NONBLOCK);
1557             fcntl(fds[1], F_SETFL, O_NONBLOCK);
1558             ps->mgr_event_rcv = fds[0];
1559             ps->mgr_event_snd = fds[1];
1560         }
1561         else
1562         {
1563             ERR("socketpair failed with error %s\n", strerror(errno));
1564             HeapFree(GetProcessHeap(), 0, ps);
1565             return NULL;
1566         }
1567     }
1568     return &ps->common;
1569 }
1570
1571 static void rpcrt4_protseq_sock_signal_state_changed(RpcServerProtseq *protseq)
1572 {
1573     RpcServerProtseq_sock *sockps = CONTAINING_RECORD(protseq, RpcServerProtseq_sock, common);
1574     char dummy = 1;
1575     write(sockps->mgr_event_snd, &dummy, sizeof(dummy));
1576 }
1577
1578 static void *rpcrt4_protseq_sock_get_wait_array(RpcServerProtseq *protseq, void *prev_array, unsigned int *count)
1579 {
1580     struct pollfd *poll_info = prev_array;
1581     RpcConnection_tcp *conn;
1582     RpcServerProtseq_sock *sockps = CONTAINING_RECORD(protseq, RpcServerProtseq_sock, common);
1583
1584     EnterCriticalSection(&protseq->cs);
1585     
1586     /* open and count connections */
1587     *count = 1;
1588     conn = (RpcConnection_tcp *)protseq->conn;
1589     while (conn) {
1590         if (conn->sock != -1)
1591             (*count)++;
1592         conn = (RpcConnection_tcp *)conn->common.Next;
1593     }
1594     
1595     /* make array of connections */
1596     if (poll_info)
1597         poll_info = HeapReAlloc(GetProcessHeap(), 0, poll_info, *count*sizeof(*poll_info));
1598     else
1599         poll_info = HeapAlloc(GetProcessHeap(), 0, *count*sizeof(*poll_info));
1600     if (!poll_info)
1601     {
1602         ERR("couldn't allocate poll_info\n");
1603         LeaveCriticalSection(&protseq->cs);
1604         return NULL;
1605     }
1606
1607     poll_info[0].fd = sockps->mgr_event_rcv;
1608     poll_info[0].events = POLLIN;
1609     *count = 1;
1610     conn =  CONTAINING_RECORD(protseq->conn, RpcConnection_tcp, common);
1611     while (conn) {
1612         if (conn->sock != -1)
1613         {
1614             poll_info[*count].fd = conn->sock;
1615             poll_info[*count].events = POLLIN;
1616             (*count)++;
1617         }
1618         conn = CONTAINING_RECORD(conn->common.Next, RpcConnection_tcp, common);
1619     }
1620     LeaveCriticalSection(&protseq->cs);
1621     return poll_info;
1622 }
1623
1624 static void rpcrt4_protseq_sock_free_wait_array(RpcServerProtseq *protseq, void *array)
1625 {
1626     HeapFree(GetProcessHeap(), 0, array);
1627 }
1628
1629 static int rpcrt4_protseq_sock_wait_for_new_connection(RpcServerProtseq *protseq, unsigned int count, void *wait_array)
1630 {
1631     struct pollfd *poll_info = wait_array;
1632     int ret;
1633     unsigned int i;
1634     RpcConnection *cconn;
1635     RpcConnection_tcp *conn;
1636     
1637     if (!poll_info)
1638         return -1;
1639     
1640     ret = poll(poll_info, count, -1);
1641     if (ret < 0)
1642     {
1643         ERR("poll failed with error %d\n", ret);
1644         return -1;
1645     }
1646
1647     for (i = 0; i < count; i++)
1648         if (poll_info[i].revents & POLLIN)
1649         {
1650             /* RPC server event */
1651             if (i == 0)
1652             {
1653                 char dummy;
1654                 read(poll_info[0].fd, &dummy, sizeof(dummy));
1655                 return 0;
1656             }
1657
1658             /* find which connection got a RPC */
1659             EnterCriticalSection(&protseq->cs);
1660             conn = CONTAINING_RECORD(protseq->conn, RpcConnection_tcp, common);
1661             while (conn) {
1662                 if (poll_info[i].fd == conn->sock) break;
1663                 conn = CONTAINING_RECORD(conn->common.Next, RpcConnection_tcp, common);
1664             }
1665             cconn = NULL;
1666             if (conn)
1667                 RPCRT4_SpawnConnection(&cconn, &conn->common);
1668             else
1669                 ERR("failed to locate connection for fd %d\n", poll_info[i].fd);
1670             LeaveCriticalSection(&protseq->cs);
1671             if (cconn)
1672                 RPCRT4_new_client(cconn);
1673             else
1674                 return -1;
1675         }
1676
1677     return 1;
1678 }
1679
1680 #else /* HAVE_SOCKETPAIR */
1681
1682 typedef struct _RpcServerProtseq_sock
1683 {
1684     RpcServerProtseq common;
1685     HANDLE mgr_event;
1686 } RpcServerProtseq_sock;
1687
1688 static RpcServerProtseq *rpcrt4_protseq_sock_alloc(void)
1689 {
1690     RpcServerProtseq_sock *ps = HeapAlloc(GetProcessHeap(), 0, sizeof(*ps));
1691     if (ps)
1692     {
1693         static BOOL wsa_inited;
1694         if (!wsa_inited)
1695         {
1696             WSADATA wsadata;
1697             WSAStartup(MAKEWORD(2, 2), &wsadata);
1698             /* Note: WSAStartup can be called more than once so we don't bother with
1699              * making accesses to wsa_inited thread-safe */
1700             wsa_inited = TRUE;
1701         }
1702         ps->mgr_event = CreateEventW(NULL, FALSE, FALSE, NULL);
1703     }
1704     return &ps->common;
1705 }
1706
1707 static void rpcrt4_protseq_sock_signal_state_changed(RpcServerProtseq *protseq)
1708 {
1709     RpcServerProtseq_sock *sockps = CONTAINING_RECORD(protseq, RpcServerProtseq_sock, common);
1710     SetEvent(sockps->mgr_event);
1711 }
1712
1713 static void *rpcrt4_protseq_sock_get_wait_array(RpcServerProtseq *protseq, void *prev_array, unsigned int *count)
1714 {
1715     HANDLE *objs = prev_array;
1716     RpcConnection_tcp *conn;
1717     RpcServerProtseq_sock *sockps = CONTAINING_RECORD(protseq, RpcServerProtseq_sock, common);
1718
1719     EnterCriticalSection(&protseq->cs);
1720
1721     /* open and count connections */
1722     *count = 1;
1723     conn = CONTAINING_RECORD(protseq->conn, RpcConnection_tcp, common);
1724     while (conn)
1725     {
1726         if (conn->sock != -1)
1727             (*count)++;
1728         conn = CONTAINING_RECORD(conn->common.Next, RpcConnection_tcp, common);
1729     }
1730
1731     /* make array of connections */
1732     if (objs)
1733         objs = HeapReAlloc(GetProcessHeap(), 0, objs, *count*sizeof(HANDLE));
1734     else
1735         objs = HeapAlloc(GetProcessHeap(), 0, *count*sizeof(HANDLE));
1736     if (!objs)
1737     {
1738         ERR("couldn't allocate objs\n");
1739         LeaveCriticalSection(&protseq->cs);
1740         return NULL;
1741     }
1742
1743     objs[0] = sockps->mgr_event;
1744     *count = 1;
1745     conn = CONTAINING_RECORD(protseq->conn, RpcConnection_tcp, common);
1746     while (conn)
1747     {
1748         if (conn->sock != -1)
1749         {
1750             int res = WSAEventSelect(conn->sock, conn->sock_event, FD_ACCEPT);
1751             if (res == SOCKET_ERROR)
1752                 ERR("WSAEventSelect() failed with error %d\n", WSAGetLastError());
1753             else
1754             {
1755                 objs[*count] = conn->sock_event;
1756                 (*count)++;
1757             }
1758         }
1759         conn = CONTAINING_RECORD(conn->common.Next, RpcConnection_tcp, common);
1760     }
1761     LeaveCriticalSection(&protseq->cs);
1762     return objs;
1763 }
1764
1765 static void rpcrt4_protseq_sock_free_wait_array(RpcServerProtseq *protseq, void *array)
1766 {
1767     HeapFree(GetProcessHeap(), 0, array);
1768 }
1769
1770 static int rpcrt4_protseq_sock_wait_for_new_connection(RpcServerProtseq *protseq, unsigned int count, void *wait_array)
1771 {
1772     HANDLE b_handle;
1773     HANDLE *objs = wait_array;
1774     DWORD res;
1775     RpcConnection *cconn;
1776     RpcConnection_tcp *conn;
1777
1778     if (!objs)
1779         return -1;
1780
1781     do
1782     {
1783         /* an alertable wait isn't strictly necessary, but due to our
1784          * overlapped I/O implementation in Wine we need to free some memory
1785          * by the file user APC being called, even if no completion routine was
1786          * specified at the time of starting the async operation */
1787         res = WaitForMultipleObjectsEx(count, objs, FALSE, INFINITE, TRUE);
1788     } while (res == WAIT_IO_COMPLETION);
1789
1790     if (res == WAIT_OBJECT_0)
1791         return 0;
1792     else if (res == WAIT_FAILED)
1793     {
1794         ERR("wait failed with error %d\n", GetLastError());
1795         return -1;
1796     }
1797     else
1798     {
1799         b_handle = objs[res - WAIT_OBJECT_0];
1800         /* find which connection got a RPC */
1801         EnterCriticalSection(&protseq->cs);
1802         conn = CONTAINING_RECORD(protseq->conn, RpcConnection_tcp, common);
1803         while (conn)
1804         {
1805             if (b_handle == conn->sock_event) break;
1806             conn = CONTAINING_RECORD(conn->common.Next, RpcConnection_tcp, common);
1807         }
1808         cconn = NULL;
1809         if (conn)
1810             RPCRT4_SpawnConnection(&cconn, &conn->common);
1811         else
1812             ERR("failed to locate connection for handle %p\n", b_handle);
1813         LeaveCriticalSection(&protseq->cs);
1814         if (cconn)
1815         {
1816             RPCRT4_new_client(cconn);
1817             return 1;
1818         }
1819         else return -1;
1820     }
1821 }
1822
1823 #endif  /* HAVE_SOCKETPAIR */
1824
1825 static RPC_STATUS rpcrt4_ncacn_ip_tcp_parse_top_of_tower(const unsigned char *tower_data,
1826                                                          size_t tower_size,
1827                                                          char **networkaddr,
1828                                                          char **endpoint)
1829 {
1830     return rpcrt4_ip_tcp_parse_top_of_tower(tower_data, tower_size,
1831                                             networkaddr, EPM_PROTOCOL_TCP,
1832                                             endpoint);
1833 }
1834
1835 /**** ncacn_http support ****/
1836
1837 /* 60 seconds is the period native uses */
1838 #define HTTP_IDLE_TIME 60000
1839
1840 /* reference counted to avoid a race between a cancelled call's connection
1841  * being destroyed and the asynchronous InternetReadFileEx call being
1842  * completed */
1843 typedef struct _RpcHttpAsyncData
1844 {
1845     LONG refs;
1846     HANDLE completion_event;
1847     INTERNET_BUFFERSA inet_buffers;
1848     void *destination_buffer; /* the address that inet_buffers.lpvBuffer will be
1849                                * copied into when the call completes */
1850     CRITICAL_SECTION cs;
1851 } RpcHttpAsyncData;
1852
1853 static ULONG RpcHttpAsyncData_AddRef(RpcHttpAsyncData *data)
1854 {
1855     return InterlockedIncrement(&data->refs);
1856 }
1857
1858 static ULONG RpcHttpAsyncData_Release(RpcHttpAsyncData *data)
1859 {
1860     ULONG refs = InterlockedDecrement(&data->refs);
1861     if (!refs)
1862     {
1863         TRACE("destroying async data %p\n", data);
1864         CloseHandle(data->completion_event);
1865         HeapFree(GetProcessHeap(), 0, data->inet_buffers.lpvBuffer);
1866         data->cs.DebugInfo->Spare[0] = 0;
1867         DeleteCriticalSection(&data->cs);
1868         HeapFree(GetProcessHeap(), 0, data);
1869     }
1870     return refs;
1871 }
1872
1873 typedef struct _RpcConnection_http
1874 {
1875     RpcConnection common;
1876     HINTERNET app_info;
1877     HINTERNET session;
1878     HINTERNET in_request;
1879     HINTERNET out_request;
1880     HANDLE timer_cancelled;
1881     HANDLE cancel_event;
1882     DWORD last_sent_time;
1883     ULONG bytes_received;
1884     ULONG flow_control_mark; /* send a control packet to the server when this many bytes received */
1885     ULONG flow_control_increment; /* number of bytes to increment flow_control_mark by */
1886     UUID connection_uuid;
1887     UUID in_pipe_uuid;
1888     UUID out_pipe_uuid;
1889     RpcHttpAsyncData *async_data;
1890 } RpcConnection_http;
1891
1892 static RpcConnection *rpcrt4_ncacn_http_alloc(void)
1893 {
1894     RpcConnection_http *httpc;
1895     httpc = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*httpc));
1896     if (!httpc) return NULL;
1897     httpc->async_data = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(RpcHttpAsyncData));
1898     if (!httpc->async_data)
1899     {
1900         HeapFree(GetProcessHeap(), 0, httpc);
1901         return NULL;
1902     }
1903     TRACE("async data = %p\n", httpc->async_data);
1904     httpc->cancel_event = CreateEventW(NULL, FALSE, FALSE, NULL);
1905     httpc->async_data->refs = 1;
1906     httpc->async_data->inet_buffers.dwStructSize = sizeof(INTERNET_BUFFERSA);
1907     httpc->async_data->inet_buffers.lpvBuffer = NULL;
1908     httpc->async_data->destination_buffer = NULL;
1909     InitializeCriticalSection(&httpc->async_data->cs);
1910     httpc->async_data->cs.DebugInfo->Spare[0] = (DWORD_PTR)(__FILE__ ": RpcHttpAsyncData.cs");
1911     return &httpc->common;
1912 }
1913
1914 typedef struct _HttpTimerThreadData
1915 {
1916     PVOID timer_param;
1917     DWORD *last_sent_time;
1918     HANDLE timer_cancelled;
1919 } HttpTimerThreadData;
1920
1921 static VOID rpcrt4_http_keep_connection_active_timer_proc(PVOID param, BOOLEAN dummy)
1922 {
1923     HINTERNET in_request = param;
1924     RpcPktHdr *idle_pkt;
1925
1926     idle_pkt = RPCRT4_BuildHttpHeader(NDR_LOCAL_DATA_REPRESENTATION, 0x0001,
1927                                       0, 0);
1928     if (idle_pkt)
1929     {
1930         DWORD bytes_written;
1931         InternetWriteFile(in_request, idle_pkt, idle_pkt->common.frag_len, &bytes_written);
1932         RPCRT4_FreeHeader(idle_pkt);
1933     }
1934 }
1935
1936 static inline DWORD rpcrt4_http_timer_calc_timeout(DWORD *last_sent_time)
1937 {
1938     DWORD cur_time = GetTickCount();
1939     DWORD cached_last_sent_time = *last_sent_time;
1940     return HTTP_IDLE_TIME - (cur_time - cached_last_sent_time > HTTP_IDLE_TIME ? 0 : cur_time - cached_last_sent_time);
1941 }
1942
1943 static DWORD CALLBACK rpcrt4_http_timer_thread(PVOID param)
1944 {
1945     HttpTimerThreadData *data_in = param;
1946     HttpTimerThreadData data;
1947     DWORD timeout;
1948
1949     data = *data_in;
1950     HeapFree(GetProcessHeap(), 0, data_in);
1951
1952     for (timeout = HTTP_IDLE_TIME;
1953          WaitForSingleObject(data.timer_cancelled, timeout) == WAIT_TIMEOUT;
1954          timeout = rpcrt4_http_timer_calc_timeout(data.last_sent_time))
1955     {
1956         /* are we too soon after last send? */
1957         if (GetTickCount() - HTTP_IDLE_TIME < *data.last_sent_time)
1958             continue;
1959         rpcrt4_http_keep_connection_active_timer_proc(data.timer_param, TRUE);
1960     }
1961
1962     CloseHandle(data.timer_cancelled);
1963     return 0;
1964 }
1965
1966 static VOID WINAPI rpcrt4_http_internet_callback(
1967      HINTERNET hInternet,
1968      DWORD_PTR dwContext,
1969      DWORD dwInternetStatus,
1970      LPVOID lpvStatusInformation,
1971      DWORD dwStatusInformationLength)
1972 {
1973     RpcHttpAsyncData *async_data = (RpcHttpAsyncData *)dwContext;
1974
1975     switch (dwInternetStatus)
1976     {
1977     case INTERNET_STATUS_REQUEST_COMPLETE:
1978         TRACE("INTERNET_STATUS_REQUEST_COMPLETED\n");
1979         if (async_data)
1980         {
1981             if (async_data->inet_buffers.lpvBuffer)
1982             {
1983                 EnterCriticalSection(&async_data->cs);
1984                 if (async_data->destination_buffer)
1985                 {
1986                     memcpy(async_data->destination_buffer,
1987                            async_data->inet_buffers.lpvBuffer,
1988                            async_data->inet_buffers.dwBufferLength);
1989                     async_data->destination_buffer = NULL;
1990                 }
1991                 LeaveCriticalSection(&async_data->cs);
1992             }
1993             HeapFree(GetProcessHeap(), 0, async_data->inet_buffers.lpvBuffer);
1994             async_data->inet_buffers.lpvBuffer = NULL;
1995             SetEvent(async_data->completion_event);
1996             RpcHttpAsyncData_Release(async_data);
1997         }
1998         break;
1999     }
2000 }
2001
2002 static RPC_STATUS rpcrt4_http_check_response(HINTERNET hor)
2003 {
2004     BOOL ret;
2005     DWORD status_code;
2006     DWORD size;
2007     DWORD index;
2008     WCHAR buf[32];
2009     WCHAR *status_text = buf;
2010     TRACE("\n");
2011
2012     index = 0;
2013     size = sizeof(status_code);
2014     ret = HttpQueryInfoW(hor, HTTP_QUERY_STATUS_CODE|HTTP_QUERY_FLAG_NUMBER, &status_code, &size, &index);
2015     if (!ret)
2016         return GetLastError();
2017     if (status_code < 400)
2018         return RPC_S_OK;
2019     index = 0;
2020     size = sizeof(buf);
2021     ret = HttpQueryInfoW(hor, HTTP_QUERY_STATUS_TEXT, status_text, &size, &index);
2022     if (!ret && GetLastError() == ERROR_INSUFFICIENT_BUFFER)
2023     {
2024         status_text = HeapAlloc(GetProcessHeap(), 0, size);
2025         ret = HttpQueryInfoW(hor, HTTP_QUERY_STATUS_TEXT, status_text, &size, &index);
2026     }
2027
2028     ERR("server returned: %d %s\n", status_code, ret ? debugstr_w(status_text) : "<status text unavailable>");
2029     if(status_text != buf) HeapFree(GetProcessHeap(), 0, status_text);
2030
2031     if (status_code == HTTP_STATUS_DENIED)
2032         return ERROR_ACCESS_DENIED;
2033     return RPC_S_SERVER_UNAVAILABLE;
2034 }
2035
2036 static RPC_STATUS rpcrt4_http_internet_connect(RpcConnection_http *httpc)
2037 {
2038     static const WCHAR wszUserAgent[] = {'M','S','R','P','C',0};
2039     LPWSTR proxy = NULL;
2040     LPWSTR user = NULL;
2041     LPWSTR password = NULL;
2042     LPWSTR servername = NULL;
2043     const WCHAR *option;
2044     INTERNET_PORT port = INTERNET_INVALID_PORT_NUMBER; /* use default port */
2045
2046     if (httpc->common.QOS &&
2047         (httpc->common.QOS->qos->AdditionalSecurityInfoType == RPC_C_AUTHN_INFO_TYPE_HTTP))
2048     {
2049         const RPC_HTTP_TRANSPORT_CREDENTIALS_W *http_cred = httpc->common.QOS->qos->u.HttpCredentials;
2050         if (http_cred->TransportCredentials)
2051         {
2052             WCHAR *p;
2053             const SEC_WINNT_AUTH_IDENTITY_W *cred = http_cred->TransportCredentials;
2054             ULONG len = cred->DomainLength + 1 + cred->UserLength;
2055             user = HeapAlloc(GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR));
2056             if (!user)
2057                 return RPC_S_OUT_OF_RESOURCES;
2058             p = user;
2059             if (cred->DomainLength)
2060             {
2061                 memcpy(p, cred->Domain, cred->DomainLength * sizeof(WCHAR));
2062                 p += cred->DomainLength;
2063                 *p = '\\';
2064                 p++;
2065             }
2066             memcpy(p, cred->User, cred->UserLength * sizeof(WCHAR));
2067             p[cred->UserLength] = 0;
2068
2069             password = RPCRT4_strndupW(cred->Password, cred->PasswordLength);
2070         }
2071     }
2072
2073     for (option = httpc->common.NetworkOptions; option;
2074          option = (strchrW(option, ',') ? strchrW(option, ',')+1 : NULL))
2075     {
2076         static const WCHAR wszRpcProxy[] = {'R','p','c','P','r','o','x','y','=',0};
2077         static const WCHAR wszHttpProxy[] = {'H','t','t','p','P','r','o','x','y','=',0};
2078
2079         if (!strncmpiW(option, wszRpcProxy, sizeof(wszRpcProxy)/sizeof(wszRpcProxy[0])-1))
2080         {
2081             const WCHAR *value_start = option + sizeof(wszRpcProxy)/sizeof(wszRpcProxy[0])-1;
2082             const WCHAR *value_end;
2083             const WCHAR *p;
2084
2085             value_end = strchrW(option, ',');
2086             if (!value_end)
2087                 value_end = value_start + strlenW(value_start);
2088             for (p = value_start; p < value_end; p++)
2089                 if (*p == ':')
2090                 {
2091                     port = atoiW(p+1);
2092                     value_end = p;
2093                     break;
2094                 }
2095             TRACE("RpcProxy value is %s\n", debugstr_wn(value_start, value_end-value_start));
2096             servername = RPCRT4_strndupW(value_start, value_end-value_start);
2097         }
2098         else if (!strncmpiW(option, wszHttpProxy, sizeof(wszHttpProxy)/sizeof(wszHttpProxy[0])-1))
2099         {
2100             const WCHAR *value_start = option + sizeof(wszHttpProxy)/sizeof(wszHttpProxy[0])-1;
2101             const WCHAR *value_end;
2102
2103             value_end = strchrW(option, ',');
2104             if (!value_end)
2105                 value_end = value_start + strlenW(value_start);
2106             TRACE("HttpProxy value is %s\n", debugstr_wn(value_start, value_end-value_start));
2107             proxy = RPCRT4_strndupW(value_start, value_end-value_start);
2108         }
2109         else
2110             FIXME("unhandled option %s\n", debugstr_w(option));
2111     }
2112
2113     httpc->app_info = InternetOpenW(wszUserAgent, proxy ? INTERNET_OPEN_TYPE_PROXY : INTERNET_OPEN_TYPE_PRECONFIG,
2114                                     NULL, NULL, INTERNET_FLAG_ASYNC);
2115     if (!httpc->app_info)
2116     {
2117         HeapFree(GetProcessHeap(), 0, password);
2118         HeapFree(GetProcessHeap(), 0, user);
2119         ERR("InternetOpenW failed with error %d\n", GetLastError());
2120         return RPC_S_SERVER_UNAVAILABLE;
2121     }
2122     InternetSetStatusCallbackW(httpc->app_info, rpcrt4_http_internet_callback);
2123
2124     /* if no RpcProxy option specified, set the HTTP server address to the
2125      * RPC server address */
2126     if (!servername)
2127     {
2128         servername = HeapAlloc(GetProcessHeap(), 0, (strlen(httpc->common.NetworkAddr) + 1)*sizeof(WCHAR));
2129         if (!servername)
2130         {
2131             HeapFree(GetProcessHeap(), 0, password);
2132             HeapFree(GetProcessHeap(), 0, user);
2133             return RPC_S_OUT_OF_RESOURCES;
2134         }
2135         MultiByteToWideChar(CP_ACP, 0, httpc->common.NetworkAddr, -1, servername, strlen(httpc->common.NetworkAddr) + 1);
2136     }
2137
2138     httpc->session = InternetConnectW(httpc->app_info, servername, port, user, password,
2139                                       INTERNET_SERVICE_HTTP, 0, 0);
2140
2141     HeapFree(GetProcessHeap(), 0, password);
2142     HeapFree(GetProcessHeap(), 0, user);
2143     HeapFree(GetProcessHeap(), 0, servername);
2144
2145     if (!httpc->session)
2146     {
2147         ERR("InternetConnectW failed with error %d\n", GetLastError());
2148         return RPC_S_SERVER_UNAVAILABLE;
2149     }
2150
2151     return RPC_S_OK;
2152 }
2153
2154 /* prepare the in pipe for use by RPC packets */
2155 static RPC_STATUS rpcrt4_http_prepare_in_pipe(HINTERNET in_request, RpcHttpAsyncData *async_data,
2156                                               const UUID *connection_uuid,
2157                                               const UUID *in_pipe_uuid,
2158                                               const UUID *association_uuid)
2159 {
2160     BYTE packet[44];
2161     BOOL ret;
2162     RPC_STATUS status;
2163     RpcPktHdr *hdr;
2164     INTERNET_BUFFERSW buffers_in;
2165     DWORD bytes_read, bytes_written;
2166
2167     /* prepare in pipe */
2168     ResetEvent(async_data->completion_event);
2169     RpcHttpAsyncData_AddRef(async_data);
2170     ret = HttpSendRequestW(in_request, NULL, 0, NULL, 0);
2171     if (!ret)
2172     {
2173         if (GetLastError() == ERROR_IO_PENDING)
2174             WaitForSingleObject(async_data->completion_event, INFINITE);
2175         else
2176         {
2177             RpcHttpAsyncData_Release(async_data);
2178             ERR("HttpSendRequestW failed with error %d\n", GetLastError());
2179             return RPC_S_SERVER_UNAVAILABLE;
2180         }
2181     }
2182     status = rpcrt4_http_check_response(in_request);
2183     if (status != RPC_S_OK) return status;
2184
2185     InternetReadFile(in_request, packet, 20, &bytes_read);
2186     /* FIXME: do something with retrieved data */
2187
2188     memset(&buffers_in, 0, sizeof(buffers_in));
2189     buffers_in.dwStructSize = sizeof(buffers_in);
2190     /* FIXME: get this from the registry */
2191     buffers_in.dwBufferTotal = 1024 * 1024 * 1024; /* 1Gb */
2192     ResetEvent(async_data->completion_event);
2193     RpcHttpAsyncData_AddRef(async_data);
2194     ret = HttpSendRequestExW(in_request, &buffers_in, NULL, 0, 0);
2195     if (!ret)
2196     {
2197         if (GetLastError() == ERROR_IO_PENDING)
2198             WaitForSingleObject(async_data->completion_event, INFINITE);
2199         else
2200         {
2201             RpcHttpAsyncData_Release(async_data);
2202             ERR("HttpSendRequestExW failed with error %d\n", GetLastError());
2203             return RPC_S_SERVER_UNAVAILABLE;
2204         }
2205     }
2206
2207     TRACE("sending HTTP connect header to server\n");
2208     hdr = RPCRT4_BuildHttpConnectHeader(0, FALSE, connection_uuid, in_pipe_uuid, association_uuid);
2209     if (!hdr) return RPC_S_OUT_OF_RESOURCES;
2210     ret = InternetWriteFile(in_request, hdr, hdr->common.frag_len, &bytes_written);
2211     RPCRT4_FreeHeader(hdr);
2212     if (!ret)
2213     {
2214         ERR("InternetWriteFile failed with error %d\n", GetLastError());
2215         return RPC_S_SERVER_UNAVAILABLE;
2216     }
2217
2218     return RPC_S_OK;
2219 }
2220
2221 static RPC_STATUS rpcrt4_http_read_http_packet(HINTERNET request, RpcPktHdr *hdr, BYTE **data)
2222 {
2223     BOOL ret;
2224     DWORD bytes_read;
2225     unsigned short data_len;
2226
2227     ret = InternetReadFile(request, hdr, sizeof(hdr->common), &bytes_read);
2228     if (!ret)
2229         return RPC_S_SERVER_UNAVAILABLE;
2230     if (hdr->common.ptype != PKT_HTTP || hdr->common.frag_len < sizeof(hdr->http))
2231     {
2232         ERR("wrong packet type received %d or wrong frag_len %d\n",
2233             hdr->common.ptype, hdr->common.frag_len);
2234         return RPC_S_PROTOCOL_ERROR;
2235     }
2236
2237     ret = InternetReadFile(request, &hdr->common + 1, sizeof(hdr->http) - sizeof(hdr->common), &bytes_read);
2238     if (!ret)
2239         return RPC_S_SERVER_UNAVAILABLE;
2240
2241     data_len = hdr->common.frag_len - sizeof(hdr->http);
2242     if (data_len)
2243     {
2244         *data = HeapAlloc(GetProcessHeap(), 0, data_len);
2245         if (!*data)
2246             return RPC_S_OUT_OF_RESOURCES;
2247         ret = InternetReadFile(request, *data, data_len, &bytes_read);
2248         if (!ret)
2249         {
2250             HeapFree(GetProcessHeap(), 0, *data);
2251             return RPC_S_SERVER_UNAVAILABLE;
2252         }
2253     }
2254     else
2255         *data = NULL;
2256
2257     if (!RPCRT4_IsValidHttpPacket(hdr, *data, data_len))
2258     {
2259         ERR("invalid http packet\n");
2260         return RPC_S_PROTOCOL_ERROR;
2261     }
2262
2263     return RPC_S_OK;
2264 }
2265
2266 /* prepare the out pipe for use by RPC packets */
2267 static RPC_STATUS rpcrt4_http_prepare_out_pipe(HINTERNET out_request,
2268                                                RpcHttpAsyncData *async_data,
2269                                                const UUID *connection_uuid,
2270                                                const UUID *out_pipe_uuid,
2271                                                ULONG *flow_control_increment)
2272 {
2273     BYTE packet[20];
2274     BOOL ret;
2275     RPC_STATUS status;
2276     RpcPktHdr *hdr;
2277     DWORD bytes_read;
2278     BYTE *data_from_server;
2279     RpcPktHdr pkt_from_server;
2280     ULONG field1, field3;
2281
2282     ResetEvent(async_data->completion_event);
2283     RpcHttpAsyncData_AddRef(async_data);
2284     ret = HttpSendRequestW(out_request, NULL, 0, NULL, 0);
2285     if (!ret)
2286     {
2287         if (GetLastError() == ERROR_IO_PENDING)
2288             WaitForSingleObject(async_data->completion_event, INFINITE);
2289         else
2290         {
2291             RpcHttpAsyncData_Release(async_data);
2292             ERR("HttpSendRequestW failed with error %d\n", GetLastError());
2293             return RPC_S_SERVER_UNAVAILABLE;
2294         }
2295     }
2296     status = rpcrt4_http_check_response(out_request);
2297     if (status != RPC_S_OK) return status;
2298
2299     InternetReadFile(out_request, packet, 20, &bytes_read);
2300     /* FIXME: do something with retrieved data */
2301
2302     hdr = RPCRT4_BuildHttpConnectHeader(0, TRUE, connection_uuid, out_pipe_uuid, NULL);
2303     if (!hdr) return RPC_S_OUT_OF_RESOURCES;
2304     ResetEvent(async_data->completion_event);
2305     RpcHttpAsyncData_AddRef(async_data);
2306     ret = HttpSendRequestW(out_request, NULL, 0, hdr, hdr->common.frag_len);
2307     if (!ret)
2308     {
2309         if (GetLastError() == ERROR_IO_PENDING)
2310             WaitForSingleObject(async_data->completion_event, INFINITE);
2311         else
2312         {
2313             RpcHttpAsyncData_Release(async_data);
2314             ERR("HttpSendRequestW failed with error %d\n", GetLastError());
2315             RPCRT4_FreeHeader(hdr);
2316             return RPC_S_SERVER_UNAVAILABLE;
2317         }
2318     }
2319     RPCRT4_FreeHeader(hdr);
2320     status = rpcrt4_http_check_response(out_request);
2321     if (status != RPC_S_OK) return status;
2322
2323     status = rpcrt4_http_read_http_packet(out_request, &pkt_from_server,
2324                                           &data_from_server);
2325     if (status != RPC_S_OK) return status;
2326     status = RPCRT4_ParseHttpPrepareHeader1(&pkt_from_server, data_from_server,
2327                                             &field1);
2328     HeapFree(GetProcessHeap(), 0, data_from_server);
2329     if (status != RPC_S_OK) return status;
2330     TRACE("received (%d) from first prepare header\n", field1);
2331
2332     status = rpcrt4_http_read_http_packet(out_request, &pkt_from_server,
2333                                           &data_from_server);
2334     if (status != RPC_S_OK) return status;
2335     status = RPCRT4_ParseHttpPrepareHeader2(&pkt_from_server, data_from_server,
2336                                             &field1, flow_control_increment,
2337                                             &field3);
2338     HeapFree(GetProcessHeap(), 0, data_from_server);
2339     if (status != RPC_S_OK) return status;
2340     TRACE("received (0x%08x 0x%08x %d) from second prepare header\n", field1, *flow_control_increment, field3);
2341
2342     return RPC_S_OK;
2343 }
2344
2345 static RPC_STATUS rpcrt4_ncacn_http_open(RpcConnection* Connection)
2346 {
2347     RpcConnection_http *httpc = (RpcConnection_http *)Connection;
2348     static const WCHAR wszVerbIn[] = {'R','P','C','_','I','N','_','D','A','T','A',0};
2349     static const WCHAR wszVerbOut[] = {'R','P','C','_','O','U','T','_','D','A','T','A',0};
2350     static const WCHAR wszRpcProxyPrefix[] = {'/','r','p','c','/','r','p','c','p','r','o','x','y','.','d','l','l','?',0};
2351     static const WCHAR wszColon[] = {':',0};
2352     static const WCHAR wszAcceptType[] = {'a','p','p','l','i','c','a','t','i','o','n','/','r','p','c',0};
2353     LPCWSTR wszAcceptTypes[] = { wszAcceptType, NULL };
2354     WCHAR *url;
2355     RPC_STATUS status;
2356     BOOL secure;
2357     HttpTimerThreadData *timer_data;
2358     HANDLE thread;
2359
2360     TRACE("(%s, %s)\n", Connection->NetworkAddr, Connection->Endpoint);
2361
2362     if (Connection->server)
2363     {
2364         ERR("ncacn_http servers not supported yet\n");
2365         return RPC_S_SERVER_UNAVAILABLE;
2366     }
2367
2368     if (httpc->in_request)
2369         return RPC_S_OK;
2370
2371     httpc->async_data->completion_event = CreateEventW(NULL, FALSE, FALSE, NULL);
2372
2373     status = UuidCreate(&httpc->connection_uuid);
2374     status = UuidCreate(&httpc->in_pipe_uuid);
2375     status = UuidCreate(&httpc->out_pipe_uuid);
2376
2377     status = rpcrt4_http_internet_connect(httpc);
2378     if (status != RPC_S_OK)
2379         return status;
2380
2381     url = HeapAlloc(GetProcessHeap(), 0, sizeof(wszRpcProxyPrefix) + (strlen(Connection->NetworkAddr) + 1 + strlen(Connection->Endpoint))*sizeof(WCHAR));
2382     if (!url)
2383         return RPC_S_OUT_OF_MEMORY;
2384     memcpy(url, wszRpcProxyPrefix, sizeof(wszRpcProxyPrefix));
2385     MultiByteToWideChar(CP_ACP, 0, Connection->NetworkAddr, -1, url+sizeof(wszRpcProxyPrefix)/sizeof(wszRpcProxyPrefix[0])-1, strlen(Connection->NetworkAddr)+1);
2386     strcatW(url, wszColon);
2387     MultiByteToWideChar(CP_ACP, 0, Connection->Endpoint, -1, url+strlenW(url), strlen(Connection->Endpoint)+1);
2388
2389     secure = httpc->common.QOS &&
2390              (httpc->common.QOS->qos->AdditionalSecurityInfoType == RPC_C_AUTHN_INFO_TYPE_HTTP) &&
2391              (httpc->common.QOS->qos->u.HttpCredentials->Flags & RPC_C_HTTP_FLAG_USE_SSL);
2392
2393     httpc->in_request = HttpOpenRequestW(httpc->session, wszVerbIn, url, NULL, NULL,
2394                                          wszAcceptTypes,
2395                                          (secure ? INTERNET_FLAG_SECURE : 0)|INTERNET_FLAG_KEEP_CONNECTION|INTERNET_FLAG_PRAGMA_NOCACHE,
2396                                          (DWORD_PTR)httpc->async_data);
2397     if (!httpc->in_request)
2398     {
2399         ERR("HttpOpenRequestW failed with error %d\n", GetLastError());
2400         return RPC_S_SERVER_UNAVAILABLE;
2401     }
2402     httpc->out_request = HttpOpenRequestW(httpc->session, wszVerbOut, url, NULL, NULL,
2403                                           wszAcceptTypes,
2404                                           (secure ? INTERNET_FLAG_SECURE : 0)|INTERNET_FLAG_KEEP_CONNECTION|INTERNET_FLAG_PRAGMA_NOCACHE,
2405                                           (DWORD_PTR)httpc->async_data);
2406     if (!httpc->out_request)
2407     {
2408         ERR("HttpOpenRequestW failed with error %d\n", GetLastError());
2409         return RPC_S_SERVER_UNAVAILABLE;
2410     }
2411
2412     status = rpcrt4_http_prepare_in_pipe(httpc->in_request,
2413                                          httpc->async_data,
2414                                          &httpc->connection_uuid,
2415                                          &httpc->in_pipe_uuid,
2416                                          &Connection->assoc->http_uuid);
2417     if (status != RPC_S_OK)
2418         return status;
2419
2420     status = rpcrt4_http_prepare_out_pipe(httpc->out_request,
2421                                           httpc->async_data,
2422                                           &httpc->connection_uuid,
2423                                           &httpc->out_pipe_uuid,
2424                                           &httpc->flow_control_increment);
2425     if (status != RPC_S_OK)
2426         return status;
2427
2428     httpc->flow_control_mark = httpc->flow_control_increment / 2;
2429     httpc->last_sent_time = GetTickCount();
2430     httpc->timer_cancelled = CreateEventW(NULL, FALSE, FALSE, NULL);
2431
2432     timer_data = HeapAlloc(GetProcessHeap(), 0, sizeof(*timer_data));
2433     if (!timer_data)
2434         return ERROR_OUTOFMEMORY;
2435     timer_data->timer_param = httpc->in_request;
2436     timer_data->last_sent_time = &httpc->last_sent_time;
2437     timer_data->timer_cancelled = httpc->timer_cancelled;
2438     /* FIXME: should use CreateTimerQueueTimer when implemented */
2439     thread = CreateThread(NULL, 0, rpcrt4_http_timer_thread, timer_data, 0, NULL);
2440     if (!thread)
2441     {
2442         HeapFree(GetProcessHeap(), 0, timer_data);
2443         return GetLastError();
2444     }
2445     CloseHandle(thread);
2446
2447     return RPC_S_OK;
2448 }
2449
2450 static RPC_STATUS rpcrt4_ncacn_http_handoff(RpcConnection *old_conn, RpcConnection *new_conn)
2451 {
2452     assert(0);
2453     return RPC_S_SERVER_UNAVAILABLE;
2454 }
2455
2456 static int rpcrt4_ncacn_http_read(RpcConnection *Connection,
2457                                 void *buffer, unsigned int count)
2458 {
2459   RpcConnection_http *httpc = (RpcConnection_http *) Connection;
2460   char *buf = buffer;
2461   BOOL ret = TRUE;
2462   unsigned int bytes_left = count;
2463
2464   ResetEvent(httpc->async_data->completion_event);
2465   while (bytes_left)
2466   {
2467     RpcHttpAsyncData_AddRef(httpc->async_data);
2468     httpc->async_data->inet_buffers.dwBufferLength = bytes_left;
2469     httpc->async_data->inet_buffers.lpvBuffer = HeapAlloc(GetProcessHeap(), 0, bytes_left);
2470     httpc->async_data->destination_buffer = buf;
2471     ret = InternetReadFileExA(httpc->out_request, &httpc->async_data->inet_buffers, IRF_ASYNC, 0);
2472     if (ret)
2473     {
2474         /* INTERNET_STATUS_REQUEST_COMPLETED won't be sent, so release our
2475          * async ref now */
2476         RpcHttpAsyncData_Release(httpc->async_data);
2477         memcpy(buf, httpc->async_data->inet_buffers.lpvBuffer,
2478                httpc->async_data->inet_buffers.dwBufferLength);
2479         HeapFree(GetProcessHeap(), 0, httpc->async_data->inet_buffers.lpvBuffer);
2480         httpc->async_data->inet_buffers.lpvBuffer = NULL;
2481         httpc->async_data->destination_buffer = NULL;
2482     }
2483     else
2484     {
2485         if (GetLastError() == ERROR_IO_PENDING)
2486         {
2487             HANDLE handles[2] = { httpc->async_data->completion_event, httpc->cancel_event };
2488             DWORD result = WaitForMultipleObjects(2, handles, FALSE, DEFAULT_NCACN_HTTP_TIMEOUT);
2489             if (result == WAIT_OBJECT_0)
2490                 ret = TRUE;
2491             else
2492             {
2493                 TRACE("call cancelled\n");
2494                 EnterCriticalSection(&httpc->async_data->cs);
2495                 httpc->async_data->destination_buffer = NULL;
2496                 LeaveCriticalSection(&httpc->async_data->cs);
2497                 break;
2498             }
2499         }
2500         else
2501         {
2502             HeapFree(GetProcessHeap(), 0, httpc->async_data->inet_buffers.lpvBuffer);
2503             httpc->async_data->inet_buffers.lpvBuffer = NULL;
2504             httpc->async_data->destination_buffer = NULL;
2505             RpcHttpAsyncData_Release(httpc->async_data);
2506             break;
2507         }
2508     }
2509     if (!httpc->async_data->inet_buffers.dwBufferLength)
2510         break;
2511     bytes_left -= httpc->async_data->inet_buffers.dwBufferLength;
2512     buf += httpc->async_data->inet_buffers.dwBufferLength;
2513   }
2514   TRACE("%p %p %u -> %s\n", httpc->out_request, buffer, count, ret ? "TRUE" : "FALSE");
2515   return ret ? count : -1;
2516 }
2517
2518 static RPC_STATUS rpcrt4_ncacn_http_receive_fragment(RpcConnection *Connection, RpcPktHdr **Header, void **Payload)
2519 {
2520   RpcConnection_http *httpc = (RpcConnection_http *) Connection;
2521   RPC_STATUS status;
2522   DWORD hdr_length;
2523   LONG dwRead;
2524   RpcPktCommonHdr common_hdr;
2525
2526   *Header = NULL;
2527
2528   TRACE("(%p, %p, %p)\n", Connection, Header, Payload);
2529
2530 again:
2531   /* read packet common header */
2532   dwRead = rpcrt4_ncacn_http_read(Connection, &common_hdr, sizeof(common_hdr));
2533   if (dwRead != sizeof(common_hdr)) {
2534     WARN("Short read of header, %d bytes\n", dwRead);
2535     status = RPC_S_PROTOCOL_ERROR;
2536     goto fail;
2537   }
2538   if (!memcmp(&common_hdr, "HTTP/1.1", sizeof("HTTP/1.1")) ||
2539       !memcmp(&common_hdr, "HTTP/1.0", sizeof("HTTP/1.0")))
2540   {
2541     FIXME("server returned %s\n", debugstr_a((const char *)&common_hdr));
2542     status = RPC_S_PROTOCOL_ERROR;
2543     goto fail;
2544   }
2545
2546   status = RPCRT4_ValidateCommonHeader(&common_hdr);
2547   if (status != RPC_S_OK) goto fail;
2548
2549   hdr_length = RPCRT4_GetHeaderSize((RpcPktHdr*)&common_hdr);
2550   if (hdr_length == 0) {
2551     WARN("header length == 0\n");
2552     status = RPC_S_PROTOCOL_ERROR;
2553     goto fail;
2554   }
2555
2556   *Header = HeapAlloc(GetProcessHeap(), 0, hdr_length);
2557   if (!*Header)
2558   {
2559     status = RPC_S_OUT_OF_RESOURCES;
2560     goto fail;
2561   }
2562   memcpy(*Header, &common_hdr, sizeof(common_hdr));
2563
2564   /* read the rest of packet header */
2565   dwRead = rpcrt4_ncacn_http_read(Connection, &(*Header)->common + 1, hdr_length - sizeof(common_hdr));
2566   if (dwRead != hdr_length - sizeof(common_hdr)) {
2567     WARN("bad header length, %d bytes, hdr_length %d\n", dwRead, hdr_length);
2568     status = RPC_S_PROTOCOL_ERROR;
2569     goto fail;
2570   }
2571
2572   if (common_hdr.frag_len - hdr_length)
2573   {
2574     *Payload = HeapAlloc(GetProcessHeap(), 0, common_hdr.frag_len - hdr_length);
2575     if (!*Payload)
2576     {
2577       status = RPC_S_OUT_OF_RESOURCES;
2578       goto fail;
2579     }
2580
2581     dwRead = rpcrt4_ncacn_http_read(Connection, *Payload, common_hdr.frag_len - hdr_length);
2582     if (dwRead != common_hdr.frag_len - hdr_length)
2583     {
2584       WARN("bad data length, %d/%d\n", dwRead, common_hdr.frag_len - hdr_length);
2585       status = RPC_S_PROTOCOL_ERROR;
2586       goto fail;
2587     }
2588   }
2589   else
2590     *Payload = NULL;
2591
2592   if ((*Header)->common.ptype == PKT_HTTP)
2593   {
2594     if (!RPCRT4_IsValidHttpPacket(*Header, *Payload, common_hdr.frag_len - hdr_length))
2595     {
2596       ERR("invalid http packet of length %d bytes\n", (*Header)->common.frag_len);
2597       status = RPC_S_PROTOCOL_ERROR;
2598       goto fail;
2599     }
2600     if ((*Header)->http.flags == 0x0001)
2601     {
2602       TRACE("http idle packet, waiting for real packet\n");
2603       if ((*Header)->http.num_data_items != 0)
2604       {
2605         ERR("HTTP idle packet should have no data items instead of %d\n", (*Header)->http.num_data_items);
2606         status = RPC_S_PROTOCOL_ERROR;
2607         goto fail;
2608       }
2609     }
2610     else if ((*Header)->http.flags == 0x0002)
2611     {
2612       ULONG bytes_transmitted;
2613       ULONG flow_control_increment;
2614       UUID pipe_uuid;
2615       status = RPCRT4_ParseHttpFlowControlHeader(*Header, *Payload,
2616                                                  Connection->server,
2617                                                  &bytes_transmitted,
2618                                                  &flow_control_increment,
2619                                                  &pipe_uuid);
2620       if (status != RPC_S_OK)
2621         goto fail;
2622       TRACE("received http flow control header (0x%x, 0x%x, %s)\n",
2623             bytes_transmitted, flow_control_increment, debugstr_guid(&pipe_uuid));
2624       /* FIXME: do something with parsed data */
2625     }
2626     else
2627     {
2628       FIXME("unrecognised http packet with flags 0x%04x\n", (*Header)->http.flags);
2629       status = RPC_S_PROTOCOL_ERROR;
2630       goto fail;
2631     }
2632     RPCRT4_FreeHeader(*Header);
2633     *Header = NULL;
2634     HeapFree(GetProcessHeap(), 0, *Payload);
2635     *Payload = NULL;
2636     goto again;
2637   }
2638
2639   /* success */
2640   status = RPC_S_OK;
2641
2642   httpc->bytes_received += common_hdr.frag_len;
2643
2644   TRACE("httpc->bytes_received = 0x%x\n", httpc->bytes_received);
2645
2646   if (httpc->bytes_received > httpc->flow_control_mark)
2647   {
2648     RpcPktHdr *hdr = RPCRT4_BuildHttpFlowControlHeader(httpc->common.server,
2649                                                        httpc->bytes_received,
2650                                                        httpc->flow_control_increment,
2651                                                        &httpc->out_pipe_uuid);
2652     if (hdr)
2653     {
2654       DWORD bytes_written;
2655       BOOL ret2;
2656       TRACE("sending flow control packet at 0x%x\n", httpc->bytes_received);
2657       ret2 = InternetWriteFile(httpc->in_request, hdr, hdr->common.frag_len, &bytes_written);
2658       RPCRT4_FreeHeader(hdr);
2659       if (ret2)
2660         httpc->flow_control_mark = httpc->bytes_received + httpc->flow_control_increment / 2;
2661     }
2662   }
2663
2664 fail:
2665   if (status != RPC_S_OK) {
2666     RPCRT4_FreeHeader(*Header);
2667     *Header = NULL;
2668     HeapFree(GetProcessHeap(), 0, *Payload);
2669     *Payload = NULL;
2670   }
2671   return status;
2672 }
2673
2674 static int rpcrt4_ncacn_http_write(RpcConnection *Connection,
2675                                  const void *buffer, unsigned int count)
2676 {
2677   RpcConnection_http *httpc = (RpcConnection_http *) Connection;
2678   DWORD bytes_written;
2679   BOOL ret;
2680
2681   httpc->last_sent_time = ~0U; /* disable idle packet sending */
2682   ret = InternetWriteFile(httpc->in_request, buffer, count, &bytes_written);
2683   httpc->last_sent_time = GetTickCount();
2684   TRACE("%p %p %u -> %s\n", httpc->in_request, buffer, count, ret ? "TRUE" : "FALSE");
2685   return ret ? bytes_written : -1;
2686 }
2687
2688 static int rpcrt4_ncacn_http_close(RpcConnection *Connection)
2689 {
2690   RpcConnection_http *httpc = (RpcConnection_http *) Connection;
2691
2692   TRACE("\n");
2693
2694   SetEvent(httpc->timer_cancelled);
2695   if (httpc->in_request)
2696     InternetCloseHandle(httpc->in_request);
2697   httpc->in_request = NULL;
2698   if (httpc->out_request)
2699     InternetCloseHandle(httpc->out_request);
2700   httpc->out_request = NULL;
2701   if (httpc->app_info)
2702     InternetCloseHandle(httpc->app_info);
2703   httpc->app_info = NULL;
2704   if (httpc->session)
2705     InternetCloseHandle(httpc->session);
2706   httpc->session = NULL;
2707   RpcHttpAsyncData_Release(httpc->async_data);
2708   if (httpc->cancel_event)
2709     CloseHandle(httpc->cancel_event);
2710
2711   return 0;
2712 }
2713
2714 static void rpcrt4_ncacn_http_cancel_call(RpcConnection *Connection)
2715 {
2716   RpcConnection_http *httpc = (RpcConnection_http *) Connection;
2717
2718   SetEvent(httpc->cancel_event);
2719 }
2720
2721 static int rpcrt4_ncacn_http_wait_for_incoming_data(RpcConnection *Connection)
2722 {
2723   BOOL ret;
2724   RpcConnection_http *httpc = (RpcConnection_http *) Connection;
2725
2726   RpcHttpAsyncData_AddRef(httpc->async_data);
2727   ret = InternetQueryDataAvailable(httpc->out_request,
2728     &httpc->async_data->inet_buffers.dwBufferLength, IRF_ASYNC, 0);
2729   if (ret)
2730   {
2731       /* INTERNET_STATUS_REQUEST_COMPLETED won't be sent, so release our
2732        * async ref now */
2733       RpcHttpAsyncData_Release(httpc->async_data);
2734   }
2735   else
2736   {
2737     if (GetLastError() == ERROR_IO_PENDING)
2738     {
2739       HANDLE handles[2] = { httpc->async_data->completion_event, httpc->cancel_event };
2740       DWORD result = WaitForMultipleObjects(2, handles, FALSE, DEFAULT_NCACN_HTTP_TIMEOUT);
2741       if (result != WAIT_OBJECT_0)
2742       {
2743         TRACE("call cancelled\n");
2744         return -1;
2745       }
2746     }
2747     else
2748     {
2749       RpcHttpAsyncData_Release(httpc->async_data);
2750       return -1;
2751     }
2752   }
2753
2754   /* success */
2755   return 0;
2756 }
2757
2758 static size_t rpcrt4_ncacn_http_get_top_of_tower(unsigned char *tower_data,
2759                                                  const char *networkaddr,
2760                                                  const char *endpoint)
2761 {
2762     return rpcrt4_ip_tcp_get_top_of_tower(tower_data, networkaddr,
2763                                           EPM_PROTOCOL_HTTP, endpoint);
2764 }
2765
2766 static RPC_STATUS rpcrt4_ncacn_http_parse_top_of_tower(const unsigned char *tower_data,
2767                                                        size_t tower_size,
2768                                                        char **networkaddr,
2769                                                        char **endpoint)
2770 {
2771     return rpcrt4_ip_tcp_parse_top_of_tower(tower_data, tower_size,
2772                                             networkaddr, EPM_PROTOCOL_HTTP,
2773                                             endpoint);
2774 }
2775
2776 static const struct connection_ops conn_protseq_list[] = {
2777   { "ncacn_np",
2778     { EPM_PROTOCOL_NCACN, EPM_PROTOCOL_SMB },
2779     rpcrt4_conn_np_alloc,
2780     rpcrt4_ncacn_np_open,
2781     rpcrt4_ncacn_np_handoff,
2782     rpcrt4_conn_np_read,
2783     rpcrt4_conn_np_write,
2784     rpcrt4_conn_np_close,
2785     rpcrt4_conn_np_cancel_call,
2786     rpcrt4_conn_np_wait_for_incoming_data,
2787     rpcrt4_ncacn_np_get_top_of_tower,
2788     rpcrt4_ncacn_np_parse_top_of_tower,
2789     NULL,
2790     RPCRT4_default_is_authorized,
2791     RPCRT4_default_authorize,
2792     RPCRT4_default_secure_packet,
2793     rpcrt4_conn_np_impersonate_client,
2794     rpcrt4_conn_np_revert_to_self,
2795     RPCRT4_default_inquire_auth_client,
2796   },
2797   { "ncalrpc",
2798     { EPM_PROTOCOL_NCALRPC, EPM_PROTOCOL_PIPE },
2799     rpcrt4_conn_np_alloc,
2800     rpcrt4_ncalrpc_open,
2801     rpcrt4_ncalrpc_handoff,
2802     rpcrt4_conn_np_read,
2803     rpcrt4_conn_np_write,
2804     rpcrt4_conn_np_close,
2805     rpcrt4_conn_np_cancel_call,
2806     rpcrt4_conn_np_wait_for_incoming_data,
2807     rpcrt4_ncalrpc_get_top_of_tower,
2808     rpcrt4_ncalrpc_parse_top_of_tower,
2809     NULL,
2810     rpcrt4_ncalrpc_is_authorized,
2811     rpcrt4_ncalrpc_authorize,
2812     rpcrt4_ncalrpc_secure_packet,
2813     rpcrt4_conn_np_impersonate_client,
2814     rpcrt4_conn_np_revert_to_self,
2815     rpcrt4_ncalrpc_inquire_auth_client,
2816   },
2817   { "ncacn_ip_tcp",
2818     { EPM_PROTOCOL_NCACN, EPM_PROTOCOL_TCP },
2819     rpcrt4_conn_tcp_alloc,
2820     rpcrt4_ncacn_ip_tcp_open,
2821     rpcrt4_conn_tcp_handoff,
2822     rpcrt4_conn_tcp_read,
2823     rpcrt4_conn_tcp_write,
2824     rpcrt4_conn_tcp_close,
2825     rpcrt4_conn_tcp_cancel_call,
2826     rpcrt4_conn_tcp_wait_for_incoming_data,
2827     rpcrt4_ncacn_ip_tcp_get_top_of_tower,
2828     rpcrt4_ncacn_ip_tcp_parse_top_of_tower,
2829     NULL,
2830     RPCRT4_default_is_authorized,
2831     RPCRT4_default_authorize,
2832     RPCRT4_default_secure_packet,
2833     RPCRT4_default_impersonate_client,
2834     RPCRT4_default_revert_to_self,
2835     RPCRT4_default_inquire_auth_client,
2836   },
2837   { "ncacn_http",
2838     { EPM_PROTOCOL_NCACN, EPM_PROTOCOL_HTTP },
2839     rpcrt4_ncacn_http_alloc,
2840     rpcrt4_ncacn_http_open,
2841     rpcrt4_ncacn_http_handoff,
2842     rpcrt4_ncacn_http_read,
2843     rpcrt4_ncacn_http_write,
2844     rpcrt4_ncacn_http_close,
2845     rpcrt4_ncacn_http_cancel_call,
2846     rpcrt4_ncacn_http_wait_for_incoming_data,
2847     rpcrt4_ncacn_http_get_top_of_tower,
2848     rpcrt4_ncacn_http_parse_top_of_tower,
2849     rpcrt4_ncacn_http_receive_fragment,
2850     RPCRT4_default_is_authorized,
2851     RPCRT4_default_authorize,
2852     RPCRT4_default_secure_packet,
2853     RPCRT4_default_impersonate_client,
2854     RPCRT4_default_revert_to_self,
2855     RPCRT4_default_inquire_auth_client,
2856   },
2857 };
2858
2859
2860 static const struct protseq_ops protseq_list[] =
2861 {
2862     {
2863         "ncacn_np",
2864         rpcrt4_protseq_np_alloc,
2865         rpcrt4_protseq_np_signal_state_changed,
2866         rpcrt4_protseq_np_get_wait_array,
2867         rpcrt4_protseq_np_free_wait_array,
2868         rpcrt4_protseq_np_wait_for_new_connection,
2869         rpcrt4_protseq_ncacn_np_open_endpoint,
2870     },
2871     {
2872         "ncalrpc",
2873         rpcrt4_protseq_np_alloc,
2874         rpcrt4_protseq_np_signal_state_changed,
2875         rpcrt4_protseq_np_get_wait_array,
2876         rpcrt4_protseq_np_free_wait_array,
2877         rpcrt4_protseq_np_wait_for_new_connection,
2878         rpcrt4_protseq_ncalrpc_open_endpoint,
2879     },
2880     {
2881         "ncacn_ip_tcp",
2882         rpcrt4_protseq_sock_alloc,
2883         rpcrt4_protseq_sock_signal_state_changed,
2884         rpcrt4_protseq_sock_get_wait_array,
2885         rpcrt4_protseq_sock_free_wait_array,
2886         rpcrt4_protseq_sock_wait_for_new_connection,
2887         rpcrt4_protseq_ncacn_ip_tcp_open_endpoint,
2888     },
2889 };
2890
2891 #define ARRAYSIZE(a) (sizeof((a)) / sizeof((a)[0]))
2892
2893 const struct protseq_ops *rpcrt4_get_protseq_ops(const char *protseq)
2894 {
2895   unsigned int i;
2896   for(i=0; i<ARRAYSIZE(protseq_list); i++)
2897     if (!strcmp(protseq_list[i].name, protseq))
2898       return &protseq_list[i];
2899   return NULL;
2900 }
2901
2902 static const struct connection_ops *rpcrt4_get_conn_protseq_ops(const char *protseq)
2903 {
2904     unsigned int i;
2905     for(i=0; i<ARRAYSIZE(conn_protseq_list); i++)
2906         if (!strcmp(conn_protseq_list[i].name, protseq))
2907             return &conn_protseq_list[i];
2908     return NULL;
2909 }
2910
2911 /**** interface to rest of code ****/
2912
2913 RPC_STATUS RPCRT4_OpenClientConnection(RpcConnection* Connection)
2914 {
2915   TRACE("(Connection == ^%p)\n", Connection);
2916
2917   assert(!Connection->server);
2918   return Connection->ops->open_connection_client(Connection);
2919 }
2920
2921 RPC_STATUS RPCRT4_CloseConnection(RpcConnection* Connection)
2922 {
2923   TRACE("(Connection == ^%p)\n", Connection);
2924   if (SecIsValidHandle(&Connection->ctx))
2925   {
2926     DeleteSecurityContext(&Connection->ctx);
2927     SecInvalidateHandle(&Connection->ctx);
2928   }
2929   rpcrt4_conn_close(Connection);
2930   return RPC_S_OK;
2931 }
2932
2933 RPC_STATUS RPCRT4_CreateConnection(RpcConnection** Connection, BOOL server,
2934     LPCSTR Protseq, LPCSTR NetworkAddr, LPCSTR Endpoint,
2935     LPCWSTR NetworkOptions, RpcAuthInfo* AuthInfo, RpcQualityOfService *QOS)
2936 {
2937   static LONG next_id;
2938   const struct connection_ops *ops;
2939   RpcConnection* NewConnection;
2940
2941   ops = rpcrt4_get_conn_protseq_ops(Protseq);
2942   if (!ops)
2943   {
2944     FIXME("not supported for protseq %s\n", Protseq);
2945     return RPC_S_PROTSEQ_NOT_SUPPORTED;
2946   }
2947
2948   NewConnection = ops->alloc();
2949   NewConnection->ref = 1;
2950   NewConnection->Next = NULL;
2951   NewConnection->server_binding = NULL;
2952   NewConnection->server = server;
2953   NewConnection->ops = ops;
2954   NewConnection->NetworkAddr = RPCRT4_strdupA(NetworkAddr);
2955   NewConnection->Endpoint = RPCRT4_strdupA(Endpoint);
2956   NewConnection->NetworkOptions = RPCRT4_strdupW(NetworkOptions);
2957   NewConnection->MaxTransmissionSize = RPC_MAX_PACKET_SIZE;
2958   memset(&NewConnection->ActiveInterface, 0, sizeof(NewConnection->ActiveInterface));
2959   NewConnection->NextCallId = 1;
2960
2961   SecInvalidateHandle(&NewConnection->ctx);
2962   memset(&NewConnection->exp, 0, sizeof(NewConnection->exp));
2963   NewConnection->attr = 0;
2964   if (AuthInfo) RpcAuthInfo_AddRef(AuthInfo);
2965   NewConnection->AuthInfo = AuthInfo;
2966   NewConnection->auth_context_id = InterlockedIncrement( &next_id );
2967   NewConnection->encryption_auth_len = 0;
2968   NewConnection->signature_auth_len = 0;
2969   if (QOS) RpcQualityOfService_AddRef(QOS);
2970   NewConnection->QOS = QOS;
2971
2972   list_init(&NewConnection->conn_pool_entry);
2973   NewConnection->async_state = NULL;
2974
2975   TRACE("connection: %p\n", NewConnection);
2976   *Connection = NewConnection;
2977
2978   return RPC_S_OK;
2979 }
2980
2981 static RPC_STATUS RPCRT4_SpawnConnection(RpcConnection** Connection, RpcConnection* OldConnection)
2982 {
2983   RPC_STATUS err;
2984
2985   err = RPCRT4_CreateConnection(Connection, OldConnection->server,
2986                                 rpcrt4_conn_get_name(OldConnection),
2987                                 OldConnection->NetworkAddr,
2988                                 OldConnection->Endpoint, NULL,
2989                                 OldConnection->AuthInfo, OldConnection->QOS);
2990   if (err == RPC_S_OK)
2991     rpcrt4_conn_handoff(OldConnection, *Connection);
2992   return err;
2993 }
2994
2995 RpcConnection *RPCRT4_GrabConnection( RpcConnection *conn )
2996 {
2997     InterlockedIncrement( &conn->ref );
2998     return conn;
2999 }
3000
3001 RPC_STATUS RPCRT4_ReleaseConnection(RpcConnection* Connection)
3002 {
3003   if (InterlockedDecrement( &Connection->ref ) > 0) return RPC_S_OK;
3004
3005   TRACE("destroying connection %p\n", Connection);
3006
3007   RPCRT4_CloseConnection(Connection);
3008   RPCRT4_strfree(Connection->Endpoint);
3009   RPCRT4_strfree(Connection->NetworkAddr);
3010   HeapFree(GetProcessHeap(), 0, Connection->NetworkOptions);
3011   if (Connection->AuthInfo) RpcAuthInfo_Release(Connection->AuthInfo);
3012   if (Connection->QOS) RpcQualityOfService_Release(Connection->QOS);
3013
3014   /* server-only */
3015   if (Connection->server_binding) RPCRT4_ReleaseBinding(Connection->server_binding);
3016
3017   HeapFree(GetProcessHeap(), 0, Connection);
3018   return RPC_S_OK;
3019 }
3020
3021 RPC_STATUS RpcTransport_GetTopOfTower(unsigned char *tower_data,
3022                                       size_t *tower_size,
3023                                       const char *protseq,
3024                                       const char *networkaddr,
3025                                       const char *endpoint)
3026 {
3027     twr_empty_floor_t *protocol_floor;
3028     const struct connection_ops *protseq_ops = rpcrt4_get_conn_protseq_ops(protseq);
3029
3030     *tower_size = 0;
3031
3032     if (!protseq_ops)
3033         return RPC_S_INVALID_RPC_PROTSEQ;
3034
3035     if (!tower_data)
3036     {
3037         *tower_size = sizeof(*protocol_floor);
3038         *tower_size += protseq_ops->get_top_of_tower(NULL, networkaddr, endpoint);
3039         return RPC_S_OK;
3040     }
3041
3042     protocol_floor = (twr_empty_floor_t *)tower_data;
3043     protocol_floor->count_lhs = sizeof(protocol_floor->protid);
3044     protocol_floor->protid = protseq_ops->epm_protocols[0];
3045     protocol_floor->count_rhs = 0;
3046
3047     tower_data += sizeof(*protocol_floor);
3048
3049     *tower_size = protseq_ops->get_top_of_tower(tower_data, networkaddr, endpoint);
3050     if (!*tower_size)
3051         return EPT_S_NOT_REGISTERED;
3052
3053     *tower_size += sizeof(*protocol_floor);
3054
3055     return RPC_S_OK;
3056 }
3057
3058 RPC_STATUS RpcTransport_ParseTopOfTower(const unsigned char *tower_data,
3059                                         size_t tower_size,
3060                                         char **protseq,
3061                                         char **networkaddr,
3062                                         char **endpoint)
3063 {
3064     const twr_empty_floor_t *protocol_floor;
3065     const twr_empty_floor_t *floor4;
3066     const struct connection_ops *protseq_ops = NULL;
3067     RPC_STATUS status;
3068     unsigned int i;
3069
3070     if (tower_size < sizeof(*protocol_floor))
3071         return EPT_S_NOT_REGISTERED;
3072
3073     protocol_floor = (const twr_empty_floor_t *)tower_data;
3074     tower_data += sizeof(*protocol_floor);
3075     tower_size -= sizeof(*protocol_floor);
3076     if ((protocol_floor->count_lhs != sizeof(protocol_floor->protid)) ||
3077         (protocol_floor->count_rhs > tower_size))
3078         return EPT_S_NOT_REGISTERED;
3079     tower_data += protocol_floor->count_rhs;
3080     tower_size -= protocol_floor->count_rhs;
3081
3082     floor4 = (const twr_empty_floor_t *)tower_data;
3083     if ((tower_size < sizeof(*floor4)) ||
3084         (floor4->count_lhs != sizeof(floor4->protid)))
3085         return EPT_S_NOT_REGISTERED;
3086
3087     for(i = 0; i < ARRAYSIZE(conn_protseq_list); i++)
3088         if ((protocol_floor->protid == conn_protseq_list[i].epm_protocols[0]) &&
3089             (floor4->protid == conn_protseq_list[i].epm_protocols[1]))
3090         {
3091             protseq_ops = &conn_protseq_list[i];
3092             break;
3093         }
3094
3095     if (!protseq_ops)
3096         return EPT_S_NOT_REGISTERED;
3097
3098     status = protseq_ops->parse_top_of_tower(tower_data, tower_size, networkaddr, endpoint);
3099
3100     if ((status == RPC_S_OK) && protseq)
3101     {
3102         *protseq = I_RpcAllocate(strlen(protseq_ops->name) + 1);
3103         strcpy(*protseq, protseq_ops->name);
3104     }
3105
3106     return status;
3107 }
3108
3109 /***********************************************************************
3110  *             RpcNetworkIsProtseqValidW (RPCRT4.@)
3111  *
3112  * Checks if the given protocol sequence is known by the RPC system.
3113  * If it is, returns RPC_S_OK, otherwise RPC_S_PROTSEQ_NOT_SUPPORTED.
3114  *
3115  */
3116 RPC_STATUS WINAPI RpcNetworkIsProtseqValidW(RPC_WSTR protseq)
3117 {
3118   char ps[0x10];
3119
3120   WideCharToMultiByte(CP_ACP, 0, protseq, -1,
3121                       ps, sizeof ps, NULL, NULL);
3122   if (rpcrt4_get_conn_protseq_ops(ps))
3123     return RPC_S_OK;
3124
3125   FIXME("Unknown protseq %s\n", debugstr_w(protseq));
3126
3127   return RPC_S_INVALID_RPC_PROTSEQ;
3128 }
3129
3130 /***********************************************************************
3131  *             RpcNetworkIsProtseqValidA (RPCRT4.@)
3132  */
3133 RPC_STATUS WINAPI RpcNetworkIsProtseqValidA(RPC_CSTR protseq)
3134 {
3135   UNICODE_STRING protseqW;
3136
3137   if (RtlCreateUnicodeStringFromAsciiz(&protseqW, (char*)protseq))
3138   {
3139     RPC_STATUS ret = RpcNetworkIsProtseqValidW(protseqW.Buffer);
3140     RtlFreeUnicodeString(&protseqW);
3141     return ret;
3142   }
3143   return RPC_S_OUT_OF_MEMORY;
3144 }
3145
3146 /***********************************************************************
3147  *             RpcProtseqVectorFreeA (RPCRT4.@)
3148  */
3149 RPC_STATUS WINAPI RpcProtseqVectorFreeA(RPC_PROTSEQ_VECTORA **protseqs)
3150 {
3151   TRACE("(%p)\n", protseqs);
3152
3153   if (*protseqs)
3154   {
3155     int i;
3156     for (i = 0; i < (*protseqs)->Count; i++)
3157       HeapFree(GetProcessHeap(), 0, (*protseqs)->Protseq[i]);
3158     HeapFree(GetProcessHeap(), 0, *protseqs);
3159     *protseqs = NULL;
3160   }
3161   return RPC_S_OK;
3162 }
3163
3164 /***********************************************************************
3165  *             RpcProtseqVectorFreeW (RPCRT4.@)
3166  */
3167 RPC_STATUS WINAPI RpcProtseqVectorFreeW(RPC_PROTSEQ_VECTORW **protseqs)
3168 {
3169   TRACE("(%p)\n", protseqs);
3170
3171   if (*protseqs)
3172   {
3173     int i;
3174     for (i = 0; i < (*protseqs)->Count; i++)
3175       HeapFree(GetProcessHeap(), 0, (*protseqs)->Protseq[i]);
3176     HeapFree(GetProcessHeap(), 0, *protseqs);
3177     *protseqs = NULL;
3178   }
3179   return RPC_S_OK;
3180 }
3181
3182 /***********************************************************************
3183  *             RpcNetworkInqProtseqsW (RPCRT4.@)
3184  */
3185 RPC_STATUS WINAPI RpcNetworkInqProtseqsW( RPC_PROTSEQ_VECTORW** protseqs )
3186 {
3187   RPC_PROTSEQ_VECTORW *pvector;
3188   int i = 0;
3189   RPC_STATUS status = RPC_S_OUT_OF_MEMORY;
3190
3191   TRACE("(%p)\n", protseqs);
3192
3193   *protseqs = HeapAlloc(GetProcessHeap(), 0, sizeof(RPC_PROTSEQ_VECTORW)+(sizeof(unsigned short*)*ARRAYSIZE(protseq_list)));
3194   if (!*protseqs)
3195     goto end;
3196   pvector = *protseqs;
3197   pvector->Count = 0;
3198   for (i = 0; i < ARRAYSIZE(protseq_list); i++)
3199   {
3200     pvector->Protseq[i] = HeapAlloc(GetProcessHeap(), 0, (strlen(protseq_list[i].name)+1)*sizeof(unsigned short));
3201     if (pvector->Protseq[i] == NULL)
3202       goto end;
3203     MultiByteToWideChar(CP_ACP, 0, (CHAR*)protseq_list[i].name, -1,
3204       (WCHAR*)pvector->Protseq[i], strlen(protseq_list[i].name) + 1);
3205     pvector->Count++;
3206   }
3207   status = RPC_S_OK;
3208
3209 end:
3210   if (status != RPC_S_OK)
3211     RpcProtseqVectorFreeW(protseqs);
3212   return status;
3213 }
3214
3215 /***********************************************************************
3216  *             RpcNetworkInqProtseqsA (RPCRT4.@)
3217  */
3218 RPC_STATUS WINAPI RpcNetworkInqProtseqsA(RPC_PROTSEQ_VECTORA** protseqs)
3219 {
3220   RPC_PROTSEQ_VECTORA *pvector;
3221   int i = 0;
3222   RPC_STATUS status = RPC_S_OUT_OF_MEMORY;
3223
3224   TRACE("(%p)\n", protseqs);
3225
3226   *protseqs = HeapAlloc(GetProcessHeap(), 0, sizeof(RPC_PROTSEQ_VECTORW)+(sizeof(unsigned char*)*ARRAYSIZE(protseq_list)));
3227   if (!*protseqs)
3228     goto end;
3229   pvector = *protseqs;
3230   pvector->Count = 0;
3231   for (i = 0; i < ARRAYSIZE(protseq_list); i++)
3232   {
3233     pvector->Protseq[i] = HeapAlloc(GetProcessHeap(), 0, strlen(protseq_list[i].name)+1);
3234     if (pvector->Protseq[i] == NULL)
3235       goto end;
3236     strcpy((char*)pvector->Protseq[i], protseq_list[i].name);
3237     pvector->Count++;
3238   }
3239   status = RPC_S_OK;
3240
3241 end:
3242   if (status != RPC_S_OK)
3243     RpcProtseqVectorFreeA(protseqs);
3244   return status;
3245 }