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