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