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
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.
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.
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
33 #include <sys/types.h>
35 #if defined(__MINGW32__) || defined (_MSC_VER)
36 # include <ws2tcpip.h>
38 # define EADDRINUSE WSAEADDRINUSE
41 # define EAGAIN WSAEWOULDBLOCK
44 # define errno WSAGetLastError()
51 # ifdef HAVE_SYS_SOCKET_H
52 # include <sys/socket.h>
54 # ifdef HAVE_NETINET_IN_H
55 # include <netinet/in.h>
57 # ifdef HAVE_NETINET_TCP_H
58 # include <netinet/tcp.h>
60 # ifdef HAVE_ARPA_INET_H
61 # include <arpa/inet.h>
66 # ifdef HAVE_SYS_POLL_H
67 # include <sys/poll.h>
69 # ifdef HAVE_SYS_FILIO_H
70 # include <sys/filio.h>
72 # ifdef HAVE_SYS_IOCTL_H
73 # include <sys/ioctl.h>
75 # define closesocket close
76 # define ioctlsocket ioctl
77 #endif /* defined(__MINGW32__) || defined (_MSC_VER) */
85 #include "wine/unicode.h"
90 #include "wine/debug.h"
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"
99 # define SOL_TCP IPPROTO_TCP
102 #define DEFAULT_NCACN_HTTP_TIMEOUT (60 * 1000)
104 WINE_DEFAULT_DEBUG_CHANNEL(rpc);
106 static RPC_STATUS RPCRT4_SpawnConnection(RpcConnection** Connection, RpcConnection* OldConnection);
108 /**** ncacn_np support ****/
110 typedef struct _RpcConnection_np
112 RpcConnection common;
118 static RpcConnection *rpcrt4_conn_np_alloc(void)
120 RpcConnection_np *npc = HeapAlloc(GetProcessHeap(), 0, sizeof(RpcConnection_np));
124 memset(&npc->ovl, 0, sizeof(npc->ovl));
125 npc->listening = FALSE;
130 static RPC_STATUS rpcrt4_conn_listen_pipe(RpcConnection_np *npc)
135 npc->listening = TRUE;
138 if (ConnectNamedPipe(npc->pipe, &npc->ovl))
141 switch(GetLastError())
143 case ERROR_PIPE_CONNECTED:
144 SetEvent(npc->ovl.hEvent);
146 case ERROR_IO_PENDING:
147 /* will be completed in rpcrt4_protseq_np_wait_for_new_connection */
149 case ERROR_NO_DATA_DETECTED:
150 /* client has disconnected, retry */
151 DisconnectNamedPipe( npc->pipe );
154 npc->listening = FALSE;
155 WARN("Couldn't ConnectNamedPipe (error was %d)\n", GetLastError());
156 return RPC_S_OUT_OF_RESOURCES;
161 static RPC_STATUS rpcrt4_conn_create_pipe(RpcConnection *Connection, LPCSTR pname)
163 RpcConnection_np *npc = (RpcConnection_np *) Connection;
164 TRACE("listening on %s\n", pname);
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;
175 return RPC_S_CANT_CREATE_ENDPOINT;
178 memset(&npc->ovl, 0, sizeof(npc->ovl));
179 npc->ovl.hEvent = CreateEventW(NULL, TRUE, FALSE, NULL);
181 /* Note: we don't call ConnectNamedPipe here because it must be done in the
182 * server thread as the thread must be alertable */
186 static RPC_STATUS rpcrt4_conn_open_pipe(RpcConnection *Connection, LPCSTR pname, BOOL wait)
188 RpcConnection_np *npc = (RpcConnection_np *) Connection;
192 TRACE("connecting to %s\n", pname);
198 dwFlags = SECURITY_SQOS_PRESENT;
199 switch (Connection->QOS->qos->ImpersonationType)
201 case RPC_C_IMP_LEVEL_DEFAULT:
202 /* FIXME: what to do here? */
204 case RPC_C_IMP_LEVEL_ANONYMOUS:
205 dwFlags |= SECURITY_ANONYMOUS;
207 case RPC_C_IMP_LEVEL_IDENTIFY:
208 dwFlags |= SECURITY_IDENTIFICATION;
210 case RPC_C_IMP_LEVEL_IMPERSONATE:
211 dwFlags |= SECURITY_IMPERSONATION;
213 case RPC_C_IMP_LEVEL_DELEGATE:
214 dwFlags |= SECURITY_DELEGATION;
217 if (Connection->QOS->qos->IdentityTracking == RPC_C_QOS_IDENTIFY_DYNAMIC)
218 dwFlags |= SECURITY_CONTEXT_TRACKING;
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;
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;
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);
246 static RPC_STATUS rpcrt4_ncalrpc_open(RpcConnection* Connection)
248 RpcConnection_np *npc = (RpcConnection_np *) Connection;
249 static const char prefix[] = "\\\\.\\pipe\\lrpc\\";
253 /* already connected? */
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);
267 static RPC_STATUS rpcrt4_protseq_ncalrpc_open_endpoint(RpcServerProtseq* protseq, const char *endpoint)
269 static const char prefix[] = "\\\\.\\pipe\\lrpc\\";
272 RpcConnection *Connection;
273 char generated_endpoint[22];
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;
285 r = RPCRT4_CreateConnection(&Connection, TRUE, protseq->Protseq, NULL,
286 endpoint, NULL, NULL, NULL);
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);
297 EnterCriticalSection(&protseq->cs);
298 Connection->Next = protseq->conn;
299 protseq->conn = Connection;
300 LeaveCriticalSection(&protseq->cs);
305 static RPC_STATUS rpcrt4_ncacn_np_open(RpcConnection* Connection)
307 RpcConnection_np *npc = (RpcConnection_np *) Connection;
308 static const char prefix[] = "\\\\.";
312 /* already connected? */
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);
325 static RPC_STATUS rpcrt4_protseq_ncacn_np_open_endpoint(RpcServerProtseq *protseq, const char *endpoint)
327 static const char prefix[] = "\\\\.";
330 RpcConnection *Connection;
331 char generated_endpoint[21];
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;
343 r = RPCRT4_CreateConnection(&Connection, TRUE, protseq->Protseq, NULL,
344 endpoint, NULL, NULL, NULL);
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);
354 EnterCriticalSection(&protseq->cs);
355 Connection->Next = protseq->conn;
356 protseq->conn = Connection;
357 LeaveCriticalSection(&protseq->cs);
362 static void rpcrt4_conn_np_handoff(RpcConnection_np *old_npc, RpcConnection_np *new_npc)
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 */
367 new_npc->pipe = old_npc->pipe;
368 new_npc->ovl = old_npc->ovl;
370 memset(&old_npc->ovl, 0, sizeof(old_npc->ovl));
371 old_npc->listening = FALSE;
374 static RPC_STATUS rpcrt4_ncacn_np_handoff(RpcConnection *old_conn, RpcConnection *new_conn)
378 static const char prefix[] = "\\\\.";
380 rpcrt4_conn_np_handoff((RpcConnection_np *)old_conn, (RpcConnection_np *)new_conn);
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);
390 static RPC_STATUS rpcrt4_ncalrpc_handoff(RpcConnection *old_conn, RpcConnection *new_conn)
394 static const char prefix[] = "\\\\.\\pipe\\lrpc\\";
396 TRACE("%s\n", old_conn->Endpoint);
398 rpcrt4_conn_np_handoff((RpcConnection_np *)old_conn, (RpcConnection_np *)new_conn);
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);
408 static int rpcrt4_conn_np_read(RpcConnection *Connection,
409 void *buffer, unsigned int count)
411 RpcConnection_np *npc = (RpcConnection_np *) Connection;
414 unsigned int bytes_left = count;
419 ret = ReadFile(npc->pipe, buf, bytes_left, &bytes_read, NULL);
420 if (!ret && GetLastError() == ERROR_MORE_DATA)
422 if (!ret || !bytes_read)
424 bytes_left -= bytes_read;
427 return ret ? count : -1;
430 static int rpcrt4_conn_np_write(RpcConnection *Connection,
431 const void *buffer, unsigned int count)
433 RpcConnection_np *npc = (RpcConnection_np *) Connection;
434 const char *buf = buffer;
436 unsigned int bytes_left = count;
441 ret = WriteFile(npc->pipe, buf, bytes_left, &bytes_written, NULL);
442 if (!ret || !bytes_written)
444 bytes_left -= bytes_written;
445 buf += bytes_written;
447 return ret ? count : -1;
450 static int rpcrt4_conn_np_close(RpcConnection *Connection)
452 RpcConnection_np *npc = (RpcConnection_np *) Connection;
454 FlushFileBuffers(npc->pipe);
455 CloseHandle(npc->pipe);
458 if (npc->ovl.hEvent) {
459 CloseHandle(npc->ovl.hEvent);
465 static void rpcrt4_conn_np_cancel_call(RpcConnection *Connection)
467 /* FIXME: implement when named pipe writes use overlapped I/O */
470 static int rpcrt4_conn_np_wait_for_incoming_data(RpcConnection *Connection)
472 /* FIXME: implement when named pipe writes use overlapped I/O */
476 static size_t rpcrt4_ncacn_np_get_top_of_tower(unsigned char *tower_data,
477 const char *networkaddr,
478 const char *endpoint)
480 twr_empty_floor_t *smb_floor;
481 twr_empty_floor_t *nb_floor;
483 size_t networkaddr_size;
484 size_t endpoint_size;
486 TRACE("(%p, %s, %s)\n", tower_data, networkaddr, endpoint);
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;
495 smb_floor = (twr_empty_floor_t *)tower_data;
497 tower_data += sizeof(*smb_floor);
499 smb_floor->count_lhs = sizeof(smb_floor->protid);
500 smb_floor->protid = EPM_PROTOCOL_SMB;
501 smb_floor->count_rhs = endpoint_size;
504 memcpy(tower_data, endpoint, endpoint_size);
507 tower_data += endpoint_size;
509 nb_floor = (twr_empty_floor_t *)tower_data;
511 tower_data += sizeof(*nb_floor);
513 nb_floor->count_lhs = sizeof(nb_floor->protid);
514 nb_floor->protid = EPM_PROTOCOL_NETBIOS;
515 nb_floor->count_rhs = networkaddr_size;
518 memcpy(tower_data, networkaddr, networkaddr_size);
525 static RPC_STATUS rpcrt4_ncacn_np_parse_top_of_tower(const unsigned char *tower_data,
530 const twr_empty_floor_t *smb_floor = (const twr_empty_floor_t *)tower_data;
531 const twr_empty_floor_t *nb_floor;
533 TRACE("(%p, %d, %p, %p)\n", tower_data, (int)tower_size, networkaddr, endpoint);
535 if (tower_size < sizeof(*smb_floor))
536 return EPT_S_NOT_REGISTERED;
538 tower_data += sizeof(*smb_floor);
539 tower_size -= sizeof(*smb_floor);
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;
549 *endpoint = I_RpcAllocate(smb_floor->count_rhs);
551 return RPC_S_OUT_OF_RESOURCES;
552 memcpy(*endpoint, tower_data, smb_floor->count_rhs);
554 tower_data += smb_floor->count_rhs;
555 tower_size -= smb_floor->count_rhs;
557 if (tower_size < sizeof(*nb_floor))
558 return EPT_S_NOT_REGISTERED;
560 nb_floor = (const twr_empty_floor_t *)tower_data;
562 tower_data += sizeof(*nb_floor);
563 tower_size -= sizeof(*nb_floor);
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;
573 *networkaddr = I_RpcAllocate(nb_floor->count_rhs);
578 I_RpcFree(*endpoint);
581 return RPC_S_OUT_OF_RESOURCES;
583 memcpy(*networkaddr, tower_data, nb_floor->count_rhs);
589 typedef struct _RpcServerProtseq_np
591 RpcServerProtseq common;
593 } RpcServerProtseq_np;
595 static RpcServerProtseq *rpcrt4_protseq_np_alloc(void)
597 RpcServerProtseq_np *ps = HeapAlloc(GetProcessHeap(), 0, sizeof(*ps));
599 ps->mgr_event = CreateEventW(NULL, FALSE, FALSE, NULL);
603 static void rpcrt4_protseq_np_signal_state_changed(RpcServerProtseq *protseq)
605 RpcServerProtseq_np *npps = CONTAINING_RECORD(protseq, RpcServerProtseq_np, common);
606 SetEvent(npps->mgr_event);
609 static void *rpcrt4_protseq_np_get_wait_array(RpcServerProtseq *protseq, void *prev_array, unsigned int *count)
611 HANDLE *objs = prev_array;
612 RpcConnection_np *conn;
613 RpcServerProtseq_np *npps = CONTAINING_RECORD(protseq, RpcServerProtseq_np, common);
615 EnterCriticalSection(&protseq->cs);
617 /* open and count connections */
619 conn = CONTAINING_RECORD(protseq->conn, RpcConnection_np, common);
621 rpcrt4_conn_listen_pipe(conn);
622 if (conn->ovl.hEvent)
624 conn = CONTAINING_RECORD(conn->common.Next, RpcConnection_np, common);
627 /* make array of connections */
629 objs = HeapReAlloc(GetProcessHeap(), 0, objs, *count*sizeof(HANDLE));
631 objs = HeapAlloc(GetProcessHeap(), 0, *count*sizeof(HANDLE));
634 ERR("couldn't allocate objs\n");
635 LeaveCriticalSection(&protseq->cs);
639 objs[0] = npps->mgr_event;
641 conn = CONTAINING_RECORD(protseq->conn, RpcConnection_np, common);
643 if ((objs[*count] = conn->ovl.hEvent))
645 conn = CONTAINING_RECORD(conn->common.Next, RpcConnection_np, common);
647 LeaveCriticalSection(&protseq->cs);
651 static void rpcrt4_protseq_np_free_wait_array(RpcServerProtseq *protseq, void *array)
653 HeapFree(GetProcessHeap(), 0, array);
656 static int rpcrt4_protseq_np_wait_for_new_connection(RpcServerProtseq *protseq, unsigned int count, void *wait_array)
659 HANDLE *objs = wait_array;
661 RpcConnection *cconn;
662 RpcConnection_np *conn;
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);
676 if (res == WAIT_OBJECT_0)
678 else if (res == WAIT_FAILED)
680 ERR("wait failed with error %d\n", GetLastError());
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);
690 if (b_handle == conn->ovl.hEvent) break;
691 conn = CONTAINING_RECORD(conn->common.Next, RpcConnection_np, common);
695 RPCRT4_SpawnConnection(&cconn, &conn->common);
697 ERR("failed to locate connection for handle %p\n", b_handle);
698 LeaveCriticalSection(&protseq->cs);
701 RPCRT4_new_client(cconn);
708 static size_t rpcrt4_ncalrpc_get_top_of_tower(unsigned char *tower_data,
709 const char *networkaddr,
710 const char *endpoint)
712 twr_empty_floor_t *pipe_floor;
714 size_t endpoint_size;
716 TRACE("(%p, %s, %s)\n", tower_data, networkaddr, endpoint);
718 endpoint_size = strlen(endpoint) + 1;
719 size = sizeof(*pipe_floor) + endpoint_size;
724 pipe_floor = (twr_empty_floor_t *)tower_data;
726 tower_data += sizeof(*pipe_floor);
728 pipe_floor->count_lhs = sizeof(pipe_floor->protid);
729 pipe_floor->protid = EPM_PROTOCOL_PIPE;
730 pipe_floor->count_rhs = endpoint_size;
732 memcpy(tower_data, endpoint, endpoint_size);
737 static RPC_STATUS rpcrt4_ncalrpc_parse_top_of_tower(const unsigned char *tower_data,
742 const twr_empty_floor_t *pipe_floor = (const twr_empty_floor_t *)tower_data;
744 TRACE("(%p, %d, %p, %p)\n", tower_data, (int)tower_size, networkaddr, endpoint);
746 if (tower_size < sizeof(*pipe_floor))
747 return EPT_S_NOT_REGISTERED;
749 tower_data += sizeof(*pipe_floor);
750 tower_size -= sizeof(*pipe_floor);
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;
763 *endpoint = I_RpcAllocate(pipe_floor->count_rhs);
765 return RPC_S_OUT_OF_RESOURCES;
766 memcpy(*endpoint, tower_data, pipe_floor->count_rhs);
772 /**** ncacn_ip_tcp support ****/
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)
779 twr_tcp_floor_t *tcp_floor;
780 twr_ipv4_floor_t *ipv4_floor;
782 struct addrinfo hints;
784 size_t size = sizeof(*tcp_floor) + sizeof(*ipv4_floor);
786 TRACE("(%p, %s, %s)\n", tower_data, networkaddr, endpoint);
791 tcp_floor = (twr_tcp_floor_t *)tower_data;
792 tower_data += sizeof(*tcp_floor);
794 ipv4_floor = (twr_ipv4_floor_t *)tower_data;
796 tcp_floor->count_lhs = sizeof(tcp_floor->protid);
797 tcp_floor->protid = tcp_protid;
798 tcp_floor->count_rhs = sizeof(tcp_floor->port);
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);
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;
814 ret = getaddrinfo(networkaddr, endpoint, &hints, &ai);
817 ret = getaddrinfo("0.0.0.0", endpoint, &hints, &ai);
820 ERR("getaddrinfo failed: %s\n", gai_strerror(ret));
825 if (ai->ai_family == PF_INET)
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;
833 ERR("unexpected protocol family %d\n", ai->ai_family);
842 static RPC_STATUS rpcrt4_ip_tcp_parse_top_of_tower(const unsigned char *tower_data,
845 unsigned char tcp_protid,
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;
852 TRACE("(%p, %d, %p, %p)\n", tower_data, (int)tower_size, networkaddr, endpoint);
854 if (tower_size < sizeof(*tcp_floor))
855 return EPT_S_NOT_REGISTERED;
857 tower_data += sizeof(*tcp_floor);
858 tower_size -= sizeof(*tcp_floor);
860 if (tower_size < sizeof(*ipv4_floor))
861 return EPT_S_NOT_REGISTERED;
863 ipv4_floor = (const twr_ipv4_floor_t *)tower_data;
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;
875 *endpoint = I_RpcAllocate(6 /* sizeof("65535") + 1 */);
877 return RPC_S_OUT_OF_RESOURCES;
878 sprintf(*endpoint, "%u", ntohs(tcp_floor->port));
883 *networkaddr = I_RpcAllocate(INET_ADDRSTRLEN);
888 I_RpcFree(*endpoint);
891 return RPC_S_OUT_OF_RESOURCES;
893 in_addr.s_addr = ipv4_floor->ipv4addr;
894 if (!inet_ntop(AF_INET, &in_addr, *networkaddr, INET_ADDRSTRLEN))
896 ERR("inet_ntop: %s\n", strerror(errno));
897 I_RpcFree(*networkaddr);
901 I_RpcFree(*endpoint);
904 return EPT_S_NOT_REGISTERED;
911 typedef struct _RpcConnection_tcp
913 RpcConnection common;
918 #ifdef HAVE_SOCKETPAIR
920 static BOOL rpcrt4_sock_wait_init(RpcConnection_tcp *tcpc)
922 if (socketpair(PF_UNIX, SOCK_STREAM, 0, tcpc->cancel_fds) < 0)
924 ERR("socketpair() failed: %s\n", strerror(errno));
930 static BOOL rpcrt4_sock_wait_for_recv(RpcConnection_tcp *tcpc)
932 struct pollfd pfds[2];
933 pfds[0].fd = tcpc->sock;
934 pfds[0].events = POLLIN;
935 pfds[1].fd = tcpc->cancel_fds[0];
936 pfds[1].events = POLLIN;
937 if (poll(pfds, 2, -1 /* infinite */) == -1 && errno != EINTR)
939 ERR("poll() failed: %s\n", strerror(errno));
942 if (pfds[1].revents & POLLIN) /* canceled */
945 read(pfds[1].fd, &dummy, sizeof(dummy));
951 static BOOL rpcrt4_sock_wait_for_send(RpcConnection_tcp *tcpc)
955 pfd.events = POLLOUT;
956 if (poll(&pfd, 1, -1 /* infinite */) == -1 && errno != EINTR)
958 ERR("poll() failed: %s\n", strerror(errno));
964 static void rpcrt4_sock_wait_cancel(RpcConnection_tcp *tcpc)
968 write(tcpc->cancel_fds[1], &dummy, 1);
971 static void rpcrt4_sock_wait_destroy(RpcConnection_tcp *tcpc)
973 close(tcpc->cancel_fds[0]);
974 close(tcpc->cancel_fds[1]);
977 #else /* HAVE_SOCKETPAIR */
979 static BOOL rpcrt4_sock_wait_init(RpcConnection_tcp *tcpc)
985 static BOOL rpcrt4_sock_wait_for_recv(RpcConnection_tcp *tcpc)
991 static BOOL rpcrt4_sock_wait_for_send(RpcConnection_tcp *tcpc)
997 static void rpcrt4_sock_wait_cancel(RpcConnection_tcp *tcpc)
1002 static void rpcrt4_sock_wait_destroy(RpcConnection_tcp *tcpc)
1009 static RpcConnection *rpcrt4_conn_tcp_alloc(void)
1011 RpcConnection_tcp *tcpc;
1012 tcpc = HeapAlloc(GetProcessHeap(), 0, sizeof(RpcConnection_tcp));
1016 if (!rpcrt4_sock_wait_init(tcpc))
1018 HeapFree(GetProcessHeap(), 0, tcpc);
1021 return &tcpc->common;
1024 static RPC_STATUS rpcrt4_ncacn_ip_tcp_open(RpcConnection* Connection)
1026 RpcConnection_tcp *tcpc = (RpcConnection_tcp *) Connection;
1029 struct addrinfo *ai;
1030 struct addrinfo *ai_cur;
1031 struct addrinfo hints;
1033 TRACE("(%s, %s)\n", Connection->NetworkAddr, Connection->Endpoint);
1035 if (tcpc->sock != -1)
1039 hints.ai_family = PF_UNSPEC;
1040 hints.ai_socktype = SOCK_STREAM;
1041 hints.ai_protocol = IPPROTO_TCP;
1042 hints.ai_addrlen = 0;
1043 hints.ai_addr = NULL;
1044 hints.ai_canonname = NULL;
1045 hints.ai_next = NULL;
1047 ret = getaddrinfo(Connection->NetworkAddr, Connection->Endpoint, &hints, &ai);
1050 ERR("getaddrinfo for %s:%s failed: %s\n", Connection->NetworkAddr,
1051 Connection->Endpoint, gai_strerror(ret));
1052 return RPC_S_SERVER_UNAVAILABLE;
1055 for (ai_cur = ai; ai_cur; ai_cur = ai_cur->ai_next)
1060 if (ai_cur->ai_family != AF_INET && ai_cur->ai_family != AF_INET6)
1062 TRACE("skipping non-IP/IPv6 address family\n");
1070 getnameinfo(ai_cur->ai_addr, ai_cur->ai_addrlen,
1071 host, sizeof(host), service, sizeof(service),
1072 NI_NUMERICHOST | NI_NUMERICSERV);
1073 TRACE("trying %s:%s\n", host, service);
1076 sock = socket(ai_cur->ai_family, ai_cur->ai_socktype, ai_cur->ai_protocol);
1079 WARN("socket() failed: %s\n", strerror(errno));
1083 if (0>connect(sock, ai_cur->ai_addr, ai_cur->ai_addrlen))
1085 WARN("connect() failed: %s\n", strerror(errno));
1090 /* RPC depends on having minimal latency so disable the Nagle algorithm */
1092 setsockopt(sock, SOL_TCP, TCP_NODELAY, (char *)&val, sizeof(val));
1094 ioctlsocket(sock, FIONBIO, &nonblocking);
1099 TRACE("connected\n");
1104 ERR("couldn't connect to %s:%s\n", Connection->NetworkAddr, Connection->Endpoint);
1105 return RPC_S_SERVER_UNAVAILABLE;
1108 #ifdef HAVE_SOCKETPAIR
1110 static RPC_STATUS rpcrt4_protseq_ncacn_ip_tcp_open_endpoint(RpcServerProtseq *protseq, const char *endpoint)
1112 RPC_STATUS status = RPC_S_CANT_CREATE_ENDPOINT;
1115 struct addrinfo *ai;
1116 struct addrinfo *ai_cur;
1117 struct addrinfo hints;
1118 RpcConnection *first_connection = NULL;
1120 TRACE("(%p, %s)\n", protseq, endpoint);
1122 hints.ai_flags = AI_PASSIVE /* for non-localhost addresses */;
1123 hints.ai_family = PF_UNSPEC;
1124 hints.ai_socktype = SOCK_STREAM;
1125 hints.ai_protocol = IPPROTO_TCP;
1126 hints.ai_addrlen = 0;
1127 hints.ai_addr = NULL;
1128 hints.ai_canonname = NULL;
1129 hints.ai_next = NULL;
1131 ret = getaddrinfo(NULL, endpoint ? endpoint : "0", &hints, &ai);
1134 ERR("getaddrinfo for port %s failed: %s\n", endpoint,
1136 if ((ret == EAI_SERVICE) || (ret == EAI_NONAME))
1137 return RPC_S_INVALID_ENDPOINT_FORMAT;
1138 return RPC_S_CANT_CREATE_ENDPOINT;
1141 for (ai_cur = ai; ai_cur; ai_cur = ai_cur->ai_next)
1143 RpcConnection_tcp *tcpc;
1144 RPC_STATUS create_status;
1145 struct sockaddr_storage sa;
1147 char service[NI_MAXSERV];
1150 if (ai_cur->ai_family != AF_INET && ai_cur->ai_family != AF_INET6)
1152 TRACE("skipping non-IP/IPv6 address family\n");
1159 getnameinfo(ai_cur->ai_addr, ai_cur->ai_addrlen,
1160 host, sizeof(host), service, sizeof(service),
1161 NI_NUMERICHOST | NI_NUMERICSERV);
1162 TRACE("trying %s:%s\n", host, service);
1165 sock = socket(ai_cur->ai_family, ai_cur->ai_socktype, ai_cur->ai_protocol);
1168 WARN("socket() failed: %s\n", strerror(errno));
1169 status = RPC_S_CANT_CREATE_ENDPOINT;
1173 ret = bind(sock, ai_cur->ai_addr, ai_cur->ai_addrlen);
1176 WARN("bind failed: %s\n", strerror(errno));
1178 if (errno == EADDRINUSE)
1179 status = RPC_S_DUPLICATE_ENDPOINT;
1181 status = RPC_S_CANT_CREATE_ENDPOINT;
1185 sa_len = sizeof(sa);
1186 if (getsockname(sock, (struct sockaddr *)&sa, &sa_len))
1188 WARN("getsockname() failed: %s\n", strerror(errno));
1189 status = RPC_S_CANT_CREATE_ENDPOINT;
1193 ret = getnameinfo((struct sockaddr *)&sa, sa_len,
1194 NULL, 0, service, sizeof(service),
1198 WARN("getnameinfo failed: %s\n", gai_strerror(ret));
1199 status = RPC_S_CANT_CREATE_ENDPOINT;
1203 create_status = RPCRT4_CreateConnection((RpcConnection **)&tcpc, TRUE,
1204 protseq->Protseq, NULL,
1205 service, NULL, NULL, NULL);
1206 if (create_status != RPC_S_OK)
1209 status = create_status;
1214 ret = listen(sock, protseq->MaxCalls);
1217 WARN("listen failed: %s\n", strerror(errno));
1218 RPCRT4_DestroyConnection(&tcpc->common);
1219 status = RPC_S_OUT_OF_RESOURCES;
1222 /* need a non-blocking socket, otherwise accept() has a potential
1223 * race-condition (poll() says it is readable, connection drops,
1224 * and accept() blocks until the next connection comes...)
1227 ret = ioctlsocket(sock, FIONBIO, &nonblocking);
1230 WARN("couldn't make socket non-blocking, error %d\n", ret);
1231 RPCRT4_DestroyConnection(&tcpc->common);
1232 status = RPC_S_OUT_OF_RESOURCES;
1236 tcpc->common.Next = first_connection;
1237 first_connection = &tcpc->common;
1239 /* since IPv4 and IPv6 share the same port space, we only need one
1240 * successful bind to listen for both */
1246 /* if at least one connection was created for an endpoint then
1248 if (first_connection)
1250 RpcConnection *conn;
1252 /* find last element in list */
1253 for (conn = first_connection; conn->Next; conn = conn->Next)
1256 EnterCriticalSection(&protseq->cs);
1257 conn->Next = protseq->conn;
1258 protseq->conn = first_connection;
1259 LeaveCriticalSection(&protseq->cs);
1261 TRACE("listening on %s\n", endpoint);
1265 ERR("couldn't listen on port %s\n", endpoint);
1271 static RPC_STATUS rpcrt4_conn_tcp_handoff(RpcConnection *old_conn, RpcConnection *new_conn)
1274 struct sockaddr_in address;
1276 RpcConnection_tcp *server = (RpcConnection_tcp*) old_conn;
1277 RpcConnection_tcp *client = (RpcConnection_tcp*) new_conn;
1280 addrsize = sizeof(address);
1281 ret = accept(server->sock, (struct sockaddr*) &address, &addrsize);
1284 ERR("Failed to accept a TCP connection: error %d\n", ret);
1285 return RPC_S_OUT_OF_RESOURCES;
1288 ioctlsocket(ret, FIONBIO, &nonblocking);
1290 TRACE("Accepted a new TCP connection\n");
1294 static int rpcrt4_conn_tcp_read(RpcConnection *Connection,
1295 void *buffer, unsigned int count)
1297 RpcConnection_tcp *tcpc = (RpcConnection_tcp *) Connection;
1301 int r = recv(tcpc->sock, (char *)buffer + bytes_read, count - bytes_read, 0);
1306 else if (errno != EAGAIN)
1308 WARN("recv() failed: %s\n", strerror(errno));
1313 if (!rpcrt4_sock_wait_for_recv(tcpc))
1316 } while (bytes_read != count);
1317 TRACE("%d %p %u -> %d\n", tcpc->sock, buffer, count, bytes_read);
1321 static int rpcrt4_conn_tcp_write(RpcConnection *Connection,
1322 const void *buffer, unsigned int count)
1324 RpcConnection_tcp *tcpc = (RpcConnection_tcp *) Connection;
1325 int bytes_written = 0;
1328 int r = send(tcpc->sock, (const char *)buffer + bytes_written, count - bytes_written, 0);
1331 else if (errno != EAGAIN)
1335 if (!rpcrt4_sock_wait_for_send(tcpc))
1338 } while (bytes_written != count);
1339 TRACE("%d %p %u -> %d\n", tcpc->sock, buffer, count, bytes_written);
1340 return bytes_written;
1343 static int rpcrt4_conn_tcp_close(RpcConnection *Connection)
1345 RpcConnection_tcp *tcpc = (RpcConnection_tcp *) Connection;
1347 TRACE("%d\n", tcpc->sock);
1349 if (tcpc->sock != -1)
1350 closesocket(tcpc->sock);
1352 rpcrt4_sock_wait_destroy(tcpc);
1356 static void rpcrt4_conn_tcp_cancel_call(RpcConnection *Connection)
1358 RpcConnection_tcp *tcpc = (RpcConnection_tcp *) Connection;
1359 TRACE("%p\n", Connection);
1360 rpcrt4_sock_wait_cancel(tcpc);
1363 static int rpcrt4_conn_tcp_wait_for_incoming_data(RpcConnection *Connection)
1365 RpcConnection_tcp *tcpc = (RpcConnection_tcp *) Connection;
1367 TRACE("%p\n", Connection);
1369 if (!rpcrt4_sock_wait_for_recv(tcpc))
1374 static size_t rpcrt4_ncacn_ip_tcp_get_top_of_tower(unsigned char *tower_data,
1375 const char *networkaddr,
1376 const char *endpoint)
1378 return rpcrt4_ip_tcp_get_top_of_tower(tower_data, networkaddr,
1379 EPM_PROTOCOL_TCP, endpoint);
1382 #ifdef HAVE_SOCKETPAIR
1384 typedef struct _RpcServerProtseq_sock
1386 RpcServerProtseq common;
1389 } RpcServerProtseq_sock;
1391 static RpcServerProtseq *rpcrt4_protseq_sock_alloc(void)
1393 RpcServerProtseq_sock *ps = HeapAlloc(GetProcessHeap(), 0, sizeof(*ps));
1397 if (!socketpair(PF_UNIX, SOCK_DGRAM, 0, fds))
1399 fcntl(fds[0], F_SETFL, O_NONBLOCK);
1400 fcntl(fds[1], F_SETFL, O_NONBLOCK);
1401 ps->mgr_event_rcv = fds[0];
1402 ps->mgr_event_snd = fds[1];
1406 ERR("socketpair failed with error %s\n", strerror(errno));
1407 HeapFree(GetProcessHeap(), 0, ps);
1414 static void rpcrt4_protseq_sock_signal_state_changed(RpcServerProtseq *protseq)
1416 RpcServerProtseq_sock *sockps = CONTAINING_RECORD(protseq, RpcServerProtseq_sock, common);
1418 write(sockps->mgr_event_snd, &dummy, sizeof(dummy));
1421 static void *rpcrt4_protseq_sock_get_wait_array(RpcServerProtseq *protseq, void *prev_array, unsigned int *count)
1423 struct pollfd *poll_info = prev_array;
1424 RpcConnection_tcp *conn;
1425 RpcServerProtseq_sock *sockps = CONTAINING_RECORD(protseq, RpcServerProtseq_sock, common);
1427 EnterCriticalSection(&protseq->cs);
1429 /* open and count connections */
1431 conn = (RpcConnection_tcp *)protseq->conn;
1433 if (conn->sock != -1)
1435 conn = (RpcConnection_tcp *)conn->common.Next;
1438 /* make array of connections */
1440 poll_info = HeapReAlloc(GetProcessHeap(), 0, poll_info, *count*sizeof(*poll_info));
1442 poll_info = HeapAlloc(GetProcessHeap(), 0, *count*sizeof(*poll_info));
1445 ERR("couldn't allocate poll_info\n");
1446 LeaveCriticalSection(&protseq->cs);
1450 poll_info[0].fd = sockps->mgr_event_rcv;
1451 poll_info[0].events = POLLIN;
1453 conn = CONTAINING_RECORD(protseq->conn, RpcConnection_tcp, common);
1455 if (conn->sock != -1)
1457 poll_info[*count].fd = conn->sock;
1458 poll_info[*count].events = POLLIN;
1461 conn = CONTAINING_RECORD(conn->common.Next, RpcConnection_tcp, common);
1463 LeaveCriticalSection(&protseq->cs);
1467 static void rpcrt4_protseq_sock_free_wait_array(RpcServerProtseq *protseq, void *array)
1469 HeapFree(GetProcessHeap(), 0, array);
1472 static int rpcrt4_protseq_sock_wait_for_new_connection(RpcServerProtseq *protseq, unsigned int count, void *wait_array)
1474 struct pollfd *poll_info = wait_array;
1477 RpcConnection *cconn;
1478 RpcConnection_tcp *conn;
1483 ret = poll(poll_info, count, -1);
1486 ERR("poll failed with error %d\n", ret);
1490 for (i = 0; i < count; i++)
1491 if (poll_info[i].revents & POLLIN)
1493 /* RPC server event */
1497 read(poll_info[0].fd, &dummy, sizeof(dummy));
1501 /* find which connection got a RPC */
1502 EnterCriticalSection(&protseq->cs);
1503 conn = CONTAINING_RECORD(protseq->conn, RpcConnection_tcp, common);
1505 if (poll_info[i].fd == conn->sock) break;
1506 conn = CONTAINING_RECORD(conn->common.Next, RpcConnection_tcp, common);
1510 RPCRT4_SpawnConnection(&cconn, &conn->common);
1512 ERR("failed to locate connection for fd %d\n", poll_info[i].fd);
1513 LeaveCriticalSection(&protseq->cs);
1515 RPCRT4_new_client(cconn);
1523 #endif /* HAVE_SOCKETPAIR */
1525 static RPC_STATUS rpcrt4_ncacn_ip_tcp_parse_top_of_tower(const unsigned char *tower_data,
1530 return rpcrt4_ip_tcp_parse_top_of_tower(tower_data, tower_size,
1531 networkaddr, EPM_PROTOCOL_TCP,
1535 /**** ncacn_http support ****/
1537 /* 60 seconds is the period native uses */
1538 #define HTTP_IDLE_TIME 60000
1540 /* reference counted to avoid a race between a cancelled call's connection
1541 * being destroyed and the asynchronous InternetReadFileEx call being
1543 typedef struct _RpcHttpAsyncData
1546 HANDLE completion_event;
1547 INTERNET_BUFFERSA inet_buffers;
1548 void *destination_buffer; /* the address that inet_buffers.lpvBuffer will be
1549 * copied into when the call completes */
1550 CRITICAL_SECTION cs;
1553 static ULONG RpcHttpAsyncData_AddRef(RpcHttpAsyncData *data)
1555 return InterlockedIncrement(&data->refs);
1558 static ULONG RpcHttpAsyncData_Release(RpcHttpAsyncData *data)
1560 ULONG refs = InterlockedDecrement(&data->refs);
1563 TRACE("destroying async data %p\n", data);
1564 CloseHandle(data->completion_event);
1565 HeapFree(GetProcessHeap(), 0, data->inet_buffers.lpvBuffer);
1566 DeleteCriticalSection(&data->cs);
1567 HeapFree(GetProcessHeap(), 0, data);
1572 typedef struct _RpcConnection_http
1574 RpcConnection common;
1577 HINTERNET in_request;
1578 HINTERNET out_request;
1579 HANDLE timer_cancelled;
1580 HANDLE cancel_event;
1581 DWORD last_sent_time;
1582 ULONG bytes_received;
1583 ULONG flow_control_mark; /* send a control packet to the server when this many bytes received */
1584 ULONG flow_control_increment; /* number of bytes to increment flow_control_mark by */
1585 UUID connection_uuid;
1588 RpcHttpAsyncData *async_data;
1589 } RpcConnection_http;
1591 static RpcConnection *rpcrt4_ncacn_http_alloc(void)
1593 RpcConnection_http *httpc;
1594 httpc = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*httpc));
1595 if (!httpc) return NULL;
1596 httpc->async_data = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(RpcHttpAsyncData));
1597 if (!httpc->async_data)
1599 HeapFree(GetProcessHeap(), 0, httpc);
1602 TRACE("async data = %p\n", httpc->async_data);
1603 httpc->cancel_event = CreateEventW(NULL, FALSE, FALSE, NULL);
1604 httpc->async_data->refs = 1;
1605 httpc->async_data->inet_buffers.dwStructSize = sizeof(INTERNET_BUFFERSA);
1606 httpc->async_data->inet_buffers.lpvBuffer = NULL;
1607 httpc->async_data->destination_buffer = NULL;
1608 InitializeCriticalSection(&httpc->async_data->cs);
1609 return &httpc->common;
1612 typedef struct _HttpTimerThreadData
1615 DWORD *last_sent_time;
1616 HANDLE timer_cancelled;
1617 } HttpTimerThreadData;
1619 static VOID CALLBACK rpcrt4_http_keep_connection_active_timer_proc(PVOID param, BOOLEAN dummy)
1621 HINTERNET in_request = param;
1622 RpcPktHdr *idle_pkt;
1624 idle_pkt = RPCRT4_BuildHttpHeader(NDR_LOCAL_DATA_REPRESENTATION, 0x0001,
1628 DWORD bytes_written;
1629 InternetWriteFile(in_request, idle_pkt, idle_pkt->common.frag_len, &bytes_written);
1630 RPCRT4_FreeHeader(idle_pkt);
1634 static inline DWORD rpcrt4_http_timer_calc_timeout(DWORD *last_sent_time)
1636 DWORD cur_time = GetTickCount();
1637 DWORD cached_last_sent_time = *last_sent_time;
1638 return HTTP_IDLE_TIME - (cur_time - cached_last_sent_time > HTTP_IDLE_TIME ? 0 : cur_time - cached_last_sent_time);
1641 static DWORD CALLBACK rpcrt4_http_timer_thread(PVOID param)
1643 HttpTimerThreadData *data_in = param;
1644 HttpTimerThreadData data;
1648 HeapFree(GetProcessHeap(), 0, data_in);
1650 for (timeout = HTTP_IDLE_TIME;
1651 WaitForSingleObject(data.timer_cancelled, timeout) == WAIT_TIMEOUT;
1652 timeout = rpcrt4_http_timer_calc_timeout(data.last_sent_time))
1654 /* are we too soon after last send? */
1655 if (GetTickCount() - HTTP_IDLE_TIME < *data.last_sent_time)
1657 rpcrt4_http_keep_connection_active_timer_proc(data.timer_param, TRUE);
1660 CloseHandle(data.timer_cancelled);
1664 static VOID WINAPI rpcrt4_http_internet_callback(
1665 HINTERNET hInternet,
1666 DWORD_PTR dwContext,
1667 DWORD dwInternetStatus,
1668 LPVOID lpvStatusInformation,
1669 DWORD dwStatusInformationLength)
1671 RpcHttpAsyncData *async_data = (RpcHttpAsyncData *)dwContext;
1673 switch (dwInternetStatus)
1675 case INTERNET_STATUS_REQUEST_COMPLETE:
1676 TRACE("INTERNET_STATUS_REQUEST_COMPLETED\n");
1679 if (async_data->inet_buffers.lpvBuffer)
1681 EnterCriticalSection(&async_data->cs);
1682 if (async_data->destination_buffer)
1684 memcpy(async_data->destination_buffer,
1685 async_data->inet_buffers.lpvBuffer,
1686 async_data->inet_buffers.dwBufferLength);
1687 async_data->destination_buffer = NULL;
1689 LeaveCriticalSection(&async_data->cs);
1691 HeapFree(GetProcessHeap(), 0, async_data->inet_buffers.lpvBuffer);
1692 async_data->inet_buffers.lpvBuffer = NULL;
1693 SetEvent(async_data->completion_event);
1694 RpcHttpAsyncData_Release(async_data);
1700 static RPC_STATUS rpcrt4_http_check_response(HINTERNET hor)
1707 WCHAR *status_text = buf;
1711 size = sizeof(status_code);
1712 ret = HttpQueryInfoW(hor, HTTP_QUERY_STATUS_CODE|HTTP_QUERY_FLAG_NUMBER, &status_code, &size, &index);
1714 return GetLastError();
1715 if (status_code < 400)
1719 ret = HttpQueryInfoW(hor, HTTP_QUERY_STATUS_TEXT, status_text, &size, &index);
1720 if (!ret && GetLastError() == ERROR_INSUFFICIENT_BUFFER)
1722 status_text = HeapAlloc(GetProcessHeap(), 0, size);
1723 ret = HttpQueryInfoW(hor, HTTP_QUERY_STATUS_TEXT, status_text, &size, &index);
1726 ERR("server returned: %d %s\n", status_code, ret ? debugstr_w(status_text) : "<status text unavailable>");
1727 if(status_text != buf) HeapFree(GetProcessHeap(), 0, status_text);
1729 if (status_code == HTTP_STATUS_DENIED)
1730 return ERROR_ACCESS_DENIED;
1731 return RPC_S_SERVER_UNAVAILABLE;
1734 static RPC_STATUS rpcrt4_http_internet_connect(RpcConnection_http *httpc)
1736 static const WCHAR wszUserAgent[] = {'M','S','R','P','C',0};
1737 LPWSTR proxy = NULL;
1739 LPWSTR password = NULL;
1740 LPWSTR servername = NULL;
1741 const WCHAR *option;
1742 INTERNET_PORT port = INTERNET_INVALID_PORT_NUMBER; /* use default port */
1744 if (httpc->common.QOS &&
1745 (httpc->common.QOS->qos->AdditionalSecurityInfoType == RPC_C_AUTHN_INFO_TYPE_HTTP))
1747 const RPC_HTTP_TRANSPORT_CREDENTIALS_W *http_cred = httpc->common.QOS->qos->u.HttpCredentials;
1748 if (http_cred->TransportCredentials)
1751 const SEC_WINNT_AUTH_IDENTITY_W *cred = http_cred->TransportCredentials;
1752 ULONG len = cred->DomainLength + 1 + cred->UserLength;
1753 user = HeapAlloc(GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR));
1755 return RPC_S_OUT_OF_RESOURCES;
1757 if (cred->DomainLength)
1759 memcpy(p, cred->Domain, cred->DomainLength * sizeof(WCHAR));
1760 p += cred->DomainLength;
1764 memcpy(p, cred->User, cred->UserLength * sizeof(WCHAR));
1765 p[cred->UserLength] = 0;
1767 password = RPCRT4_strndupW(cred->Password, cred->PasswordLength);
1771 for (option = httpc->common.NetworkOptions; option;
1772 option = (strchrW(option, ',') ? strchrW(option, ',')+1 : NULL))
1774 static const WCHAR wszRpcProxy[] = {'R','p','c','P','r','o','x','y','=',0};
1775 static const WCHAR wszHttpProxy[] = {'H','t','t','p','P','r','o','x','y','=',0};
1777 if (!strncmpiW(option, wszRpcProxy, sizeof(wszRpcProxy)/sizeof(wszRpcProxy[0])-1))
1779 const WCHAR *value_start = option + sizeof(wszRpcProxy)/sizeof(wszRpcProxy[0])-1;
1780 const WCHAR *value_end;
1783 value_end = strchrW(option, ',');
1785 value_end = value_start + strlenW(value_start);
1786 for (p = value_start; p < value_end; p++)
1793 TRACE("RpcProxy value is %s\n", debugstr_wn(value_start, value_end-value_start));
1794 servername = RPCRT4_strndupW(value_start, value_end-value_start);
1796 else if (!strncmpiW(option, wszHttpProxy, sizeof(wszHttpProxy)/sizeof(wszHttpProxy[0])-1))
1798 const WCHAR *value_start = option + sizeof(wszHttpProxy)/sizeof(wszHttpProxy[0])-1;
1799 const WCHAR *value_end;
1801 value_end = strchrW(option, ',');
1803 value_end = value_start + strlenW(value_start);
1804 TRACE("HttpProxy value is %s\n", debugstr_wn(value_start, value_end-value_start));
1805 proxy = RPCRT4_strndupW(value_start, value_end-value_start);
1808 FIXME("unhandled option %s\n", debugstr_w(option));
1811 httpc->app_info = InternetOpenW(wszUserAgent, proxy ? INTERNET_OPEN_TYPE_PROXY : INTERNET_OPEN_TYPE_PRECONFIG,
1812 NULL, NULL, INTERNET_FLAG_ASYNC);
1813 if (!httpc->app_info)
1815 HeapFree(GetProcessHeap(), 0, password);
1816 HeapFree(GetProcessHeap(), 0, user);
1817 ERR("InternetOpenW failed with error %d\n", GetLastError());
1818 return RPC_S_SERVER_UNAVAILABLE;
1820 InternetSetStatusCallbackW(httpc->app_info, rpcrt4_http_internet_callback);
1822 /* if no RpcProxy option specified, set the HTTP server address to the
1823 * RPC server address */
1826 servername = HeapAlloc(GetProcessHeap(), 0, (strlen(httpc->common.NetworkAddr) + 1)*sizeof(WCHAR));
1829 HeapFree(GetProcessHeap(), 0, password);
1830 HeapFree(GetProcessHeap(), 0, user);
1831 return RPC_S_OUT_OF_RESOURCES;
1833 MultiByteToWideChar(CP_ACP, 0, httpc->common.NetworkAddr, -1, servername, strlen(httpc->common.NetworkAddr) + 1);
1836 httpc->session = InternetConnectW(httpc->app_info, servername, port, user, password,
1837 INTERNET_SERVICE_HTTP, 0, 0);
1839 HeapFree(GetProcessHeap(), 0, password);
1840 HeapFree(GetProcessHeap(), 0, user);
1841 HeapFree(GetProcessHeap(), 0, servername);
1843 if (!httpc->session)
1845 ERR("InternetConnectW failed with error %d\n", GetLastError());
1846 return RPC_S_SERVER_UNAVAILABLE;
1852 /* prepare the in pipe for use by RPC packets */
1853 static RPC_STATUS rpcrt4_http_prepare_in_pipe(HINTERNET in_request, RpcHttpAsyncData *async_data,
1854 const UUID *connection_uuid,
1855 const UUID *in_pipe_uuid,
1856 const UUID *association_uuid)
1862 INTERNET_BUFFERSW buffers_in;
1863 DWORD bytes_read, bytes_written;
1865 /* prepare in pipe */
1866 ResetEvent(async_data->completion_event);
1867 RpcHttpAsyncData_AddRef(async_data);
1868 ret = HttpSendRequestW(in_request, NULL, 0, NULL, 0);
1871 if (GetLastError() == ERROR_IO_PENDING)
1872 WaitForSingleObject(async_data->completion_event, INFINITE);
1875 RpcHttpAsyncData_Release(async_data);
1876 ERR("HttpSendRequestW failed with error %d\n", GetLastError());
1877 return RPC_S_SERVER_UNAVAILABLE;
1880 status = rpcrt4_http_check_response(in_request);
1881 if (status != RPC_S_OK) return status;
1883 InternetReadFile(in_request, packet, 20, &bytes_read);
1884 /* FIXME: do something with retrieved data */
1886 memset(&buffers_in, 0, sizeof(buffers_in));
1887 buffers_in.dwStructSize = sizeof(buffers_in);
1888 /* FIXME: get this from the registry */
1889 buffers_in.dwBufferTotal = 1024 * 1024 * 1024; /* 1Gb */
1890 ResetEvent(async_data->completion_event);
1891 RpcHttpAsyncData_AddRef(async_data);
1892 ret = HttpSendRequestExW(in_request, &buffers_in, NULL, 0, 0);
1895 if (GetLastError() == ERROR_IO_PENDING)
1896 WaitForSingleObject(async_data->completion_event, INFINITE);
1899 RpcHttpAsyncData_Release(async_data);
1900 ERR("HttpSendRequestExW failed with error %d\n", GetLastError());
1901 return RPC_S_SERVER_UNAVAILABLE;
1905 TRACE("sending HTTP connect header to server\n");
1906 hdr = RPCRT4_BuildHttpConnectHeader(0, FALSE, connection_uuid, in_pipe_uuid, association_uuid);
1907 if (!hdr) return RPC_S_OUT_OF_RESOURCES;
1908 ret = InternetWriteFile(in_request, hdr, hdr->common.frag_len, &bytes_written);
1909 RPCRT4_FreeHeader(hdr);
1912 ERR("InternetWriteFile failed with error %d\n", GetLastError());
1913 return RPC_S_SERVER_UNAVAILABLE;
1919 static RPC_STATUS rpcrt4_http_read_http_packet(HINTERNET request, RpcPktHdr *hdr, BYTE **data)
1923 unsigned short data_len;
1925 ret = InternetReadFile(request, hdr, sizeof(hdr->common), &bytes_read);
1927 return RPC_S_SERVER_UNAVAILABLE;
1928 if (hdr->common.ptype != PKT_HTTP || hdr->common.frag_len < sizeof(hdr->http))
1930 ERR("wrong packet type received %d or wrong frag_len %d\n",
1931 hdr->common.ptype, hdr->common.frag_len);
1932 return RPC_S_PROTOCOL_ERROR;
1935 ret = InternetReadFile(request, &hdr->common + 1, sizeof(hdr->http) - sizeof(hdr->common), &bytes_read);
1937 return RPC_S_SERVER_UNAVAILABLE;
1939 data_len = hdr->common.frag_len - sizeof(hdr->http);
1942 *data = HeapAlloc(GetProcessHeap(), 0, data_len);
1944 return RPC_S_OUT_OF_RESOURCES;
1945 ret = InternetReadFile(request, *data, data_len, &bytes_read);
1948 HeapFree(GetProcessHeap(), 0, *data);
1949 return RPC_S_SERVER_UNAVAILABLE;
1955 if (!RPCRT4_IsValidHttpPacket(hdr, *data, data_len))
1957 ERR("invalid http packet\n");
1958 return RPC_S_PROTOCOL_ERROR;
1964 /* prepare the out pipe for use by RPC packets */
1965 static RPC_STATUS rpcrt4_http_prepare_out_pipe(HINTERNET out_request,
1966 RpcHttpAsyncData *async_data,
1967 const UUID *connection_uuid,
1968 const UUID *out_pipe_uuid,
1969 ULONG *flow_control_increment)
1976 BYTE *data_from_server;
1977 RpcPktHdr pkt_from_server;
1978 ULONG field1, field3;
1980 ResetEvent(async_data->completion_event);
1981 RpcHttpAsyncData_AddRef(async_data);
1982 ret = HttpSendRequestW(out_request, NULL, 0, NULL, 0);
1985 if (GetLastError() == ERROR_IO_PENDING)
1986 WaitForSingleObject(async_data->completion_event, INFINITE);
1989 RpcHttpAsyncData_Release(async_data);
1990 ERR("HttpSendRequestW failed with error %d\n", GetLastError());
1991 return RPC_S_SERVER_UNAVAILABLE;
1994 status = rpcrt4_http_check_response(out_request);
1995 if (status != RPC_S_OK) return status;
1997 InternetReadFile(out_request, packet, 20, &bytes_read);
1998 /* FIXME: do something with retrieved data */
2000 hdr = RPCRT4_BuildHttpConnectHeader(0, TRUE, connection_uuid, out_pipe_uuid, NULL);
2001 if (!hdr) return RPC_S_OUT_OF_RESOURCES;
2002 ResetEvent(async_data->completion_event);
2003 RpcHttpAsyncData_AddRef(async_data);
2004 ret = HttpSendRequestW(out_request, NULL, 0, hdr, hdr->common.frag_len);
2007 if (GetLastError() == ERROR_IO_PENDING)
2008 WaitForSingleObject(async_data->completion_event, INFINITE);
2011 RpcHttpAsyncData_Release(async_data);
2012 ERR("HttpSendRequestW failed with error %d\n", GetLastError());
2013 RPCRT4_FreeHeader(hdr);
2014 return RPC_S_SERVER_UNAVAILABLE;
2017 RPCRT4_FreeHeader(hdr);
2018 status = rpcrt4_http_check_response(out_request);
2019 if (status != RPC_S_OK) return status;
2021 status = rpcrt4_http_read_http_packet(out_request, &pkt_from_server,
2023 if (status != RPC_S_OK) return status;
2024 status = RPCRT4_ParseHttpPrepareHeader1(&pkt_from_server, data_from_server,
2026 HeapFree(GetProcessHeap(), 0, data_from_server);
2027 if (status != RPC_S_OK) return status;
2028 TRACE("received (%d) from first prepare header\n", field1);
2030 status = rpcrt4_http_read_http_packet(out_request, &pkt_from_server,
2032 if (status != RPC_S_OK) return status;
2033 status = RPCRT4_ParseHttpPrepareHeader2(&pkt_from_server, data_from_server,
2034 &field1, flow_control_increment,
2036 HeapFree(GetProcessHeap(), 0, data_from_server);
2037 if (status != RPC_S_OK) return status;
2038 TRACE("received (0x%08x 0x%08x %d) from second prepare header\n", field1, *flow_control_increment, field3);
2043 static RPC_STATUS rpcrt4_ncacn_http_open(RpcConnection* Connection)
2045 RpcConnection_http *httpc = (RpcConnection_http *)Connection;
2046 static const WCHAR wszVerbIn[] = {'R','P','C','_','I','N','_','D','A','T','A',0};
2047 static const WCHAR wszVerbOut[] = {'R','P','C','_','O','U','T','_','D','A','T','A',0};
2048 static const WCHAR wszRpcProxyPrefix[] = {'/','r','p','c','/','r','p','c','p','r','o','x','y','.','d','l','l','?',0};
2049 static const WCHAR wszColon[] = {':',0};
2050 static const WCHAR wszAcceptType[] = {'a','p','p','l','i','c','a','t','i','o','n','/','r','p','c',0};
2051 LPCWSTR wszAcceptTypes[] = { wszAcceptType, NULL };
2055 HttpTimerThreadData *timer_data;
2058 TRACE("(%s, %s)\n", Connection->NetworkAddr, Connection->Endpoint);
2060 if (Connection->server)
2062 ERR("ncacn_http servers not supported yet\n");
2063 return RPC_S_SERVER_UNAVAILABLE;
2066 if (httpc->in_request)
2069 httpc->async_data->completion_event = CreateEventW(NULL, FALSE, FALSE, NULL);
2071 status = UuidCreate(&httpc->connection_uuid);
2072 status = UuidCreate(&httpc->in_pipe_uuid);
2073 status = UuidCreate(&httpc->out_pipe_uuid);
2075 status = rpcrt4_http_internet_connect(httpc);
2076 if (status != RPC_S_OK)
2079 url = HeapAlloc(GetProcessHeap(), 0, sizeof(wszRpcProxyPrefix) + (strlen(Connection->NetworkAddr) + 1 + strlen(Connection->Endpoint))*sizeof(WCHAR));
2081 return RPC_S_OUT_OF_MEMORY;
2082 memcpy(url, wszRpcProxyPrefix, sizeof(wszRpcProxyPrefix));
2083 MultiByteToWideChar(CP_ACP, 0, Connection->NetworkAddr, -1, url+sizeof(wszRpcProxyPrefix)/sizeof(wszRpcProxyPrefix[0])-1, strlen(Connection->NetworkAddr)+1);
2084 strcatW(url, wszColon);
2085 MultiByteToWideChar(CP_ACP, 0, Connection->Endpoint, -1, url+strlenW(url), strlen(Connection->Endpoint)+1);
2087 secure = httpc->common.QOS &&
2088 (httpc->common.QOS->qos->AdditionalSecurityInfoType == RPC_C_AUTHN_INFO_TYPE_HTTP) &&
2089 (httpc->common.QOS->qos->u.HttpCredentials->Flags & RPC_C_HTTP_FLAG_USE_SSL);
2091 httpc->in_request = HttpOpenRequestW(httpc->session, wszVerbIn, url, NULL, NULL,
2093 (secure ? INTERNET_FLAG_SECURE : 0)|INTERNET_FLAG_KEEP_CONNECTION|INTERNET_FLAG_PRAGMA_NOCACHE,
2094 (DWORD_PTR)httpc->async_data);
2095 if (!httpc->in_request)
2097 ERR("HttpOpenRequestW failed with error %d\n", GetLastError());
2098 return RPC_S_SERVER_UNAVAILABLE;
2100 httpc->out_request = HttpOpenRequestW(httpc->session, wszVerbOut, url, NULL, NULL,
2102 (secure ? INTERNET_FLAG_SECURE : 0)|INTERNET_FLAG_KEEP_CONNECTION|INTERNET_FLAG_PRAGMA_NOCACHE,
2103 (DWORD_PTR)httpc->async_data);
2104 if (!httpc->out_request)
2106 ERR("HttpOpenRequestW failed with error %d\n", GetLastError());
2107 return RPC_S_SERVER_UNAVAILABLE;
2110 status = rpcrt4_http_prepare_in_pipe(httpc->in_request,
2112 &httpc->connection_uuid,
2113 &httpc->in_pipe_uuid,
2114 &Connection->assoc->http_uuid);
2115 if (status != RPC_S_OK)
2118 status = rpcrt4_http_prepare_out_pipe(httpc->out_request,
2120 &httpc->connection_uuid,
2121 &httpc->out_pipe_uuid,
2122 &httpc->flow_control_increment);
2123 if (status != RPC_S_OK)
2126 httpc->flow_control_mark = httpc->flow_control_increment / 2;
2127 httpc->last_sent_time = GetTickCount();
2128 httpc->timer_cancelled = CreateEventW(NULL, FALSE, FALSE, NULL);
2130 timer_data = HeapAlloc(GetProcessHeap(), 0, sizeof(*timer_data));
2132 return ERROR_OUTOFMEMORY;
2133 timer_data->timer_param = httpc->in_request;
2134 timer_data->last_sent_time = &httpc->last_sent_time;
2135 timer_data->timer_cancelled = httpc->timer_cancelled;
2136 /* FIXME: should use CreateTimerQueueTimer when implemented */
2137 thread = CreateThread(NULL, 0, rpcrt4_http_timer_thread, timer_data, 0, NULL);
2140 HeapFree(GetProcessHeap(), 0, timer_data);
2141 return GetLastError();
2143 CloseHandle(thread);
2148 static RPC_STATUS rpcrt4_ncacn_http_handoff(RpcConnection *old_conn, RpcConnection *new_conn)
2151 return RPC_S_SERVER_UNAVAILABLE;
2154 static int rpcrt4_ncacn_http_read(RpcConnection *Connection,
2155 void *buffer, unsigned int count)
2157 RpcConnection_http *httpc = (RpcConnection_http *) Connection;
2160 unsigned int bytes_left = count;
2162 ResetEvent(httpc->async_data->completion_event);
2165 RpcHttpAsyncData_AddRef(httpc->async_data);
2166 httpc->async_data->inet_buffers.dwBufferLength = bytes_left;
2167 httpc->async_data->inet_buffers.lpvBuffer = HeapAlloc(GetProcessHeap(), 0, bytes_left);
2168 httpc->async_data->destination_buffer = buf;
2169 ret = InternetReadFileExA(httpc->out_request, &httpc->async_data->inet_buffers, IRF_ASYNC, 0);
2172 /* INTERNET_STATUS_REQUEST_COMPLETED won't be sent, so release our
2174 RpcHttpAsyncData_Release(httpc->async_data);
2175 memcpy(buf, httpc->async_data->inet_buffers.lpvBuffer,
2176 httpc->async_data->inet_buffers.dwBufferLength);
2177 HeapFree(GetProcessHeap(), 0, httpc->async_data->inet_buffers.lpvBuffer);
2178 httpc->async_data->inet_buffers.lpvBuffer = NULL;
2179 httpc->async_data->destination_buffer = NULL;
2183 if (GetLastError() == ERROR_IO_PENDING)
2185 HANDLE handles[2] = { httpc->async_data->completion_event, httpc->cancel_event };
2186 DWORD result = WaitForMultipleObjects(2, handles, FALSE, DEFAULT_NCACN_HTTP_TIMEOUT);
2187 if (result == WAIT_OBJECT_0)
2191 TRACE("call cancelled\n");
2192 EnterCriticalSection(&httpc->async_data->cs);
2193 httpc->async_data->destination_buffer = NULL;
2194 LeaveCriticalSection(&httpc->async_data->cs);
2200 HeapFree(GetProcessHeap(), 0, httpc->async_data->inet_buffers.lpvBuffer);
2201 httpc->async_data->inet_buffers.lpvBuffer = NULL;
2202 httpc->async_data->destination_buffer = NULL;
2203 RpcHttpAsyncData_Release(httpc->async_data);
2207 if (!httpc->async_data->inet_buffers.dwBufferLength)
2209 bytes_left -= httpc->async_data->inet_buffers.dwBufferLength;
2210 buf += httpc->async_data->inet_buffers.dwBufferLength;
2212 TRACE("%p %p %u -> %s\n", httpc->out_request, buffer, count, ret ? "TRUE" : "FALSE");
2213 return ret ? count : -1;
2216 static RPC_STATUS rpcrt4_ncacn_http_receive_fragment(RpcConnection *Connection, RpcPktHdr **Header, void **Payload)
2218 RpcConnection_http *httpc = (RpcConnection_http *) Connection;
2222 RpcPktCommonHdr common_hdr;
2226 TRACE("(%p, %p, %p)\n", Connection, Header, Payload);
2229 /* read packet common header */
2230 dwRead = rpcrt4_ncacn_http_read(Connection, &common_hdr, sizeof(common_hdr));
2231 if (dwRead != sizeof(common_hdr)) {
2232 WARN("Short read of header, %d bytes\n", dwRead);
2233 status = RPC_S_PROTOCOL_ERROR;
2236 if (!memcmp(&common_hdr, "HTTP/1.1", sizeof("HTTP/1.1")) ||
2237 !memcmp(&common_hdr, "HTTP/1.0", sizeof("HTTP/1.0")))
2239 FIXME("server returned %s\n", debugstr_a((const char *)&common_hdr));
2240 status = RPC_S_PROTOCOL_ERROR;
2244 status = RPCRT4_ValidateCommonHeader(&common_hdr);
2245 if (status != RPC_S_OK) goto fail;
2247 hdr_length = RPCRT4_GetHeaderSize((RpcPktHdr*)&common_hdr);
2248 if (hdr_length == 0) {
2249 WARN("header length == 0\n");
2250 status = RPC_S_PROTOCOL_ERROR;
2254 *Header = HeapAlloc(GetProcessHeap(), 0, hdr_length);
2257 status = RPC_S_OUT_OF_RESOURCES;
2260 memcpy(*Header, &common_hdr, sizeof(common_hdr));
2262 /* read the rest of packet header */
2263 dwRead = rpcrt4_ncacn_http_read(Connection, &(*Header)->common + 1, hdr_length - sizeof(common_hdr));
2264 if (dwRead != hdr_length - sizeof(common_hdr)) {
2265 WARN("bad header length, %d bytes, hdr_length %d\n", dwRead, hdr_length);
2266 status = RPC_S_PROTOCOL_ERROR;
2270 if (common_hdr.frag_len - hdr_length)
2272 *Payload = HeapAlloc(GetProcessHeap(), 0, common_hdr.frag_len - hdr_length);
2275 status = RPC_S_OUT_OF_RESOURCES;
2279 dwRead = rpcrt4_ncacn_http_read(Connection, *Payload, common_hdr.frag_len - hdr_length);
2280 if (dwRead != common_hdr.frag_len - hdr_length)
2282 WARN("bad data length, %d/%d\n", dwRead, common_hdr.frag_len - hdr_length);
2283 status = RPC_S_PROTOCOL_ERROR;
2290 if ((*Header)->common.ptype == PKT_HTTP)
2292 if (!RPCRT4_IsValidHttpPacket(*Header, *Payload, common_hdr.frag_len - hdr_length))
2294 ERR("invalid http packet of length %d bytes\n", (*Header)->common.frag_len);
2295 status = RPC_S_PROTOCOL_ERROR;
2298 if ((*Header)->http.flags == 0x0001)
2300 TRACE("http idle packet, waiting for real packet\n");
2301 if ((*Header)->http.num_data_items != 0)
2303 ERR("HTTP idle packet should have no data items instead of %d\n", (*Header)->http.num_data_items);
2304 status = RPC_S_PROTOCOL_ERROR;
2308 else if ((*Header)->http.flags == 0x0002)
2310 ULONG bytes_transmitted;
2311 ULONG flow_control_increment;
2313 status = RPCRT4_ParseHttpFlowControlHeader(*Header, *Payload,
2316 &flow_control_increment,
2318 if (status != RPC_S_OK)
2320 TRACE("received http flow control header (0x%x, 0x%x, %s)\n",
2321 bytes_transmitted, flow_control_increment, debugstr_guid(&pipe_uuid));
2322 /* FIXME: do something with parsed data */
2326 FIXME("unrecognised http packet with flags 0x%04x\n", (*Header)->http.flags);
2327 status = RPC_S_PROTOCOL_ERROR;
2330 RPCRT4_FreeHeader(*Header);
2332 HeapFree(GetProcessHeap(), 0, *Payload);
2340 httpc->bytes_received += common_hdr.frag_len;
2342 TRACE("httpc->bytes_received = 0x%x\n", httpc->bytes_received);
2344 if (httpc->bytes_received > httpc->flow_control_mark)
2346 RpcPktHdr *hdr = RPCRT4_BuildHttpFlowControlHeader(httpc->common.server,
2347 httpc->bytes_received,
2348 httpc->flow_control_increment,
2349 &httpc->out_pipe_uuid);
2352 DWORD bytes_written;
2354 TRACE("sending flow control packet at 0x%x\n", httpc->bytes_received);
2355 ret2 = InternetWriteFile(httpc->in_request, hdr, hdr->common.frag_len, &bytes_written);
2356 RPCRT4_FreeHeader(hdr);
2358 httpc->flow_control_mark = httpc->bytes_received + httpc->flow_control_increment / 2;
2363 if (status != RPC_S_OK) {
2364 RPCRT4_FreeHeader(*Header);
2366 HeapFree(GetProcessHeap(), 0, *Payload);
2372 static int rpcrt4_ncacn_http_write(RpcConnection *Connection,
2373 const void *buffer, unsigned int count)
2375 RpcConnection_http *httpc = (RpcConnection_http *) Connection;
2376 DWORD bytes_written;
2379 httpc->last_sent_time = ~0UL; /* disable idle packet sending */
2380 ret = InternetWriteFile(httpc->in_request, buffer, count, &bytes_written);
2381 httpc->last_sent_time = GetTickCount();
2382 TRACE("%p %p %u -> %s\n", httpc->in_request, buffer, count, ret ? "TRUE" : "FALSE");
2383 return ret ? bytes_written : -1;
2386 static int rpcrt4_ncacn_http_close(RpcConnection *Connection)
2388 RpcConnection_http *httpc = (RpcConnection_http *) Connection;
2392 SetEvent(httpc->timer_cancelled);
2393 if (httpc->in_request)
2394 InternetCloseHandle(httpc->in_request);
2395 httpc->in_request = NULL;
2396 if (httpc->out_request)
2397 InternetCloseHandle(httpc->out_request);
2398 httpc->out_request = NULL;
2399 if (httpc->app_info)
2400 InternetCloseHandle(httpc->app_info);
2401 httpc->app_info = NULL;
2403 InternetCloseHandle(httpc->session);
2404 httpc->session = NULL;
2405 RpcHttpAsyncData_Release(httpc->async_data);
2406 if (httpc->cancel_event)
2407 CloseHandle(httpc->cancel_event);
2412 static void rpcrt4_ncacn_http_cancel_call(RpcConnection *Connection)
2414 RpcConnection_http *httpc = (RpcConnection_http *) Connection;
2416 SetEvent(httpc->cancel_event);
2419 static int rpcrt4_ncacn_http_wait_for_incoming_data(RpcConnection *Connection)
2422 RpcConnection_http *httpc = (RpcConnection_http *) Connection;
2424 RpcHttpAsyncData_AddRef(httpc->async_data);
2425 ret = InternetQueryDataAvailable(httpc->out_request,
2426 &httpc->async_data->inet_buffers.dwBufferLength, IRF_ASYNC, 0);
2429 /* INTERNET_STATUS_REQUEST_COMPLETED won't be sent, so release our
2431 RpcHttpAsyncData_Release(httpc->async_data);
2435 if (GetLastError() == ERROR_IO_PENDING)
2437 HANDLE handles[2] = { httpc->async_data->completion_event, httpc->cancel_event };
2438 DWORD result = WaitForMultipleObjects(2, handles, FALSE, DEFAULT_NCACN_HTTP_TIMEOUT);
2439 if (result != WAIT_OBJECT_0)
2441 TRACE("call cancelled\n");
2447 RpcHttpAsyncData_Release(httpc->async_data);
2456 static size_t rpcrt4_ncacn_http_get_top_of_tower(unsigned char *tower_data,
2457 const char *networkaddr,
2458 const char *endpoint)
2460 return rpcrt4_ip_tcp_get_top_of_tower(tower_data, networkaddr,
2461 EPM_PROTOCOL_HTTP, endpoint);
2464 static RPC_STATUS rpcrt4_ncacn_http_parse_top_of_tower(const unsigned char *tower_data,
2469 return rpcrt4_ip_tcp_parse_top_of_tower(tower_data, tower_size,
2470 networkaddr, EPM_PROTOCOL_HTTP,
2474 static const struct connection_ops conn_protseq_list[] = {
2476 { EPM_PROTOCOL_NCACN, EPM_PROTOCOL_SMB },
2477 rpcrt4_conn_np_alloc,
2478 rpcrt4_ncacn_np_open,
2479 rpcrt4_ncacn_np_handoff,
2480 rpcrt4_conn_np_read,
2481 rpcrt4_conn_np_write,
2482 rpcrt4_conn_np_close,
2483 rpcrt4_conn_np_cancel_call,
2484 rpcrt4_conn_np_wait_for_incoming_data,
2485 rpcrt4_ncacn_np_get_top_of_tower,
2486 rpcrt4_ncacn_np_parse_top_of_tower,
2490 { EPM_PROTOCOL_NCALRPC, EPM_PROTOCOL_PIPE },
2491 rpcrt4_conn_np_alloc,
2492 rpcrt4_ncalrpc_open,
2493 rpcrt4_ncalrpc_handoff,
2494 rpcrt4_conn_np_read,
2495 rpcrt4_conn_np_write,
2496 rpcrt4_conn_np_close,
2497 rpcrt4_conn_np_cancel_call,
2498 rpcrt4_conn_np_wait_for_incoming_data,
2499 rpcrt4_ncalrpc_get_top_of_tower,
2500 rpcrt4_ncalrpc_parse_top_of_tower,
2504 { EPM_PROTOCOL_NCACN, EPM_PROTOCOL_TCP },
2505 rpcrt4_conn_tcp_alloc,
2506 rpcrt4_ncacn_ip_tcp_open,
2507 rpcrt4_conn_tcp_handoff,
2508 rpcrt4_conn_tcp_read,
2509 rpcrt4_conn_tcp_write,
2510 rpcrt4_conn_tcp_close,
2511 rpcrt4_conn_tcp_cancel_call,
2512 rpcrt4_conn_tcp_wait_for_incoming_data,
2513 rpcrt4_ncacn_ip_tcp_get_top_of_tower,
2514 rpcrt4_ncacn_ip_tcp_parse_top_of_tower,
2518 { EPM_PROTOCOL_NCACN, EPM_PROTOCOL_HTTP },
2519 rpcrt4_ncacn_http_alloc,
2520 rpcrt4_ncacn_http_open,
2521 rpcrt4_ncacn_http_handoff,
2522 rpcrt4_ncacn_http_read,
2523 rpcrt4_ncacn_http_write,
2524 rpcrt4_ncacn_http_close,
2525 rpcrt4_ncacn_http_cancel_call,
2526 rpcrt4_ncacn_http_wait_for_incoming_data,
2527 rpcrt4_ncacn_http_get_top_of_tower,
2528 rpcrt4_ncacn_http_parse_top_of_tower,
2529 rpcrt4_ncacn_http_receive_fragment,
2534 static const struct protseq_ops protseq_list[] =
2538 rpcrt4_protseq_np_alloc,
2539 rpcrt4_protseq_np_signal_state_changed,
2540 rpcrt4_protseq_np_get_wait_array,
2541 rpcrt4_protseq_np_free_wait_array,
2542 rpcrt4_protseq_np_wait_for_new_connection,
2543 rpcrt4_protseq_ncacn_np_open_endpoint,
2547 rpcrt4_protseq_np_alloc,
2548 rpcrt4_protseq_np_signal_state_changed,
2549 rpcrt4_protseq_np_get_wait_array,
2550 rpcrt4_protseq_np_free_wait_array,
2551 rpcrt4_protseq_np_wait_for_new_connection,
2552 rpcrt4_protseq_ncalrpc_open_endpoint,
2554 #ifdef HAVE_SOCKETPAIR
2557 rpcrt4_protseq_sock_alloc,
2558 rpcrt4_protseq_sock_signal_state_changed,
2559 rpcrt4_protseq_sock_get_wait_array,
2560 rpcrt4_protseq_sock_free_wait_array,
2561 rpcrt4_protseq_sock_wait_for_new_connection,
2562 rpcrt4_protseq_ncacn_ip_tcp_open_endpoint,
2567 #define ARRAYSIZE(a) (sizeof((a)) / sizeof((a)[0]))
2569 const struct protseq_ops *rpcrt4_get_protseq_ops(const char *protseq)
2572 for(i=0; i<ARRAYSIZE(protseq_list); i++)
2573 if (!strcmp(protseq_list[i].name, protseq))
2574 return &protseq_list[i];
2578 static const struct connection_ops *rpcrt4_get_conn_protseq_ops(const char *protseq)
2581 for(i=0; i<ARRAYSIZE(conn_protseq_list); i++)
2582 if (!strcmp(conn_protseq_list[i].name, protseq))
2583 return &conn_protseq_list[i];
2587 /**** interface to rest of code ****/
2589 RPC_STATUS RPCRT4_OpenClientConnection(RpcConnection* Connection)
2591 TRACE("(Connection == ^%p)\n", Connection);
2593 assert(!Connection->server);
2594 return Connection->ops->open_connection_client(Connection);
2597 RPC_STATUS RPCRT4_CloseConnection(RpcConnection* Connection)
2599 TRACE("(Connection == ^%p)\n", Connection);
2600 if (SecIsValidHandle(&Connection->ctx))
2602 DeleteSecurityContext(&Connection->ctx);
2603 SecInvalidateHandle(&Connection->ctx);
2605 rpcrt4_conn_close(Connection);
2609 RPC_STATUS RPCRT4_CreateConnection(RpcConnection** Connection, BOOL server,
2610 LPCSTR Protseq, LPCSTR NetworkAddr, LPCSTR Endpoint,
2611 LPCWSTR NetworkOptions, RpcAuthInfo* AuthInfo, RpcQualityOfService *QOS)
2613 const struct connection_ops *ops;
2614 RpcConnection* NewConnection;
2616 ops = rpcrt4_get_conn_protseq_ops(Protseq);
2619 FIXME("not supported for protseq %s\n", Protseq);
2620 return RPC_S_PROTSEQ_NOT_SUPPORTED;
2623 NewConnection = ops->alloc();
2624 NewConnection->Next = NULL;
2625 NewConnection->server_binding = NULL;
2626 NewConnection->server = server;
2627 NewConnection->ops = ops;
2628 NewConnection->NetworkAddr = RPCRT4_strdupA(NetworkAddr);
2629 NewConnection->Endpoint = RPCRT4_strdupA(Endpoint);
2630 NewConnection->NetworkOptions = RPCRT4_strdupW(NetworkOptions);
2631 NewConnection->MaxTransmissionSize = RPC_MAX_PACKET_SIZE;
2632 memset(&NewConnection->ActiveInterface, 0, sizeof(NewConnection->ActiveInterface));
2633 NewConnection->NextCallId = 1;
2635 SecInvalidateHandle(&NewConnection->ctx);
2636 memset(&NewConnection->exp, 0, sizeof(NewConnection->exp));
2637 NewConnection->attr = 0;
2638 if (AuthInfo) RpcAuthInfo_AddRef(AuthInfo);
2639 NewConnection->AuthInfo = AuthInfo;
2640 NewConnection->encryption_auth_len = 0;
2641 NewConnection->signature_auth_len = 0;
2642 if (QOS) RpcQualityOfService_AddRef(QOS);
2643 NewConnection->QOS = QOS;
2645 list_init(&NewConnection->conn_pool_entry);
2646 NewConnection->async_state = NULL;
2648 TRACE("connection: %p\n", NewConnection);
2649 *Connection = NewConnection;
2654 static RPC_STATUS RPCRT4_SpawnConnection(RpcConnection** Connection, RpcConnection* OldConnection)
2658 err = RPCRT4_CreateConnection(Connection, OldConnection->server,
2659 rpcrt4_conn_get_name(OldConnection),
2660 OldConnection->NetworkAddr,
2661 OldConnection->Endpoint, NULL,
2662 OldConnection->AuthInfo, OldConnection->QOS);
2663 if (err == RPC_S_OK)
2664 rpcrt4_conn_handoff(OldConnection, *Connection);
2668 RPC_STATUS RPCRT4_DestroyConnection(RpcConnection* Connection)
2670 TRACE("connection: %p\n", Connection);
2672 RPCRT4_CloseConnection(Connection);
2673 RPCRT4_strfree(Connection->Endpoint);
2674 RPCRT4_strfree(Connection->NetworkAddr);
2675 HeapFree(GetProcessHeap(), 0, Connection->NetworkOptions);
2676 if (Connection->AuthInfo) RpcAuthInfo_Release(Connection->AuthInfo);
2677 if (Connection->QOS) RpcQualityOfService_Release(Connection->QOS);
2680 if (Connection->server_binding) RPCRT4_ReleaseBinding(Connection->server_binding);
2682 HeapFree(GetProcessHeap(), 0, Connection);
2686 RPC_STATUS RpcTransport_GetTopOfTower(unsigned char *tower_data,
2688 const char *protseq,
2689 const char *networkaddr,
2690 const char *endpoint)
2692 twr_empty_floor_t *protocol_floor;
2693 const struct connection_ops *protseq_ops = rpcrt4_get_conn_protseq_ops(protseq);
2698 return RPC_S_INVALID_RPC_PROTSEQ;
2702 *tower_size = sizeof(*protocol_floor);
2703 *tower_size += protseq_ops->get_top_of_tower(NULL, networkaddr, endpoint);
2707 protocol_floor = (twr_empty_floor_t *)tower_data;
2708 protocol_floor->count_lhs = sizeof(protocol_floor->protid);
2709 protocol_floor->protid = protseq_ops->epm_protocols[0];
2710 protocol_floor->count_rhs = 0;
2712 tower_data += sizeof(*protocol_floor);
2714 *tower_size = protseq_ops->get_top_of_tower(tower_data, networkaddr, endpoint);
2716 return EPT_S_NOT_REGISTERED;
2718 *tower_size += sizeof(*protocol_floor);
2723 RPC_STATUS RpcTransport_ParseTopOfTower(const unsigned char *tower_data,
2729 const twr_empty_floor_t *protocol_floor;
2730 const twr_empty_floor_t *floor4;
2731 const struct connection_ops *protseq_ops = NULL;
2735 if (tower_size < sizeof(*protocol_floor))
2736 return EPT_S_NOT_REGISTERED;
2738 protocol_floor = (const twr_empty_floor_t *)tower_data;
2739 tower_data += sizeof(*protocol_floor);
2740 tower_size -= sizeof(*protocol_floor);
2741 if ((protocol_floor->count_lhs != sizeof(protocol_floor->protid)) ||
2742 (protocol_floor->count_rhs > tower_size))
2743 return EPT_S_NOT_REGISTERED;
2744 tower_data += protocol_floor->count_rhs;
2745 tower_size -= protocol_floor->count_rhs;
2747 floor4 = (const twr_empty_floor_t *)tower_data;
2748 if ((tower_size < sizeof(*floor4)) ||
2749 (floor4->count_lhs != sizeof(floor4->protid)))
2750 return EPT_S_NOT_REGISTERED;
2752 for(i = 0; i < ARRAYSIZE(conn_protseq_list); i++)
2753 if ((protocol_floor->protid == conn_protseq_list[i].epm_protocols[0]) &&
2754 (floor4->protid == conn_protseq_list[i].epm_protocols[1]))
2756 protseq_ops = &conn_protseq_list[i];
2761 return EPT_S_NOT_REGISTERED;
2763 status = protseq_ops->parse_top_of_tower(tower_data, tower_size, networkaddr, endpoint);
2765 if ((status == RPC_S_OK) && protseq)
2767 *protseq = I_RpcAllocate(strlen(protseq_ops->name) + 1);
2768 strcpy(*protseq, protseq_ops->name);
2774 /***********************************************************************
2775 * RpcNetworkIsProtseqValidW (RPCRT4.@)
2777 * Checks if the given protocol sequence is known by the RPC system.
2778 * If it is, returns RPC_S_OK, otherwise RPC_S_PROTSEQ_NOT_SUPPORTED.
2781 RPC_STATUS WINAPI RpcNetworkIsProtseqValidW(RPC_WSTR protseq)
2785 WideCharToMultiByte(CP_ACP, 0, protseq, -1,
2786 ps, sizeof ps, NULL, NULL);
2787 if (rpcrt4_get_conn_protseq_ops(ps))
2790 FIXME("Unknown protseq %s\n", debugstr_w(protseq));
2792 return RPC_S_INVALID_RPC_PROTSEQ;
2795 /***********************************************************************
2796 * RpcNetworkIsProtseqValidA (RPCRT4.@)
2798 RPC_STATUS WINAPI RpcNetworkIsProtseqValidA(RPC_CSTR protseq)
2800 UNICODE_STRING protseqW;
2802 if (RtlCreateUnicodeStringFromAsciiz(&protseqW, (char*)protseq))
2804 RPC_STATUS ret = RpcNetworkIsProtseqValidW(protseqW.Buffer);
2805 RtlFreeUnicodeString(&protseqW);
2808 return RPC_S_OUT_OF_MEMORY;