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;
114 HANDLE listen_thread;
118 static RpcConnection *rpcrt4_conn_np_alloc(void)
120 RpcConnection_np *npc = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(RpcConnection_np));
124 static DWORD CALLBACK listen_thread(void *arg)
126 RpcConnection_np *npc = arg;
129 if (ConnectNamedPipe(npc->pipe, NULL))
132 switch(GetLastError())
134 case ERROR_PIPE_CONNECTED:
136 case ERROR_HANDLES_CLOSED:
137 /* connection closed during listen */
138 return RPC_S_NO_CONTEXT_AVAILABLE;
139 case ERROR_NO_DATA_DETECTED:
140 /* client has disconnected, retry */
141 DisconnectNamedPipe( npc->pipe );
144 npc->listening = FALSE;
145 WARN("Couldn't ConnectNamedPipe (error was %d)\n", GetLastError());
146 return RPC_S_OUT_OF_RESOURCES;
151 static RPC_STATUS rpcrt4_conn_listen_pipe(RpcConnection_np *npc)
156 npc->listening = TRUE;
157 npc->listen_thread = CreateThread(NULL, 0, listen_thread, npc, 0, NULL);
158 if (!npc->listen_thread)
160 npc->listening = FALSE;
161 ERR("Couldn't create listen thread (error was %d)\n", GetLastError());
162 return RPC_S_OUT_OF_RESOURCES;
167 static RPC_STATUS rpcrt4_conn_create_pipe(RpcConnection *Connection, LPCSTR pname)
169 RpcConnection_np *npc = (RpcConnection_np *) Connection;
170 TRACE("listening on %s\n", pname);
172 npc->pipe = CreateNamedPipeA(pname, PIPE_ACCESS_DUPLEX,
173 PIPE_TYPE_MESSAGE | PIPE_READMODE_MESSAGE,
174 PIPE_UNLIMITED_INSTANCES,
175 RPC_MAX_PACKET_SIZE, RPC_MAX_PACKET_SIZE, 5000, NULL);
176 if (npc->pipe == INVALID_HANDLE_VALUE) {
177 WARN("CreateNamedPipe failed with error %d\n", GetLastError());
178 if (GetLastError() == ERROR_FILE_EXISTS)
179 return RPC_S_DUPLICATE_ENDPOINT;
181 return RPC_S_CANT_CREATE_ENDPOINT;
184 /* Note: we don't call ConnectNamedPipe here because it must be done in the
185 * server thread as the thread must be alertable */
189 static RPC_STATUS rpcrt4_conn_open_pipe(RpcConnection *Connection, LPCSTR pname, BOOL wait)
191 RpcConnection_np *npc = (RpcConnection_np *) Connection;
195 TRACE("connecting to %s\n", pname);
201 dwFlags = SECURITY_SQOS_PRESENT;
202 switch (Connection->QOS->qos->ImpersonationType)
204 case RPC_C_IMP_LEVEL_DEFAULT:
205 /* FIXME: what to do here? */
207 case RPC_C_IMP_LEVEL_ANONYMOUS:
208 dwFlags |= SECURITY_ANONYMOUS;
210 case RPC_C_IMP_LEVEL_IDENTIFY:
211 dwFlags |= SECURITY_IDENTIFICATION;
213 case RPC_C_IMP_LEVEL_IMPERSONATE:
214 dwFlags |= SECURITY_IMPERSONATION;
216 case RPC_C_IMP_LEVEL_DELEGATE:
217 dwFlags |= SECURITY_DELEGATION;
220 if (Connection->QOS->qos->IdentityTracking == RPC_C_QOS_IDENTITY_DYNAMIC)
221 dwFlags |= SECURITY_CONTEXT_TRACKING;
223 pipe = CreateFileA(pname, GENERIC_READ|GENERIC_WRITE, 0, NULL,
224 OPEN_EXISTING, dwFlags, 0);
225 if (pipe != INVALID_HANDLE_VALUE) break;
226 err = GetLastError();
227 if (err == ERROR_PIPE_BUSY) {
228 TRACE("connection failed, error=%x\n", err);
229 return RPC_S_SERVER_TOO_BUSY;
231 if (!wait || !WaitNamedPipeA(pname, NMPWAIT_WAIT_FOREVER)) {
232 err = GetLastError();
233 WARN("connection failed, error=%x\n", err);
234 return RPC_S_SERVER_UNAVAILABLE;
239 /* pipe is connected; change to message-read mode. */
240 dwMode = PIPE_READMODE_MESSAGE;
241 SetNamedPipeHandleState(pipe, &dwMode, NULL, NULL);
247 static RPC_STATUS rpcrt4_ncalrpc_open(RpcConnection* Connection)
249 RpcConnection_np *npc = (RpcConnection_np *) Connection;
250 static const char prefix[] = "\\\\.\\pipe\\lrpc\\";
254 /* already connected? */
258 /* protseq=ncalrpc: supposed to use NT LPC ports,
259 * but we'll implement it with named pipes for now */
260 pname = I_RpcAllocate(strlen(prefix) + strlen(Connection->Endpoint) + 1);
261 strcat(strcpy(pname, prefix), Connection->Endpoint);
262 r = rpcrt4_conn_open_pipe(Connection, pname, TRUE);
268 static RPC_STATUS rpcrt4_protseq_ncalrpc_open_endpoint(RpcServerProtseq* protseq, const char *endpoint)
270 static const char prefix[] = "\\\\.\\pipe\\lrpc\\";
273 RpcConnection *Connection;
274 char generated_endpoint[22];
278 static LONG lrpc_nameless_id;
279 DWORD process_id = GetCurrentProcessId();
280 ULONG id = InterlockedIncrement(&lrpc_nameless_id);
281 snprintf(generated_endpoint, sizeof(generated_endpoint),
282 "LRPC%08x.%08x", process_id, id);
283 endpoint = generated_endpoint;
286 r = RPCRT4_CreateConnection(&Connection, TRUE, protseq->Protseq, NULL,
287 endpoint, NULL, NULL, NULL);
291 /* protseq=ncalrpc: supposed to use NT LPC ports,
292 * but we'll implement it with named pipes for now */
293 pname = I_RpcAllocate(strlen(prefix) + strlen(Connection->Endpoint) + 1);
294 strcat(strcpy(pname, prefix), Connection->Endpoint);
295 r = rpcrt4_conn_create_pipe(Connection, pname);
298 EnterCriticalSection(&protseq->cs);
299 Connection->Next = protseq->conn;
300 protseq->conn = Connection;
301 LeaveCriticalSection(&protseq->cs);
306 static RPC_STATUS rpcrt4_ncacn_np_open(RpcConnection* Connection)
308 RpcConnection_np *npc = (RpcConnection_np *) Connection;
309 static const char prefix[] = "\\\\.";
313 /* already connected? */
317 /* protseq=ncacn_np: named pipes */
318 pname = I_RpcAllocate(strlen(prefix) + strlen(Connection->Endpoint) + 1);
319 strcat(strcpy(pname, prefix), Connection->Endpoint);
320 r = rpcrt4_conn_open_pipe(Connection, pname, FALSE);
326 static RPC_STATUS rpcrt4_protseq_ncacn_np_open_endpoint(RpcServerProtseq *protseq, const char *endpoint)
328 static const char prefix[] = "\\\\.";
331 RpcConnection *Connection;
332 char generated_endpoint[21];
336 static LONG np_nameless_id;
337 DWORD process_id = GetCurrentProcessId();
338 ULONG id = InterlockedExchangeAdd(&np_nameless_id, 1 );
339 snprintf(generated_endpoint, sizeof(generated_endpoint),
340 "\\\\pipe\\\\%08x.%03x", process_id, id);
341 endpoint = generated_endpoint;
344 r = RPCRT4_CreateConnection(&Connection, TRUE, protseq->Protseq, NULL,
345 endpoint, NULL, NULL, NULL);
349 /* protseq=ncacn_np: named pipes */
350 pname = I_RpcAllocate(strlen(prefix) + strlen(Connection->Endpoint) + 1);
351 strcat(strcpy(pname, prefix), Connection->Endpoint);
352 r = rpcrt4_conn_create_pipe(Connection, pname);
355 EnterCriticalSection(&protseq->cs);
356 Connection->Next = protseq->conn;
357 protseq->conn = Connection;
358 LeaveCriticalSection(&protseq->cs);
363 static void rpcrt4_conn_np_handoff(RpcConnection_np *old_npc, RpcConnection_np *new_npc)
365 /* because of the way named pipes work, we'll transfer the connected pipe
366 * to the child, then reopen the server binding to continue listening */
368 new_npc->pipe = old_npc->pipe;
369 new_npc->listen_thread = old_npc->listen_thread;
371 old_npc->listen_thread = 0;
372 old_npc->listening = FALSE;
375 static RPC_STATUS rpcrt4_ncacn_np_handoff(RpcConnection *old_conn, RpcConnection *new_conn)
379 static const char prefix[] = "\\\\.";
381 rpcrt4_conn_np_handoff((RpcConnection_np *)old_conn, (RpcConnection_np *)new_conn);
383 pname = I_RpcAllocate(strlen(prefix) + strlen(old_conn->Endpoint) + 1);
384 strcat(strcpy(pname, prefix), old_conn->Endpoint);
385 status = rpcrt4_conn_create_pipe(old_conn, pname);
391 static RPC_STATUS rpcrt4_ncalrpc_handoff(RpcConnection *old_conn, RpcConnection *new_conn)
395 static const char prefix[] = "\\\\.\\pipe\\lrpc\\";
397 TRACE("%s\n", old_conn->Endpoint);
399 rpcrt4_conn_np_handoff((RpcConnection_np *)old_conn, (RpcConnection_np *)new_conn);
401 pname = I_RpcAllocate(strlen(prefix) + strlen(old_conn->Endpoint) + 1);
402 strcat(strcpy(pname, prefix), old_conn->Endpoint);
403 status = rpcrt4_conn_create_pipe(old_conn, pname);
409 static int rpcrt4_conn_np_read(RpcConnection *Connection,
410 void *buffer, unsigned int count)
412 RpcConnection_np *npc = (RpcConnection_np *) Connection;
415 unsigned int bytes_left = count;
420 ret = ReadFile(npc->pipe, buf, bytes_left, &bytes_read, NULL);
421 if (!ret && GetLastError() == ERROR_MORE_DATA)
423 if (!ret || !bytes_read)
425 bytes_left -= bytes_read;
428 return ret ? count : -1;
431 static int rpcrt4_conn_np_write(RpcConnection *Connection,
432 const void *buffer, unsigned int count)
434 RpcConnection_np *npc = (RpcConnection_np *) Connection;
435 const char *buf = buffer;
437 unsigned int bytes_left = count;
442 ret = WriteFile(npc->pipe, buf, bytes_left, &bytes_written, NULL);
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->listen_thread) {
460 CloseHandle(npc->listen_thread);
461 npc->listen_thread = 0;
466 static void rpcrt4_conn_np_cancel_call(RpcConnection *Connection)
468 /* FIXME: implement when named pipe writes use overlapped I/O */
471 static int rpcrt4_conn_np_wait_for_incoming_data(RpcConnection *Connection)
473 /* FIXME: implement when named pipe writes use overlapped I/O */
477 static size_t rpcrt4_ncacn_np_get_top_of_tower(unsigned char *tower_data,
478 const char *networkaddr,
479 const char *endpoint)
481 twr_empty_floor_t *smb_floor;
482 twr_empty_floor_t *nb_floor;
484 size_t networkaddr_size;
485 size_t endpoint_size;
487 TRACE("(%p, %s, %s)\n", tower_data, networkaddr, endpoint);
489 networkaddr_size = networkaddr ? strlen(networkaddr) + 1 : 1;
490 endpoint_size = endpoint ? strlen(endpoint) + 1 : 1;
491 size = sizeof(*smb_floor) + endpoint_size + sizeof(*nb_floor) + networkaddr_size;
496 smb_floor = (twr_empty_floor_t *)tower_data;
498 tower_data += sizeof(*smb_floor);
500 smb_floor->count_lhs = sizeof(smb_floor->protid);
501 smb_floor->protid = EPM_PROTOCOL_SMB;
502 smb_floor->count_rhs = endpoint_size;
505 memcpy(tower_data, endpoint, endpoint_size);
508 tower_data += endpoint_size;
510 nb_floor = (twr_empty_floor_t *)tower_data;
512 tower_data += sizeof(*nb_floor);
514 nb_floor->count_lhs = sizeof(nb_floor->protid);
515 nb_floor->protid = EPM_PROTOCOL_NETBIOS;
516 nb_floor->count_rhs = networkaddr_size;
519 memcpy(tower_data, networkaddr, networkaddr_size);
526 static RPC_STATUS rpcrt4_ncacn_np_parse_top_of_tower(const unsigned char *tower_data,
531 const twr_empty_floor_t *smb_floor = (const twr_empty_floor_t *)tower_data;
532 const twr_empty_floor_t *nb_floor;
534 TRACE("(%p, %d, %p, %p)\n", tower_data, (int)tower_size, networkaddr, endpoint);
536 if (tower_size < sizeof(*smb_floor))
537 return EPT_S_NOT_REGISTERED;
539 tower_data += sizeof(*smb_floor);
540 tower_size -= sizeof(*smb_floor);
542 if ((smb_floor->count_lhs != sizeof(smb_floor->protid)) ||
543 (smb_floor->protid != EPM_PROTOCOL_SMB) ||
544 (smb_floor->count_rhs > tower_size) ||
545 (tower_data[smb_floor->count_rhs - 1] != '\0'))
546 return EPT_S_NOT_REGISTERED;
550 *endpoint = I_RpcAllocate(smb_floor->count_rhs);
552 return RPC_S_OUT_OF_RESOURCES;
553 memcpy(*endpoint, tower_data, smb_floor->count_rhs);
555 tower_data += smb_floor->count_rhs;
556 tower_size -= smb_floor->count_rhs;
558 if (tower_size < sizeof(*nb_floor))
559 return EPT_S_NOT_REGISTERED;
561 nb_floor = (const twr_empty_floor_t *)tower_data;
563 tower_data += sizeof(*nb_floor);
564 tower_size -= sizeof(*nb_floor);
566 if ((nb_floor->count_lhs != sizeof(nb_floor->protid)) ||
567 (nb_floor->protid != EPM_PROTOCOL_NETBIOS) ||
568 (nb_floor->count_rhs > tower_size) ||
569 (tower_data[nb_floor->count_rhs - 1] != '\0'))
570 return EPT_S_NOT_REGISTERED;
574 *networkaddr = I_RpcAllocate(nb_floor->count_rhs);
579 I_RpcFree(*endpoint);
582 return RPC_S_OUT_OF_RESOURCES;
584 memcpy(*networkaddr, tower_data, nb_floor->count_rhs);
590 static RPC_STATUS rpcrt4_conn_np_impersonate_client(RpcConnection *conn)
592 RpcConnection_np *npc = (RpcConnection_np *)conn;
595 TRACE("(%p)\n", conn);
597 if (conn->AuthInfo && SecIsValidHandle(&conn->ctx))
598 return RPCRT4_default_impersonate_client(conn);
600 ret = ImpersonateNamedPipeClient(npc->pipe);
603 DWORD error = GetLastError();
604 WARN("ImpersonateNamedPipeClient failed with error %u\n", error);
607 case ERROR_CANNOT_IMPERSONATE:
608 return RPC_S_NO_CONTEXT_AVAILABLE;
614 static RPC_STATUS rpcrt4_conn_np_revert_to_self(RpcConnection *conn)
618 TRACE("(%p)\n", conn);
620 if (conn->AuthInfo && SecIsValidHandle(&conn->ctx))
621 return RPCRT4_default_revert_to_self(conn);
623 ret = RevertToSelf();
626 WARN("RevertToSelf failed with error %u\n", GetLastError());
627 return RPC_S_NO_CONTEXT_AVAILABLE;
632 typedef struct _RpcServerProtseq_np
634 RpcServerProtseq common;
636 } RpcServerProtseq_np;
638 static RpcServerProtseq *rpcrt4_protseq_np_alloc(void)
640 RpcServerProtseq_np *ps = HeapAlloc(GetProcessHeap(), 0, sizeof(*ps));
642 ps->mgr_event = CreateEventW(NULL, FALSE, FALSE, NULL);
646 static void rpcrt4_protseq_np_signal_state_changed(RpcServerProtseq *protseq)
648 RpcServerProtseq_np *npps = CONTAINING_RECORD(protseq, RpcServerProtseq_np, common);
649 SetEvent(npps->mgr_event);
652 static void *rpcrt4_protseq_np_get_wait_array(RpcServerProtseq *protseq, void *prev_array, unsigned int *count)
654 HANDLE *objs = prev_array;
655 RpcConnection_np *conn;
656 RpcServerProtseq_np *npps = CONTAINING_RECORD(protseq, RpcServerProtseq_np, common);
658 EnterCriticalSection(&protseq->cs);
660 /* open and count connections */
662 conn = CONTAINING_RECORD(protseq->conn, RpcConnection_np, common);
664 rpcrt4_conn_listen_pipe(conn);
665 if (conn->listen_thread)
667 conn = CONTAINING_RECORD(conn->common.Next, RpcConnection_np, common);
670 /* make array of connections */
672 objs = HeapReAlloc(GetProcessHeap(), 0, objs, *count*sizeof(HANDLE));
674 objs = HeapAlloc(GetProcessHeap(), 0, *count*sizeof(HANDLE));
677 ERR("couldn't allocate objs\n");
678 LeaveCriticalSection(&protseq->cs);
682 objs[0] = npps->mgr_event;
684 conn = CONTAINING_RECORD(protseq->conn, RpcConnection_np, common);
686 if ((objs[*count] = conn->listen_thread))
688 conn = CONTAINING_RECORD(conn->common.Next, RpcConnection_np, common);
690 LeaveCriticalSection(&protseq->cs);
694 static void rpcrt4_protseq_np_free_wait_array(RpcServerProtseq *protseq, void *array)
696 HeapFree(GetProcessHeap(), 0, array);
699 static int rpcrt4_protseq_np_wait_for_new_connection(RpcServerProtseq *protseq, unsigned int count, void *wait_array)
702 HANDLE *objs = wait_array;
704 RpcConnection *cconn;
705 RpcConnection_np *conn;
712 /* an alertable wait isn't strictly necessary, but due to our
713 * overlapped I/O implementation in Wine we need to free some memory
714 * by the file user APC being called, even if no completion routine was
715 * specified at the time of starting the async operation */
716 res = WaitForMultipleObjectsEx(count, objs, FALSE, INFINITE, TRUE);
717 } while (res == WAIT_IO_COMPLETION);
719 if (res == WAIT_OBJECT_0)
721 else if (res == WAIT_FAILED)
723 ERR("wait failed with error %d\n", GetLastError());
728 b_handle = objs[res - WAIT_OBJECT_0];
729 /* find which connection got a RPC */
730 EnterCriticalSection(&protseq->cs);
731 conn = CONTAINING_RECORD(protseq->conn, RpcConnection_np, common);
733 if (b_handle == conn->listen_thread) break;
734 conn = CONTAINING_RECORD(conn->common.Next, RpcConnection_np, common);
740 if (GetExitCodeThread(conn->listen_thread, &exit_code) && exit_code == RPC_S_OK)
741 RPCRT4_SpawnConnection(&cconn, &conn->common);
742 CloseHandle(conn->listen_thread);
743 conn->listen_thread = 0;
746 ERR("failed to locate connection for handle %p\n", b_handle);
747 LeaveCriticalSection(&protseq->cs);
750 RPCRT4_new_client(cconn);
757 static size_t rpcrt4_ncalrpc_get_top_of_tower(unsigned char *tower_data,
758 const char *networkaddr,
759 const char *endpoint)
761 twr_empty_floor_t *pipe_floor;
763 size_t endpoint_size;
765 TRACE("(%p, %s, %s)\n", tower_data, networkaddr, endpoint);
767 endpoint_size = strlen(endpoint) + 1;
768 size = sizeof(*pipe_floor) + endpoint_size;
773 pipe_floor = (twr_empty_floor_t *)tower_data;
775 tower_data += sizeof(*pipe_floor);
777 pipe_floor->count_lhs = sizeof(pipe_floor->protid);
778 pipe_floor->protid = EPM_PROTOCOL_PIPE;
779 pipe_floor->count_rhs = endpoint_size;
781 memcpy(tower_data, endpoint, endpoint_size);
786 static RPC_STATUS rpcrt4_ncalrpc_parse_top_of_tower(const unsigned char *tower_data,
791 const twr_empty_floor_t *pipe_floor = (const twr_empty_floor_t *)tower_data;
793 TRACE("(%p, %d, %p, %p)\n", tower_data, (int)tower_size, networkaddr, endpoint);
795 if (tower_size < sizeof(*pipe_floor))
796 return EPT_S_NOT_REGISTERED;
798 tower_data += sizeof(*pipe_floor);
799 tower_size -= sizeof(*pipe_floor);
801 if ((pipe_floor->count_lhs != sizeof(pipe_floor->protid)) ||
802 (pipe_floor->protid != EPM_PROTOCOL_PIPE) ||
803 (pipe_floor->count_rhs > tower_size) ||
804 (tower_data[pipe_floor->count_rhs - 1] != '\0'))
805 return EPT_S_NOT_REGISTERED;
812 *endpoint = I_RpcAllocate(pipe_floor->count_rhs);
814 return RPC_S_OUT_OF_RESOURCES;
815 memcpy(*endpoint, tower_data, pipe_floor->count_rhs);
821 static BOOL rpcrt4_ncalrpc_is_authorized(RpcConnection *conn)
826 static RPC_STATUS rpcrt4_ncalrpc_authorize(RpcConnection *conn, BOOL first_time,
827 unsigned char *in_buffer,
828 unsigned int in_size,
829 unsigned char *out_buffer,
830 unsigned int *out_size)
832 /* since this protocol is local to the machine there is no need to
833 * authenticate the caller */
838 static RPC_STATUS rpcrt4_ncalrpc_secure_packet(RpcConnection *conn,
839 enum secure_packet_direction dir,
840 RpcPktHdr *hdr, unsigned int hdr_size,
841 unsigned char *stub_data, unsigned int stub_data_size,
842 RpcAuthVerifier *auth_hdr,
843 unsigned char *auth_value, unsigned int auth_value_size)
845 /* since this protocol is local to the machine there is no need to secure
850 static RPC_STATUS rpcrt4_ncalrpc_inquire_auth_client(
851 RpcConnection *conn, RPC_AUTHZ_HANDLE *privs, RPC_WSTR *server_princ_name,
852 ULONG *authn_level, ULONG *authn_svc, ULONG *authz_svc, ULONG flags)
854 TRACE("(%p, %p, %p, %p, %p, %p, 0x%x)\n", conn, privs,
855 server_princ_name, authn_level, authn_svc, authz_svc, flags);
859 FIXME("privs not implemented\n");
862 if (server_princ_name)
864 FIXME("server_princ_name not implemented\n");
865 *server_princ_name = NULL;
867 if (authn_level) *authn_level = RPC_C_AUTHN_LEVEL_PKT_PRIVACY;
868 if (authn_svc) *authn_svc = RPC_C_AUTHN_WINNT;
871 FIXME("authorization service not implemented\n");
872 *authz_svc = RPC_C_AUTHZ_NONE;
875 FIXME("flags 0x%x not implemented\n", flags);
880 /**** ncacn_ip_tcp support ****/
882 static size_t rpcrt4_ip_tcp_get_top_of_tower(unsigned char *tower_data,
883 const char *networkaddr,
884 unsigned char tcp_protid,
885 const char *endpoint)
887 twr_tcp_floor_t *tcp_floor;
888 twr_ipv4_floor_t *ipv4_floor;
890 struct addrinfo hints;
892 size_t size = sizeof(*tcp_floor) + sizeof(*ipv4_floor);
894 TRACE("(%p, %s, %s)\n", tower_data, networkaddr, endpoint);
899 tcp_floor = (twr_tcp_floor_t *)tower_data;
900 tower_data += sizeof(*tcp_floor);
902 ipv4_floor = (twr_ipv4_floor_t *)tower_data;
904 tcp_floor->count_lhs = sizeof(tcp_floor->protid);
905 tcp_floor->protid = tcp_protid;
906 tcp_floor->count_rhs = sizeof(tcp_floor->port);
908 ipv4_floor->count_lhs = sizeof(ipv4_floor->protid);
909 ipv4_floor->protid = EPM_PROTOCOL_IP;
910 ipv4_floor->count_rhs = sizeof(ipv4_floor->ipv4addr);
912 hints.ai_flags = AI_NUMERICHOST;
913 /* FIXME: only support IPv4 at the moment. how is IPv6 represented by the EPM? */
914 hints.ai_family = PF_INET;
915 hints.ai_socktype = SOCK_STREAM;
916 hints.ai_protocol = IPPROTO_TCP;
917 hints.ai_addrlen = 0;
918 hints.ai_addr = NULL;
919 hints.ai_canonname = NULL;
920 hints.ai_next = NULL;
922 ret = getaddrinfo(networkaddr, endpoint, &hints, &ai);
925 ret = getaddrinfo("0.0.0.0", endpoint, &hints, &ai);
928 ERR("getaddrinfo failed: %s\n", gai_strerror(ret));
933 if (ai->ai_family == PF_INET)
935 const struct sockaddr_in *sin = (const struct sockaddr_in *)ai->ai_addr;
936 tcp_floor->port = sin->sin_port;
937 ipv4_floor->ipv4addr = sin->sin_addr.s_addr;
941 ERR("unexpected protocol family %d\n", ai->ai_family);
950 static RPC_STATUS rpcrt4_ip_tcp_parse_top_of_tower(const unsigned char *tower_data,
953 unsigned char tcp_protid,
956 const twr_tcp_floor_t *tcp_floor = (const twr_tcp_floor_t *)tower_data;
957 const twr_ipv4_floor_t *ipv4_floor;
958 struct in_addr in_addr;
960 TRACE("(%p, %d, %p, %p)\n", tower_data, (int)tower_size, networkaddr, endpoint);
962 if (tower_size < sizeof(*tcp_floor))
963 return EPT_S_NOT_REGISTERED;
965 tower_data += sizeof(*tcp_floor);
966 tower_size -= sizeof(*tcp_floor);
968 if (tower_size < sizeof(*ipv4_floor))
969 return EPT_S_NOT_REGISTERED;
971 ipv4_floor = (const twr_ipv4_floor_t *)tower_data;
973 if ((tcp_floor->count_lhs != sizeof(tcp_floor->protid)) ||
974 (tcp_floor->protid != tcp_protid) ||
975 (tcp_floor->count_rhs != sizeof(tcp_floor->port)) ||
976 (ipv4_floor->count_lhs != sizeof(ipv4_floor->protid)) ||
977 (ipv4_floor->protid != EPM_PROTOCOL_IP) ||
978 (ipv4_floor->count_rhs != sizeof(ipv4_floor->ipv4addr)))
979 return EPT_S_NOT_REGISTERED;
983 *endpoint = I_RpcAllocate(6 /* sizeof("65535") + 1 */);
985 return RPC_S_OUT_OF_RESOURCES;
986 sprintf(*endpoint, "%u", ntohs(tcp_floor->port));
991 *networkaddr = I_RpcAllocate(INET_ADDRSTRLEN);
996 I_RpcFree(*endpoint);
999 return RPC_S_OUT_OF_RESOURCES;
1001 in_addr.s_addr = ipv4_floor->ipv4addr;
1002 if (!inet_ntop(AF_INET, &in_addr, *networkaddr, INET_ADDRSTRLEN))
1004 ERR("inet_ntop: %s\n", strerror(errno));
1005 I_RpcFree(*networkaddr);
1006 *networkaddr = NULL;
1009 I_RpcFree(*endpoint);
1012 return EPT_S_NOT_REGISTERED;
1019 typedef struct _RpcConnection_tcp
1021 RpcConnection common;
1023 #ifdef HAVE_SOCKETPAIR
1027 HANDLE cancel_event;
1029 } RpcConnection_tcp;
1031 #ifdef HAVE_SOCKETPAIR
1033 static BOOL rpcrt4_sock_wait_init(RpcConnection_tcp *tcpc)
1035 if (socketpair(PF_UNIX, SOCK_STREAM, 0, tcpc->cancel_fds) < 0)
1037 ERR("socketpair() failed: %s\n", strerror(errno));
1043 static BOOL rpcrt4_sock_wait_for_recv(RpcConnection_tcp *tcpc)
1045 struct pollfd pfds[2];
1046 pfds[0].fd = tcpc->sock;
1047 pfds[0].events = POLLIN;
1048 pfds[1].fd = tcpc->cancel_fds[0];
1049 pfds[1].events = POLLIN;
1050 if (poll(pfds, 2, -1 /* infinite */) == -1 && errno != EINTR)
1052 ERR("poll() failed: %s\n", strerror(errno));
1055 if (pfds[1].revents & POLLIN) /* canceled */
1058 read(pfds[1].fd, &dummy, sizeof(dummy));
1064 static BOOL rpcrt4_sock_wait_for_send(RpcConnection_tcp *tcpc)
1067 pfd.fd = tcpc->sock;
1068 pfd.events = POLLOUT;
1069 if (poll(&pfd, 1, -1 /* infinite */) == -1 && errno != EINTR)
1071 ERR("poll() failed: %s\n", strerror(errno));
1077 static void rpcrt4_sock_wait_cancel(RpcConnection_tcp *tcpc)
1081 write(tcpc->cancel_fds[1], &dummy, 1);
1084 static void rpcrt4_sock_wait_destroy(RpcConnection_tcp *tcpc)
1086 close(tcpc->cancel_fds[0]);
1087 close(tcpc->cancel_fds[1]);
1090 #else /* HAVE_SOCKETPAIR */
1092 static BOOL rpcrt4_sock_wait_init(RpcConnection_tcp *tcpc)
1094 static BOOL wsa_inited;
1098 WSAStartup(MAKEWORD(2, 2), &wsadata);
1099 /* Note: WSAStartup can be called more than once so we don't bother with
1100 * making accesses to wsa_inited thread-safe */
1103 tcpc->sock_event = CreateEventW(NULL, FALSE, FALSE, NULL);
1104 tcpc->cancel_event = CreateEventW(NULL, FALSE, FALSE, NULL);
1105 if (!tcpc->sock_event || !tcpc->cancel_event)
1107 ERR("event creation failed\n");
1108 if (tcpc->sock_event) CloseHandle(tcpc->sock_event);
1114 static BOOL rpcrt4_sock_wait_for_recv(RpcConnection_tcp *tcpc)
1116 HANDLE wait_handles[2];
1118 if (WSAEventSelect(tcpc->sock, tcpc->sock_event, FD_READ | FD_CLOSE) == SOCKET_ERROR)
1120 ERR("WSAEventSelect() failed with error %d\n", WSAGetLastError());
1123 wait_handles[0] = tcpc->sock_event;
1124 wait_handles[1] = tcpc->cancel_event;
1125 res = WaitForMultipleObjects(2, wait_handles, FALSE, INFINITE);
1130 case WAIT_OBJECT_0 + 1:
1133 ERR("WaitForMultipleObjects() failed with error %d\n", GetLastError());
1138 static BOOL rpcrt4_sock_wait_for_send(RpcConnection_tcp *tcpc)
1141 if (WSAEventSelect(tcpc->sock, tcpc->sock_event, FD_WRITE | FD_CLOSE) == SOCKET_ERROR)
1143 ERR("WSAEventSelect() failed with error %d\n", WSAGetLastError());
1146 res = WaitForSingleObject(tcpc->sock_event, INFINITE);
1152 ERR("WaitForMultipleObjects() failed with error %d\n", GetLastError());
1157 static void rpcrt4_sock_wait_cancel(RpcConnection_tcp *tcpc)
1159 SetEvent(tcpc->cancel_event);
1162 static void rpcrt4_sock_wait_destroy(RpcConnection_tcp *tcpc)
1164 CloseHandle(tcpc->sock_event);
1165 CloseHandle(tcpc->cancel_event);
1170 static RpcConnection *rpcrt4_conn_tcp_alloc(void)
1172 RpcConnection_tcp *tcpc;
1173 tcpc = HeapAlloc(GetProcessHeap(), 0, sizeof(RpcConnection_tcp));
1177 if (!rpcrt4_sock_wait_init(tcpc))
1179 HeapFree(GetProcessHeap(), 0, tcpc);
1182 return &tcpc->common;
1185 static RPC_STATUS rpcrt4_ncacn_ip_tcp_open(RpcConnection* Connection)
1187 RpcConnection_tcp *tcpc = (RpcConnection_tcp *) Connection;
1190 struct addrinfo *ai;
1191 struct addrinfo *ai_cur;
1192 struct addrinfo hints;
1194 TRACE("(%s, %s)\n", Connection->NetworkAddr, Connection->Endpoint);
1196 if (tcpc->sock != -1)
1200 hints.ai_family = PF_UNSPEC;
1201 hints.ai_socktype = SOCK_STREAM;
1202 hints.ai_protocol = IPPROTO_TCP;
1203 hints.ai_addrlen = 0;
1204 hints.ai_addr = NULL;
1205 hints.ai_canonname = NULL;
1206 hints.ai_next = NULL;
1208 ret = getaddrinfo(Connection->NetworkAddr, Connection->Endpoint, &hints, &ai);
1211 ERR("getaddrinfo for %s:%s failed: %s\n", Connection->NetworkAddr,
1212 Connection->Endpoint, gai_strerror(ret));
1213 return RPC_S_SERVER_UNAVAILABLE;
1216 for (ai_cur = ai; ai_cur; ai_cur = ai_cur->ai_next)
1221 if (ai_cur->ai_family != AF_INET && ai_cur->ai_family != AF_INET6)
1223 TRACE("skipping non-IP/IPv6 address family\n");
1231 getnameinfo(ai_cur->ai_addr, ai_cur->ai_addrlen,
1232 host, sizeof(host), service, sizeof(service),
1233 NI_NUMERICHOST | NI_NUMERICSERV);
1234 TRACE("trying %s:%s\n", host, service);
1237 sock = socket(ai_cur->ai_family, ai_cur->ai_socktype, ai_cur->ai_protocol);
1240 WARN("socket() failed: %s\n", strerror(errno));
1244 if (0>connect(sock, ai_cur->ai_addr, ai_cur->ai_addrlen))
1246 WARN("connect() failed: %s\n", strerror(errno));
1251 /* RPC depends on having minimal latency so disable the Nagle algorithm */
1253 setsockopt(sock, SOL_TCP, TCP_NODELAY, (char *)&val, sizeof(val));
1255 ioctlsocket(sock, FIONBIO, &nonblocking);
1260 TRACE("connected\n");
1265 ERR("couldn't connect to %s:%s\n", Connection->NetworkAddr, Connection->Endpoint);
1266 return RPC_S_SERVER_UNAVAILABLE;
1269 static RPC_STATUS rpcrt4_protseq_ncacn_ip_tcp_open_endpoint(RpcServerProtseq *protseq, const char *endpoint)
1271 RPC_STATUS status = RPC_S_CANT_CREATE_ENDPOINT;
1274 struct addrinfo *ai;
1275 struct addrinfo *ai_cur;
1276 struct addrinfo hints;
1277 RpcConnection *first_connection = NULL;
1279 TRACE("(%p, %s)\n", protseq, endpoint);
1281 hints.ai_flags = AI_PASSIVE /* for non-localhost addresses */;
1282 hints.ai_family = PF_UNSPEC;
1283 hints.ai_socktype = SOCK_STREAM;
1284 hints.ai_protocol = IPPROTO_TCP;
1285 hints.ai_addrlen = 0;
1286 hints.ai_addr = NULL;
1287 hints.ai_canonname = NULL;
1288 hints.ai_next = NULL;
1290 ret = getaddrinfo(NULL, endpoint ? endpoint : "0", &hints, &ai);
1293 ERR("getaddrinfo for port %s failed: %s\n", endpoint,
1295 if ((ret == EAI_SERVICE) || (ret == EAI_NONAME))
1296 return RPC_S_INVALID_ENDPOINT_FORMAT;
1297 return RPC_S_CANT_CREATE_ENDPOINT;
1300 for (ai_cur = ai; ai_cur; ai_cur = ai_cur->ai_next)
1302 RpcConnection_tcp *tcpc;
1303 RPC_STATUS create_status;
1304 struct sockaddr_storage sa;
1306 char service[NI_MAXSERV];
1309 if (ai_cur->ai_family != AF_INET && ai_cur->ai_family != AF_INET6)
1311 TRACE("skipping non-IP/IPv6 address family\n");
1318 getnameinfo(ai_cur->ai_addr, ai_cur->ai_addrlen,
1319 host, sizeof(host), service, sizeof(service),
1320 NI_NUMERICHOST | NI_NUMERICSERV);
1321 TRACE("trying %s:%s\n", host, service);
1324 sock = socket(ai_cur->ai_family, ai_cur->ai_socktype, ai_cur->ai_protocol);
1327 WARN("socket() failed: %s\n", strerror(errno));
1328 status = RPC_S_CANT_CREATE_ENDPOINT;
1332 ret = bind(sock, ai_cur->ai_addr, ai_cur->ai_addrlen);
1335 WARN("bind failed: %s\n", strerror(errno));
1337 if (errno == EADDRINUSE)
1338 status = RPC_S_DUPLICATE_ENDPOINT;
1340 status = RPC_S_CANT_CREATE_ENDPOINT;
1344 sa_len = sizeof(sa);
1345 if (getsockname(sock, (struct sockaddr *)&sa, &sa_len))
1347 WARN("getsockname() failed: %s\n", strerror(errno));
1348 status = RPC_S_CANT_CREATE_ENDPOINT;
1352 ret = getnameinfo((struct sockaddr *)&sa, sa_len,
1353 NULL, 0, service, sizeof(service),
1357 WARN("getnameinfo failed: %s\n", gai_strerror(ret));
1358 status = RPC_S_CANT_CREATE_ENDPOINT;
1362 create_status = RPCRT4_CreateConnection((RpcConnection **)&tcpc, TRUE,
1363 protseq->Protseq, NULL,
1364 service, NULL, NULL, NULL);
1365 if (create_status != RPC_S_OK)
1368 status = create_status;
1373 ret = listen(sock, protseq->MaxCalls);
1376 WARN("listen failed: %s\n", strerror(errno));
1377 RPCRT4_ReleaseConnection(&tcpc->common);
1378 status = RPC_S_OUT_OF_RESOURCES;
1381 /* need a non-blocking socket, otherwise accept() has a potential
1382 * race-condition (poll() says it is readable, connection drops,
1383 * and accept() blocks until the next connection comes...)
1386 ret = ioctlsocket(sock, FIONBIO, &nonblocking);
1389 WARN("couldn't make socket non-blocking, error %d\n", ret);
1390 RPCRT4_ReleaseConnection(&tcpc->common);
1391 status = RPC_S_OUT_OF_RESOURCES;
1395 tcpc->common.Next = first_connection;
1396 first_connection = &tcpc->common;
1398 /* since IPv4 and IPv6 share the same port space, we only need one
1399 * successful bind to listen for both */
1405 /* if at least one connection was created for an endpoint then
1407 if (first_connection)
1409 RpcConnection *conn;
1411 /* find last element in list */
1412 for (conn = first_connection; conn->Next; conn = conn->Next)
1415 EnterCriticalSection(&protseq->cs);
1416 conn->Next = protseq->conn;
1417 protseq->conn = first_connection;
1418 LeaveCriticalSection(&protseq->cs);
1420 TRACE("listening on %s\n", endpoint);
1424 ERR("couldn't listen on port %s\n", endpoint);
1428 static RPC_STATUS rpcrt4_conn_tcp_handoff(RpcConnection *old_conn, RpcConnection *new_conn)
1431 struct sockaddr_in address;
1433 RpcConnection_tcp *server = (RpcConnection_tcp*) old_conn;
1434 RpcConnection_tcp *client = (RpcConnection_tcp*) new_conn;
1437 addrsize = sizeof(address);
1438 ret = accept(server->sock, (struct sockaddr*) &address, &addrsize);
1441 ERR("Failed to accept a TCP connection: error %d\n", ret);
1442 return RPC_S_OUT_OF_RESOURCES;
1445 ioctlsocket(ret, FIONBIO, &nonblocking);
1447 TRACE("Accepted a new TCP connection\n");
1451 static int rpcrt4_conn_tcp_read(RpcConnection *Connection,
1452 void *buffer, unsigned int count)
1454 RpcConnection_tcp *tcpc = (RpcConnection_tcp *) Connection;
1456 while (bytes_read != count)
1458 int r = recv(tcpc->sock, (char *)buffer + bytes_read, count - bytes_read, 0);
1463 else if (errno != EAGAIN)
1465 WARN("recv() failed: %s\n", strerror(errno));
1470 if (!rpcrt4_sock_wait_for_recv(tcpc))
1474 TRACE("%d %p %u -> %d\n", tcpc->sock, buffer, count, bytes_read);
1478 static int rpcrt4_conn_tcp_write(RpcConnection *Connection,
1479 const void *buffer, unsigned int count)
1481 RpcConnection_tcp *tcpc = (RpcConnection_tcp *) Connection;
1482 int bytes_written = 0;
1483 while (bytes_written != count)
1485 int r = send(tcpc->sock, (const char *)buffer + bytes_written, count - bytes_written, 0);
1488 else if (errno != EAGAIN)
1492 if (!rpcrt4_sock_wait_for_send(tcpc))
1496 TRACE("%d %p %u -> %d\n", tcpc->sock, buffer, count, bytes_written);
1497 return bytes_written;
1500 static int rpcrt4_conn_tcp_close(RpcConnection *Connection)
1502 RpcConnection_tcp *tcpc = (RpcConnection_tcp *) Connection;
1504 TRACE("%d\n", tcpc->sock);
1506 if (tcpc->sock != -1)
1507 closesocket(tcpc->sock);
1509 rpcrt4_sock_wait_destroy(tcpc);
1513 static void rpcrt4_conn_tcp_cancel_call(RpcConnection *Connection)
1515 RpcConnection_tcp *tcpc = (RpcConnection_tcp *) Connection;
1516 TRACE("%p\n", Connection);
1517 rpcrt4_sock_wait_cancel(tcpc);
1520 static int rpcrt4_conn_tcp_wait_for_incoming_data(RpcConnection *Connection)
1522 RpcConnection_tcp *tcpc = (RpcConnection_tcp *) Connection;
1524 TRACE("%p\n", Connection);
1526 if (!rpcrt4_sock_wait_for_recv(tcpc))
1531 static size_t rpcrt4_ncacn_ip_tcp_get_top_of_tower(unsigned char *tower_data,
1532 const char *networkaddr,
1533 const char *endpoint)
1535 return rpcrt4_ip_tcp_get_top_of_tower(tower_data, networkaddr,
1536 EPM_PROTOCOL_TCP, endpoint);
1539 #ifdef HAVE_SOCKETPAIR
1541 typedef struct _RpcServerProtseq_sock
1543 RpcServerProtseq common;
1546 } RpcServerProtseq_sock;
1548 static RpcServerProtseq *rpcrt4_protseq_sock_alloc(void)
1550 RpcServerProtseq_sock *ps = HeapAlloc(GetProcessHeap(), 0, sizeof(*ps));
1554 if (!socketpair(PF_UNIX, SOCK_DGRAM, 0, fds))
1556 fcntl(fds[0], F_SETFL, O_NONBLOCK);
1557 fcntl(fds[1], F_SETFL, O_NONBLOCK);
1558 ps->mgr_event_rcv = fds[0];
1559 ps->mgr_event_snd = fds[1];
1563 ERR("socketpair failed with error %s\n", strerror(errno));
1564 HeapFree(GetProcessHeap(), 0, ps);
1571 static void rpcrt4_protseq_sock_signal_state_changed(RpcServerProtseq *protseq)
1573 RpcServerProtseq_sock *sockps = CONTAINING_RECORD(protseq, RpcServerProtseq_sock, common);
1575 write(sockps->mgr_event_snd, &dummy, sizeof(dummy));
1578 static void *rpcrt4_protseq_sock_get_wait_array(RpcServerProtseq *protseq, void *prev_array, unsigned int *count)
1580 struct pollfd *poll_info = prev_array;
1581 RpcConnection_tcp *conn;
1582 RpcServerProtseq_sock *sockps = CONTAINING_RECORD(protseq, RpcServerProtseq_sock, common);
1584 EnterCriticalSection(&protseq->cs);
1586 /* open and count connections */
1588 conn = (RpcConnection_tcp *)protseq->conn;
1590 if (conn->sock != -1)
1592 conn = (RpcConnection_tcp *)conn->common.Next;
1595 /* make array of connections */
1597 poll_info = HeapReAlloc(GetProcessHeap(), 0, poll_info, *count*sizeof(*poll_info));
1599 poll_info = HeapAlloc(GetProcessHeap(), 0, *count*sizeof(*poll_info));
1602 ERR("couldn't allocate poll_info\n");
1603 LeaveCriticalSection(&protseq->cs);
1607 poll_info[0].fd = sockps->mgr_event_rcv;
1608 poll_info[0].events = POLLIN;
1610 conn = CONTAINING_RECORD(protseq->conn, RpcConnection_tcp, common);
1612 if (conn->sock != -1)
1614 poll_info[*count].fd = conn->sock;
1615 poll_info[*count].events = POLLIN;
1618 conn = CONTAINING_RECORD(conn->common.Next, RpcConnection_tcp, common);
1620 LeaveCriticalSection(&protseq->cs);
1624 static void rpcrt4_protseq_sock_free_wait_array(RpcServerProtseq *protseq, void *array)
1626 HeapFree(GetProcessHeap(), 0, array);
1629 static int rpcrt4_protseq_sock_wait_for_new_connection(RpcServerProtseq *protseq, unsigned int count, void *wait_array)
1631 struct pollfd *poll_info = wait_array;
1634 RpcConnection *cconn;
1635 RpcConnection_tcp *conn;
1640 ret = poll(poll_info, count, -1);
1643 ERR("poll failed with error %d\n", ret);
1647 for (i = 0; i < count; i++)
1648 if (poll_info[i].revents & POLLIN)
1650 /* RPC server event */
1654 read(poll_info[0].fd, &dummy, sizeof(dummy));
1658 /* find which connection got a RPC */
1659 EnterCriticalSection(&protseq->cs);
1660 conn = CONTAINING_RECORD(protseq->conn, RpcConnection_tcp, common);
1662 if (poll_info[i].fd == conn->sock) break;
1663 conn = CONTAINING_RECORD(conn->common.Next, RpcConnection_tcp, common);
1667 RPCRT4_SpawnConnection(&cconn, &conn->common);
1669 ERR("failed to locate connection for fd %d\n", poll_info[i].fd);
1670 LeaveCriticalSection(&protseq->cs);
1672 RPCRT4_new_client(cconn);
1680 #else /* HAVE_SOCKETPAIR */
1682 typedef struct _RpcServerProtseq_sock
1684 RpcServerProtseq common;
1686 } RpcServerProtseq_sock;
1688 static RpcServerProtseq *rpcrt4_protseq_sock_alloc(void)
1690 RpcServerProtseq_sock *ps = HeapAlloc(GetProcessHeap(), 0, sizeof(*ps));
1693 static BOOL wsa_inited;
1697 WSAStartup(MAKEWORD(2, 2), &wsadata);
1698 /* Note: WSAStartup can be called more than once so we don't bother with
1699 * making accesses to wsa_inited thread-safe */
1702 ps->mgr_event = CreateEventW(NULL, FALSE, FALSE, NULL);
1707 static void rpcrt4_protseq_sock_signal_state_changed(RpcServerProtseq *protseq)
1709 RpcServerProtseq_sock *sockps = CONTAINING_RECORD(protseq, RpcServerProtseq_sock, common);
1710 SetEvent(sockps->mgr_event);
1713 static void *rpcrt4_protseq_sock_get_wait_array(RpcServerProtseq *protseq, void *prev_array, unsigned int *count)
1715 HANDLE *objs = prev_array;
1716 RpcConnection_tcp *conn;
1717 RpcServerProtseq_sock *sockps = CONTAINING_RECORD(protseq, RpcServerProtseq_sock, common);
1719 EnterCriticalSection(&protseq->cs);
1721 /* open and count connections */
1723 conn = CONTAINING_RECORD(protseq->conn, RpcConnection_tcp, common);
1726 if (conn->sock != -1)
1728 conn = CONTAINING_RECORD(conn->common.Next, RpcConnection_tcp, common);
1731 /* make array of connections */
1733 objs = HeapReAlloc(GetProcessHeap(), 0, objs, *count*sizeof(HANDLE));
1735 objs = HeapAlloc(GetProcessHeap(), 0, *count*sizeof(HANDLE));
1738 ERR("couldn't allocate objs\n");
1739 LeaveCriticalSection(&protseq->cs);
1743 objs[0] = sockps->mgr_event;
1745 conn = CONTAINING_RECORD(protseq->conn, RpcConnection_tcp, common);
1748 if (conn->sock != -1)
1750 int res = WSAEventSelect(conn->sock, conn->sock_event, FD_ACCEPT);
1751 if (res == SOCKET_ERROR)
1752 ERR("WSAEventSelect() failed with error %d\n", WSAGetLastError());
1755 objs[*count] = conn->sock_event;
1759 conn = CONTAINING_RECORD(conn->common.Next, RpcConnection_tcp, common);
1761 LeaveCriticalSection(&protseq->cs);
1765 static void rpcrt4_protseq_sock_free_wait_array(RpcServerProtseq *protseq, void *array)
1767 HeapFree(GetProcessHeap(), 0, array);
1770 static int rpcrt4_protseq_sock_wait_for_new_connection(RpcServerProtseq *protseq, unsigned int count, void *wait_array)
1773 HANDLE *objs = wait_array;
1775 RpcConnection *cconn;
1776 RpcConnection_tcp *conn;
1783 /* an alertable wait isn't strictly necessary, but due to our
1784 * overlapped I/O implementation in Wine we need to free some memory
1785 * by the file user APC being called, even if no completion routine was
1786 * specified at the time of starting the async operation */
1787 res = WaitForMultipleObjectsEx(count, objs, FALSE, INFINITE, TRUE);
1788 } while (res == WAIT_IO_COMPLETION);
1790 if (res == WAIT_OBJECT_0)
1792 else if (res == WAIT_FAILED)
1794 ERR("wait failed with error %d\n", GetLastError());
1799 b_handle = objs[res - WAIT_OBJECT_0];
1800 /* find which connection got a RPC */
1801 EnterCriticalSection(&protseq->cs);
1802 conn = CONTAINING_RECORD(protseq->conn, RpcConnection_tcp, common);
1805 if (b_handle == conn->sock_event) break;
1806 conn = CONTAINING_RECORD(conn->common.Next, RpcConnection_tcp, common);
1810 RPCRT4_SpawnConnection(&cconn, &conn->common);
1812 ERR("failed to locate connection for handle %p\n", b_handle);
1813 LeaveCriticalSection(&protseq->cs);
1816 RPCRT4_new_client(cconn);
1823 #endif /* HAVE_SOCKETPAIR */
1825 static RPC_STATUS rpcrt4_ncacn_ip_tcp_parse_top_of_tower(const unsigned char *tower_data,
1830 return rpcrt4_ip_tcp_parse_top_of_tower(tower_data, tower_size,
1831 networkaddr, EPM_PROTOCOL_TCP,
1835 /**** ncacn_http support ****/
1837 /* 60 seconds is the period native uses */
1838 #define HTTP_IDLE_TIME 60000
1840 /* reference counted to avoid a race between a cancelled call's connection
1841 * being destroyed and the asynchronous InternetReadFileEx call being
1843 typedef struct _RpcHttpAsyncData
1846 HANDLE completion_event;
1848 INTERNET_BUFFERSA inet_buffers;
1849 CRITICAL_SECTION cs;
1852 static ULONG RpcHttpAsyncData_AddRef(RpcHttpAsyncData *data)
1854 return InterlockedIncrement(&data->refs);
1857 static ULONG RpcHttpAsyncData_Release(RpcHttpAsyncData *data)
1859 ULONG refs = InterlockedDecrement(&data->refs);
1862 TRACE("destroying async data %p\n", data);
1863 CloseHandle(data->completion_event);
1864 HeapFree(GetProcessHeap(), 0, data->inet_buffers.lpvBuffer);
1865 data->cs.DebugInfo->Spare[0] = 0;
1866 DeleteCriticalSection(&data->cs);
1867 HeapFree(GetProcessHeap(), 0, data);
1872 static void prepare_async_request(RpcHttpAsyncData *async_data)
1874 ResetEvent(async_data->completion_event);
1875 RpcHttpAsyncData_AddRef(async_data);
1878 static RPC_STATUS wait_async_request(RpcHttpAsyncData *async_data, BOOL call_ret, HANDLE cancel_event)
1880 HANDLE handles[2] = { async_data->completion_event, cancel_event };
1884 RpcHttpAsyncData_Release(async_data);
1888 if(GetLastError() != ERROR_IO_PENDING) {
1889 RpcHttpAsyncData_Release(async_data);
1890 ERR("Request failed with error %d\n", GetLastError());
1891 return RPC_S_SERVER_UNAVAILABLE;
1894 res = WaitForMultipleObjects(2, handles, FALSE, DEFAULT_NCACN_HTTP_TIMEOUT);
1895 if(res != WAIT_OBJECT_0) {
1896 TRACE("Cancelled\n");
1897 return RPC_S_CALL_CANCELLED;
1900 if(async_data->async_result) {
1901 ERR("Async request failed with error %d\n", async_data->async_result);
1902 return RPC_S_SERVER_UNAVAILABLE;
1908 typedef struct _RpcConnection_http
1910 RpcConnection common;
1913 HINTERNET in_request;
1914 HINTERNET out_request;
1915 HANDLE timer_cancelled;
1916 HANDLE cancel_event;
1917 DWORD last_sent_time;
1918 ULONG bytes_received;
1919 ULONG flow_control_mark; /* send a control packet to the server when this many bytes received */
1920 ULONG flow_control_increment; /* number of bytes to increment flow_control_mark by */
1921 UUID connection_uuid;
1924 RpcHttpAsyncData *async_data;
1925 } RpcConnection_http;
1927 static RpcConnection *rpcrt4_ncacn_http_alloc(void)
1929 RpcConnection_http *httpc;
1930 httpc = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*httpc));
1931 if (!httpc) return NULL;
1932 httpc->async_data = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(RpcHttpAsyncData));
1933 if (!httpc->async_data)
1935 HeapFree(GetProcessHeap(), 0, httpc);
1938 TRACE("async data = %p\n", httpc->async_data);
1939 httpc->cancel_event = CreateEventW(NULL, FALSE, FALSE, NULL);
1940 httpc->async_data->refs = 1;
1941 httpc->async_data->inet_buffers.dwStructSize = sizeof(INTERNET_BUFFERSA);
1942 httpc->async_data->inet_buffers.lpvBuffer = NULL;
1943 InitializeCriticalSection(&httpc->async_data->cs);
1944 httpc->async_data->cs.DebugInfo->Spare[0] = (DWORD_PTR)(__FILE__ ": RpcHttpAsyncData.cs");
1945 return &httpc->common;
1948 typedef struct _HttpTimerThreadData
1951 DWORD *last_sent_time;
1952 HANDLE timer_cancelled;
1953 } HttpTimerThreadData;
1955 static VOID rpcrt4_http_keep_connection_active_timer_proc(PVOID param, BOOLEAN dummy)
1957 HINTERNET in_request = param;
1958 RpcPktHdr *idle_pkt;
1960 idle_pkt = RPCRT4_BuildHttpHeader(NDR_LOCAL_DATA_REPRESENTATION, 0x0001,
1964 DWORD bytes_written;
1965 InternetWriteFile(in_request, idle_pkt, idle_pkt->common.frag_len, &bytes_written);
1966 RPCRT4_FreeHeader(idle_pkt);
1970 static inline DWORD rpcrt4_http_timer_calc_timeout(DWORD *last_sent_time)
1972 DWORD cur_time = GetTickCount();
1973 DWORD cached_last_sent_time = *last_sent_time;
1974 return HTTP_IDLE_TIME - (cur_time - cached_last_sent_time > HTTP_IDLE_TIME ? 0 : cur_time - cached_last_sent_time);
1977 static DWORD CALLBACK rpcrt4_http_timer_thread(PVOID param)
1979 HttpTimerThreadData *data_in = param;
1980 HttpTimerThreadData data;
1984 HeapFree(GetProcessHeap(), 0, data_in);
1986 for (timeout = HTTP_IDLE_TIME;
1987 WaitForSingleObject(data.timer_cancelled, timeout) == WAIT_TIMEOUT;
1988 timeout = rpcrt4_http_timer_calc_timeout(data.last_sent_time))
1990 /* are we too soon after last send? */
1991 if (GetTickCount() - HTTP_IDLE_TIME < *data.last_sent_time)
1993 rpcrt4_http_keep_connection_active_timer_proc(data.timer_param, TRUE);
1996 CloseHandle(data.timer_cancelled);
2000 static VOID WINAPI rpcrt4_http_internet_callback(
2001 HINTERNET hInternet,
2002 DWORD_PTR dwContext,
2003 DWORD dwInternetStatus,
2004 LPVOID lpvStatusInformation,
2005 DWORD dwStatusInformationLength)
2007 RpcHttpAsyncData *async_data = (RpcHttpAsyncData *)dwContext;
2009 switch (dwInternetStatus)
2011 case INTERNET_STATUS_REQUEST_COMPLETE:
2012 TRACE("INTERNET_STATUS_REQUEST_COMPLETED\n");
2015 INTERNET_ASYNC_RESULT *async_result = lpvStatusInformation;
2017 async_data->async_result = async_result->dwResult ? ERROR_SUCCESS : async_result->dwError;
2018 SetEvent(async_data->completion_event);
2019 RpcHttpAsyncData_Release(async_data);
2025 static RPC_STATUS rpcrt4_http_check_response(HINTERNET hor)
2032 WCHAR *status_text = buf;
2036 size = sizeof(status_code);
2037 ret = HttpQueryInfoW(hor, HTTP_QUERY_STATUS_CODE|HTTP_QUERY_FLAG_NUMBER, &status_code, &size, &index);
2039 return GetLastError();
2040 if (status_code < 400)
2044 ret = HttpQueryInfoW(hor, HTTP_QUERY_STATUS_TEXT, status_text, &size, &index);
2045 if (!ret && GetLastError() == ERROR_INSUFFICIENT_BUFFER)
2047 status_text = HeapAlloc(GetProcessHeap(), 0, size);
2048 ret = HttpQueryInfoW(hor, HTTP_QUERY_STATUS_TEXT, status_text, &size, &index);
2051 ERR("server returned: %d %s\n", status_code, ret ? debugstr_w(status_text) : "<status text unavailable>");
2052 if(status_text != buf) HeapFree(GetProcessHeap(), 0, status_text);
2054 if (status_code == HTTP_STATUS_DENIED)
2055 return ERROR_ACCESS_DENIED;
2056 return RPC_S_SERVER_UNAVAILABLE;
2059 static RPC_STATUS rpcrt4_http_internet_connect(RpcConnection_http *httpc)
2061 static const WCHAR wszUserAgent[] = {'M','S','R','P','C',0};
2062 LPWSTR proxy = NULL;
2064 LPWSTR password = NULL;
2065 LPWSTR servername = NULL;
2066 const WCHAR *option;
2067 INTERNET_PORT port = INTERNET_INVALID_PORT_NUMBER; /* use default port */
2069 if (httpc->common.QOS &&
2070 (httpc->common.QOS->qos->AdditionalSecurityInfoType == RPC_C_AUTHN_INFO_TYPE_HTTP))
2072 const RPC_HTTP_TRANSPORT_CREDENTIALS_W *http_cred = httpc->common.QOS->qos->u.HttpCredentials;
2073 if (http_cred->TransportCredentials)
2076 const SEC_WINNT_AUTH_IDENTITY_W *cred = http_cred->TransportCredentials;
2077 ULONG len = cred->DomainLength + 1 + cred->UserLength;
2078 user = HeapAlloc(GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR));
2080 return RPC_S_OUT_OF_RESOURCES;
2082 if (cred->DomainLength)
2084 memcpy(p, cred->Domain, cred->DomainLength * sizeof(WCHAR));
2085 p += cred->DomainLength;
2089 memcpy(p, cred->User, cred->UserLength * sizeof(WCHAR));
2090 p[cred->UserLength] = 0;
2092 password = RPCRT4_strndupW(cred->Password, cred->PasswordLength);
2096 for (option = httpc->common.NetworkOptions; option;
2097 option = (strchrW(option, ',') ? strchrW(option, ',')+1 : NULL))
2099 static const WCHAR wszRpcProxy[] = {'R','p','c','P','r','o','x','y','=',0};
2100 static const WCHAR wszHttpProxy[] = {'H','t','t','p','P','r','o','x','y','=',0};
2102 if (!strncmpiW(option, wszRpcProxy, sizeof(wszRpcProxy)/sizeof(wszRpcProxy[0])-1))
2104 const WCHAR *value_start = option + sizeof(wszRpcProxy)/sizeof(wszRpcProxy[0])-1;
2105 const WCHAR *value_end;
2108 value_end = strchrW(option, ',');
2110 value_end = value_start + strlenW(value_start);
2111 for (p = value_start; p < value_end; p++)
2118 TRACE("RpcProxy value is %s\n", debugstr_wn(value_start, value_end-value_start));
2119 servername = RPCRT4_strndupW(value_start, value_end-value_start);
2121 else if (!strncmpiW(option, wszHttpProxy, sizeof(wszHttpProxy)/sizeof(wszHttpProxy[0])-1))
2123 const WCHAR *value_start = option + sizeof(wszHttpProxy)/sizeof(wszHttpProxy[0])-1;
2124 const WCHAR *value_end;
2126 value_end = strchrW(option, ',');
2128 value_end = value_start + strlenW(value_start);
2129 TRACE("HttpProxy value is %s\n", debugstr_wn(value_start, value_end-value_start));
2130 proxy = RPCRT4_strndupW(value_start, value_end-value_start);
2133 FIXME("unhandled option %s\n", debugstr_w(option));
2136 httpc->app_info = InternetOpenW(wszUserAgent, proxy ? INTERNET_OPEN_TYPE_PROXY : INTERNET_OPEN_TYPE_PRECONFIG,
2137 NULL, NULL, INTERNET_FLAG_ASYNC);
2138 if (!httpc->app_info)
2140 HeapFree(GetProcessHeap(), 0, password);
2141 HeapFree(GetProcessHeap(), 0, user);
2142 ERR("InternetOpenW failed with error %d\n", GetLastError());
2143 return RPC_S_SERVER_UNAVAILABLE;
2145 InternetSetStatusCallbackW(httpc->app_info, rpcrt4_http_internet_callback);
2147 /* if no RpcProxy option specified, set the HTTP server address to the
2148 * RPC server address */
2151 servername = HeapAlloc(GetProcessHeap(), 0, (strlen(httpc->common.NetworkAddr) + 1)*sizeof(WCHAR));
2154 HeapFree(GetProcessHeap(), 0, password);
2155 HeapFree(GetProcessHeap(), 0, user);
2156 return RPC_S_OUT_OF_RESOURCES;
2158 MultiByteToWideChar(CP_ACP, 0, httpc->common.NetworkAddr, -1, servername, strlen(httpc->common.NetworkAddr) + 1);
2161 httpc->session = InternetConnectW(httpc->app_info, servername, port, user, password,
2162 INTERNET_SERVICE_HTTP, 0, 0);
2164 HeapFree(GetProcessHeap(), 0, password);
2165 HeapFree(GetProcessHeap(), 0, user);
2166 HeapFree(GetProcessHeap(), 0, servername);
2168 if (!httpc->session)
2170 ERR("InternetConnectW failed with error %d\n", GetLastError());
2171 return RPC_S_SERVER_UNAVAILABLE;
2177 static RPC_STATUS send_echo_request(HINTERNET req, RpcHttpAsyncData *async_data, HANDLE cancel_event)
2184 prepare_async_request(async_data);
2185 ret = HttpSendRequestW(req, NULL, 0, NULL, 0);
2186 status = wait_async_request(async_data, ret, cancel_event);
2187 if (status != RPC_S_OK) return status;
2189 status = rpcrt4_http_check_response(req);
2190 if (status != RPC_S_OK) return status;
2192 InternetReadFile(req, buf, sizeof(buf), &bytes_read);
2193 /* FIXME: do something with retrieved data */
2198 /* prepare the in pipe for use by RPC packets */
2199 static RPC_STATUS rpcrt4_http_prepare_in_pipe(HINTERNET in_request, RpcHttpAsyncData *async_data, HANDLE cancel_event,
2200 const UUID *connection_uuid,
2201 const UUID *in_pipe_uuid,
2202 const UUID *association_uuid)
2207 INTERNET_BUFFERSW buffers_in;
2208 DWORD bytes_written;
2210 /* prepare in pipe */
2211 status = send_echo_request(in_request, async_data, cancel_event);
2212 if (status != RPC_S_OK) return status;
2214 memset(&buffers_in, 0, sizeof(buffers_in));
2215 buffers_in.dwStructSize = sizeof(buffers_in);
2216 /* FIXME: get this from the registry */
2217 buffers_in.dwBufferTotal = 1024 * 1024 * 1024; /* 1Gb */
2218 prepare_async_request(async_data);
2219 ret = HttpSendRequestExW(in_request, &buffers_in, NULL, 0, 0);
2220 status = wait_async_request(async_data, ret, cancel_event);
2221 if (status != RPC_S_OK) return status;
2223 TRACE("sending HTTP connect header to server\n");
2224 hdr = RPCRT4_BuildHttpConnectHeader(0, FALSE, connection_uuid, in_pipe_uuid, association_uuid);
2225 if (!hdr) return RPC_S_OUT_OF_RESOURCES;
2226 ret = InternetWriteFile(in_request, hdr, hdr->common.frag_len, &bytes_written);
2227 RPCRT4_FreeHeader(hdr);
2230 ERR("InternetWriteFile failed with error %d\n", GetLastError());
2231 return RPC_S_SERVER_UNAVAILABLE;
2237 static RPC_STATUS rpcrt4_http_read_http_packet(HINTERNET request, RpcPktHdr *hdr, BYTE **data)
2241 unsigned short data_len;
2243 ret = InternetReadFile(request, hdr, sizeof(hdr->common), &bytes_read);
2245 return RPC_S_SERVER_UNAVAILABLE;
2246 if (hdr->common.ptype != PKT_HTTP || hdr->common.frag_len < sizeof(hdr->http))
2248 ERR("wrong packet type received %d or wrong frag_len %d\n",
2249 hdr->common.ptype, hdr->common.frag_len);
2250 return RPC_S_PROTOCOL_ERROR;
2253 ret = InternetReadFile(request, &hdr->common + 1, sizeof(hdr->http) - sizeof(hdr->common), &bytes_read);
2255 return RPC_S_SERVER_UNAVAILABLE;
2257 data_len = hdr->common.frag_len - sizeof(hdr->http);
2260 *data = HeapAlloc(GetProcessHeap(), 0, data_len);
2262 return RPC_S_OUT_OF_RESOURCES;
2263 ret = InternetReadFile(request, *data, data_len, &bytes_read);
2266 HeapFree(GetProcessHeap(), 0, *data);
2267 return RPC_S_SERVER_UNAVAILABLE;
2273 if (!RPCRT4_IsValidHttpPacket(hdr, *data, data_len))
2275 ERR("invalid http packet\n");
2276 return RPC_S_PROTOCOL_ERROR;
2282 /* prepare the out pipe for use by RPC packets */
2283 static RPC_STATUS rpcrt4_http_prepare_out_pipe(HINTERNET out_request,
2284 RpcHttpAsyncData *async_data,
2285 HANDLE cancel_event,
2286 const UUID *connection_uuid,
2287 const UUID *out_pipe_uuid,
2288 ULONG *flow_control_increment)
2293 BYTE *data_from_server;
2294 RpcPktHdr pkt_from_server;
2295 ULONG field1, field3;
2297 status = send_echo_request(out_request, async_data, cancel_event);
2298 if (status != RPC_S_OK) return status;
2300 hdr = RPCRT4_BuildHttpConnectHeader(0, TRUE, connection_uuid, out_pipe_uuid, NULL);
2301 if (!hdr) return RPC_S_OUT_OF_RESOURCES;
2303 prepare_async_request(async_data);
2304 ret = HttpSendRequestW(out_request, NULL, 0, hdr, hdr->common.frag_len);
2305 status = wait_async_request(async_data, ret, cancel_event);
2306 RPCRT4_FreeHeader(hdr);
2307 if (status != RPC_S_OK) return status;
2309 status = rpcrt4_http_check_response(out_request);
2310 if (status != RPC_S_OK) return status;
2312 status = rpcrt4_http_read_http_packet(out_request, &pkt_from_server,
2314 if (status != RPC_S_OK) return status;
2315 status = RPCRT4_ParseHttpPrepareHeader1(&pkt_from_server, data_from_server,
2317 HeapFree(GetProcessHeap(), 0, data_from_server);
2318 if (status != RPC_S_OK) return status;
2319 TRACE("received (%d) from first prepare header\n", field1);
2321 status = rpcrt4_http_read_http_packet(out_request, &pkt_from_server,
2323 if (status != RPC_S_OK) return status;
2324 status = RPCRT4_ParseHttpPrepareHeader2(&pkt_from_server, data_from_server,
2325 &field1, flow_control_increment,
2327 HeapFree(GetProcessHeap(), 0, data_from_server);
2328 if (status != RPC_S_OK) return status;
2329 TRACE("received (0x%08x 0x%08x %d) from second prepare header\n", field1, *flow_control_increment, field3);
2334 static RPC_STATUS rpcrt4_ncacn_http_open(RpcConnection* Connection)
2336 RpcConnection_http *httpc = (RpcConnection_http *)Connection;
2337 static const WCHAR wszVerbIn[] = {'R','P','C','_','I','N','_','D','A','T','A',0};
2338 static const WCHAR wszVerbOut[] = {'R','P','C','_','O','U','T','_','D','A','T','A',0};
2339 static const WCHAR wszRpcProxyPrefix[] = {'/','r','p','c','/','r','p','c','p','r','o','x','y','.','d','l','l','?',0};
2340 static const WCHAR wszColon[] = {':',0};
2341 static const WCHAR wszAcceptType[] = {'a','p','p','l','i','c','a','t','i','o','n','/','r','p','c',0};
2342 LPCWSTR wszAcceptTypes[] = { wszAcceptType, NULL };
2346 HttpTimerThreadData *timer_data;
2349 TRACE("(%s, %s)\n", Connection->NetworkAddr, Connection->Endpoint);
2351 if (Connection->server)
2353 ERR("ncacn_http servers not supported yet\n");
2354 return RPC_S_SERVER_UNAVAILABLE;
2357 if (httpc->in_request)
2360 httpc->async_data->completion_event = CreateEventW(NULL, FALSE, FALSE, NULL);
2362 status = UuidCreate(&httpc->connection_uuid);
2363 status = UuidCreate(&httpc->in_pipe_uuid);
2364 status = UuidCreate(&httpc->out_pipe_uuid);
2366 status = rpcrt4_http_internet_connect(httpc);
2367 if (status != RPC_S_OK)
2370 url = HeapAlloc(GetProcessHeap(), 0, sizeof(wszRpcProxyPrefix) + (strlen(Connection->NetworkAddr) + 1 + strlen(Connection->Endpoint))*sizeof(WCHAR));
2372 return RPC_S_OUT_OF_MEMORY;
2373 memcpy(url, wszRpcProxyPrefix, sizeof(wszRpcProxyPrefix));
2374 MultiByteToWideChar(CP_ACP, 0, Connection->NetworkAddr, -1, url+sizeof(wszRpcProxyPrefix)/sizeof(wszRpcProxyPrefix[0])-1, strlen(Connection->NetworkAddr)+1);
2375 strcatW(url, wszColon);
2376 MultiByteToWideChar(CP_ACP, 0, Connection->Endpoint, -1, url+strlenW(url), strlen(Connection->Endpoint)+1);
2378 secure = httpc->common.QOS &&
2379 (httpc->common.QOS->qos->AdditionalSecurityInfoType == RPC_C_AUTHN_INFO_TYPE_HTTP) &&
2380 (httpc->common.QOS->qos->u.HttpCredentials->Flags & RPC_C_HTTP_FLAG_USE_SSL);
2382 httpc->in_request = HttpOpenRequestW(httpc->session, wszVerbIn, url, NULL, NULL,
2384 (secure ? INTERNET_FLAG_SECURE : 0)|INTERNET_FLAG_KEEP_CONNECTION|INTERNET_FLAG_PRAGMA_NOCACHE,
2385 (DWORD_PTR)httpc->async_data);
2386 if (!httpc->in_request)
2388 ERR("HttpOpenRequestW failed with error %d\n", GetLastError());
2389 HeapFree(GetProcessHeap(), 0, url);
2390 return RPC_S_SERVER_UNAVAILABLE;
2392 httpc->out_request = HttpOpenRequestW(httpc->session, wszVerbOut, url, NULL, NULL,
2394 (secure ? INTERNET_FLAG_SECURE : 0)|INTERNET_FLAG_KEEP_CONNECTION|INTERNET_FLAG_PRAGMA_NOCACHE,
2395 (DWORD_PTR)httpc->async_data);
2396 HeapFree(GetProcessHeap(), 0, url);
2397 if (!httpc->out_request)
2399 ERR("HttpOpenRequestW failed with error %d\n", GetLastError());
2400 return RPC_S_SERVER_UNAVAILABLE;
2403 status = rpcrt4_http_prepare_in_pipe(httpc->in_request,
2405 httpc->cancel_event,
2406 &httpc->connection_uuid,
2407 &httpc->in_pipe_uuid,
2408 &Connection->assoc->http_uuid);
2409 if (status != RPC_S_OK)
2412 status = rpcrt4_http_prepare_out_pipe(httpc->out_request,
2414 httpc->cancel_event,
2415 &httpc->connection_uuid,
2416 &httpc->out_pipe_uuid,
2417 &httpc->flow_control_increment);
2418 if (status != RPC_S_OK)
2421 httpc->flow_control_mark = httpc->flow_control_increment / 2;
2422 httpc->last_sent_time = GetTickCount();
2423 httpc->timer_cancelled = CreateEventW(NULL, FALSE, FALSE, NULL);
2425 timer_data = HeapAlloc(GetProcessHeap(), 0, sizeof(*timer_data));
2427 return ERROR_OUTOFMEMORY;
2428 timer_data->timer_param = httpc->in_request;
2429 timer_data->last_sent_time = &httpc->last_sent_time;
2430 timer_data->timer_cancelled = httpc->timer_cancelled;
2431 /* FIXME: should use CreateTimerQueueTimer when implemented */
2432 thread = CreateThread(NULL, 0, rpcrt4_http_timer_thread, timer_data, 0, NULL);
2435 HeapFree(GetProcessHeap(), 0, timer_data);
2436 return GetLastError();
2438 CloseHandle(thread);
2443 static RPC_STATUS rpcrt4_ncacn_http_handoff(RpcConnection *old_conn, RpcConnection *new_conn)
2446 return RPC_S_SERVER_UNAVAILABLE;
2449 static int rpcrt4_ncacn_http_read(RpcConnection *Connection,
2450 void *buffer, unsigned int count)
2452 RpcConnection_http *httpc = (RpcConnection_http *) Connection;
2455 unsigned int bytes_left = count;
2456 RPC_STATUS status = RPC_S_OK;
2458 httpc->async_data->inet_buffers.lpvBuffer = HeapAlloc(GetProcessHeap(), 0, count);
2462 httpc->async_data->inet_buffers.dwBufferLength = bytes_left;
2463 prepare_async_request(httpc->async_data);
2464 ret = InternetReadFileExA(httpc->out_request, &httpc->async_data->inet_buffers, IRF_ASYNC, 0);
2465 status = wait_async_request(httpc->async_data, ret, httpc->cancel_event);
2466 if(status != RPC_S_OK) {
2467 if(status == RPC_S_CALL_CANCELLED)
2468 TRACE("call cancelled\n");
2472 if(!httpc->async_data->inet_buffers.dwBufferLength)
2474 memcpy(buf, httpc->async_data->inet_buffers.lpvBuffer,
2475 httpc->async_data->inet_buffers.dwBufferLength);
2477 bytes_left -= httpc->async_data->inet_buffers.dwBufferLength;
2478 buf += httpc->async_data->inet_buffers.dwBufferLength;
2481 HeapFree(GetProcessHeap(), 0, httpc->async_data->inet_buffers.lpvBuffer);
2482 httpc->async_data->inet_buffers.lpvBuffer = NULL;
2484 TRACE("%p %p %u -> %u\n", httpc->out_request, buffer, count, status);
2485 return status == RPC_S_OK ? count : -1;
2488 static RPC_STATUS rpcrt4_ncacn_http_receive_fragment(RpcConnection *Connection, RpcPktHdr **Header, void **Payload)
2490 RpcConnection_http *httpc = (RpcConnection_http *) Connection;
2494 RpcPktCommonHdr common_hdr;
2498 TRACE("(%p, %p, %p)\n", Connection, Header, Payload);
2501 /* read packet common header */
2502 dwRead = rpcrt4_ncacn_http_read(Connection, &common_hdr, sizeof(common_hdr));
2503 if (dwRead != sizeof(common_hdr)) {
2504 WARN("Short read of header, %d bytes\n", dwRead);
2505 status = RPC_S_PROTOCOL_ERROR;
2508 if (!memcmp(&common_hdr, "HTTP/1.1", sizeof("HTTP/1.1")) ||
2509 !memcmp(&common_hdr, "HTTP/1.0", sizeof("HTTP/1.0")))
2511 FIXME("server returned %s\n", debugstr_a((const char *)&common_hdr));
2512 status = RPC_S_PROTOCOL_ERROR;
2516 status = RPCRT4_ValidateCommonHeader(&common_hdr);
2517 if (status != RPC_S_OK) goto fail;
2519 hdr_length = RPCRT4_GetHeaderSize((RpcPktHdr*)&common_hdr);
2520 if (hdr_length == 0) {
2521 WARN("header length == 0\n");
2522 status = RPC_S_PROTOCOL_ERROR;
2526 *Header = HeapAlloc(GetProcessHeap(), 0, hdr_length);
2529 status = RPC_S_OUT_OF_RESOURCES;
2532 memcpy(*Header, &common_hdr, sizeof(common_hdr));
2534 /* read the rest of packet header */
2535 dwRead = rpcrt4_ncacn_http_read(Connection, &(*Header)->common + 1, hdr_length - sizeof(common_hdr));
2536 if (dwRead != hdr_length - sizeof(common_hdr)) {
2537 WARN("bad header length, %d bytes, hdr_length %d\n", dwRead, hdr_length);
2538 status = RPC_S_PROTOCOL_ERROR;
2542 if (common_hdr.frag_len - hdr_length)
2544 *Payload = HeapAlloc(GetProcessHeap(), 0, common_hdr.frag_len - hdr_length);
2547 status = RPC_S_OUT_OF_RESOURCES;
2551 dwRead = rpcrt4_ncacn_http_read(Connection, *Payload, common_hdr.frag_len - hdr_length);
2552 if (dwRead != common_hdr.frag_len - hdr_length)
2554 WARN("bad data length, %d/%d\n", dwRead, common_hdr.frag_len - hdr_length);
2555 status = RPC_S_PROTOCOL_ERROR;
2562 if ((*Header)->common.ptype == PKT_HTTP)
2564 if (!RPCRT4_IsValidHttpPacket(*Header, *Payload, common_hdr.frag_len - hdr_length))
2566 ERR("invalid http packet of length %d bytes\n", (*Header)->common.frag_len);
2567 status = RPC_S_PROTOCOL_ERROR;
2570 if ((*Header)->http.flags == 0x0001)
2572 TRACE("http idle packet, waiting for real packet\n");
2573 if ((*Header)->http.num_data_items != 0)
2575 ERR("HTTP idle packet should have no data items instead of %d\n", (*Header)->http.num_data_items);
2576 status = RPC_S_PROTOCOL_ERROR;
2580 else if ((*Header)->http.flags == 0x0002)
2582 ULONG bytes_transmitted;
2583 ULONG flow_control_increment;
2585 status = RPCRT4_ParseHttpFlowControlHeader(*Header, *Payload,
2588 &flow_control_increment,
2590 if (status != RPC_S_OK)
2592 TRACE("received http flow control header (0x%x, 0x%x, %s)\n",
2593 bytes_transmitted, flow_control_increment, debugstr_guid(&pipe_uuid));
2594 /* FIXME: do something with parsed data */
2598 FIXME("unrecognised http packet with flags 0x%04x\n", (*Header)->http.flags);
2599 status = RPC_S_PROTOCOL_ERROR;
2602 RPCRT4_FreeHeader(*Header);
2604 HeapFree(GetProcessHeap(), 0, *Payload);
2612 httpc->bytes_received += common_hdr.frag_len;
2614 TRACE("httpc->bytes_received = 0x%x\n", httpc->bytes_received);
2616 if (httpc->bytes_received > httpc->flow_control_mark)
2618 RpcPktHdr *hdr = RPCRT4_BuildHttpFlowControlHeader(httpc->common.server,
2619 httpc->bytes_received,
2620 httpc->flow_control_increment,
2621 &httpc->out_pipe_uuid);
2624 DWORD bytes_written;
2626 TRACE("sending flow control packet at 0x%x\n", httpc->bytes_received);
2627 ret2 = InternetWriteFile(httpc->in_request, hdr, hdr->common.frag_len, &bytes_written);
2628 RPCRT4_FreeHeader(hdr);
2630 httpc->flow_control_mark = httpc->bytes_received + httpc->flow_control_increment / 2;
2635 if (status != RPC_S_OK) {
2636 RPCRT4_FreeHeader(*Header);
2638 HeapFree(GetProcessHeap(), 0, *Payload);
2644 static int rpcrt4_ncacn_http_write(RpcConnection *Connection,
2645 const void *buffer, unsigned int count)
2647 RpcConnection_http *httpc = (RpcConnection_http *) Connection;
2648 DWORD bytes_written;
2651 httpc->last_sent_time = ~0U; /* disable idle packet sending */
2652 ret = InternetWriteFile(httpc->in_request, buffer, count, &bytes_written);
2653 httpc->last_sent_time = GetTickCount();
2654 TRACE("%p %p %u -> %s\n", httpc->in_request, buffer, count, ret ? "TRUE" : "FALSE");
2655 return ret ? bytes_written : -1;
2658 static int rpcrt4_ncacn_http_close(RpcConnection *Connection)
2660 RpcConnection_http *httpc = (RpcConnection_http *) Connection;
2664 SetEvent(httpc->timer_cancelled);
2665 if (httpc->in_request)
2666 InternetCloseHandle(httpc->in_request);
2667 httpc->in_request = NULL;
2668 if (httpc->out_request)
2669 InternetCloseHandle(httpc->out_request);
2670 httpc->out_request = NULL;
2671 if (httpc->app_info)
2672 InternetCloseHandle(httpc->app_info);
2673 httpc->app_info = NULL;
2675 InternetCloseHandle(httpc->session);
2676 httpc->session = NULL;
2677 RpcHttpAsyncData_Release(httpc->async_data);
2678 if (httpc->cancel_event)
2679 CloseHandle(httpc->cancel_event);
2684 static void rpcrt4_ncacn_http_cancel_call(RpcConnection *Connection)
2686 RpcConnection_http *httpc = (RpcConnection_http *) Connection;
2688 SetEvent(httpc->cancel_event);
2691 static int rpcrt4_ncacn_http_wait_for_incoming_data(RpcConnection *Connection)
2693 RpcConnection_http *httpc = (RpcConnection_http *) Connection;
2697 prepare_async_request(httpc->async_data);
2698 ret = InternetQueryDataAvailable(httpc->out_request,
2699 &httpc->async_data->inet_buffers.dwBufferLength, IRF_ASYNC, 0);
2700 status = wait_async_request(httpc->async_data, ret, httpc->cancel_event);
2701 return status == RPC_S_OK ? 0 : -1;
2704 static size_t rpcrt4_ncacn_http_get_top_of_tower(unsigned char *tower_data,
2705 const char *networkaddr,
2706 const char *endpoint)
2708 return rpcrt4_ip_tcp_get_top_of_tower(tower_data, networkaddr,
2709 EPM_PROTOCOL_HTTP, endpoint);
2712 static RPC_STATUS rpcrt4_ncacn_http_parse_top_of_tower(const unsigned char *tower_data,
2717 return rpcrt4_ip_tcp_parse_top_of_tower(tower_data, tower_size,
2718 networkaddr, EPM_PROTOCOL_HTTP,
2722 static const struct connection_ops conn_protseq_list[] = {
2724 { EPM_PROTOCOL_NCACN, EPM_PROTOCOL_SMB },
2725 rpcrt4_conn_np_alloc,
2726 rpcrt4_ncacn_np_open,
2727 rpcrt4_ncacn_np_handoff,
2728 rpcrt4_conn_np_read,
2729 rpcrt4_conn_np_write,
2730 rpcrt4_conn_np_close,
2731 rpcrt4_conn_np_cancel_call,
2732 rpcrt4_conn_np_wait_for_incoming_data,
2733 rpcrt4_ncacn_np_get_top_of_tower,
2734 rpcrt4_ncacn_np_parse_top_of_tower,
2736 RPCRT4_default_is_authorized,
2737 RPCRT4_default_authorize,
2738 RPCRT4_default_secure_packet,
2739 rpcrt4_conn_np_impersonate_client,
2740 rpcrt4_conn_np_revert_to_self,
2741 RPCRT4_default_inquire_auth_client,
2744 { EPM_PROTOCOL_NCALRPC, EPM_PROTOCOL_PIPE },
2745 rpcrt4_conn_np_alloc,
2746 rpcrt4_ncalrpc_open,
2747 rpcrt4_ncalrpc_handoff,
2748 rpcrt4_conn_np_read,
2749 rpcrt4_conn_np_write,
2750 rpcrt4_conn_np_close,
2751 rpcrt4_conn_np_cancel_call,
2752 rpcrt4_conn_np_wait_for_incoming_data,
2753 rpcrt4_ncalrpc_get_top_of_tower,
2754 rpcrt4_ncalrpc_parse_top_of_tower,
2756 rpcrt4_ncalrpc_is_authorized,
2757 rpcrt4_ncalrpc_authorize,
2758 rpcrt4_ncalrpc_secure_packet,
2759 rpcrt4_conn_np_impersonate_client,
2760 rpcrt4_conn_np_revert_to_self,
2761 rpcrt4_ncalrpc_inquire_auth_client,
2764 { EPM_PROTOCOL_NCACN, EPM_PROTOCOL_TCP },
2765 rpcrt4_conn_tcp_alloc,
2766 rpcrt4_ncacn_ip_tcp_open,
2767 rpcrt4_conn_tcp_handoff,
2768 rpcrt4_conn_tcp_read,
2769 rpcrt4_conn_tcp_write,
2770 rpcrt4_conn_tcp_close,
2771 rpcrt4_conn_tcp_cancel_call,
2772 rpcrt4_conn_tcp_wait_for_incoming_data,
2773 rpcrt4_ncacn_ip_tcp_get_top_of_tower,
2774 rpcrt4_ncacn_ip_tcp_parse_top_of_tower,
2776 RPCRT4_default_is_authorized,
2777 RPCRT4_default_authorize,
2778 RPCRT4_default_secure_packet,
2779 RPCRT4_default_impersonate_client,
2780 RPCRT4_default_revert_to_self,
2781 RPCRT4_default_inquire_auth_client,
2784 { EPM_PROTOCOL_NCACN, EPM_PROTOCOL_HTTP },
2785 rpcrt4_ncacn_http_alloc,
2786 rpcrt4_ncacn_http_open,
2787 rpcrt4_ncacn_http_handoff,
2788 rpcrt4_ncacn_http_read,
2789 rpcrt4_ncacn_http_write,
2790 rpcrt4_ncacn_http_close,
2791 rpcrt4_ncacn_http_cancel_call,
2792 rpcrt4_ncacn_http_wait_for_incoming_data,
2793 rpcrt4_ncacn_http_get_top_of_tower,
2794 rpcrt4_ncacn_http_parse_top_of_tower,
2795 rpcrt4_ncacn_http_receive_fragment,
2796 RPCRT4_default_is_authorized,
2797 RPCRT4_default_authorize,
2798 RPCRT4_default_secure_packet,
2799 RPCRT4_default_impersonate_client,
2800 RPCRT4_default_revert_to_self,
2801 RPCRT4_default_inquire_auth_client,
2806 static const struct protseq_ops protseq_list[] =
2810 rpcrt4_protseq_np_alloc,
2811 rpcrt4_protseq_np_signal_state_changed,
2812 rpcrt4_protseq_np_get_wait_array,
2813 rpcrt4_protseq_np_free_wait_array,
2814 rpcrt4_protseq_np_wait_for_new_connection,
2815 rpcrt4_protseq_ncacn_np_open_endpoint,
2819 rpcrt4_protseq_np_alloc,
2820 rpcrt4_protseq_np_signal_state_changed,
2821 rpcrt4_protseq_np_get_wait_array,
2822 rpcrt4_protseq_np_free_wait_array,
2823 rpcrt4_protseq_np_wait_for_new_connection,
2824 rpcrt4_protseq_ncalrpc_open_endpoint,
2828 rpcrt4_protseq_sock_alloc,
2829 rpcrt4_protseq_sock_signal_state_changed,
2830 rpcrt4_protseq_sock_get_wait_array,
2831 rpcrt4_protseq_sock_free_wait_array,
2832 rpcrt4_protseq_sock_wait_for_new_connection,
2833 rpcrt4_protseq_ncacn_ip_tcp_open_endpoint,
2837 #define ARRAYSIZE(a) (sizeof((a)) / sizeof((a)[0]))
2839 const struct protseq_ops *rpcrt4_get_protseq_ops(const char *protseq)
2842 for(i=0; i<ARRAYSIZE(protseq_list); i++)
2843 if (!strcmp(protseq_list[i].name, protseq))
2844 return &protseq_list[i];
2848 static const struct connection_ops *rpcrt4_get_conn_protseq_ops(const char *protseq)
2851 for(i=0; i<ARRAYSIZE(conn_protseq_list); i++)
2852 if (!strcmp(conn_protseq_list[i].name, protseq))
2853 return &conn_protseq_list[i];
2857 /**** interface to rest of code ****/
2859 RPC_STATUS RPCRT4_OpenClientConnection(RpcConnection* Connection)
2861 TRACE("(Connection == ^%p)\n", Connection);
2863 assert(!Connection->server);
2864 return Connection->ops->open_connection_client(Connection);
2867 RPC_STATUS RPCRT4_CloseConnection(RpcConnection* Connection)
2869 TRACE("(Connection == ^%p)\n", Connection);
2870 if (SecIsValidHandle(&Connection->ctx))
2872 DeleteSecurityContext(&Connection->ctx);
2873 SecInvalidateHandle(&Connection->ctx);
2875 rpcrt4_conn_close(Connection);
2879 RPC_STATUS RPCRT4_CreateConnection(RpcConnection** Connection, BOOL server,
2880 LPCSTR Protseq, LPCSTR NetworkAddr, LPCSTR Endpoint,
2881 LPCWSTR NetworkOptions, RpcAuthInfo* AuthInfo, RpcQualityOfService *QOS)
2883 static LONG next_id;
2884 const struct connection_ops *ops;
2885 RpcConnection* NewConnection;
2887 ops = rpcrt4_get_conn_protseq_ops(Protseq);
2890 FIXME("not supported for protseq %s\n", Protseq);
2891 return RPC_S_PROTSEQ_NOT_SUPPORTED;
2894 NewConnection = ops->alloc();
2895 NewConnection->ref = 1;
2896 NewConnection->Next = NULL;
2897 NewConnection->server_binding = NULL;
2898 NewConnection->server = server;
2899 NewConnection->ops = ops;
2900 NewConnection->NetworkAddr = RPCRT4_strdupA(NetworkAddr);
2901 NewConnection->Endpoint = RPCRT4_strdupA(Endpoint);
2902 NewConnection->NetworkOptions = RPCRT4_strdupW(NetworkOptions);
2903 NewConnection->MaxTransmissionSize = RPC_MAX_PACKET_SIZE;
2904 memset(&NewConnection->ActiveInterface, 0, sizeof(NewConnection->ActiveInterface));
2905 NewConnection->NextCallId = 1;
2907 SecInvalidateHandle(&NewConnection->ctx);
2908 memset(&NewConnection->exp, 0, sizeof(NewConnection->exp));
2909 NewConnection->attr = 0;
2910 if (AuthInfo) RpcAuthInfo_AddRef(AuthInfo);
2911 NewConnection->AuthInfo = AuthInfo;
2912 NewConnection->auth_context_id = InterlockedIncrement( &next_id );
2913 NewConnection->encryption_auth_len = 0;
2914 NewConnection->signature_auth_len = 0;
2915 if (QOS) RpcQualityOfService_AddRef(QOS);
2916 NewConnection->QOS = QOS;
2918 list_init(&NewConnection->conn_pool_entry);
2919 NewConnection->async_state = NULL;
2921 TRACE("connection: %p\n", NewConnection);
2922 *Connection = NewConnection;
2927 static RPC_STATUS RPCRT4_SpawnConnection(RpcConnection** Connection, RpcConnection* OldConnection)
2931 err = RPCRT4_CreateConnection(Connection, OldConnection->server,
2932 rpcrt4_conn_get_name(OldConnection),
2933 OldConnection->NetworkAddr,
2934 OldConnection->Endpoint, NULL,
2935 OldConnection->AuthInfo, OldConnection->QOS);
2936 if (err == RPC_S_OK)
2937 rpcrt4_conn_handoff(OldConnection, *Connection);
2941 RpcConnection *RPCRT4_GrabConnection( RpcConnection *conn )
2943 InterlockedIncrement( &conn->ref );
2947 RPC_STATUS RPCRT4_ReleaseConnection(RpcConnection* Connection)
2949 if (InterlockedDecrement( &Connection->ref ) > 0) return RPC_S_OK;
2951 TRACE("destroying connection %p\n", Connection);
2953 RPCRT4_CloseConnection(Connection);
2954 RPCRT4_strfree(Connection->Endpoint);
2955 RPCRT4_strfree(Connection->NetworkAddr);
2956 HeapFree(GetProcessHeap(), 0, Connection->NetworkOptions);
2957 if (Connection->AuthInfo) RpcAuthInfo_Release(Connection->AuthInfo);
2958 if (Connection->QOS) RpcQualityOfService_Release(Connection->QOS);
2961 if (Connection->server_binding) RPCRT4_ReleaseBinding(Connection->server_binding);
2963 HeapFree(GetProcessHeap(), 0, Connection);
2967 RPC_STATUS RpcTransport_GetTopOfTower(unsigned char *tower_data,
2969 const char *protseq,
2970 const char *networkaddr,
2971 const char *endpoint)
2973 twr_empty_floor_t *protocol_floor;
2974 const struct connection_ops *protseq_ops = rpcrt4_get_conn_protseq_ops(protseq);
2979 return RPC_S_INVALID_RPC_PROTSEQ;
2983 *tower_size = sizeof(*protocol_floor);
2984 *tower_size += protseq_ops->get_top_of_tower(NULL, networkaddr, endpoint);
2988 protocol_floor = (twr_empty_floor_t *)tower_data;
2989 protocol_floor->count_lhs = sizeof(protocol_floor->protid);
2990 protocol_floor->protid = protseq_ops->epm_protocols[0];
2991 protocol_floor->count_rhs = 0;
2993 tower_data += sizeof(*protocol_floor);
2995 *tower_size = protseq_ops->get_top_of_tower(tower_data, networkaddr, endpoint);
2997 return EPT_S_NOT_REGISTERED;
2999 *tower_size += sizeof(*protocol_floor);
3004 RPC_STATUS RpcTransport_ParseTopOfTower(const unsigned char *tower_data,
3010 const twr_empty_floor_t *protocol_floor;
3011 const twr_empty_floor_t *floor4;
3012 const struct connection_ops *protseq_ops = NULL;
3016 if (tower_size < sizeof(*protocol_floor))
3017 return EPT_S_NOT_REGISTERED;
3019 protocol_floor = (const twr_empty_floor_t *)tower_data;
3020 tower_data += sizeof(*protocol_floor);
3021 tower_size -= sizeof(*protocol_floor);
3022 if ((protocol_floor->count_lhs != sizeof(protocol_floor->protid)) ||
3023 (protocol_floor->count_rhs > tower_size))
3024 return EPT_S_NOT_REGISTERED;
3025 tower_data += protocol_floor->count_rhs;
3026 tower_size -= protocol_floor->count_rhs;
3028 floor4 = (const twr_empty_floor_t *)tower_data;
3029 if ((tower_size < sizeof(*floor4)) ||
3030 (floor4->count_lhs != sizeof(floor4->protid)))
3031 return EPT_S_NOT_REGISTERED;
3033 for(i = 0; i < ARRAYSIZE(conn_protseq_list); i++)
3034 if ((protocol_floor->protid == conn_protseq_list[i].epm_protocols[0]) &&
3035 (floor4->protid == conn_protseq_list[i].epm_protocols[1]))
3037 protseq_ops = &conn_protseq_list[i];
3042 return EPT_S_NOT_REGISTERED;
3044 status = protseq_ops->parse_top_of_tower(tower_data, tower_size, networkaddr, endpoint);
3046 if ((status == RPC_S_OK) && protseq)
3048 *protseq = I_RpcAllocate(strlen(protseq_ops->name) + 1);
3049 strcpy(*protseq, protseq_ops->name);
3055 /***********************************************************************
3056 * RpcNetworkIsProtseqValidW (RPCRT4.@)
3058 * Checks if the given protocol sequence is known by the RPC system.
3059 * If it is, returns RPC_S_OK, otherwise RPC_S_PROTSEQ_NOT_SUPPORTED.
3062 RPC_STATUS WINAPI RpcNetworkIsProtseqValidW(RPC_WSTR protseq)
3066 WideCharToMultiByte(CP_ACP, 0, protseq, -1,
3067 ps, sizeof ps, NULL, NULL);
3068 if (rpcrt4_get_conn_protseq_ops(ps))
3071 FIXME("Unknown protseq %s\n", debugstr_w(protseq));
3073 return RPC_S_INVALID_RPC_PROTSEQ;
3076 /***********************************************************************
3077 * RpcNetworkIsProtseqValidA (RPCRT4.@)
3079 RPC_STATUS WINAPI RpcNetworkIsProtseqValidA(RPC_CSTR protseq)
3081 UNICODE_STRING protseqW;
3083 if (RtlCreateUnicodeStringFromAsciiz(&protseqW, (char*)protseq))
3085 RPC_STATUS ret = RpcNetworkIsProtseqValidW(protseqW.Buffer);
3086 RtlFreeUnicodeString(&protseqW);
3089 return RPC_S_OUT_OF_MEMORY;
3092 /***********************************************************************
3093 * RpcProtseqVectorFreeA (RPCRT4.@)
3095 RPC_STATUS WINAPI RpcProtseqVectorFreeA(RPC_PROTSEQ_VECTORA **protseqs)
3097 TRACE("(%p)\n", protseqs);
3102 for (i = 0; i < (*protseqs)->Count; i++)
3103 HeapFree(GetProcessHeap(), 0, (*protseqs)->Protseq[i]);
3104 HeapFree(GetProcessHeap(), 0, *protseqs);
3110 /***********************************************************************
3111 * RpcProtseqVectorFreeW (RPCRT4.@)
3113 RPC_STATUS WINAPI RpcProtseqVectorFreeW(RPC_PROTSEQ_VECTORW **protseqs)
3115 TRACE("(%p)\n", protseqs);
3120 for (i = 0; i < (*protseqs)->Count; i++)
3121 HeapFree(GetProcessHeap(), 0, (*protseqs)->Protseq[i]);
3122 HeapFree(GetProcessHeap(), 0, *protseqs);
3128 /***********************************************************************
3129 * RpcNetworkInqProtseqsW (RPCRT4.@)
3131 RPC_STATUS WINAPI RpcNetworkInqProtseqsW( RPC_PROTSEQ_VECTORW** protseqs )
3133 RPC_PROTSEQ_VECTORW *pvector;
3135 RPC_STATUS status = RPC_S_OUT_OF_MEMORY;
3137 TRACE("(%p)\n", protseqs);
3139 *protseqs = HeapAlloc(GetProcessHeap(), 0, sizeof(RPC_PROTSEQ_VECTORW)+(sizeof(unsigned short*)*ARRAYSIZE(protseq_list)));
3142 pvector = *protseqs;
3144 for (i = 0; i < ARRAYSIZE(protseq_list); i++)
3146 pvector->Protseq[i] = HeapAlloc(GetProcessHeap(), 0, (strlen(protseq_list[i].name)+1)*sizeof(unsigned short));
3147 if (pvector->Protseq[i] == NULL)
3149 MultiByteToWideChar(CP_ACP, 0, (CHAR*)protseq_list[i].name, -1,
3150 (WCHAR*)pvector->Protseq[i], strlen(protseq_list[i].name) + 1);
3156 if (status != RPC_S_OK)
3157 RpcProtseqVectorFreeW(protseqs);
3161 /***********************************************************************
3162 * RpcNetworkInqProtseqsA (RPCRT4.@)
3164 RPC_STATUS WINAPI RpcNetworkInqProtseqsA(RPC_PROTSEQ_VECTORA** protseqs)
3166 RPC_PROTSEQ_VECTORA *pvector;
3168 RPC_STATUS status = RPC_S_OUT_OF_MEMORY;
3170 TRACE("(%p)\n", protseqs);
3172 *protseqs = HeapAlloc(GetProcessHeap(), 0, sizeof(RPC_PROTSEQ_VECTORW)+(sizeof(unsigned char*)*ARRAYSIZE(protseq_list)));
3175 pvector = *protseqs;
3177 for (i = 0; i < ARRAYSIZE(protseq_list); i++)
3179 pvector->Protseq[i] = HeapAlloc(GetProcessHeap(), 0, strlen(protseq_list[i].name)+1);
3180 if (pvector->Protseq[i] == NULL)
3182 strcpy((char*)pvector->Protseq[i], protseq_list[i].name);
3188 if (status != RPC_S_OK)
3189 RpcProtseqVectorFreeA(protseqs);