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;
115 OVERLAPPED write_ovl;
119 static RpcConnection *rpcrt4_conn_np_alloc(void)
121 RpcConnection_np *npc = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(RpcConnection_np));
125 static RPC_STATUS rpcrt4_conn_listen_pipe(RpcConnection_np *npc)
130 npc->listening = TRUE;
133 if (ConnectNamedPipe(npc->pipe, &npc->read_ovl))
136 switch(GetLastError())
138 case ERROR_PIPE_CONNECTED:
139 SetEvent(npc->read_ovl.hEvent);
141 case ERROR_IO_PENDING:
142 /* will be completed in rpcrt4_protseq_np_wait_for_new_connection */
144 case ERROR_NO_DATA_DETECTED:
145 /* client has disconnected, retry */
146 DisconnectNamedPipe( npc->pipe );
149 npc->listening = FALSE;
150 WARN("Couldn't ConnectNamedPipe (error was %d)\n", GetLastError());
151 return RPC_S_OUT_OF_RESOURCES;
156 static RPC_STATUS rpcrt4_conn_create_pipe(RpcConnection *Connection, LPCSTR pname)
158 RpcConnection_np *npc = (RpcConnection_np *) Connection;
159 TRACE("listening on %s\n", pname);
161 npc->pipe = CreateNamedPipeA(pname, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
162 PIPE_TYPE_MESSAGE | PIPE_READMODE_MESSAGE,
163 PIPE_UNLIMITED_INSTANCES,
164 RPC_MAX_PACKET_SIZE, RPC_MAX_PACKET_SIZE, 5000, NULL);
165 if (npc->pipe == INVALID_HANDLE_VALUE) {
166 WARN("CreateNamedPipe failed with error %d\n", GetLastError());
167 if (GetLastError() == ERROR_FILE_EXISTS)
168 return RPC_S_DUPLICATE_ENDPOINT;
170 return RPC_S_CANT_CREATE_ENDPOINT;
173 npc->read_ovl.hEvent = CreateEventW(NULL, TRUE, FALSE, NULL);
174 npc->write_ovl.hEvent = CreateEventW(NULL, TRUE, FALSE, NULL);
176 /* Note: we don't call ConnectNamedPipe here because it must be done in the
177 * server thread as the thread must be alertable */
181 static RPC_STATUS rpcrt4_conn_open_pipe(RpcConnection *Connection, LPCSTR pname, BOOL wait)
183 RpcConnection_np *npc = (RpcConnection_np *) Connection;
187 TRACE("connecting to %s\n", pname);
193 dwFlags = SECURITY_SQOS_PRESENT;
194 switch (Connection->QOS->qos->ImpersonationType)
196 case RPC_C_IMP_LEVEL_DEFAULT:
197 /* FIXME: what to do here? */
199 case RPC_C_IMP_LEVEL_ANONYMOUS:
200 dwFlags |= SECURITY_ANONYMOUS;
202 case RPC_C_IMP_LEVEL_IDENTIFY:
203 dwFlags |= SECURITY_IDENTIFICATION;
205 case RPC_C_IMP_LEVEL_IMPERSONATE:
206 dwFlags |= SECURITY_IMPERSONATION;
208 case RPC_C_IMP_LEVEL_DELEGATE:
209 dwFlags |= SECURITY_DELEGATION;
212 if (Connection->QOS->qos->IdentityTracking == RPC_C_QOS_IDENTITY_DYNAMIC)
213 dwFlags |= SECURITY_CONTEXT_TRACKING;
215 pipe = CreateFileA(pname, GENERIC_READ|GENERIC_WRITE, 0, NULL,
216 OPEN_EXISTING, dwFlags, 0);
217 if (pipe != INVALID_HANDLE_VALUE) break;
218 err = GetLastError();
219 if (err == ERROR_PIPE_BUSY) {
220 TRACE("connection failed, error=%x\n", err);
221 return RPC_S_SERVER_TOO_BUSY;
223 if (!wait || !WaitNamedPipeA(pname, NMPWAIT_WAIT_FOREVER)) {
224 err = GetLastError();
225 WARN("connection failed, error=%x\n", err);
226 return RPC_S_SERVER_UNAVAILABLE;
231 /* pipe is connected; change to message-read mode. */
232 dwMode = PIPE_READMODE_MESSAGE;
233 SetNamedPipeHandleState(pipe, &dwMode, NULL, NULL);
234 npc->read_ovl.hEvent = CreateEventW(NULL, TRUE, FALSE, NULL);
235 npc->write_ovl.hEvent = CreateEventW(NULL, TRUE, FALSE, NULL);
241 static RPC_STATUS rpcrt4_ncalrpc_open(RpcConnection* Connection)
243 RpcConnection_np *npc = (RpcConnection_np *) Connection;
244 static const char prefix[] = "\\\\.\\pipe\\lrpc\\";
248 /* already connected? */
252 /* protseq=ncalrpc: supposed to use NT LPC ports,
253 * but we'll implement it with named pipes for now */
254 pname = I_RpcAllocate(strlen(prefix) + strlen(Connection->Endpoint) + 1);
255 strcat(strcpy(pname, prefix), Connection->Endpoint);
256 r = rpcrt4_conn_open_pipe(Connection, pname, TRUE);
262 static RPC_STATUS rpcrt4_protseq_ncalrpc_open_endpoint(RpcServerProtseq* protseq, const char *endpoint)
264 static const char prefix[] = "\\\\.\\pipe\\lrpc\\";
267 RpcConnection *Connection;
268 char generated_endpoint[22];
272 static LONG lrpc_nameless_id;
273 DWORD process_id = GetCurrentProcessId();
274 ULONG id = InterlockedIncrement(&lrpc_nameless_id);
275 snprintf(generated_endpoint, sizeof(generated_endpoint),
276 "LRPC%08x.%08x", process_id, id);
277 endpoint = generated_endpoint;
280 r = RPCRT4_CreateConnection(&Connection, TRUE, protseq->Protseq, NULL,
281 endpoint, NULL, NULL, NULL);
285 /* protseq=ncalrpc: supposed to use NT LPC ports,
286 * but we'll implement it with named pipes for now */
287 pname = I_RpcAllocate(strlen(prefix) + strlen(Connection->Endpoint) + 1);
288 strcat(strcpy(pname, prefix), Connection->Endpoint);
289 r = rpcrt4_conn_create_pipe(Connection, pname);
292 EnterCriticalSection(&protseq->cs);
293 Connection->Next = protseq->conn;
294 protseq->conn = Connection;
295 LeaveCriticalSection(&protseq->cs);
300 static RPC_STATUS rpcrt4_ncacn_np_open(RpcConnection* Connection)
302 RpcConnection_np *npc = (RpcConnection_np *) Connection;
303 static const char prefix[] = "\\\\.";
307 /* already connected? */
311 /* protseq=ncacn_np: named pipes */
312 pname = I_RpcAllocate(strlen(prefix) + strlen(Connection->Endpoint) + 1);
313 strcat(strcpy(pname, prefix), Connection->Endpoint);
314 r = rpcrt4_conn_open_pipe(Connection, pname, FALSE);
320 static RPC_STATUS rpcrt4_protseq_ncacn_np_open_endpoint(RpcServerProtseq *protseq, const char *endpoint)
322 static const char prefix[] = "\\\\.";
325 RpcConnection *Connection;
326 char generated_endpoint[21];
330 static LONG np_nameless_id;
331 DWORD process_id = GetCurrentProcessId();
332 ULONG id = InterlockedExchangeAdd(&np_nameless_id, 1 );
333 snprintf(generated_endpoint, sizeof(generated_endpoint),
334 "\\\\pipe\\\\%08x.%03x", process_id, id);
335 endpoint = generated_endpoint;
338 r = RPCRT4_CreateConnection(&Connection, TRUE, protseq->Protseq, NULL,
339 endpoint, NULL, NULL, NULL);
343 /* protseq=ncacn_np: named pipes */
344 pname = I_RpcAllocate(strlen(prefix) + strlen(Connection->Endpoint) + 1);
345 strcat(strcpy(pname, prefix), Connection->Endpoint);
346 r = rpcrt4_conn_create_pipe(Connection, pname);
349 EnterCriticalSection(&protseq->cs);
350 Connection->Next = protseq->conn;
351 protseq->conn = Connection;
352 LeaveCriticalSection(&protseq->cs);
357 static void rpcrt4_conn_np_handoff(RpcConnection_np *old_npc, RpcConnection_np *new_npc)
359 /* because of the way named pipes work, we'll transfer the connected pipe
360 * to the child, then reopen the server binding to continue listening */
362 new_npc->pipe = old_npc->pipe;
363 new_npc->read_ovl = old_npc->read_ovl;
364 new_npc->write_ovl = old_npc->write_ovl;
366 memset(&old_npc->read_ovl, 0, sizeof(old_npc->read_ovl));
367 memset(&old_npc->write_ovl, 0, sizeof(old_npc->write_ovl));
368 old_npc->listening = FALSE;
371 static RPC_STATUS rpcrt4_ncacn_np_handoff(RpcConnection *old_conn, RpcConnection *new_conn)
375 static const char prefix[] = "\\\\.";
377 rpcrt4_conn_np_handoff((RpcConnection_np *)old_conn, (RpcConnection_np *)new_conn);
379 pname = I_RpcAllocate(strlen(prefix) + strlen(old_conn->Endpoint) + 1);
380 strcat(strcpy(pname, prefix), old_conn->Endpoint);
381 status = rpcrt4_conn_create_pipe(old_conn, pname);
387 static RPC_STATUS rpcrt4_ncalrpc_handoff(RpcConnection *old_conn, RpcConnection *new_conn)
391 static const char prefix[] = "\\\\.\\pipe\\lrpc\\";
393 TRACE("%s\n", old_conn->Endpoint);
395 rpcrt4_conn_np_handoff((RpcConnection_np *)old_conn, (RpcConnection_np *)new_conn);
397 pname = I_RpcAllocate(strlen(prefix) + strlen(old_conn->Endpoint) + 1);
398 strcat(strcpy(pname, prefix), old_conn->Endpoint);
399 status = rpcrt4_conn_create_pipe(old_conn, pname);
405 static int rpcrt4_conn_np_read(RpcConnection *Connection,
406 void *buffer, unsigned int count)
408 RpcConnection_np *npc = (RpcConnection_np *) Connection;
411 unsigned int bytes_left = count;
416 ret = ReadFile(npc->pipe, buf, bytes_left, &bytes_read, &npc->read_ovl);
417 if (!ret && GetLastError() == ERROR_IO_PENDING)
418 ret = GetOverlappedResult(npc->pipe, &npc->read_ovl, &bytes_read, TRUE);
419 if (!ret && GetLastError() == ERROR_MORE_DATA)
421 if (!ret || !bytes_read)
423 bytes_left -= bytes_read;
426 return ret ? count : -1;
429 static int rpcrt4_conn_np_write(RpcConnection *Connection,
430 const void *buffer, unsigned int count)
432 RpcConnection_np *npc = (RpcConnection_np *) Connection;
433 const char *buf = buffer;
435 unsigned int bytes_left = count;
440 ret = WriteFile(npc->pipe, buf, bytes_left, &bytes_written, &npc->write_ovl);
441 if (!ret && GetLastError() == ERROR_IO_PENDING)
442 ret = GetOverlappedResult(npc->pipe, &npc->write_ovl, &bytes_written, TRUE);
443 if (!ret || !bytes_written)
445 bytes_left -= bytes_written;
446 buf += bytes_written;
448 return ret ? count : -1;
451 static int rpcrt4_conn_np_close(RpcConnection *Connection)
453 RpcConnection_np *npc = (RpcConnection_np *) Connection;
455 FlushFileBuffers(npc->pipe);
456 CloseHandle(npc->pipe);
459 if (npc->read_ovl.hEvent) {
460 CloseHandle(npc->read_ovl.hEvent);
461 npc->read_ovl.hEvent = 0;
463 if (npc->write_ovl.hEvent) {
464 CloseHandle(npc->write_ovl.hEvent);
465 npc->write_ovl.hEvent = 0;
470 static void rpcrt4_conn_np_cancel_call(RpcConnection *Connection)
472 /* FIXME: implement when named pipe writes use overlapped I/O */
475 static int rpcrt4_conn_np_wait_for_incoming_data(RpcConnection *Connection)
477 /* FIXME: implement when named pipe writes use overlapped I/O */
481 static size_t rpcrt4_ncacn_np_get_top_of_tower(unsigned char *tower_data,
482 const char *networkaddr,
483 const char *endpoint)
485 twr_empty_floor_t *smb_floor;
486 twr_empty_floor_t *nb_floor;
488 size_t networkaddr_size;
489 size_t endpoint_size;
491 TRACE("(%p, %s, %s)\n", tower_data, networkaddr, endpoint);
493 networkaddr_size = networkaddr ? strlen(networkaddr) + 1 : 1;
494 endpoint_size = endpoint ? strlen(endpoint) + 1 : 1;
495 size = sizeof(*smb_floor) + endpoint_size + sizeof(*nb_floor) + networkaddr_size;
500 smb_floor = (twr_empty_floor_t *)tower_data;
502 tower_data += sizeof(*smb_floor);
504 smb_floor->count_lhs = sizeof(smb_floor->protid);
505 smb_floor->protid = EPM_PROTOCOL_SMB;
506 smb_floor->count_rhs = endpoint_size;
509 memcpy(tower_data, endpoint, endpoint_size);
512 tower_data += endpoint_size;
514 nb_floor = (twr_empty_floor_t *)tower_data;
516 tower_data += sizeof(*nb_floor);
518 nb_floor->count_lhs = sizeof(nb_floor->protid);
519 nb_floor->protid = EPM_PROTOCOL_NETBIOS;
520 nb_floor->count_rhs = networkaddr_size;
523 memcpy(tower_data, networkaddr, networkaddr_size);
530 static RPC_STATUS rpcrt4_ncacn_np_parse_top_of_tower(const unsigned char *tower_data,
535 const twr_empty_floor_t *smb_floor = (const twr_empty_floor_t *)tower_data;
536 const twr_empty_floor_t *nb_floor;
538 TRACE("(%p, %d, %p, %p)\n", tower_data, (int)tower_size, networkaddr, endpoint);
540 if (tower_size < sizeof(*smb_floor))
541 return EPT_S_NOT_REGISTERED;
543 tower_data += sizeof(*smb_floor);
544 tower_size -= sizeof(*smb_floor);
546 if ((smb_floor->count_lhs != sizeof(smb_floor->protid)) ||
547 (smb_floor->protid != EPM_PROTOCOL_SMB) ||
548 (smb_floor->count_rhs > tower_size) ||
549 (tower_data[smb_floor->count_rhs - 1] != '\0'))
550 return EPT_S_NOT_REGISTERED;
554 *endpoint = I_RpcAllocate(smb_floor->count_rhs);
556 return RPC_S_OUT_OF_RESOURCES;
557 memcpy(*endpoint, tower_data, smb_floor->count_rhs);
559 tower_data += smb_floor->count_rhs;
560 tower_size -= smb_floor->count_rhs;
562 if (tower_size < sizeof(*nb_floor))
563 return EPT_S_NOT_REGISTERED;
565 nb_floor = (const twr_empty_floor_t *)tower_data;
567 tower_data += sizeof(*nb_floor);
568 tower_size -= sizeof(*nb_floor);
570 if ((nb_floor->count_lhs != sizeof(nb_floor->protid)) ||
571 (nb_floor->protid != EPM_PROTOCOL_NETBIOS) ||
572 (nb_floor->count_rhs > tower_size) ||
573 (tower_data[nb_floor->count_rhs - 1] != '\0'))
574 return EPT_S_NOT_REGISTERED;
578 *networkaddr = I_RpcAllocate(nb_floor->count_rhs);
583 I_RpcFree(*endpoint);
586 return RPC_S_OUT_OF_RESOURCES;
588 memcpy(*networkaddr, tower_data, nb_floor->count_rhs);
594 static RPC_STATUS rpcrt4_conn_np_impersonate_client(RpcConnection *conn)
596 RpcConnection_np *npc = (RpcConnection_np *)conn;
599 TRACE("(%p)\n", conn);
601 if (conn->AuthInfo && SecIsValidHandle(&conn->ctx))
602 return RPCRT4_default_impersonate_client(conn);
604 ret = ImpersonateNamedPipeClient(npc->pipe);
607 DWORD error = GetLastError();
608 WARN("ImpersonateNamedPipeClient failed with error %u\n", error);
611 case ERROR_CANNOT_IMPERSONATE:
612 return RPC_S_NO_CONTEXT_AVAILABLE;
618 static RPC_STATUS rpcrt4_conn_np_revert_to_self(RpcConnection *conn)
622 TRACE("(%p)\n", conn);
624 if (conn->AuthInfo && SecIsValidHandle(&conn->ctx))
625 return RPCRT4_default_revert_to_self(conn);
627 ret = RevertToSelf();
630 WARN("RevertToSelf failed with error %u\n", GetLastError());
631 return RPC_S_NO_CONTEXT_AVAILABLE;
636 typedef struct _RpcServerProtseq_np
638 RpcServerProtseq common;
640 } RpcServerProtseq_np;
642 static RpcServerProtseq *rpcrt4_protseq_np_alloc(void)
644 RpcServerProtseq_np *ps = HeapAlloc(GetProcessHeap(), 0, sizeof(*ps));
646 ps->mgr_event = CreateEventW(NULL, FALSE, FALSE, NULL);
650 static void rpcrt4_protseq_np_signal_state_changed(RpcServerProtseq *protseq)
652 RpcServerProtseq_np *npps = CONTAINING_RECORD(protseq, RpcServerProtseq_np, common);
653 SetEvent(npps->mgr_event);
656 static void *rpcrt4_protseq_np_get_wait_array(RpcServerProtseq *protseq, void *prev_array, unsigned int *count)
658 HANDLE *objs = prev_array;
659 RpcConnection_np *conn;
660 RpcServerProtseq_np *npps = CONTAINING_RECORD(protseq, RpcServerProtseq_np, common);
662 EnterCriticalSection(&protseq->cs);
664 /* open and count connections */
666 conn = CONTAINING_RECORD(protseq->conn, RpcConnection_np, common);
668 rpcrt4_conn_listen_pipe(conn);
669 if (conn->read_ovl.hEvent)
671 conn = CONTAINING_RECORD(conn->common.Next, RpcConnection_np, common);
674 /* make array of connections */
676 objs = HeapReAlloc(GetProcessHeap(), 0, objs, *count*sizeof(HANDLE));
678 objs = HeapAlloc(GetProcessHeap(), 0, *count*sizeof(HANDLE));
681 ERR("couldn't allocate objs\n");
682 LeaveCriticalSection(&protseq->cs);
686 objs[0] = npps->mgr_event;
688 conn = CONTAINING_RECORD(protseq->conn, RpcConnection_np, common);
690 if ((objs[*count] = conn->read_ovl.hEvent))
692 conn = CONTAINING_RECORD(conn->common.Next, RpcConnection_np, common);
694 LeaveCriticalSection(&protseq->cs);
698 static void rpcrt4_protseq_np_free_wait_array(RpcServerProtseq *protseq, void *array)
700 HeapFree(GetProcessHeap(), 0, array);
703 static int rpcrt4_protseq_np_wait_for_new_connection(RpcServerProtseq *protseq, unsigned int count, void *wait_array)
706 HANDLE *objs = wait_array;
708 RpcConnection *cconn;
709 RpcConnection_np *conn;
716 /* an alertable wait isn't strictly necessary, but due to our
717 * overlapped I/O implementation in Wine we need to free some memory
718 * by the file user APC being called, even if no completion routine was
719 * specified at the time of starting the async operation */
720 res = WaitForMultipleObjectsEx(count, objs, FALSE, INFINITE, TRUE);
721 } while (res == WAIT_IO_COMPLETION);
723 if (res == WAIT_OBJECT_0)
725 else if (res == WAIT_FAILED)
727 ERR("wait failed with error %d\n", GetLastError());
732 b_handle = objs[res - WAIT_OBJECT_0];
733 /* find which connection got a RPC */
734 EnterCriticalSection(&protseq->cs);
735 conn = CONTAINING_RECORD(protseq->conn, RpcConnection_np, common);
737 if (b_handle == conn->read_ovl.hEvent) break;
738 conn = CONTAINING_RECORD(conn->common.Next, RpcConnection_np, common);
742 RPCRT4_SpawnConnection(&cconn, &conn->common);
744 ERR("failed to locate connection for handle %p\n", b_handle);
745 LeaveCriticalSection(&protseq->cs);
748 RPCRT4_new_client(cconn);
755 static size_t rpcrt4_ncalrpc_get_top_of_tower(unsigned char *tower_data,
756 const char *networkaddr,
757 const char *endpoint)
759 twr_empty_floor_t *pipe_floor;
761 size_t endpoint_size;
763 TRACE("(%p, %s, %s)\n", tower_data, networkaddr, endpoint);
765 endpoint_size = strlen(endpoint) + 1;
766 size = sizeof(*pipe_floor) + endpoint_size;
771 pipe_floor = (twr_empty_floor_t *)tower_data;
773 tower_data += sizeof(*pipe_floor);
775 pipe_floor->count_lhs = sizeof(pipe_floor->protid);
776 pipe_floor->protid = EPM_PROTOCOL_PIPE;
777 pipe_floor->count_rhs = endpoint_size;
779 memcpy(tower_data, endpoint, endpoint_size);
784 static RPC_STATUS rpcrt4_ncalrpc_parse_top_of_tower(const unsigned char *tower_data,
789 const twr_empty_floor_t *pipe_floor = (const twr_empty_floor_t *)tower_data;
791 TRACE("(%p, %d, %p, %p)\n", tower_data, (int)tower_size, networkaddr, endpoint);
793 if (tower_size < sizeof(*pipe_floor))
794 return EPT_S_NOT_REGISTERED;
796 tower_data += sizeof(*pipe_floor);
797 tower_size -= sizeof(*pipe_floor);
799 if ((pipe_floor->count_lhs != sizeof(pipe_floor->protid)) ||
800 (pipe_floor->protid != EPM_PROTOCOL_PIPE) ||
801 (pipe_floor->count_rhs > tower_size) ||
802 (tower_data[pipe_floor->count_rhs - 1] != '\0'))
803 return EPT_S_NOT_REGISTERED;
810 *endpoint = I_RpcAllocate(pipe_floor->count_rhs);
812 return RPC_S_OUT_OF_RESOURCES;
813 memcpy(*endpoint, tower_data, pipe_floor->count_rhs);
819 static BOOL rpcrt4_ncalrpc_is_authorized(RpcConnection *conn)
824 static RPC_STATUS rpcrt4_ncalrpc_authorize(RpcConnection *conn, BOOL first_time,
825 unsigned char *in_buffer,
826 unsigned int in_size,
827 unsigned char *out_buffer,
828 unsigned int *out_size)
830 /* since this protocol is local to the machine there is no need to
831 * authenticate the caller */
836 static RPC_STATUS rpcrt4_ncalrpc_secure_packet(RpcConnection *conn,
837 enum secure_packet_direction dir,
838 RpcPktHdr *hdr, unsigned int hdr_size,
839 unsigned char *stub_data, unsigned int stub_data_size,
840 RpcAuthVerifier *auth_hdr,
841 unsigned char *auth_value, unsigned int auth_value_size)
843 /* since this protocol is local to the machine there is no need to secure
848 static RPC_STATUS rpcrt4_ncalrpc_inquire_auth_client(
849 RpcConnection *conn, RPC_AUTHZ_HANDLE *privs, RPC_WSTR *server_princ_name,
850 ULONG *authn_level, ULONG *authn_svc, ULONG *authz_svc, ULONG flags)
852 TRACE("(%p, %p, %p, %p, %p, %p, 0x%x)\n", conn, privs,
853 server_princ_name, authn_level, authn_svc, authz_svc, flags);
857 FIXME("privs not implemented\n");
860 if (server_princ_name)
862 FIXME("server_princ_name not implemented\n");
863 *server_princ_name = NULL;
865 if (authn_level) *authn_level = RPC_C_AUTHN_LEVEL_PKT_PRIVACY;
866 if (authn_svc) *authn_svc = RPC_C_AUTHN_WINNT;
869 FIXME("authorization service not implemented\n");
870 *authz_svc = RPC_C_AUTHZ_NONE;
873 FIXME("flags 0x%x not implemented\n", flags);
878 /**** ncacn_ip_tcp support ****/
880 static size_t rpcrt4_ip_tcp_get_top_of_tower(unsigned char *tower_data,
881 const char *networkaddr,
882 unsigned char tcp_protid,
883 const char *endpoint)
885 twr_tcp_floor_t *tcp_floor;
886 twr_ipv4_floor_t *ipv4_floor;
888 struct addrinfo hints;
890 size_t size = sizeof(*tcp_floor) + sizeof(*ipv4_floor);
892 TRACE("(%p, %s, %s)\n", tower_data, networkaddr, endpoint);
897 tcp_floor = (twr_tcp_floor_t *)tower_data;
898 tower_data += sizeof(*tcp_floor);
900 ipv4_floor = (twr_ipv4_floor_t *)tower_data;
902 tcp_floor->count_lhs = sizeof(tcp_floor->protid);
903 tcp_floor->protid = tcp_protid;
904 tcp_floor->count_rhs = sizeof(tcp_floor->port);
906 ipv4_floor->count_lhs = sizeof(ipv4_floor->protid);
907 ipv4_floor->protid = EPM_PROTOCOL_IP;
908 ipv4_floor->count_rhs = sizeof(ipv4_floor->ipv4addr);
910 hints.ai_flags = AI_NUMERICHOST;
911 /* FIXME: only support IPv4 at the moment. how is IPv6 represented by the EPM? */
912 hints.ai_family = PF_INET;
913 hints.ai_socktype = SOCK_STREAM;
914 hints.ai_protocol = IPPROTO_TCP;
915 hints.ai_addrlen = 0;
916 hints.ai_addr = NULL;
917 hints.ai_canonname = NULL;
918 hints.ai_next = NULL;
920 ret = getaddrinfo(networkaddr, endpoint, &hints, &ai);
923 ret = getaddrinfo("0.0.0.0", endpoint, &hints, &ai);
926 ERR("getaddrinfo failed: %s\n", gai_strerror(ret));
931 if (ai->ai_family == PF_INET)
933 const struct sockaddr_in *sin = (const struct sockaddr_in *)ai->ai_addr;
934 tcp_floor->port = sin->sin_port;
935 ipv4_floor->ipv4addr = sin->sin_addr.s_addr;
939 ERR("unexpected protocol family %d\n", ai->ai_family);
948 static RPC_STATUS rpcrt4_ip_tcp_parse_top_of_tower(const unsigned char *tower_data,
951 unsigned char tcp_protid,
954 const twr_tcp_floor_t *tcp_floor = (const twr_tcp_floor_t *)tower_data;
955 const twr_ipv4_floor_t *ipv4_floor;
956 struct in_addr in_addr;
958 TRACE("(%p, %d, %p, %p)\n", tower_data, (int)tower_size, networkaddr, endpoint);
960 if (tower_size < sizeof(*tcp_floor))
961 return EPT_S_NOT_REGISTERED;
963 tower_data += sizeof(*tcp_floor);
964 tower_size -= sizeof(*tcp_floor);
966 if (tower_size < sizeof(*ipv4_floor))
967 return EPT_S_NOT_REGISTERED;
969 ipv4_floor = (const twr_ipv4_floor_t *)tower_data;
971 if ((tcp_floor->count_lhs != sizeof(tcp_floor->protid)) ||
972 (tcp_floor->protid != tcp_protid) ||
973 (tcp_floor->count_rhs != sizeof(tcp_floor->port)) ||
974 (ipv4_floor->count_lhs != sizeof(ipv4_floor->protid)) ||
975 (ipv4_floor->protid != EPM_PROTOCOL_IP) ||
976 (ipv4_floor->count_rhs != sizeof(ipv4_floor->ipv4addr)))
977 return EPT_S_NOT_REGISTERED;
981 *endpoint = I_RpcAllocate(6 /* sizeof("65535") + 1 */);
983 return RPC_S_OUT_OF_RESOURCES;
984 sprintf(*endpoint, "%u", ntohs(tcp_floor->port));
989 *networkaddr = I_RpcAllocate(INET_ADDRSTRLEN);
994 I_RpcFree(*endpoint);
997 return RPC_S_OUT_OF_RESOURCES;
999 in_addr.s_addr = ipv4_floor->ipv4addr;
1000 if (!inet_ntop(AF_INET, &in_addr, *networkaddr, INET_ADDRSTRLEN))
1002 ERR("inet_ntop: %s\n", strerror(errno));
1003 I_RpcFree(*networkaddr);
1004 *networkaddr = NULL;
1007 I_RpcFree(*endpoint);
1010 return EPT_S_NOT_REGISTERED;
1017 typedef struct _RpcConnection_tcp
1019 RpcConnection common;
1021 #ifdef HAVE_SOCKETPAIR
1025 HANDLE cancel_event;
1027 } RpcConnection_tcp;
1029 #ifdef HAVE_SOCKETPAIR
1031 static BOOL rpcrt4_sock_wait_init(RpcConnection_tcp *tcpc)
1033 if (socketpair(PF_UNIX, SOCK_STREAM, 0, tcpc->cancel_fds) < 0)
1035 ERR("socketpair() failed: %s\n", strerror(errno));
1041 static BOOL rpcrt4_sock_wait_for_recv(RpcConnection_tcp *tcpc)
1043 struct pollfd pfds[2];
1044 pfds[0].fd = tcpc->sock;
1045 pfds[0].events = POLLIN;
1046 pfds[1].fd = tcpc->cancel_fds[0];
1047 pfds[1].events = POLLIN;
1048 if (poll(pfds, 2, -1 /* infinite */) == -1 && errno != EINTR)
1050 ERR("poll() failed: %s\n", strerror(errno));
1053 if (pfds[1].revents & POLLIN) /* canceled */
1056 read(pfds[1].fd, &dummy, sizeof(dummy));
1062 static BOOL rpcrt4_sock_wait_for_send(RpcConnection_tcp *tcpc)
1065 pfd.fd = tcpc->sock;
1066 pfd.events = POLLOUT;
1067 if (poll(&pfd, 1, -1 /* infinite */) == -1 && errno != EINTR)
1069 ERR("poll() failed: %s\n", strerror(errno));
1075 static void rpcrt4_sock_wait_cancel(RpcConnection_tcp *tcpc)
1079 write(tcpc->cancel_fds[1], &dummy, 1);
1082 static void rpcrt4_sock_wait_destroy(RpcConnection_tcp *tcpc)
1084 close(tcpc->cancel_fds[0]);
1085 close(tcpc->cancel_fds[1]);
1088 #else /* HAVE_SOCKETPAIR */
1090 static BOOL rpcrt4_sock_wait_init(RpcConnection_tcp *tcpc)
1092 static BOOL wsa_inited;
1096 WSAStartup(MAKEWORD(2, 2), &wsadata);
1097 /* Note: WSAStartup can be called more than once so we don't bother with
1098 * making accesses to wsa_inited thread-safe */
1101 tcpc->sock_event = CreateEventW(NULL, FALSE, FALSE, NULL);
1102 tcpc->cancel_event = CreateEventW(NULL, FALSE, FALSE, NULL);
1103 if (!tcpc->sock_event || !tcpc->cancel_event)
1105 ERR("event creation failed\n");
1106 if (tcpc->sock_event) CloseHandle(tcpc->sock_event);
1112 static BOOL rpcrt4_sock_wait_for_recv(RpcConnection_tcp *tcpc)
1114 HANDLE wait_handles[2];
1116 if (WSAEventSelect(tcpc->sock, tcpc->sock_event, FD_READ | FD_CLOSE) == SOCKET_ERROR)
1118 ERR("WSAEventSelect() failed with error %d\n", WSAGetLastError());
1121 wait_handles[0] = tcpc->sock_event;
1122 wait_handles[1] = tcpc->cancel_event;
1123 res = WaitForMultipleObjects(2, wait_handles, FALSE, INFINITE);
1128 case WAIT_OBJECT_0 + 1:
1131 ERR("WaitForMultipleObjects() failed with error %d\n", GetLastError());
1136 static BOOL rpcrt4_sock_wait_for_send(RpcConnection_tcp *tcpc)
1139 if (WSAEventSelect(tcpc->sock, tcpc->sock_event, FD_WRITE | FD_CLOSE) == SOCKET_ERROR)
1141 ERR("WSAEventSelect() failed with error %d\n", WSAGetLastError());
1144 res = WaitForSingleObject(tcpc->sock_event, INFINITE);
1150 ERR("WaitForMultipleObjects() failed with error %d\n", GetLastError());
1155 static void rpcrt4_sock_wait_cancel(RpcConnection_tcp *tcpc)
1157 SetEvent(tcpc->cancel_event);
1160 static void rpcrt4_sock_wait_destroy(RpcConnection_tcp *tcpc)
1162 CloseHandle(tcpc->sock_event);
1163 CloseHandle(tcpc->cancel_event);
1168 static RpcConnection *rpcrt4_conn_tcp_alloc(void)
1170 RpcConnection_tcp *tcpc;
1171 tcpc = HeapAlloc(GetProcessHeap(), 0, sizeof(RpcConnection_tcp));
1175 if (!rpcrt4_sock_wait_init(tcpc))
1177 HeapFree(GetProcessHeap(), 0, tcpc);
1180 return &tcpc->common;
1183 static RPC_STATUS rpcrt4_ncacn_ip_tcp_open(RpcConnection* Connection)
1185 RpcConnection_tcp *tcpc = (RpcConnection_tcp *) Connection;
1188 struct addrinfo *ai;
1189 struct addrinfo *ai_cur;
1190 struct addrinfo hints;
1192 TRACE("(%s, %s)\n", Connection->NetworkAddr, Connection->Endpoint);
1194 if (tcpc->sock != -1)
1198 hints.ai_family = PF_UNSPEC;
1199 hints.ai_socktype = SOCK_STREAM;
1200 hints.ai_protocol = IPPROTO_TCP;
1201 hints.ai_addrlen = 0;
1202 hints.ai_addr = NULL;
1203 hints.ai_canonname = NULL;
1204 hints.ai_next = NULL;
1206 ret = getaddrinfo(Connection->NetworkAddr, Connection->Endpoint, &hints, &ai);
1209 ERR("getaddrinfo for %s:%s failed: %s\n", Connection->NetworkAddr,
1210 Connection->Endpoint, gai_strerror(ret));
1211 return RPC_S_SERVER_UNAVAILABLE;
1214 for (ai_cur = ai; ai_cur; ai_cur = ai_cur->ai_next)
1219 if (ai_cur->ai_family != AF_INET && ai_cur->ai_family != AF_INET6)
1221 TRACE("skipping non-IP/IPv6 address family\n");
1229 getnameinfo(ai_cur->ai_addr, ai_cur->ai_addrlen,
1230 host, sizeof(host), service, sizeof(service),
1231 NI_NUMERICHOST | NI_NUMERICSERV);
1232 TRACE("trying %s:%s\n", host, service);
1235 sock = socket(ai_cur->ai_family, ai_cur->ai_socktype, ai_cur->ai_protocol);
1238 WARN("socket() failed: %s\n", strerror(errno));
1242 if (0>connect(sock, ai_cur->ai_addr, ai_cur->ai_addrlen))
1244 WARN("connect() failed: %s\n", strerror(errno));
1249 /* RPC depends on having minimal latency so disable the Nagle algorithm */
1251 setsockopt(sock, SOL_TCP, TCP_NODELAY, (char *)&val, sizeof(val));
1253 ioctlsocket(sock, FIONBIO, &nonblocking);
1258 TRACE("connected\n");
1263 ERR("couldn't connect to %s:%s\n", Connection->NetworkAddr, Connection->Endpoint);
1264 return RPC_S_SERVER_UNAVAILABLE;
1267 static RPC_STATUS rpcrt4_protseq_ncacn_ip_tcp_open_endpoint(RpcServerProtseq *protseq, const char *endpoint)
1269 RPC_STATUS status = RPC_S_CANT_CREATE_ENDPOINT;
1272 struct addrinfo *ai;
1273 struct addrinfo *ai_cur;
1274 struct addrinfo hints;
1275 RpcConnection *first_connection = NULL;
1277 TRACE("(%p, %s)\n", protseq, endpoint);
1279 hints.ai_flags = AI_PASSIVE /* for non-localhost addresses */;
1280 hints.ai_family = PF_UNSPEC;
1281 hints.ai_socktype = SOCK_STREAM;
1282 hints.ai_protocol = IPPROTO_TCP;
1283 hints.ai_addrlen = 0;
1284 hints.ai_addr = NULL;
1285 hints.ai_canonname = NULL;
1286 hints.ai_next = NULL;
1288 ret = getaddrinfo(NULL, endpoint ? endpoint : "0", &hints, &ai);
1291 ERR("getaddrinfo for port %s failed: %s\n", endpoint,
1293 if ((ret == EAI_SERVICE) || (ret == EAI_NONAME))
1294 return RPC_S_INVALID_ENDPOINT_FORMAT;
1295 return RPC_S_CANT_CREATE_ENDPOINT;
1298 for (ai_cur = ai; ai_cur; ai_cur = ai_cur->ai_next)
1300 RpcConnection_tcp *tcpc;
1301 RPC_STATUS create_status;
1302 struct sockaddr_storage sa;
1304 char service[NI_MAXSERV];
1307 if (ai_cur->ai_family != AF_INET && ai_cur->ai_family != AF_INET6)
1309 TRACE("skipping non-IP/IPv6 address family\n");
1316 getnameinfo(ai_cur->ai_addr, ai_cur->ai_addrlen,
1317 host, sizeof(host), service, sizeof(service),
1318 NI_NUMERICHOST | NI_NUMERICSERV);
1319 TRACE("trying %s:%s\n", host, service);
1322 sock = socket(ai_cur->ai_family, ai_cur->ai_socktype, ai_cur->ai_protocol);
1325 WARN("socket() failed: %s\n", strerror(errno));
1326 status = RPC_S_CANT_CREATE_ENDPOINT;
1330 ret = bind(sock, ai_cur->ai_addr, ai_cur->ai_addrlen);
1333 WARN("bind failed: %s\n", strerror(errno));
1335 if (errno == EADDRINUSE)
1336 status = RPC_S_DUPLICATE_ENDPOINT;
1338 status = RPC_S_CANT_CREATE_ENDPOINT;
1342 sa_len = sizeof(sa);
1343 if (getsockname(sock, (struct sockaddr *)&sa, &sa_len))
1345 WARN("getsockname() failed: %s\n", strerror(errno));
1346 status = RPC_S_CANT_CREATE_ENDPOINT;
1350 ret = getnameinfo((struct sockaddr *)&sa, sa_len,
1351 NULL, 0, service, sizeof(service),
1355 WARN("getnameinfo failed: %s\n", gai_strerror(ret));
1356 status = RPC_S_CANT_CREATE_ENDPOINT;
1360 create_status = RPCRT4_CreateConnection((RpcConnection **)&tcpc, TRUE,
1361 protseq->Protseq, NULL,
1362 service, NULL, NULL, NULL);
1363 if (create_status != RPC_S_OK)
1366 status = create_status;
1371 ret = listen(sock, protseq->MaxCalls);
1374 WARN("listen failed: %s\n", strerror(errno));
1375 RPCRT4_DestroyConnection(&tcpc->common);
1376 status = RPC_S_OUT_OF_RESOURCES;
1379 /* need a non-blocking socket, otherwise accept() has a potential
1380 * race-condition (poll() says it is readable, connection drops,
1381 * and accept() blocks until the next connection comes...)
1384 ret = ioctlsocket(sock, FIONBIO, &nonblocking);
1387 WARN("couldn't make socket non-blocking, error %d\n", ret);
1388 RPCRT4_DestroyConnection(&tcpc->common);
1389 status = RPC_S_OUT_OF_RESOURCES;
1393 tcpc->common.Next = first_connection;
1394 first_connection = &tcpc->common;
1396 /* since IPv4 and IPv6 share the same port space, we only need one
1397 * successful bind to listen for both */
1403 /* if at least one connection was created for an endpoint then
1405 if (first_connection)
1407 RpcConnection *conn;
1409 /* find last element in list */
1410 for (conn = first_connection; conn->Next; conn = conn->Next)
1413 EnterCriticalSection(&protseq->cs);
1414 conn->Next = protseq->conn;
1415 protseq->conn = first_connection;
1416 LeaveCriticalSection(&protseq->cs);
1418 TRACE("listening on %s\n", endpoint);
1422 ERR("couldn't listen on port %s\n", endpoint);
1426 static RPC_STATUS rpcrt4_conn_tcp_handoff(RpcConnection *old_conn, RpcConnection *new_conn)
1429 struct sockaddr_in address;
1431 RpcConnection_tcp *server = (RpcConnection_tcp*) old_conn;
1432 RpcConnection_tcp *client = (RpcConnection_tcp*) new_conn;
1435 addrsize = sizeof(address);
1436 ret = accept(server->sock, (struct sockaddr*) &address, &addrsize);
1439 ERR("Failed to accept a TCP connection: error %d\n", ret);
1440 return RPC_S_OUT_OF_RESOURCES;
1443 ioctlsocket(ret, FIONBIO, &nonblocking);
1445 TRACE("Accepted a new TCP connection\n");
1449 static int rpcrt4_conn_tcp_read(RpcConnection *Connection,
1450 void *buffer, unsigned int count)
1452 RpcConnection_tcp *tcpc = (RpcConnection_tcp *) Connection;
1454 while (bytes_read != count)
1456 int r = recv(tcpc->sock, (char *)buffer + bytes_read, count - bytes_read, 0);
1461 else if (errno != EAGAIN)
1463 WARN("recv() failed: %s\n", strerror(errno));
1468 if (!rpcrt4_sock_wait_for_recv(tcpc))
1472 TRACE("%d %p %u -> %d\n", tcpc->sock, buffer, count, bytes_read);
1476 static int rpcrt4_conn_tcp_write(RpcConnection *Connection,
1477 const void *buffer, unsigned int count)
1479 RpcConnection_tcp *tcpc = (RpcConnection_tcp *) Connection;
1480 int bytes_written = 0;
1481 while (bytes_written != count)
1483 int r = send(tcpc->sock, (const char *)buffer + bytes_written, count - bytes_written, 0);
1486 else if (errno != EAGAIN)
1490 if (!rpcrt4_sock_wait_for_send(tcpc))
1494 TRACE("%d %p %u -> %d\n", tcpc->sock, buffer, count, bytes_written);
1495 return bytes_written;
1498 static int rpcrt4_conn_tcp_close(RpcConnection *Connection)
1500 RpcConnection_tcp *tcpc = (RpcConnection_tcp *) Connection;
1502 TRACE("%d\n", tcpc->sock);
1504 if (tcpc->sock != -1)
1505 closesocket(tcpc->sock);
1507 rpcrt4_sock_wait_destroy(tcpc);
1511 static void rpcrt4_conn_tcp_cancel_call(RpcConnection *Connection)
1513 RpcConnection_tcp *tcpc = (RpcConnection_tcp *) Connection;
1514 TRACE("%p\n", Connection);
1515 rpcrt4_sock_wait_cancel(tcpc);
1518 static int rpcrt4_conn_tcp_wait_for_incoming_data(RpcConnection *Connection)
1520 RpcConnection_tcp *tcpc = (RpcConnection_tcp *) Connection;
1522 TRACE("%p\n", Connection);
1524 if (!rpcrt4_sock_wait_for_recv(tcpc))
1529 static size_t rpcrt4_ncacn_ip_tcp_get_top_of_tower(unsigned char *tower_data,
1530 const char *networkaddr,
1531 const char *endpoint)
1533 return rpcrt4_ip_tcp_get_top_of_tower(tower_data, networkaddr,
1534 EPM_PROTOCOL_TCP, endpoint);
1537 #ifdef HAVE_SOCKETPAIR
1539 typedef struct _RpcServerProtseq_sock
1541 RpcServerProtseq common;
1544 } RpcServerProtseq_sock;
1546 static RpcServerProtseq *rpcrt4_protseq_sock_alloc(void)
1548 RpcServerProtseq_sock *ps = HeapAlloc(GetProcessHeap(), 0, sizeof(*ps));
1552 if (!socketpair(PF_UNIX, SOCK_DGRAM, 0, fds))
1554 fcntl(fds[0], F_SETFL, O_NONBLOCK);
1555 fcntl(fds[1], F_SETFL, O_NONBLOCK);
1556 ps->mgr_event_rcv = fds[0];
1557 ps->mgr_event_snd = fds[1];
1561 ERR("socketpair failed with error %s\n", strerror(errno));
1562 HeapFree(GetProcessHeap(), 0, ps);
1569 static void rpcrt4_protseq_sock_signal_state_changed(RpcServerProtseq *protseq)
1571 RpcServerProtseq_sock *sockps = CONTAINING_RECORD(protseq, RpcServerProtseq_sock, common);
1573 write(sockps->mgr_event_snd, &dummy, sizeof(dummy));
1576 static void *rpcrt4_protseq_sock_get_wait_array(RpcServerProtseq *protseq, void *prev_array, unsigned int *count)
1578 struct pollfd *poll_info = prev_array;
1579 RpcConnection_tcp *conn;
1580 RpcServerProtseq_sock *sockps = CONTAINING_RECORD(protseq, RpcServerProtseq_sock, common);
1582 EnterCriticalSection(&protseq->cs);
1584 /* open and count connections */
1586 conn = (RpcConnection_tcp *)protseq->conn;
1588 if (conn->sock != -1)
1590 conn = (RpcConnection_tcp *)conn->common.Next;
1593 /* make array of connections */
1595 poll_info = HeapReAlloc(GetProcessHeap(), 0, poll_info, *count*sizeof(*poll_info));
1597 poll_info = HeapAlloc(GetProcessHeap(), 0, *count*sizeof(*poll_info));
1600 ERR("couldn't allocate poll_info\n");
1601 LeaveCriticalSection(&protseq->cs);
1605 poll_info[0].fd = sockps->mgr_event_rcv;
1606 poll_info[0].events = POLLIN;
1608 conn = CONTAINING_RECORD(protseq->conn, RpcConnection_tcp, common);
1610 if (conn->sock != -1)
1612 poll_info[*count].fd = conn->sock;
1613 poll_info[*count].events = POLLIN;
1616 conn = CONTAINING_RECORD(conn->common.Next, RpcConnection_tcp, common);
1618 LeaveCriticalSection(&protseq->cs);
1622 static void rpcrt4_protseq_sock_free_wait_array(RpcServerProtseq *protseq, void *array)
1624 HeapFree(GetProcessHeap(), 0, array);
1627 static int rpcrt4_protseq_sock_wait_for_new_connection(RpcServerProtseq *protseq, unsigned int count, void *wait_array)
1629 struct pollfd *poll_info = wait_array;
1632 RpcConnection *cconn;
1633 RpcConnection_tcp *conn;
1638 ret = poll(poll_info, count, -1);
1641 ERR("poll failed with error %d\n", ret);
1645 for (i = 0; i < count; i++)
1646 if (poll_info[i].revents & POLLIN)
1648 /* RPC server event */
1652 read(poll_info[0].fd, &dummy, sizeof(dummy));
1656 /* find which connection got a RPC */
1657 EnterCriticalSection(&protseq->cs);
1658 conn = CONTAINING_RECORD(protseq->conn, RpcConnection_tcp, common);
1660 if (poll_info[i].fd == conn->sock) break;
1661 conn = CONTAINING_RECORD(conn->common.Next, RpcConnection_tcp, common);
1665 RPCRT4_SpawnConnection(&cconn, &conn->common);
1667 ERR("failed to locate connection for fd %d\n", poll_info[i].fd);
1668 LeaveCriticalSection(&protseq->cs);
1670 RPCRT4_new_client(cconn);
1678 #else /* HAVE_SOCKETPAIR */
1680 typedef struct _RpcServerProtseq_sock
1682 RpcServerProtseq common;
1684 } RpcServerProtseq_sock;
1686 static RpcServerProtseq *rpcrt4_protseq_sock_alloc(void)
1688 RpcServerProtseq_sock *ps = HeapAlloc(GetProcessHeap(), 0, sizeof(*ps));
1691 static BOOL wsa_inited;
1695 WSAStartup(MAKEWORD(2, 2), &wsadata);
1696 /* Note: WSAStartup can be called more than once so we don't bother with
1697 * making accesses to wsa_inited thread-safe */
1700 ps->mgr_event = CreateEventW(NULL, FALSE, FALSE, NULL);
1705 static void rpcrt4_protseq_sock_signal_state_changed(RpcServerProtseq *protseq)
1707 RpcServerProtseq_sock *sockps = CONTAINING_RECORD(protseq, RpcServerProtseq_sock, common);
1708 SetEvent(sockps->mgr_event);
1711 static void *rpcrt4_protseq_sock_get_wait_array(RpcServerProtseq *protseq, void *prev_array, unsigned int *count)
1713 HANDLE *objs = prev_array;
1714 RpcConnection_tcp *conn;
1715 RpcServerProtseq_sock *sockps = CONTAINING_RECORD(protseq, RpcServerProtseq_sock, common);
1717 EnterCriticalSection(&protseq->cs);
1719 /* open and count connections */
1721 conn = CONTAINING_RECORD(protseq->conn, RpcConnection_tcp, common);
1724 if (conn->sock != -1)
1726 conn = CONTAINING_RECORD(conn->common.Next, RpcConnection_tcp, common);
1729 /* make array of connections */
1731 objs = HeapReAlloc(GetProcessHeap(), 0, objs, *count*sizeof(HANDLE));
1733 objs = HeapAlloc(GetProcessHeap(), 0, *count*sizeof(HANDLE));
1736 ERR("couldn't allocate objs\n");
1737 LeaveCriticalSection(&protseq->cs);
1741 objs[0] = sockps->mgr_event;
1743 conn = CONTAINING_RECORD(protseq->conn, RpcConnection_tcp, common);
1746 if (conn->sock != -1)
1748 int res = WSAEventSelect(conn->sock, conn->sock_event, FD_ACCEPT);
1749 if (res == SOCKET_ERROR)
1750 ERR("WSAEventSelect() failed with error %d\n", WSAGetLastError());
1753 objs[*count] = conn->sock_event;
1757 conn = CONTAINING_RECORD(conn->common.Next, RpcConnection_tcp, common);
1759 LeaveCriticalSection(&protseq->cs);
1763 static void rpcrt4_protseq_sock_free_wait_array(RpcServerProtseq *protseq, void *array)
1765 HeapFree(GetProcessHeap(), 0, array);
1768 static int rpcrt4_protseq_sock_wait_for_new_connection(RpcServerProtseq *protseq, unsigned int count, void *wait_array)
1771 HANDLE *objs = wait_array;
1773 RpcConnection *cconn;
1774 RpcConnection_tcp *conn;
1781 /* an alertable wait isn't strictly necessary, but due to our
1782 * overlapped I/O implementation in Wine we need to free some memory
1783 * by the file user APC being called, even if no completion routine was
1784 * specified at the time of starting the async operation */
1785 res = WaitForMultipleObjectsEx(count, objs, FALSE, INFINITE, TRUE);
1786 } while (res == WAIT_IO_COMPLETION);
1788 if (res == WAIT_OBJECT_0)
1790 else if (res == WAIT_FAILED)
1792 ERR("wait failed with error %d\n", GetLastError());
1797 b_handle = objs[res - WAIT_OBJECT_0];
1798 /* find which connection got a RPC */
1799 EnterCriticalSection(&protseq->cs);
1800 conn = CONTAINING_RECORD(protseq->conn, RpcConnection_tcp, common);
1803 if (b_handle == conn->sock_event) break;
1804 conn = CONTAINING_RECORD(conn->common.Next, RpcConnection_tcp, common);
1808 RPCRT4_SpawnConnection(&cconn, &conn->common);
1810 ERR("failed to locate connection for handle %p\n", b_handle);
1811 LeaveCriticalSection(&protseq->cs);
1814 RPCRT4_new_client(cconn);
1821 #endif /* HAVE_SOCKETPAIR */
1823 static RPC_STATUS rpcrt4_ncacn_ip_tcp_parse_top_of_tower(const unsigned char *tower_data,
1828 return rpcrt4_ip_tcp_parse_top_of_tower(tower_data, tower_size,
1829 networkaddr, EPM_PROTOCOL_TCP,
1833 /**** ncacn_http support ****/
1835 /* 60 seconds is the period native uses */
1836 #define HTTP_IDLE_TIME 60000
1838 /* reference counted to avoid a race between a cancelled call's connection
1839 * being destroyed and the asynchronous InternetReadFileEx call being
1841 typedef struct _RpcHttpAsyncData
1844 HANDLE completion_event;
1845 INTERNET_BUFFERSA inet_buffers;
1846 void *destination_buffer; /* the address that inet_buffers.lpvBuffer will be
1847 * copied into when the call completes */
1848 CRITICAL_SECTION cs;
1851 static ULONG RpcHttpAsyncData_AddRef(RpcHttpAsyncData *data)
1853 return InterlockedIncrement(&data->refs);
1856 static ULONG RpcHttpAsyncData_Release(RpcHttpAsyncData *data)
1858 ULONG refs = InterlockedDecrement(&data->refs);
1861 TRACE("destroying async data %p\n", data);
1862 CloseHandle(data->completion_event);
1863 HeapFree(GetProcessHeap(), 0, data->inet_buffers.lpvBuffer);
1864 DeleteCriticalSection(&data->cs);
1865 HeapFree(GetProcessHeap(), 0, data);
1870 typedef struct _RpcConnection_http
1872 RpcConnection common;
1875 HINTERNET in_request;
1876 HINTERNET out_request;
1877 HANDLE timer_cancelled;
1878 HANDLE cancel_event;
1879 DWORD last_sent_time;
1880 ULONG bytes_received;
1881 ULONG flow_control_mark; /* send a control packet to the server when this many bytes received */
1882 ULONG flow_control_increment; /* number of bytes to increment flow_control_mark by */
1883 UUID connection_uuid;
1886 RpcHttpAsyncData *async_data;
1887 } RpcConnection_http;
1889 static RpcConnection *rpcrt4_ncacn_http_alloc(void)
1891 RpcConnection_http *httpc;
1892 httpc = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*httpc));
1893 if (!httpc) return NULL;
1894 httpc->async_data = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(RpcHttpAsyncData));
1895 if (!httpc->async_data)
1897 HeapFree(GetProcessHeap(), 0, httpc);
1900 TRACE("async data = %p\n", httpc->async_data);
1901 httpc->cancel_event = CreateEventW(NULL, FALSE, FALSE, NULL);
1902 httpc->async_data->refs = 1;
1903 httpc->async_data->inet_buffers.dwStructSize = sizeof(INTERNET_BUFFERSA);
1904 httpc->async_data->inet_buffers.lpvBuffer = NULL;
1905 httpc->async_data->destination_buffer = NULL;
1906 InitializeCriticalSection(&httpc->async_data->cs);
1907 return &httpc->common;
1910 typedef struct _HttpTimerThreadData
1913 DWORD *last_sent_time;
1914 HANDLE timer_cancelled;
1915 } HttpTimerThreadData;
1917 static VOID rpcrt4_http_keep_connection_active_timer_proc(PVOID param, BOOLEAN dummy)
1919 HINTERNET in_request = param;
1920 RpcPktHdr *idle_pkt;
1922 idle_pkt = RPCRT4_BuildHttpHeader(NDR_LOCAL_DATA_REPRESENTATION, 0x0001,
1926 DWORD bytes_written;
1927 InternetWriteFile(in_request, idle_pkt, idle_pkt->common.frag_len, &bytes_written);
1928 RPCRT4_FreeHeader(idle_pkt);
1932 static inline DWORD rpcrt4_http_timer_calc_timeout(DWORD *last_sent_time)
1934 DWORD cur_time = GetTickCount();
1935 DWORD cached_last_sent_time = *last_sent_time;
1936 return HTTP_IDLE_TIME - (cur_time - cached_last_sent_time > HTTP_IDLE_TIME ? 0 : cur_time - cached_last_sent_time);
1939 static DWORD CALLBACK rpcrt4_http_timer_thread(PVOID param)
1941 HttpTimerThreadData *data_in = param;
1942 HttpTimerThreadData data;
1946 HeapFree(GetProcessHeap(), 0, data_in);
1948 for (timeout = HTTP_IDLE_TIME;
1949 WaitForSingleObject(data.timer_cancelled, timeout) == WAIT_TIMEOUT;
1950 timeout = rpcrt4_http_timer_calc_timeout(data.last_sent_time))
1952 /* are we too soon after last send? */
1953 if (GetTickCount() - HTTP_IDLE_TIME < *data.last_sent_time)
1955 rpcrt4_http_keep_connection_active_timer_proc(data.timer_param, TRUE);
1958 CloseHandle(data.timer_cancelled);
1962 static VOID WINAPI rpcrt4_http_internet_callback(
1963 HINTERNET hInternet,
1964 DWORD_PTR dwContext,
1965 DWORD dwInternetStatus,
1966 LPVOID lpvStatusInformation,
1967 DWORD dwStatusInformationLength)
1969 RpcHttpAsyncData *async_data = (RpcHttpAsyncData *)dwContext;
1971 switch (dwInternetStatus)
1973 case INTERNET_STATUS_REQUEST_COMPLETE:
1974 TRACE("INTERNET_STATUS_REQUEST_COMPLETED\n");
1977 if (async_data->inet_buffers.lpvBuffer)
1979 EnterCriticalSection(&async_data->cs);
1980 if (async_data->destination_buffer)
1982 memcpy(async_data->destination_buffer,
1983 async_data->inet_buffers.lpvBuffer,
1984 async_data->inet_buffers.dwBufferLength);
1985 async_data->destination_buffer = NULL;
1987 LeaveCriticalSection(&async_data->cs);
1989 HeapFree(GetProcessHeap(), 0, async_data->inet_buffers.lpvBuffer);
1990 async_data->inet_buffers.lpvBuffer = NULL;
1991 SetEvent(async_data->completion_event);
1992 RpcHttpAsyncData_Release(async_data);
1998 static RPC_STATUS rpcrt4_http_check_response(HINTERNET hor)
2005 WCHAR *status_text = buf;
2009 size = sizeof(status_code);
2010 ret = HttpQueryInfoW(hor, HTTP_QUERY_STATUS_CODE|HTTP_QUERY_FLAG_NUMBER, &status_code, &size, &index);
2012 return GetLastError();
2013 if (status_code < 400)
2017 ret = HttpQueryInfoW(hor, HTTP_QUERY_STATUS_TEXT, status_text, &size, &index);
2018 if (!ret && GetLastError() == ERROR_INSUFFICIENT_BUFFER)
2020 status_text = HeapAlloc(GetProcessHeap(), 0, size);
2021 ret = HttpQueryInfoW(hor, HTTP_QUERY_STATUS_TEXT, status_text, &size, &index);
2024 ERR("server returned: %d %s\n", status_code, ret ? debugstr_w(status_text) : "<status text unavailable>");
2025 if(status_text != buf) HeapFree(GetProcessHeap(), 0, status_text);
2027 if (status_code == HTTP_STATUS_DENIED)
2028 return ERROR_ACCESS_DENIED;
2029 return RPC_S_SERVER_UNAVAILABLE;
2032 static RPC_STATUS rpcrt4_http_internet_connect(RpcConnection_http *httpc)
2034 static const WCHAR wszUserAgent[] = {'M','S','R','P','C',0};
2035 LPWSTR proxy = NULL;
2037 LPWSTR password = NULL;
2038 LPWSTR servername = NULL;
2039 const WCHAR *option;
2040 INTERNET_PORT port = INTERNET_INVALID_PORT_NUMBER; /* use default port */
2042 if (httpc->common.QOS &&
2043 (httpc->common.QOS->qos->AdditionalSecurityInfoType == RPC_C_AUTHN_INFO_TYPE_HTTP))
2045 const RPC_HTTP_TRANSPORT_CREDENTIALS_W *http_cred = httpc->common.QOS->qos->u.HttpCredentials;
2046 if (http_cred->TransportCredentials)
2049 const SEC_WINNT_AUTH_IDENTITY_W *cred = http_cred->TransportCredentials;
2050 ULONG len = cred->DomainLength + 1 + cred->UserLength;
2051 user = HeapAlloc(GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR));
2053 return RPC_S_OUT_OF_RESOURCES;
2055 if (cred->DomainLength)
2057 memcpy(p, cred->Domain, cred->DomainLength * sizeof(WCHAR));
2058 p += cred->DomainLength;
2062 memcpy(p, cred->User, cred->UserLength * sizeof(WCHAR));
2063 p[cred->UserLength] = 0;
2065 password = RPCRT4_strndupW(cred->Password, cred->PasswordLength);
2069 for (option = httpc->common.NetworkOptions; option;
2070 option = (strchrW(option, ',') ? strchrW(option, ',')+1 : NULL))
2072 static const WCHAR wszRpcProxy[] = {'R','p','c','P','r','o','x','y','=',0};
2073 static const WCHAR wszHttpProxy[] = {'H','t','t','p','P','r','o','x','y','=',0};
2075 if (!strncmpiW(option, wszRpcProxy, sizeof(wszRpcProxy)/sizeof(wszRpcProxy[0])-1))
2077 const WCHAR *value_start = option + sizeof(wszRpcProxy)/sizeof(wszRpcProxy[0])-1;
2078 const WCHAR *value_end;
2081 value_end = strchrW(option, ',');
2083 value_end = value_start + strlenW(value_start);
2084 for (p = value_start; p < value_end; p++)
2091 TRACE("RpcProxy value is %s\n", debugstr_wn(value_start, value_end-value_start));
2092 servername = RPCRT4_strndupW(value_start, value_end-value_start);
2094 else if (!strncmpiW(option, wszHttpProxy, sizeof(wszHttpProxy)/sizeof(wszHttpProxy[0])-1))
2096 const WCHAR *value_start = option + sizeof(wszHttpProxy)/sizeof(wszHttpProxy[0])-1;
2097 const WCHAR *value_end;
2099 value_end = strchrW(option, ',');
2101 value_end = value_start + strlenW(value_start);
2102 TRACE("HttpProxy value is %s\n", debugstr_wn(value_start, value_end-value_start));
2103 proxy = RPCRT4_strndupW(value_start, value_end-value_start);
2106 FIXME("unhandled option %s\n", debugstr_w(option));
2109 httpc->app_info = InternetOpenW(wszUserAgent, proxy ? INTERNET_OPEN_TYPE_PROXY : INTERNET_OPEN_TYPE_PRECONFIG,
2110 NULL, NULL, INTERNET_FLAG_ASYNC);
2111 if (!httpc->app_info)
2113 HeapFree(GetProcessHeap(), 0, password);
2114 HeapFree(GetProcessHeap(), 0, user);
2115 ERR("InternetOpenW failed with error %d\n", GetLastError());
2116 return RPC_S_SERVER_UNAVAILABLE;
2118 InternetSetStatusCallbackW(httpc->app_info, rpcrt4_http_internet_callback);
2120 /* if no RpcProxy option specified, set the HTTP server address to the
2121 * RPC server address */
2124 servername = HeapAlloc(GetProcessHeap(), 0, (strlen(httpc->common.NetworkAddr) + 1)*sizeof(WCHAR));
2127 HeapFree(GetProcessHeap(), 0, password);
2128 HeapFree(GetProcessHeap(), 0, user);
2129 return RPC_S_OUT_OF_RESOURCES;
2131 MultiByteToWideChar(CP_ACP, 0, httpc->common.NetworkAddr, -1, servername, strlen(httpc->common.NetworkAddr) + 1);
2134 httpc->session = InternetConnectW(httpc->app_info, servername, port, user, password,
2135 INTERNET_SERVICE_HTTP, 0, 0);
2137 HeapFree(GetProcessHeap(), 0, password);
2138 HeapFree(GetProcessHeap(), 0, user);
2139 HeapFree(GetProcessHeap(), 0, servername);
2141 if (!httpc->session)
2143 ERR("InternetConnectW failed with error %d\n", GetLastError());
2144 return RPC_S_SERVER_UNAVAILABLE;
2150 /* prepare the in pipe for use by RPC packets */
2151 static RPC_STATUS rpcrt4_http_prepare_in_pipe(HINTERNET in_request, RpcHttpAsyncData *async_data,
2152 const UUID *connection_uuid,
2153 const UUID *in_pipe_uuid,
2154 const UUID *association_uuid)
2160 INTERNET_BUFFERSW buffers_in;
2161 DWORD bytes_read, bytes_written;
2163 /* prepare in pipe */
2164 ResetEvent(async_data->completion_event);
2165 RpcHttpAsyncData_AddRef(async_data);
2166 ret = HttpSendRequestW(in_request, NULL, 0, NULL, 0);
2169 if (GetLastError() == ERROR_IO_PENDING)
2170 WaitForSingleObject(async_data->completion_event, INFINITE);
2173 RpcHttpAsyncData_Release(async_data);
2174 ERR("HttpSendRequestW failed with error %d\n", GetLastError());
2175 return RPC_S_SERVER_UNAVAILABLE;
2178 status = rpcrt4_http_check_response(in_request);
2179 if (status != RPC_S_OK) return status;
2181 InternetReadFile(in_request, packet, 20, &bytes_read);
2182 /* FIXME: do something with retrieved data */
2184 memset(&buffers_in, 0, sizeof(buffers_in));
2185 buffers_in.dwStructSize = sizeof(buffers_in);
2186 /* FIXME: get this from the registry */
2187 buffers_in.dwBufferTotal = 1024 * 1024 * 1024; /* 1Gb */
2188 ResetEvent(async_data->completion_event);
2189 RpcHttpAsyncData_AddRef(async_data);
2190 ret = HttpSendRequestExW(in_request, &buffers_in, NULL, 0, 0);
2193 if (GetLastError() == ERROR_IO_PENDING)
2194 WaitForSingleObject(async_data->completion_event, INFINITE);
2197 RpcHttpAsyncData_Release(async_data);
2198 ERR("HttpSendRequestExW failed with error %d\n", GetLastError());
2199 return RPC_S_SERVER_UNAVAILABLE;
2203 TRACE("sending HTTP connect header to server\n");
2204 hdr = RPCRT4_BuildHttpConnectHeader(0, FALSE, connection_uuid, in_pipe_uuid, association_uuid);
2205 if (!hdr) return RPC_S_OUT_OF_RESOURCES;
2206 ret = InternetWriteFile(in_request, hdr, hdr->common.frag_len, &bytes_written);
2207 RPCRT4_FreeHeader(hdr);
2210 ERR("InternetWriteFile failed with error %d\n", GetLastError());
2211 return RPC_S_SERVER_UNAVAILABLE;
2217 static RPC_STATUS rpcrt4_http_read_http_packet(HINTERNET request, RpcPktHdr *hdr, BYTE **data)
2221 unsigned short data_len;
2223 ret = InternetReadFile(request, hdr, sizeof(hdr->common), &bytes_read);
2225 return RPC_S_SERVER_UNAVAILABLE;
2226 if (hdr->common.ptype != PKT_HTTP || hdr->common.frag_len < sizeof(hdr->http))
2228 ERR("wrong packet type received %d or wrong frag_len %d\n",
2229 hdr->common.ptype, hdr->common.frag_len);
2230 return RPC_S_PROTOCOL_ERROR;
2233 ret = InternetReadFile(request, &hdr->common + 1, sizeof(hdr->http) - sizeof(hdr->common), &bytes_read);
2235 return RPC_S_SERVER_UNAVAILABLE;
2237 data_len = hdr->common.frag_len - sizeof(hdr->http);
2240 *data = HeapAlloc(GetProcessHeap(), 0, data_len);
2242 return RPC_S_OUT_OF_RESOURCES;
2243 ret = InternetReadFile(request, *data, data_len, &bytes_read);
2246 HeapFree(GetProcessHeap(), 0, *data);
2247 return RPC_S_SERVER_UNAVAILABLE;
2253 if (!RPCRT4_IsValidHttpPacket(hdr, *data, data_len))
2255 ERR("invalid http packet\n");
2256 return RPC_S_PROTOCOL_ERROR;
2262 /* prepare the out pipe for use by RPC packets */
2263 static RPC_STATUS rpcrt4_http_prepare_out_pipe(HINTERNET out_request,
2264 RpcHttpAsyncData *async_data,
2265 const UUID *connection_uuid,
2266 const UUID *out_pipe_uuid,
2267 ULONG *flow_control_increment)
2274 BYTE *data_from_server;
2275 RpcPktHdr pkt_from_server;
2276 ULONG field1, field3;
2278 ResetEvent(async_data->completion_event);
2279 RpcHttpAsyncData_AddRef(async_data);
2280 ret = HttpSendRequestW(out_request, NULL, 0, NULL, 0);
2283 if (GetLastError() == ERROR_IO_PENDING)
2284 WaitForSingleObject(async_data->completion_event, INFINITE);
2287 RpcHttpAsyncData_Release(async_data);
2288 ERR("HttpSendRequestW failed with error %d\n", GetLastError());
2289 return RPC_S_SERVER_UNAVAILABLE;
2292 status = rpcrt4_http_check_response(out_request);
2293 if (status != RPC_S_OK) return status;
2295 InternetReadFile(out_request, packet, 20, &bytes_read);
2296 /* FIXME: do something with retrieved data */
2298 hdr = RPCRT4_BuildHttpConnectHeader(0, TRUE, connection_uuid, out_pipe_uuid, NULL);
2299 if (!hdr) return RPC_S_OUT_OF_RESOURCES;
2300 ResetEvent(async_data->completion_event);
2301 RpcHttpAsyncData_AddRef(async_data);
2302 ret = HttpSendRequestW(out_request, NULL, 0, hdr, hdr->common.frag_len);
2305 if (GetLastError() == ERROR_IO_PENDING)
2306 WaitForSingleObject(async_data->completion_event, INFINITE);
2309 RpcHttpAsyncData_Release(async_data);
2310 ERR("HttpSendRequestW failed with error %d\n", GetLastError());
2311 RPCRT4_FreeHeader(hdr);
2312 return RPC_S_SERVER_UNAVAILABLE;
2315 RPCRT4_FreeHeader(hdr);
2316 status = rpcrt4_http_check_response(out_request);
2317 if (status != RPC_S_OK) return status;
2319 status = rpcrt4_http_read_http_packet(out_request, &pkt_from_server,
2321 if (status != RPC_S_OK) return status;
2322 status = RPCRT4_ParseHttpPrepareHeader1(&pkt_from_server, data_from_server,
2324 HeapFree(GetProcessHeap(), 0, data_from_server);
2325 if (status != RPC_S_OK) return status;
2326 TRACE("received (%d) from first prepare header\n", field1);
2328 status = rpcrt4_http_read_http_packet(out_request, &pkt_from_server,
2330 if (status != RPC_S_OK) return status;
2331 status = RPCRT4_ParseHttpPrepareHeader2(&pkt_from_server, data_from_server,
2332 &field1, flow_control_increment,
2334 HeapFree(GetProcessHeap(), 0, data_from_server);
2335 if (status != RPC_S_OK) return status;
2336 TRACE("received (0x%08x 0x%08x %d) from second prepare header\n", field1, *flow_control_increment, field3);
2341 static RPC_STATUS rpcrt4_ncacn_http_open(RpcConnection* Connection)
2343 RpcConnection_http *httpc = (RpcConnection_http *)Connection;
2344 static const WCHAR wszVerbIn[] = {'R','P','C','_','I','N','_','D','A','T','A',0};
2345 static const WCHAR wszVerbOut[] = {'R','P','C','_','O','U','T','_','D','A','T','A',0};
2346 static const WCHAR wszRpcProxyPrefix[] = {'/','r','p','c','/','r','p','c','p','r','o','x','y','.','d','l','l','?',0};
2347 static const WCHAR wszColon[] = {':',0};
2348 static const WCHAR wszAcceptType[] = {'a','p','p','l','i','c','a','t','i','o','n','/','r','p','c',0};
2349 LPCWSTR wszAcceptTypes[] = { wszAcceptType, NULL };
2353 HttpTimerThreadData *timer_data;
2356 TRACE("(%s, %s)\n", Connection->NetworkAddr, Connection->Endpoint);
2358 if (Connection->server)
2360 ERR("ncacn_http servers not supported yet\n");
2361 return RPC_S_SERVER_UNAVAILABLE;
2364 if (httpc->in_request)
2367 httpc->async_data->completion_event = CreateEventW(NULL, FALSE, FALSE, NULL);
2369 status = UuidCreate(&httpc->connection_uuid);
2370 status = UuidCreate(&httpc->in_pipe_uuid);
2371 status = UuidCreate(&httpc->out_pipe_uuid);
2373 status = rpcrt4_http_internet_connect(httpc);
2374 if (status != RPC_S_OK)
2377 url = HeapAlloc(GetProcessHeap(), 0, sizeof(wszRpcProxyPrefix) + (strlen(Connection->NetworkAddr) + 1 + strlen(Connection->Endpoint))*sizeof(WCHAR));
2379 return RPC_S_OUT_OF_MEMORY;
2380 memcpy(url, wszRpcProxyPrefix, sizeof(wszRpcProxyPrefix));
2381 MultiByteToWideChar(CP_ACP, 0, Connection->NetworkAddr, -1, url+sizeof(wszRpcProxyPrefix)/sizeof(wszRpcProxyPrefix[0])-1, strlen(Connection->NetworkAddr)+1);
2382 strcatW(url, wszColon);
2383 MultiByteToWideChar(CP_ACP, 0, Connection->Endpoint, -1, url+strlenW(url), strlen(Connection->Endpoint)+1);
2385 secure = httpc->common.QOS &&
2386 (httpc->common.QOS->qos->AdditionalSecurityInfoType == RPC_C_AUTHN_INFO_TYPE_HTTP) &&
2387 (httpc->common.QOS->qos->u.HttpCredentials->Flags & RPC_C_HTTP_FLAG_USE_SSL);
2389 httpc->in_request = HttpOpenRequestW(httpc->session, wszVerbIn, url, NULL, NULL,
2391 (secure ? INTERNET_FLAG_SECURE : 0)|INTERNET_FLAG_KEEP_CONNECTION|INTERNET_FLAG_PRAGMA_NOCACHE,
2392 (DWORD_PTR)httpc->async_data);
2393 if (!httpc->in_request)
2395 ERR("HttpOpenRequestW failed with error %d\n", GetLastError());
2396 return RPC_S_SERVER_UNAVAILABLE;
2398 httpc->out_request = HttpOpenRequestW(httpc->session, wszVerbOut, url, NULL, NULL,
2400 (secure ? INTERNET_FLAG_SECURE : 0)|INTERNET_FLAG_KEEP_CONNECTION|INTERNET_FLAG_PRAGMA_NOCACHE,
2401 (DWORD_PTR)httpc->async_data);
2402 if (!httpc->out_request)
2404 ERR("HttpOpenRequestW failed with error %d\n", GetLastError());
2405 return RPC_S_SERVER_UNAVAILABLE;
2408 status = rpcrt4_http_prepare_in_pipe(httpc->in_request,
2410 &httpc->connection_uuid,
2411 &httpc->in_pipe_uuid,
2412 &Connection->assoc->http_uuid);
2413 if (status != RPC_S_OK)
2416 status = rpcrt4_http_prepare_out_pipe(httpc->out_request,
2418 &httpc->connection_uuid,
2419 &httpc->out_pipe_uuid,
2420 &httpc->flow_control_increment);
2421 if (status != RPC_S_OK)
2424 httpc->flow_control_mark = httpc->flow_control_increment / 2;
2425 httpc->last_sent_time = GetTickCount();
2426 httpc->timer_cancelled = CreateEventW(NULL, FALSE, FALSE, NULL);
2428 timer_data = HeapAlloc(GetProcessHeap(), 0, sizeof(*timer_data));
2430 return ERROR_OUTOFMEMORY;
2431 timer_data->timer_param = httpc->in_request;
2432 timer_data->last_sent_time = &httpc->last_sent_time;
2433 timer_data->timer_cancelled = httpc->timer_cancelled;
2434 /* FIXME: should use CreateTimerQueueTimer when implemented */
2435 thread = CreateThread(NULL, 0, rpcrt4_http_timer_thread, timer_data, 0, NULL);
2438 HeapFree(GetProcessHeap(), 0, timer_data);
2439 return GetLastError();
2441 CloseHandle(thread);
2446 static RPC_STATUS rpcrt4_ncacn_http_handoff(RpcConnection *old_conn, RpcConnection *new_conn)
2449 return RPC_S_SERVER_UNAVAILABLE;
2452 static int rpcrt4_ncacn_http_read(RpcConnection *Connection,
2453 void *buffer, unsigned int count)
2455 RpcConnection_http *httpc = (RpcConnection_http *) Connection;
2458 unsigned int bytes_left = count;
2460 ResetEvent(httpc->async_data->completion_event);
2463 RpcHttpAsyncData_AddRef(httpc->async_data);
2464 httpc->async_data->inet_buffers.dwBufferLength = bytes_left;
2465 httpc->async_data->inet_buffers.lpvBuffer = HeapAlloc(GetProcessHeap(), 0, bytes_left);
2466 httpc->async_data->destination_buffer = buf;
2467 ret = InternetReadFileExA(httpc->out_request, &httpc->async_data->inet_buffers, IRF_ASYNC, 0);
2470 /* INTERNET_STATUS_REQUEST_COMPLETED won't be sent, so release our
2472 RpcHttpAsyncData_Release(httpc->async_data);
2473 memcpy(buf, httpc->async_data->inet_buffers.lpvBuffer,
2474 httpc->async_data->inet_buffers.dwBufferLength);
2475 HeapFree(GetProcessHeap(), 0, httpc->async_data->inet_buffers.lpvBuffer);
2476 httpc->async_data->inet_buffers.lpvBuffer = NULL;
2477 httpc->async_data->destination_buffer = NULL;
2481 if (GetLastError() == ERROR_IO_PENDING)
2483 HANDLE handles[2] = { httpc->async_data->completion_event, httpc->cancel_event };
2484 DWORD result = WaitForMultipleObjects(2, handles, FALSE, DEFAULT_NCACN_HTTP_TIMEOUT);
2485 if (result == WAIT_OBJECT_0)
2489 TRACE("call cancelled\n");
2490 EnterCriticalSection(&httpc->async_data->cs);
2491 httpc->async_data->destination_buffer = NULL;
2492 LeaveCriticalSection(&httpc->async_data->cs);
2498 HeapFree(GetProcessHeap(), 0, httpc->async_data->inet_buffers.lpvBuffer);
2499 httpc->async_data->inet_buffers.lpvBuffer = NULL;
2500 httpc->async_data->destination_buffer = NULL;
2501 RpcHttpAsyncData_Release(httpc->async_data);
2505 if (!httpc->async_data->inet_buffers.dwBufferLength)
2507 bytes_left -= httpc->async_data->inet_buffers.dwBufferLength;
2508 buf += httpc->async_data->inet_buffers.dwBufferLength;
2510 TRACE("%p %p %u -> %s\n", httpc->out_request, buffer, count, ret ? "TRUE" : "FALSE");
2511 return ret ? count : -1;
2514 static RPC_STATUS rpcrt4_ncacn_http_receive_fragment(RpcConnection *Connection, RpcPktHdr **Header, void **Payload)
2516 RpcConnection_http *httpc = (RpcConnection_http *) Connection;
2520 RpcPktCommonHdr common_hdr;
2524 TRACE("(%p, %p, %p)\n", Connection, Header, Payload);
2527 /* read packet common header */
2528 dwRead = rpcrt4_ncacn_http_read(Connection, &common_hdr, sizeof(common_hdr));
2529 if (dwRead != sizeof(common_hdr)) {
2530 WARN("Short read of header, %d bytes\n", dwRead);
2531 status = RPC_S_PROTOCOL_ERROR;
2534 if (!memcmp(&common_hdr, "HTTP/1.1", sizeof("HTTP/1.1")) ||
2535 !memcmp(&common_hdr, "HTTP/1.0", sizeof("HTTP/1.0")))
2537 FIXME("server returned %s\n", debugstr_a((const char *)&common_hdr));
2538 status = RPC_S_PROTOCOL_ERROR;
2542 status = RPCRT4_ValidateCommonHeader(&common_hdr);
2543 if (status != RPC_S_OK) goto fail;
2545 hdr_length = RPCRT4_GetHeaderSize((RpcPktHdr*)&common_hdr);
2546 if (hdr_length == 0) {
2547 WARN("header length == 0\n");
2548 status = RPC_S_PROTOCOL_ERROR;
2552 *Header = HeapAlloc(GetProcessHeap(), 0, hdr_length);
2555 status = RPC_S_OUT_OF_RESOURCES;
2558 memcpy(*Header, &common_hdr, sizeof(common_hdr));
2560 /* read the rest of packet header */
2561 dwRead = rpcrt4_ncacn_http_read(Connection, &(*Header)->common + 1, hdr_length - sizeof(common_hdr));
2562 if (dwRead != hdr_length - sizeof(common_hdr)) {
2563 WARN("bad header length, %d bytes, hdr_length %d\n", dwRead, hdr_length);
2564 status = RPC_S_PROTOCOL_ERROR;
2568 if (common_hdr.frag_len - hdr_length)
2570 *Payload = HeapAlloc(GetProcessHeap(), 0, common_hdr.frag_len - hdr_length);
2573 status = RPC_S_OUT_OF_RESOURCES;
2577 dwRead = rpcrt4_ncacn_http_read(Connection, *Payload, common_hdr.frag_len - hdr_length);
2578 if (dwRead != common_hdr.frag_len - hdr_length)
2580 WARN("bad data length, %d/%d\n", dwRead, common_hdr.frag_len - hdr_length);
2581 status = RPC_S_PROTOCOL_ERROR;
2588 if ((*Header)->common.ptype == PKT_HTTP)
2590 if (!RPCRT4_IsValidHttpPacket(*Header, *Payload, common_hdr.frag_len - hdr_length))
2592 ERR("invalid http packet of length %d bytes\n", (*Header)->common.frag_len);
2593 status = RPC_S_PROTOCOL_ERROR;
2596 if ((*Header)->http.flags == 0x0001)
2598 TRACE("http idle packet, waiting for real packet\n");
2599 if ((*Header)->http.num_data_items != 0)
2601 ERR("HTTP idle packet should have no data items instead of %d\n", (*Header)->http.num_data_items);
2602 status = RPC_S_PROTOCOL_ERROR;
2606 else if ((*Header)->http.flags == 0x0002)
2608 ULONG bytes_transmitted;
2609 ULONG flow_control_increment;
2611 status = RPCRT4_ParseHttpFlowControlHeader(*Header, *Payload,
2614 &flow_control_increment,
2616 if (status != RPC_S_OK)
2618 TRACE("received http flow control header (0x%x, 0x%x, %s)\n",
2619 bytes_transmitted, flow_control_increment, debugstr_guid(&pipe_uuid));
2620 /* FIXME: do something with parsed data */
2624 FIXME("unrecognised http packet with flags 0x%04x\n", (*Header)->http.flags);
2625 status = RPC_S_PROTOCOL_ERROR;
2628 RPCRT4_FreeHeader(*Header);
2630 HeapFree(GetProcessHeap(), 0, *Payload);
2638 httpc->bytes_received += common_hdr.frag_len;
2640 TRACE("httpc->bytes_received = 0x%x\n", httpc->bytes_received);
2642 if (httpc->bytes_received > httpc->flow_control_mark)
2644 RpcPktHdr *hdr = RPCRT4_BuildHttpFlowControlHeader(httpc->common.server,
2645 httpc->bytes_received,
2646 httpc->flow_control_increment,
2647 &httpc->out_pipe_uuid);
2650 DWORD bytes_written;
2652 TRACE("sending flow control packet at 0x%x\n", httpc->bytes_received);
2653 ret2 = InternetWriteFile(httpc->in_request, hdr, hdr->common.frag_len, &bytes_written);
2654 RPCRT4_FreeHeader(hdr);
2656 httpc->flow_control_mark = httpc->bytes_received + httpc->flow_control_increment / 2;
2661 if (status != RPC_S_OK) {
2662 RPCRT4_FreeHeader(*Header);
2664 HeapFree(GetProcessHeap(), 0, *Payload);
2670 static int rpcrt4_ncacn_http_write(RpcConnection *Connection,
2671 const void *buffer, unsigned int count)
2673 RpcConnection_http *httpc = (RpcConnection_http *) Connection;
2674 DWORD bytes_written;
2677 httpc->last_sent_time = ~0U; /* disable idle packet sending */
2678 ret = InternetWriteFile(httpc->in_request, buffer, count, &bytes_written);
2679 httpc->last_sent_time = GetTickCount();
2680 TRACE("%p %p %u -> %s\n", httpc->in_request, buffer, count, ret ? "TRUE" : "FALSE");
2681 return ret ? bytes_written : -1;
2684 static int rpcrt4_ncacn_http_close(RpcConnection *Connection)
2686 RpcConnection_http *httpc = (RpcConnection_http *) Connection;
2690 SetEvent(httpc->timer_cancelled);
2691 if (httpc->in_request)
2692 InternetCloseHandle(httpc->in_request);
2693 httpc->in_request = NULL;
2694 if (httpc->out_request)
2695 InternetCloseHandle(httpc->out_request);
2696 httpc->out_request = NULL;
2697 if (httpc->app_info)
2698 InternetCloseHandle(httpc->app_info);
2699 httpc->app_info = NULL;
2701 InternetCloseHandle(httpc->session);
2702 httpc->session = NULL;
2703 RpcHttpAsyncData_Release(httpc->async_data);
2704 if (httpc->cancel_event)
2705 CloseHandle(httpc->cancel_event);
2710 static void rpcrt4_ncacn_http_cancel_call(RpcConnection *Connection)
2712 RpcConnection_http *httpc = (RpcConnection_http *) Connection;
2714 SetEvent(httpc->cancel_event);
2717 static int rpcrt4_ncacn_http_wait_for_incoming_data(RpcConnection *Connection)
2720 RpcConnection_http *httpc = (RpcConnection_http *) Connection;
2722 RpcHttpAsyncData_AddRef(httpc->async_data);
2723 ret = InternetQueryDataAvailable(httpc->out_request,
2724 &httpc->async_data->inet_buffers.dwBufferLength, IRF_ASYNC, 0);
2727 /* INTERNET_STATUS_REQUEST_COMPLETED won't be sent, so release our
2729 RpcHttpAsyncData_Release(httpc->async_data);
2733 if (GetLastError() == ERROR_IO_PENDING)
2735 HANDLE handles[2] = { httpc->async_data->completion_event, httpc->cancel_event };
2736 DWORD result = WaitForMultipleObjects(2, handles, FALSE, DEFAULT_NCACN_HTTP_TIMEOUT);
2737 if (result != WAIT_OBJECT_0)
2739 TRACE("call cancelled\n");
2745 RpcHttpAsyncData_Release(httpc->async_data);
2754 static size_t rpcrt4_ncacn_http_get_top_of_tower(unsigned char *tower_data,
2755 const char *networkaddr,
2756 const char *endpoint)
2758 return rpcrt4_ip_tcp_get_top_of_tower(tower_data, networkaddr,
2759 EPM_PROTOCOL_HTTP, endpoint);
2762 static RPC_STATUS rpcrt4_ncacn_http_parse_top_of_tower(const unsigned char *tower_data,
2767 return rpcrt4_ip_tcp_parse_top_of_tower(tower_data, tower_size,
2768 networkaddr, EPM_PROTOCOL_HTTP,
2772 static const struct connection_ops conn_protseq_list[] = {
2774 { EPM_PROTOCOL_NCACN, EPM_PROTOCOL_SMB },
2775 rpcrt4_conn_np_alloc,
2776 rpcrt4_ncacn_np_open,
2777 rpcrt4_ncacn_np_handoff,
2778 rpcrt4_conn_np_read,
2779 rpcrt4_conn_np_write,
2780 rpcrt4_conn_np_close,
2781 rpcrt4_conn_np_cancel_call,
2782 rpcrt4_conn_np_wait_for_incoming_data,
2783 rpcrt4_ncacn_np_get_top_of_tower,
2784 rpcrt4_ncacn_np_parse_top_of_tower,
2786 RPCRT4_default_is_authorized,
2787 RPCRT4_default_authorize,
2788 RPCRT4_default_secure_packet,
2789 rpcrt4_conn_np_impersonate_client,
2790 rpcrt4_conn_np_revert_to_self,
2791 RPCRT4_default_inquire_auth_client,
2794 { EPM_PROTOCOL_NCALRPC, EPM_PROTOCOL_PIPE },
2795 rpcrt4_conn_np_alloc,
2796 rpcrt4_ncalrpc_open,
2797 rpcrt4_ncalrpc_handoff,
2798 rpcrt4_conn_np_read,
2799 rpcrt4_conn_np_write,
2800 rpcrt4_conn_np_close,
2801 rpcrt4_conn_np_cancel_call,
2802 rpcrt4_conn_np_wait_for_incoming_data,
2803 rpcrt4_ncalrpc_get_top_of_tower,
2804 rpcrt4_ncalrpc_parse_top_of_tower,
2806 rpcrt4_ncalrpc_is_authorized,
2807 rpcrt4_ncalrpc_authorize,
2808 rpcrt4_ncalrpc_secure_packet,
2809 rpcrt4_conn_np_impersonate_client,
2810 rpcrt4_conn_np_revert_to_self,
2811 rpcrt4_ncalrpc_inquire_auth_client,
2814 { EPM_PROTOCOL_NCACN, EPM_PROTOCOL_TCP },
2815 rpcrt4_conn_tcp_alloc,
2816 rpcrt4_ncacn_ip_tcp_open,
2817 rpcrt4_conn_tcp_handoff,
2818 rpcrt4_conn_tcp_read,
2819 rpcrt4_conn_tcp_write,
2820 rpcrt4_conn_tcp_close,
2821 rpcrt4_conn_tcp_cancel_call,
2822 rpcrt4_conn_tcp_wait_for_incoming_data,
2823 rpcrt4_ncacn_ip_tcp_get_top_of_tower,
2824 rpcrt4_ncacn_ip_tcp_parse_top_of_tower,
2826 RPCRT4_default_is_authorized,
2827 RPCRT4_default_authorize,
2828 RPCRT4_default_secure_packet,
2829 RPCRT4_default_impersonate_client,
2830 RPCRT4_default_revert_to_self,
2831 RPCRT4_default_inquire_auth_client,
2834 { EPM_PROTOCOL_NCACN, EPM_PROTOCOL_HTTP },
2835 rpcrt4_ncacn_http_alloc,
2836 rpcrt4_ncacn_http_open,
2837 rpcrt4_ncacn_http_handoff,
2838 rpcrt4_ncacn_http_read,
2839 rpcrt4_ncacn_http_write,
2840 rpcrt4_ncacn_http_close,
2841 rpcrt4_ncacn_http_cancel_call,
2842 rpcrt4_ncacn_http_wait_for_incoming_data,
2843 rpcrt4_ncacn_http_get_top_of_tower,
2844 rpcrt4_ncacn_http_parse_top_of_tower,
2845 rpcrt4_ncacn_http_receive_fragment,
2846 RPCRT4_default_is_authorized,
2847 RPCRT4_default_authorize,
2848 RPCRT4_default_secure_packet,
2849 RPCRT4_default_impersonate_client,
2850 RPCRT4_default_revert_to_self,
2851 RPCRT4_default_inquire_auth_client,
2856 static const struct protseq_ops protseq_list[] =
2860 rpcrt4_protseq_np_alloc,
2861 rpcrt4_protseq_np_signal_state_changed,
2862 rpcrt4_protseq_np_get_wait_array,
2863 rpcrt4_protseq_np_free_wait_array,
2864 rpcrt4_protseq_np_wait_for_new_connection,
2865 rpcrt4_protseq_ncacn_np_open_endpoint,
2869 rpcrt4_protseq_np_alloc,
2870 rpcrt4_protseq_np_signal_state_changed,
2871 rpcrt4_protseq_np_get_wait_array,
2872 rpcrt4_protseq_np_free_wait_array,
2873 rpcrt4_protseq_np_wait_for_new_connection,
2874 rpcrt4_protseq_ncalrpc_open_endpoint,
2878 rpcrt4_protseq_sock_alloc,
2879 rpcrt4_protseq_sock_signal_state_changed,
2880 rpcrt4_protseq_sock_get_wait_array,
2881 rpcrt4_protseq_sock_free_wait_array,
2882 rpcrt4_protseq_sock_wait_for_new_connection,
2883 rpcrt4_protseq_ncacn_ip_tcp_open_endpoint,
2887 #define ARRAYSIZE(a) (sizeof((a)) / sizeof((a)[0]))
2889 const struct protseq_ops *rpcrt4_get_protseq_ops(const char *protseq)
2892 for(i=0; i<ARRAYSIZE(protseq_list); i++)
2893 if (!strcmp(protseq_list[i].name, protseq))
2894 return &protseq_list[i];
2898 static const struct connection_ops *rpcrt4_get_conn_protseq_ops(const char *protseq)
2901 for(i=0; i<ARRAYSIZE(conn_protseq_list); i++)
2902 if (!strcmp(conn_protseq_list[i].name, protseq))
2903 return &conn_protseq_list[i];
2907 /**** interface to rest of code ****/
2909 RPC_STATUS RPCRT4_OpenClientConnection(RpcConnection* Connection)
2911 TRACE("(Connection == ^%p)\n", Connection);
2913 assert(!Connection->server);
2914 return Connection->ops->open_connection_client(Connection);
2917 RPC_STATUS RPCRT4_CloseConnection(RpcConnection* Connection)
2919 TRACE("(Connection == ^%p)\n", Connection);
2920 if (SecIsValidHandle(&Connection->ctx))
2922 DeleteSecurityContext(&Connection->ctx);
2923 SecInvalidateHandle(&Connection->ctx);
2925 rpcrt4_conn_close(Connection);
2929 RPC_STATUS RPCRT4_CreateConnection(RpcConnection** Connection, BOOL server,
2930 LPCSTR Protseq, LPCSTR NetworkAddr, LPCSTR Endpoint,
2931 LPCWSTR NetworkOptions, RpcAuthInfo* AuthInfo, RpcQualityOfService *QOS)
2933 static LONG next_id;
2934 const struct connection_ops *ops;
2935 RpcConnection* NewConnection;
2937 ops = rpcrt4_get_conn_protseq_ops(Protseq);
2940 FIXME("not supported for protseq %s\n", Protseq);
2941 return RPC_S_PROTSEQ_NOT_SUPPORTED;
2944 NewConnection = ops->alloc();
2945 NewConnection->Next = NULL;
2946 NewConnection->server_binding = NULL;
2947 NewConnection->server = server;
2948 NewConnection->ops = ops;
2949 NewConnection->NetworkAddr = RPCRT4_strdupA(NetworkAddr);
2950 NewConnection->Endpoint = RPCRT4_strdupA(Endpoint);
2951 NewConnection->NetworkOptions = RPCRT4_strdupW(NetworkOptions);
2952 NewConnection->MaxTransmissionSize = RPC_MAX_PACKET_SIZE;
2953 memset(&NewConnection->ActiveInterface, 0, sizeof(NewConnection->ActiveInterface));
2954 NewConnection->NextCallId = 1;
2956 SecInvalidateHandle(&NewConnection->ctx);
2957 memset(&NewConnection->exp, 0, sizeof(NewConnection->exp));
2958 NewConnection->attr = 0;
2959 if (AuthInfo) RpcAuthInfo_AddRef(AuthInfo);
2960 NewConnection->AuthInfo = AuthInfo;
2961 NewConnection->auth_context_id = InterlockedIncrement( &next_id );
2962 NewConnection->encryption_auth_len = 0;
2963 NewConnection->signature_auth_len = 0;
2964 if (QOS) RpcQualityOfService_AddRef(QOS);
2965 NewConnection->QOS = QOS;
2967 list_init(&NewConnection->conn_pool_entry);
2968 NewConnection->async_state = NULL;
2970 TRACE("connection: %p\n", NewConnection);
2971 *Connection = NewConnection;
2976 static RPC_STATUS RPCRT4_SpawnConnection(RpcConnection** Connection, RpcConnection* OldConnection)
2980 err = RPCRT4_CreateConnection(Connection, OldConnection->server,
2981 rpcrt4_conn_get_name(OldConnection),
2982 OldConnection->NetworkAddr,
2983 OldConnection->Endpoint, NULL,
2984 OldConnection->AuthInfo, OldConnection->QOS);
2985 if (err == RPC_S_OK)
2986 rpcrt4_conn_handoff(OldConnection, *Connection);
2990 RPC_STATUS RPCRT4_DestroyConnection(RpcConnection* Connection)
2992 TRACE("connection: %p\n", Connection);
2994 RPCRT4_CloseConnection(Connection);
2995 RPCRT4_strfree(Connection->Endpoint);
2996 RPCRT4_strfree(Connection->NetworkAddr);
2997 HeapFree(GetProcessHeap(), 0, Connection->NetworkOptions);
2998 if (Connection->AuthInfo) RpcAuthInfo_Release(Connection->AuthInfo);
2999 if (Connection->QOS) RpcQualityOfService_Release(Connection->QOS);
3002 if (Connection->server_binding) RPCRT4_ReleaseBinding(Connection->server_binding);
3004 HeapFree(GetProcessHeap(), 0, Connection);
3008 RPC_STATUS RpcTransport_GetTopOfTower(unsigned char *tower_data,
3010 const char *protseq,
3011 const char *networkaddr,
3012 const char *endpoint)
3014 twr_empty_floor_t *protocol_floor;
3015 const struct connection_ops *protseq_ops = rpcrt4_get_conn_protseq_ops(protseq);
3020 return RPC_S_INVALID_RPC_PROTSEQ;
3024 *tower_size = sizeof(*protocol_floor);
3025 *tower_size += protseq_ops->get_top_of_tower(NULL, networkaddr, endpoint);
3029 protocol_floor = (twr_empty_floor_t *)tower_data;
3030 protocol_floor->count_lhs = sizeof(protocol_floor->protid);
3031 protocol_floor->protid = protseq_ops->epm_protocols[0];
3032 protocol_floor->count_rhs = 0;
3034 tower_data += sizeof(*protocol_floor);
3036 *tower_size = protseq_ops->get_top_of_tower(tower_data, networkaddr, endpoint);
3038 return EPT_S_NOT_REGISTERED;
3040 *tower_size += sizeof(*protocol_floor);
3045 RPC_STATUS RpcTransport_ParseTopOfTower(const unsigned char *tower_data,
3051 const twr_empty_floor_t *protocol_floor;
3052 const twr_empty_floor_t *floor4;
3053 const struct connection_ops *protseq_ops = NULL;
3057 if (tower_size < sizeof(*protocol_floor))
3058 return EPT_S_NOT_REGISTERED;
3060 protocol_floor = (const twr_empty_floor_t *)tower_data;
3061 tower_data += sizeof(*protocol_floor);
3062 tower_size -= sizeof(*protocol_floor);
3063 if ((protocol_floor->count_lhs != sizeof(protocol_floor->protid)) ||
3064 (protocol_floor->count_rhs > tower_size))
3065 return EPT_S_NOT_REGISTERED;
3066 tower_data += protocol_floor->count_rhs;
3067 tower_size -= protocol_floor->count_rhs;
3069 floor4 = (const twr_empty_floor_t *)tower_data;
3070 if ((tower_size < sizeof(*floor4)) ||
3071 (floor4->count_lhs != sizeof(floor4->protid)))
3072 return EPT_S_NOT_REGISTERED;
3074 for(i = 0; i < ARRAYSIZE(conn_protseq_list); i++)
3075 if ((protocol_floor->protid == conn_protseq_list[i].epm_protocols[0]) &&
3076 (floor4->protid == conn_protseq_list[i].epm_protocols[1]))
3078 protseq_ops = &conn_protseq_list[i];
3083 return EPT_S_NOT_REGISTERED;
3085 status = protseq_ops->parse_top_of_tower(tower_data, tower_size, networkaddr, endpoint);
3087 if ((status == RPC_S_OK) && protseq)
3089 *protseq = I_RpcAllocate(strlen(protseq_ops->name) + 1);
3090 strcpy(*protseq, protseq_ops->name);
3096 /***********************************************************************
3097 * RpcNetworkIsProtseqValidW (RPCRT4.@)
3099 * Checks if the given protocol sequence is known by the RPC system.
3100 * If it is, returns RPC_S_OK, otherwise RPC_S_PROTSEQ_NOT_SUPPORTED.
3103 RPC_STATUS WINAPI RpcNetworkIsProtseqValidW(RPC_WSTR protseq)
3107 WideCharToMultiByte(CP_ACP, 0, protseq, -1,
3108 ps, sizeof ps, NULL, NULL);
3109 if (rpcrt4_get_conn_protseq_ops(ps))
3112 FIXME("Unknown protseq %s\n", debugstr_w(protseq));
3114 return RPC_S_INVALID_RPC_PROTSEQ;
3117 /***********************************************************************
3118 * RpcNetworkIsProtseqValidA (RPCRT4.@)
3120 RPC_STATUS WINAPI RpcNetworkIsProtseqValidA(RPC_CSTR protseq)
3122 UNICODE_STRING protseqW;
3124 if (RtlCreateUnicodeStringFromAsciiz(&protseqW, (char*)protseq))
3126 RPC_STATUS ret = RpcNetworkIsProtseqValidW(protseqW.Buffer);
3127 RtlFreeUnicodeString(&protseqW);
3130 return RPC_S_OUT_OF_MEMORY;
3133 /***********************************************************************
3134 * RpcProtseqVectorFreeA (RPCRT4.@)
3136 RPC_STATUS WINAPI RpcProtseqVectorFreeA(RPC_PROTSEQ_VECTORA **protseqs)
3138 TRACE("(%p)\n", protseqs);
3143 for (i = 0; i < (*protseqs)->Count; i++)
3144 HeapFree(GetProcessHeap(), 0, (*protseqs)->Protseq[i]);
3145 HeapFree(GetProcessHeap(), 0, *protseqs);
3151 /***********************************************************************
3152 * RpcProtseqVectorFreeW (RPCRT4.@)
3154 RPC_STATUS WINAPI RpcProtseqVectorFreeW(RPC_PROTSEQ_VECTORW **protseqs)
3156 TRACE("(%p)\n", protseqs);
3161 for (i = 0; i < (*protseqs)->Count; i++)
3162 HeapFree(GetProcessHeap(), 0, (*protseqs)->Protseq[i]);
3163 HeapFree(GetProcessHeap(), 0, *protseqs);
3169 /***********************************************************************
3170 * RpcNetworkInqProtseqsW (RPCRT4.@)
3172 RPC_STATUS WINAPI RpcNetworkInqProtseqsW( RPC_PROTSEQ_VECTORW** protseqs )
3174 RPC_PROTSEQ_VECTORW *pvector;
3176 RPC_STATUS status = RPC_S_OUT_OF_MEMORY;
3178 TRACE("(%p)\n", protseqs);
3180 *protseqs = HeapAlloc(GetProcessHeap(), 0, sizeof(RPC_PROTSEQ_VECTORW)+(sizeof(unsigned short*)*ARRAYSIZE(protseq_list)));
3183 pvector = *protseqs;
3185 for (i = 0; i < ARRAYSIZE(protseq_list); i++)
3187 pvector->Protseq[i] = HeapAlloc(GetProcessHeap(), 0, (strlen(protseq_list[i].name)+1)*sizeof(unsigned short));
3188 if (pvector->Protseq[i] == NULL)
3190 MultiByteToWideChar(CP_ACP, 0, (CHAR*)protseq_list[i].name, -1,
3191 (WCHAR*)pvector->Protseq[i], strlen(protseq_list[i].name) + 1);
3197 if (status != RPC_S_OK)
3198 RpcProtseqVectorFreeW(protseqs);
3202 /***********************************************************************
3203 * RpcNetworkInqProtseqsA (RPCRT4.@)
3205 RPC_STATUS WINAPI RpcNetworkInqProtseqsA(RPC_PROTSEQ_VECTORA** protseqs)
3207 RPC_PROTSEQ_VECTORA *pvector;
3209 RPC_STATUS status = RPC_S_OUT_OF_MEMORY;
3211 TRACE("(%p)\n", protseqs);
3213 *protseqs = HeapAlloc(GetProcessHeap(), 0, sizeof(RPC_PROTSEQ_VECTORW)+(sizeof(unsigned char*)*ARRAYSIZE(protseq_list)));
3216 pvector = *protseqs;
3218 for (i = 0; i < ARRAYSIZE(protseq_list); i++)
3220 pvector->Protseq[i] = HeapAlloc(GetProcessHeap(), 0, strlen(protseq_list[i].name)+1);
3221 if (pvector->Protseq[i] == NULL)
3223 strcpy((char*)pvector->Protseq[i], protseq_list[i].name);
3229 if (status != RPC_S_OK)
3230 RpcProtseqVectorFreeA(protseqs);