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
34 #include <sys/types.h>
36 #if defined(__MINGW32__) || defined (_MSC_VER)
37 # include <ws2tcpip.h>
39 # define EADDRINUSE WSAEADDRINUSE
42 # define EAGAIN WSAEWOULDBLOCK
45 # define errno WSAGetLastError()
52 # ifdef HAVE_SYS_SOCKET_H
53 # include <sys/socket.h>
55 # ifdef HAVE_NETINET_IN_H
56 # include <netinet/in.h>
58 # ifdef HAVE_NETINET_TCP_H
59 # include <netinet/tcp.h>
61 # ifdef HAVE_ARPA_INET_H
62 # include <arpa/inet.h>
67 # ifdef HAVE_SYS_POLL_H
68 # include <sys/poll.h>
70 # ifdef HAVE_SYS_FILIO_H
71 # include <sys/filio.h>
73 # ifdef HAVE_SYS_IOCTL_H
74 # include <sys/ioctl.h>
76 # define closesocket close
77 # define ioctlsocket ioctl
78 #endif /* defined(__MINGW32__) || defined (_MSC_VER) */
86 #include "wine/unicode.h"
91 #include "wine/debug.h"
93 #include "rpc_binding.h"
94 #include "rpc_assoc.h"
95 #include "rpc_message.h"
96 #include "rpc_server.h"
97 #include "epm_towers.h"
100 # define SOL_TCP IPPROTO_TCP
103 #define DEFAULT_NCACN_HTTP_TIMEOUT (60 * 1000)
105 #define ARRAYSIZE(a) (sizeof((a)) / sizeof((a)[0]))
107 WINE_DEFAULT_DEBUG_CHANNEL(rpc
);
109 static RPC_STATUS
RPCRT4_SpawnConnection(RpcConnection
** Connection
, RpcConnection
* OldConnection
);
111 /**** ncacn_np support ****/
113 typedef struct _RpcConnection_np
115 RpcConnection common
;
117 HANDLE listen_thread
;
121 static RpcConnection
*rpcrt4_conn_np_alloc(void)
123 RpcConnection_np
*npc
= HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY
, sizeof(RpcConnection_np
));
127 static DWORD CALLBACK
listen_thread(void *arg
)
129 RpcConnection_np
*npc
= arg
;
132 if (ConnectNamedPipe(npc
->pipe
, NULL
))
135 switch(GetLastError())
137 case ERROR_PIPE_CONNECTED
:
139 case ERROR_HANDLES_CLOSED
:
140 /* connection closed during listen */
141 return RPC_S_NO_CONTEXT_AVAILABLE
;
142 case ERROR_NO_DATA_DETECTED
:
143 /* client has disconnected, retry */
144 DisconnectNamedPipe( npc
->pipe
);
147 npc
->listening
= FALSE
;
148 WARN("Couldn't ConnectNamedPipe (error was %d)\n", GetLastError());
149 return RPC_S_OUT_OF_RESOURCES
;
154 static RPC_STATUS
rpcrt4_conn_listen_pipe(RpcConnection_np
*npc
)
159 npc
->listening
= TRUE
;
160 npc
->listen_thread
= CreateThread(NULL
, 0, listen_thread
, npc
, 0, NULL
);
161 if (!npc
->listen_thread
)
163 npc
->listening
= FALSE
;
164 ERR("Couldn't create listen thread (error was %d)\n", GetLastError());
165 return RPC_S_OUT_OF_RESOURCES
;
170 static RPC_STATUS
rpcrt4_conn_create_pipe(RpcConnection
*Connection
, LPCSTR pname
)
172 RpcConnection_np
*npc
= (RpcConnection_np
*) Connection
;
173 TRACE("listening on %s\n", pname
);
175 npc
->pipe
= CreateNamedPipeA(pname
, PIPE_ACCESS_DUPLEX
,
176 PIPE_TYPE_MESSAGE
| PIPE_READMODE_MESSAGE
,
177 PIPE_UNLIMITED_INSTANCES
,
178 RPC_MAX_PACKET_SIZE
, RPC_MAX_PACKET_SIZE
, 5000, NULL
);
179 if (npc
->pipe
== INVALID_HANDLE_VALUE
) {
180 WARN("CreateNamedPipe failed with error %d\n", GetLastError());
181 if (GetLastError() == ERROR_FILE_EXISTS
)
182 return RPC_S_DUPLICATE_ENDPOINT
;
184 return RPC_S_CANT_CREATE_ENDPOINT
;
187 /* Note: we don't call ConnectNamedPipe here because it must be done in the
188 * server thread as the thread must be alertable */
192 static RPC_STATUS
rpcrt4_conn_open_pipe(RpcConnection
*Connection
, LPCSTR pname
, BOOL wait
)
194 RpcConnection_np
*npc
= (RpcConnection_np
*) Connection
;
198 TRACE("connecting to %s\n", pname
);
204 dwFlags
= SECURITY_SQOS_PRESENT
;
205 switch (Connection
->QOS
->qos
->ImpersonationType
)
207 case RPC_C_IMP_LEVEL_DEFAULT
:
208 /* FIXME: what to do here? */
210 case RPC_C_IMP_LEVEL_ANONYMOUS
:
211 dwFlags
|= SECURITY_ANONYMOUS
;
213 case RPC_C_IMP_LEVEL_IDENTIFY
:
214 dwFlags
|= SECURITY_IDENTIFICATION
;
216 case RPC_C_IMP_LEVEL_IMPERSONATE
:
217 dwFlags
|= SECURITY_IMPERSONATION
;
219 case RPC_C_IMP_LEVEL_DELEGATE
:
220 dwFlags
|= SECURITY_DELEGATION
;
223 if (Connection
->QOS
->qos
->IdentityTracking
== RPC_C_QOS_IDENTITY_DYNAMIC
)
224 dwFlags
|= SECURITY_CONTEXT_TRACKING
;
226 pipe
= CreateFileA(pname
, GENERIC_READ
|GENERIC_WRITE
, 0, NULL
,
227 OPEN_EXISTING
, dwFlags
, 0);
228 if (pipe
!= INVALID_HANDLE_VALUE
) break;
229 err
= GetLastError();
230 if (err
== ERROR_PIPE_BUSY
) {
231 TRACE("connection failed, error=%x\n", err
);
232 return RPC_S_SERVER_TOO_BUSY
;
234 if (!wait
|| !WaitNamedPipeA(pname
, NMPWAIT_WAIT_FOREVER
)) {
235 err
= GetLastError();
236 WARN("connection failed, error=%x\n", err
);
237 return RPC_S_SERVER_UNAVAILABLE
;
242 /* pipe is connected; change to message-read mode. */
243 dwMode
= PIPE_READMODE_MESSAGE
;
244 SetNamedPipeHandleState(pipe
, &dwMode
, NULL
, NULL
);
250 static RPC_STATUS
rpcrt4_ncalrpc_open(RpcConnection
* Connection
)
252 RpcConnection_np
*npc
= (RpcConnection_np
*) Connection
;
253 static const char prefix
[] = "\\\\.\\pipe\\lrpc\\";
257 /* already connected? */
261 /* protseq=ncalrpc: supposed to use NT LPC ports,
262 * but we'll implement it with named pipes for now */
263 pname
= I_RpcAllocate(strlen(prefix
) + strlen(Connection
->Endpoint
) + 1);
264 strcat(strcpy(pname
, prefix
), Connection
->Endpoint
);
265 r
= rpcrt4_conn_open_pipe(Connection
, pname
, TRUE
);
271 static RPC_STATUS
rpcrt4_protseq_ncalrpc_open_endpoint(RpcServerProtseq
* protseq
, const char *endpoint
)
273 static const char prefix
[] = "\\\\.\\pipe\\lrpc\\";
276 RpcConnection
*Connection
;
277 char generated_endpoint
[22];
281 static LONG lrpc_nameless_id
;
282 DWORD process_id
= GetCurrentProcessId();
283 ULONG id
= InterlockedIncrement(&lrpc_nameless_id
);
284 snprintf(generated_endpoint
, sizeof(generated_endpoint
),
285 "LRPC%08x.%08x", process_id
, id
);
286 endpoint
= generated_endpoint
;
289 r
= RPCRT4_CreateConnection(&Connection
, TRUE
, protseq
->Protseq
, NULL
,
290 endpoint
, NULL
, NULL
, NULL
, NULL
);
294 /* protseq=ncalrpc: supposed to use NT LPC ports,
295 * but we'll implement it with named pipes for now */
296 pname
= I_RpcAllocate(strlen(prefix
) + strlen(Connection
->Endpoint
) + 1);
297 strcat(strcpy(pname
, prefix
), Connection
->Endpoint
);
298 r
= rpcrt4_conn_create_pipe(Connection
, pname
);
301 EnterCriticalSection(&protseq
->cs
);
302 Connection
->Next
= protseq
->conn
;
303 protseq
->conn
= Connection
;
304 LeaveCriticalSection(&protseq
->cs
);
309 static RPC_STATUS
rpcrt4_ncacn_np_open(RpcConnection
* Connection
)
311 RpcConnection_np
*npc
= (RpcConnection_np
*) Connection
;
312 static const char prefix
[] = "\\\\.";
316 /* already connected? */
320 /* protseq=ncacn_np: named pipes */
321 pname
= I_RpcAllocate(strlen(prefix
) + strlen(Connection
->Endpoint
) + 1);
322 strcat(strcpy(pname
, prefix
), Connection
->Endpoint
);
323 r
= rpcrt4_conn_open_pipe(Connection
, pname
, FALSE
);
329 static RPC_STATUS
rpcrt4_protseq_ncacn_np_open_endpoint(RpcServerProtseq
*protseq
, const char *endpoint
)
331 static const char prefix
[] = "\\\\.";
334 RpcConnection
*Connection
;
335 char generated_endpoint
[21];
339 static LONG np_nameless_id
;
340 DWORD process_id
= GetCurrentProcessId();
341 ULONG id
= InterlockedExchangeAdd(&np_nameless_id
, 1 );
342 snprintf(generated_endpoint
, sizeof(generated_endpoint
),
343 "\\\\pipe\\\\%08x.%03x", process_id
, id
);
344 endpoint
= generated_endpoint
;
347 r
= RPCRT4_CreateConnection(&Connection
, TRUE
, protseq
->Protseq
, NULL
,
348 endpoint
, NULL
, NULL
, NULL
, NULL
);
352 /* protseq=ncacn_np: named pipes */
353 pname
= I_RpcAllocate(strlen(prefix
) + strlen(Connection
->Endpoint
) + 1);
354 strcat(strcpy(pname
, prefix
), Connection
->Endpoint
);
355 r
= rpcrt4_conn_create_pipe(Connection
, pname
);
358 EnterCriticalSection(&protseq
->cs
);
359 Connection
->Next
= protseq
->conn
;
360 protseq
->conn
= Connection
;
361 LeaveCriticalSection(&protseq
->cs
);
366 static void rpcrt4_conn_np_handoff(RpcConnection_np
*old_npc
, RpcConnection_np
*new_npc
)
368 /* because of the way named pipes work, we'll transfer the connected pipe
369 * to the child, then reopen the server binding to continue listening */
371 new_npc
->pipe
= old_npc
->pipe
;
372 new_npc
->listen_thread
= old_npc
->listen_thread
;
374 old_npc
->listen_thread
= 0;
375 old_npc
->listening
= FALSE
;
378 static RPC_STATUS
rpcrt4_ncacn_np_handoff(RpcConnection
*old_conn
, RpcConnection
*new_conn
)
382 static const char prefix
[] = "\\\\.";
384 rpcrt4_conn_np_handoff((RpcConnection_np
*)old_conn
, (RpcConnection_np
*)new_conn
);
386 pname
= I_RpcAllocate(strlen(prefix
) + strlen(old_conn
->Endpoint
) + 1);
387 strcat(strcpy(pname
, prefix
), old_conn
->Endpoint
);
388 status
= rpcrt4_conn_create_pipe(old_conn
, pname
);
394 static RPC_STATUS
rpcrt4_ncalrpc_handoff(RpcConnection
*old_conn
, RpcConnection
*new_conn
)
398 static const char prefix
[] = "\\\\.\\pipe\\lrpc\\";
400 TRACE("%s\n", old_conn
->Endpoint
);
402 rpcrt4_conn_np_handoff((RpcConnection_np
*)old_conn
, (RpcConnection_np
*)new_conn
);
404 pname
= I_RpcAllocate(strlen(prefix
) + strlen(old_conn
->Endpoint
) + 1);
405 strcat(strcpy(pname
, prefix
), old_conn
->Endpoint
);
406 status
= rpcrt4_conn_create_pipe(old_conn
, pname
);
412 static int rpcrt4_conn_np_read(RpcConnection
*Connection
,
413 void *buffer
, unsigned int count
)
415 RpcConnection_np
*npc
= (RpcConnection_np
*) Connection
;
418 unsigned int bytes_left
= count
;
423 ret
= ReadFile(npc
->pipe
, buf
, bytes_left
, &bytes_read
, NULL
);
424 if (!ret
&& GetLastError() == ERROR_MORE_DATA
)
426 if (!ret
|| !bytes_read
)
428 bytes_left
-= bytes_read
;
431 return ret
? count
: -1;
434 static int rpcrt4_conn_np_write(RpcConnection
*Connection
,
435 const void *buffer
, unsigned int count
)
437 RpcConnection_np
*npc
= (RpcConnection_np
*) Connection
;
438 const char *buf
= buffer
;
440 unsigned int bytes_left
= count
;
445 ret
= WriteFile(npc
->pipe
, buf
, bytes_left
, &bytes_written
, NULL
);
446 if (!ret
|| !bytes_written
)
448 bytes_left
-= bytes_written
;
449 buf
+= bytes_written
;
451 return ret
? count
: -1;
454 static int rpcrt4_conn_np_close(RpcConnection
*Connection
)
456 RpcConnection_np
*npc
= (RpcConnection_np
*) Connection
;
458 FlushFileBuffers(npc
->pipe
);
459 CloseHandle(npc
->pipe
);
462 if (npc
->listen_thread
) {
463 CloseHandle(npc
->listen_thread
);
464 npc
->listen_thread
= 0;
469 static void rpcrt4_conn_np_cancel_call(RpcConnection
*Connection
)
471 /* FIXME: implement when named pipe writes use overlapped I/O */
474 static int rpcrt4_conn_np_wait_for_incoming_data(RpcConnection
*Connection
)
476 /* FIXME: implement when named pipe writes use overlapped I/O */
480 static size_t rpcrt4_ncacn_np_get_top_of_tower(unsigned char *tower_data
,
481 const char *networkaddr
,
482 const char *endpoint
)
484 twr_empty_floor_t
*smb_floor
;
485 twr_empty_floor_t
*nb_floor
;
487 size_t networkaddr_size
;
488 size_t endpoint_size
;
490 TRACE("(%p, %s, %s)\n", tower_data
, networkaddr
, endpoint
);
492 networkaddr_size
= networkaddr
? strlen(networkaddr
) + 1 : 1;
493 endpoint_size
= endpoint
? strlen(endpoint
) + 1 : 1;
494 size
= sizeof(*smb_floor
) + endpoint_size
+ sizeof(*nb_floor
) + networkaddr_size
;
499 smb_floor
= (twr_empty_floor_t
*)tower_data
;
501 tower_data
+= sizeof(*smb_floor
);
503 smb_floor
->count_lhs
= sizeof(smb_floor
->protid
);
504 smb_floor
->protid
= EPM_PROTOCOL_SMB
;
505 smb_floor
->count_rhs
= endpoint_size
;
508 memcpy(tower_data
, endpoint
, endpoint_size
);
511 tower_data
+= endpoint_size
;
513 nb_floor
= (twr_empty_floor_t
*)tower_data
;
515 tower_data
+= sizeof(*nb_floor
);
517 nb_floor
->count_lhs
= sizeof(nb_floor
->protid
);
518 nb_floor
->protid
= EPM_PROTOCOL_NETBIOS
;
519 nb_floor
->count_rhs
= networkaddr_size
;
522 memcpy(tower_data
, networkaddr
, networkaddr_size
);
529 static RPC_STATUS
rpcrt4_ncacn_np_parse_top_of_tower(const unsigned char *tower_data
,
534 const twr_empty_floor_t
*smb_floor
= (const twr_empty_floor_t
*)tower_data
;
535 const twr_empty_floor_t
*nb_floor
;
537 TRACE("(%p, %d, %p, %p)\n", tower_data
, (int)tower_size
, networkaddr
, endpoint
);
539 if (tower_size
< sizeof(*smb_floor
))
540 return EPT_S_NOT_REGISTERED
;
542 tower_data
+= sizeof(*smb_floor
);
543 tower_size
-= sizeof(*smb_floor
);
545 if ((smb_floor
->count_lhs
!= sizeof(smb_floor
->protid
)) ||
546 (smb_floor
->protid
!= EPM_PROTOCOL_SMB
) ||
547 (smb_floor
->count_rhs
> tower_size
) ||
548 (tower_data
[smb_floor
->count_rhs
- 1] != '\0'))
549 return EPT_S_NOT_REGISTERED
;
553 *endpoint
= I_RpcAllocate(smb_floor
->count_rhs
);
555 return RPC_S_OUT_OF_RESOURCES
;
556 memcpy(*endpoint
, tower_data
, smb_floor
->count_rhs
);
558 tower_data
+= smb_floor
->count_rhs
;
559 tower_size
-= smb_floor
->count_rhs
;
561 if (tower_size
< sizeof(*nb_floor
))
562 return EPT_S_NOT_REGISTERED
;
564 nb_floor
= (const twr_empty_floor_t
*)tower_data
;
566 tower_data
+= sizeof(*nb_floor
);
567 tower_size
-= sizeof(*nb_floor
);
569 if ((nb_floor
->count_lhs
!= sizeof(nb_floor
->protid
)) ||
570 (nb_floor
->protid
!= EPM_PROTOCOL_NETBIOS
) ||
571 (nb_floor
->count_rhs
> tower_size
) ||
572 (tower_data
[nb_floor
->count_rhs
- 1] != '\0'))
573 return EPT_S_NOT_REGISTERED
;
577 *networkaddr
= I_RpcAllocate(nb_floor
->count_rhs
);
582 I_RpcFree(*endpoint
);
585 return RPC_S_OUT_OF_RESOURCES
;
587 memcpy(*networkaddr
, tower_data
, nb_floor
->count_rhs
);
593 static RPC_STATUS
rpcrt4_conn_np_impersonate_client(RpcConnection
*conn
)
595 RpcConnection_np
*npc
= (RpcConnection_np
*)conn
;
598 TRACE("(%p)\n", conn
);
600 if (conn
->AuthInfo
&& SecIsValidHandle(&conn
->ctx
))
601 return RPCRT4_default_impersonate_client(conn
);
603 ret
= ImpersonateNamedPipeClient(npc
->pipe
);
606 DWORD error
= GetLastError();
607 WARN("ImpersonateNamedPipeClient failed with error %u\n", error
);
610 case ERROR_CANNOT_IMPERSONATE
:
611 return RPC_S_NO_CONTEXT_AVAILABLE
;
617 static RPC_STATUS
rpcrt4_conn_np_revert_to_self(RpcConnection
*conn
)
621 TRACE("(%p)\n", conn
);
623 if (conn
->AuthInfo
&& SecIsValidHandle(&conn
->ctx
))
624 return RPCRT4_default_revert_to_self(conn
);
626 ret
= RevertToSelf();
629 WARN("RevertToSelf failed with error %u\n", GetLastError());
630 return RPC_S_NO_CONTEXT_AVAILABLE
;
635 typedef struct _RpcServerProtseq_np
637 RpcServerProtseq common
;
639 } RpcServerProtseq_np
;
641 static RpcServerProtseq
*rpcrt4_protseq_np_alloc(void)
643 RpcServerProtseq_np
*ps
= HeapAlloc(GetProcessHeap(), 0, sizeof(*ps
));
645 ps
->mgr_event
= CreateEventW(NULL
, FALSE
, FALSE
, NULL
);
649 static void rpcrt4_protseq_np_signal_state_changed(RpcServerProtseq
*protseq
)
651 RpcServerProtseq_np
*npps
= CONTAINING_RECORD(protseq
, RpcServerProtseq_np
, common
);
652 SetEvent(npps
->mgr_event
);
655 static void *rpcrt4_protseq_np_get_wait_array(RpcServerProtseq
*protseq
, void *prev_array
, unsigned int *count
)
657 HANDLE
*objs
= prev_array
;
658 RpcConnection_np
*conn
;
659 RpcServerProtseq_np
*npps
= CONTAINING_RECORD(protseq
, RpcServerProtseq_np
, common
);
661 EnterCriticalSection(&protseq
->cs
);
663 /* open and count connections */
665 conn
= CONTAINING_RECORD(protseq
->conn
, RpcConnection_np
, common
);
667 rpcrt4_conn_listen_pipe(conn
);
668 if (conn
->listen_thread
)
670 conn
= CONTAINING_RECORD(conn
->common
.Next
, RpcConnection_np
, common
);
673 /* make array of connections */
675 objs
= HeapReAlloc(GetProcessHeap(), 0, objs
, *count
*sizeof(HANDLE
));
677 objs
= HeapAlloc(GetProcessHeap(), 0, *count
*sizeof(HANDLE
));
680 ERR("couldn't allocate objs\n");
681 LeaveCriticalSection(&protseq
->cs
);
685 objs
[0] = npps
->mgr_event
;
687 conn
= CONTAINING_RECORD(protseq
->conn
, RpcConnection_np
, common
);
689 if ((objs
[*count
] = conn
->listen_thread
))
691 conn
= CONTAINING_RECORD(conn
->common
.Next
, RpcConnection_np
, common
);
693 LeaveCriticalSection(&protseq
->cs
);
697 static void rpcrt4_protseq_np_free_wait_array(RpcServerProtseq
*protseq
, void *array
)
699 HeapFree(GetProcessHeap(), 0, array
);
702 static int rpcrt4_protseq_np_wait_for_new_connection(RpcServerProtseq
*protseq
, unsigned int count
, void *wait_array
)
705 HANDLE
*objs
= wait_array
;
707 RpcConnection
*cconn
;
708 RpcConnection_np
*conn
;
715 /* an alertable wait isn't strictly necessary, but due to our
716 * overlapped I/O implementation in Wine we need to free some memory
717 * by the file user APC being called, even if no completion routine was
718 * specified at the time of starting the async operation */
719 res
= WaitForMultipleObjectsEx(count
, objs
, FALSE
, INFINITE
, TRUE
);
720 } while (res
== WAIT_IO_COMPLETION
);
722 if (res
== WAIT_OBJECT_0
)
724 else if (res
== WAIT_FAILED
)
726 ERR("wait failed with error %d\n", GetLastError());
731 b_handle
= objs
[res
- WAIT_OBJECT_0
];
732 /* find which connection got a RPC */
733 EnterCriticalSection(&protseq
->cs
);
734 conn
= CONTAINING_RECORD(protseq
->conn
, RpcConnection_np
, common
);
736 if (b_handle
== conn
->listen_thread
) break;
737 conn
= CONTAINING_RECORD(conn
->common
.Next
, RpcConnection_np
, common
);
743 if (GetExitCodeThread(conn
->listen_thread
, &exit_code
) && exit_code
== RPC_S_OK
)
744 RPCRT4_SpawnConnection(&cconn
, &conn
->common
);
745 CloseHandle(conn
->listen_thread
);
746 conn
->listen_thread
= 0;
749 ERR("failed to locate connection for handle %p\n", b_handle
);
750 LeaveCriticalSection(&protseq
->cs
);
753 RPCRT4_new_client(cconn
);
760 static size_t rpcrt4_ncalrpc_get_top_of_tower(unsigned char *tower_data
,
761 const char *networkaddr
,
762 const char *endpoint
)
764 twr_empty_floor_t
*pipe_floor
;
766 size_t endpoint_size
;
768 TRACE("(%p, %s, %s)\n", tower_data
, networkaddr
, endpoint
);
770 endpoint_size
= strlen(endpoint
) + 1;
771 size
= sizeof(*pipe_floor
) + endpoint_size
;
776 pipe_floor
= (twr_empty_floor_t
*)tower_data
;
778 tower_data
+= sizeof(*pipe_floor
);
780 pipe_floor
->count_lhs
= sizeof(pipe_floor
->protid
);
781 pipe_floor
->protid
= EPM_PROTOCOL_PIPE
;
782 pipe_floor
->count_rhs
= endpoint_size
;
784 memcpy(tower_data
, endpoint
, endpoint_size
);
789 static RPC_STATUS
rpcrt4_ncalrpc_parse_top_of_tower(const unsigned char *tower_data
,
794 const twr_empty_floor_t
*pipe_floor
= (const twr_empty_floor_t
*)tower_data
;
796 TRACE("(%p, %d, %p, %p)\n", tower_data
, (int)tower_size
, networkaddr
, endpoint
);
798 if (tower_size
< sizeof(*pipe_floor
))
799 return EPT_S_NOT_REGISTERED
;
801 tower_data
+= sizeof(*pipe_floor
);
802 tower_size
-= sizeof(*pipe_floor
);
804 if ((pipe_floor
->count_lhs
!= sizeof(pipe_floor
->protid
)) ||
805 (pipe_floor
->protid
!= EPM_PROTOCOL_PIPE
) ||
806 (pipe_floor
->count_rhs
> tower_size
) ||
807 (tower_data
[pipe_floor
->count_rhs
- 1] != '\0'))
808 return EPT_S_NOT_REGISTERED
;
815 *endpoint
= I_RpcAllocate(pipe_floor
->count_rhs
);
817 return RPC_S_OUT_OF_RESOURCES
;
818 memcpy(*endpoint
, tower_data
, pipe_floor
->count_rhs
);
824 static BOOL
rpcrt4_ncalrpc_is_authorized(RpcConnection
*conn
)
829 static RPC_STATUS
rpcrt4_ncalrpc_authorize(RpcConnection
*conn
, BOOL first_time
,
830 unsigned char *in_buffer
,
831 unsigned int in_size
,
832 unsigned char *out_buffer
,
833 unsigned int *out_size
)
835 /* since this protocol is local to the machine there is no need to
836 * authenticate the caller */
841 static RPC_STATUS
rpcrt4_ncalrpc_secure_packet(RpcConnection
*conn
,
842 enum secure_packet_direction dir
,
843 RpcPktHdr
*hdr
, unsigned int hdr_size
,
844 unsigned char *stub_data
, unsigned int stub_data_size
,
845 RpcAuthVerifier
*auth_hdr
,
846 unsigned char *auth_value
, unsigned int auth_value_size
)
848 /* since this protocol is local to the machine there is no need to secure
853 static RPC_STATUS
rpcrt4_ncalrpc_inquire_auth_client(
854 RpcConnection
*conn
, RPC_AUTHZ_HANDLE
*privs
, RPC_WSTR
*server_princ_name
,
855 ULONG
*authn_level
, ULONG
*authn_svc
, ULONG
*authz_svc
, ULONG flags
)
857 TRACE("(%p, %p, %p, %p, %p, %p, 0x%x)\n", conn
, privs
,
858 server_princ_name
, authn_level
, authn_svc
, authz_svc
, flags
);
862 FIXME("privs not implemented\n");
865 if (server_princ_name
)
867 FIXME("server_princ_name not implemented\n");
868 *server_princ_name
= NULL
;
870 if (authn_level
) *authn_level
= RPC_C_AUTHN_LEVEL_PKT_PRIVACY
;
871 if (authn_svc
) *authn_svc
= RPC_C_AUTHN_WINNT
;
874 FIXME("authorization service not implemented\n");
875 *authz_svc
= RPC_C_AUTHZ_NONE
;
878 FIXME("flags 0x%x not implemented\n", flags
);
883 /**** ncacn_ip_tcp support ****/
885 static size_t rpcrt4_ip_tcp_get_top_of_tower(unsigned char *tower_data
,
886 const char *networkaddr
,
887 unsigned char tcp_protid
,
888 const char *endpoint
)
890 twr_tcp_floor_t
*tcp_floor
;
891 twr_ipv4_floor_t
*ipv4_floor
;
893 struct addrinfo hints
;
895 size_t size
= sizeof(*tcp_floor
) + sizeof(*ipv4_floor
);
897 TRACE("(%p, %s, %s)\n", tower_data
, networkaddr
, endpoint
);
902 tcp_floor
= (twr_tcp_floor_t
*)tower_data
;
903 tower_data
+= sizeof(*tcp_floor
);
905 ipv4_floor
= (twr_ipv4_floor_t
*)tower_data
;
907 tcp_floor
->count_lhs
= sizeof(tcp_floor
->protid
);
908 tcp_floor
->protid
= tcp_protid
;
909 tcp_floor
->count_rhs
= sizeof(tcp_floor
->port
);
911 ipv4_floor
->count_lhs
= sizeof(ipv4_floor
->protid
);
912 ipv4_floor
->protid
= EPM_PROTOCOL_IP
;
913 ipv4_floor
->count_rhs
= sizeof(ipv4_floor
->ipv4addr
);
915 hints
.ai_flags
= AI_NUMERICHOST
;
916 /* FIXME: only support IPv4 at the moment. how is IPv6 represented by the EPM? */
917 hints
.ai_family
= PF_INET
;
918 hints
.ai_socktype
= SOCK_STREAM
;
919 hints
.ai_protocol
= IPPROTO_TCP
;
920 hints
.ai_addrlen
= 0;
921 hints
.ai_addr
= NULL
;
922 hints
.ai_canonname
= NULL
;
923 hints
.ai_next
= NULL
;
925 ret
= getaddrinfo(networkaddr
, endpoint
, &hints
, &ai
);
928 ret
= getaddrinfo("0.0.0.0", endpoint
, &hints
, &ai
);
931 ERR("getaddrinfo failed: %s\n", gai_strerror(ret
));
936 if (ai
->ai_family
== PF_INET
)
938 const struct sockaddr_in
*sin
= (const struct sockaddr_in
*)ai
->ai_addr
;
939 tcp_floor
->port
= sin
->sin_port
;
940 ipv4_floor
->ipv4addr
= sin
->sin_addr
.s_addr
;
944 ERR("unexpected protocol family %d\n", ai
->ai_family
);
953 static RPC_STATUS
rpcrt4_ip_tcp_parse_top_of_tower(const unsigned char *tower_data
,
956 unsigned char tcp_protid
,
959 const twr_tcp_floor_t
*tcp_floor
= (const twr_tcp_floor_t
*)tower_data
;
960 const twr_ipv4_floor_t
*ipv4_floor
;
961 struct in_addr in_addr
;
963 TRACE("(%p, %d, %p, %p)\n", tower_data
, (int)tower_size
, networkaddr
, endpoint
);
965 if (tower_size
< sizeof(*tcp_floor
))
966 return EPT_S_NOT_REGISTERED
;
968 tower_data
+= sizeof(*tcp_floor
);
969 tower_size
-= sizeof(*tcp_floor
);
971 if (tower_size
< sizeof(*ipv4_floor
))
972 return EPT_S_NOT_REGISTERED
;
974 ipv4_floor
= (const twr_ipv4_floor_t
*)tower_data
;
976 if ((tcp_floor
->count_lhs
!= sizeof(tcp_floor
->protid
)) ||
977 (tcp_floor
->protid
!= tcp_protid
) ||
978 (tcp_floor
->count_rhs
!= sizeof(tcp_floor
->port
)) ||
979 (ipv4_floor
->count_lhs
!= sizeof(ipv4_floor
->protid
)) ||
980 (ipv4_floor
->protid
!= EPM_PROTOCOL_IP
) ||
981 (ipv4_floor
->count_rhs
!= sizeof(ipv4_floor
->ipv4addr
)))
982 return EPT_S_NOT_REGISTERED
;
986 *endpoint
= I_RpcAllocate(6 /* sizeof("65535") + 1 */);
988 return RPC_S_OUT_OF_RESOURCES
;
989 sprintf(*endpoint
, "%u", ntohs(tcp_floor
->port
));
994 *networkaddr
= I_RpcAllocate(INET_ADDRSTRLEN
);
999 I_RpcFree(*endpoint
);
1002 return RPC_S_OUT_OF_RESOURCES
;
1004 in_addr
.s_addr
= ipv4_floor
->ipv4addr
;
1005 if (!inet_ntop(AF_INET
, &in_addr
, *networkaddr
, INET_ADDRSTRLEN
))
1007 ERR("inet_ntop: %s\n", strerror(errno
));
1008 I_RpcFree(*networkaddr
);
1009 *networkaddr
= NULL
;
1012 I_RpcFree(*endpoint
);
1015 return EPT_S_NOT_REGISTERED
;
1022 typedef struct _RpcConnection_tcp
1024 RpcConnection common
;
1026 #ifdef HAVE_SOCKETPAIR
1030 HANDLE cancel_event
;
1032 } RpcConnection_tcp
;
1034 #ifdef HAVE_SOCKETPAIR
1036 static BOOL
rpcrt4_sock_wait_init(RpcConnection_tcp
*tcpc
)
1038 if (socketpair(PF_UNIX
, SOCK_STREAM
, 0, tcpc
->cancel_fds
) < 0)
1040 ERR("socketpair() failed: %s\n", strerror(errno
));
1046 static BOOL
rpcrt4_sock_wait_for_recv(RpcConnection_tcp
*tcpc
)
1048 struct pollfd pfds
[2];
1049 pfds
[0].fd
= tcpc
->sock
;
1050 pfds
[0].events
= POLLIN
;
1051 pfds
[1].fd
= tcpc
->cancel_fds
[0];
1052 pfds
[1].events
= POLLIN
;
1053 if (poll(pfds
, 2, -1 /* infinite */) == -1 && errno
!= EINTR
)
1055 ERR("poll() failed: %s\n", strerror(errno
));
1058 if (pfds
[1].revents
& POLLIN
) /* canceled */
1061 read(pfds
[1].fd
, &dummy
, sizeof(dummy
));
1067 static BOOL
rpcrt4_sock_wait_for_send(RpcConnection_tcp
*tcpc
)
1070 pfd
.fd
= tcpc
->sock
;
1071 pfd
.events
= POLLOUT
;
1072 if (poll(&pfd
, 1, -1 /* infinite */) == -1 && errno
!= EINTR
)
1074 ERR("poll() failed: %s\n", strerror(errno
));
1080 static void rpcrt4_sock_wait_cancel(RpcConnection_tcp
*tcpc
)
1084 write(tcpc
->cancel_fds
[1], &dummy
, 1);
1087 static void rpcrt4_sock_wait_destroy(RpcConnection_tcp
*tcpc
)
1089 close(tcpc
->cancel_fds
[0]);
1090 close(tcpc
->cancel_fds
[1]);
1093 #else /* HAVE_SOCKETPAIR */
1095 static BOOL
rpcrt4_sock_wait_init(RpcConnection_tcp
*tcpc
)
1097 static BOOL wsa_inited
;
1101 WSAStartup(MAKEWORD(2, 2), &wsadata
);
1102 /* Note: WSAStartup can be called more than once so we don't bother with
1103 * making accesses to wsa_inited thread-safe */
1106 tcpc
->sock_event
= CreateEventW(NULL
, FALSE
, FALSE
, NULL
);
1107 tcpc
->cancel_event
= CreateEventW(NULL
, FALSE
, FALSE
, NULL
);
1108 if (!tcpc
->sock_event
|| !tcpc
->cancel_event
)
1110 ERR("event creation failed\n");
1111 if (tcpc
->sock_event
) CloseHandle(tcpc
->sock_event
);
1117 static BOOL
rpcrt4_sock_wait_for_recv(RpcConnection_tcp
*tcpc
)
1119 HANDLE wait_handles
[2];
1121 if (WSAEventSelect(tcpc
->sock
, tcpc
->sock_event
, FD_READ
| FD_CLOSE
) == SOCKET_ERROR
)
1123 ERR("WSAEventSelect() failed with error %d\n", WSAGetLastError());
1126 wait_handles
[0] = tcpc
->sock_event
;
1127 wait_handles
[1] = tcpc
->cancel_event
;
1128 res
= WaitForMultipleObjects(2, wait_handles
, FALSE
, INFINITE
);
1133 case WAIT_OBJECT_0
+ 1:
1136 ERR("WaitForMultipleObjects() failed with error %d\n", GetLastError());
1141 static BOOL
rpcrt4_sock_wait_for_send(RpcConnection_tcp
*tcpc
)
1144 if (WSAEventSelect(tcpc
->sock
, tcpc
->sock_event
, FD_WRITE
| FD_CLOSE
) == SOCKET_ERROR
)
1146 ERR("WSAEventSelect() failed with error %d\n", WSAGetLastError());
1149 res
= WaitForSingleObject(tcpc
->sock_event
, INFINITE
);
1155 ERR("WaitForMultipleObjects() failed with error %d\n", GetLastError());
1160 static void rpcrt4_sock_wait_cancel(RpcConnection_tcp
*tcpc
)
1162 SetEvent(tcpc
->cancel_event
);
1165 static void rpcrt4_sock_wait_destroy(RpcConnection_tcp
*tcpc
)
1167 CloseHandle(tcpc
->sock_event
);
1168 CloseHandle(tcpc
->cancel_event
);
1173 static RpcConnection
*rpcrt4_conn_tcp_alloc(void)
1175 RpcConnection_tcp
*tcpc
;
1176 tcpc
= HeapAlloc(GetProcessHeap(), 0, sizeof(RpcConnection_tcp
));
1180 if (!rpcrt4_sock_wait_init(tcpc
))
1182 HeapFree(GetProcessHeap(), 0, tcpc
);
1185 return &tcpc
->common
;
1188 static RPC_STATUS
rpcrt4_ncacn_ip_tcp_open(RpcConnection
* Connection
)
1190 RpcConnection_tcp
*tcpc
= (RpcConnection_tcp
*) Connection
;
1193 struct addrinfo
*ai
;
1194 struct addrinfo
*ai_cur
;
1195 struct addrinfo hints
;
1197 TRACE("(%s, %s)\n", Connection
->NetworkAddr
, Connection
->Endpoint
);
1199 if (tcpc
->sock
!= -1)
1203 hints
.ai_family
= PF_UNSPEC
;
1204 hints
.ai_socktype
= SOCK_STREAM
;
1205 hints
.ai_protocol
= IPPROTO_TCP
;
1206 hints
.ai_addrlen
= 0;
1207 hints
.ai_addr
= NULL
;
1208 hints
.ai_canonname
= NULL
;
1209 hints
.ai_next
= NULL
;
1211 ret
= getaddrinfo(Connection
->NetworkAddr
, Connection
->Endpoint
, &hints
, &ai
);
1214 ERR("getaddrinfo for %s:%s failed: %s\n", Connection
->NetworkAddr
,
1215 Connection
->Endpoint
, gai_strerror(ret
));
1216 return RPC_S_SERVER_UNAVAILABLE
;
1219 for (ai_cur
= ai
; ai_cur
; ai_cur
= ai_cur
->ai_next
)
1224 if (ai_cur
->ai_family
!= AF_INET
&& ai_cur
->ai_family
!= AF_INET6
)
1226 TRACE("skipping non-IP/IPv6 address family\n");
1234 getnameinfo(ai_cur
->ai_addr
, ai_cur
->ai_addrlen
,
1235 host
, sizeof(host
), service
, sizeof(service
),
1236 NI_NUMERICHOST
| NI_NUMERICSERV
);
1237 TRACE("trying %s:%s\n", host
, service
);
1240 sock
= socket(ai_cur
->ai_family
, ai_cur
->ai_socktype
, ai_cur
->ai_protocol
);
1243 WARN("socket() failed: %s\n", strerror(errno
));
1247 if (0>connect(sock
, ai_cur
->ai_addr
, ai_cur
->ai_addrlen
))
1249 WARN("connect() failed: %s\n", strerror(errno
));
1254 /* RPC depends on having minimal latency so disable the Nagle algorithm */
1256 setsockopt(sock
, SOL_TCP
, TCP_NODELAY
, (char *)&val
, sizeof(val
));
1258 ioctlsocket(sock
, FIONBIO
, &nonblocking
);
1263 TRACE("connected\n");
1268 ERR("couldn't connect to %s:%s\n", Connection
->NetworkAddr
, Connection
->Endpoint
);
1269 return RPC_S_SERVER_UNAVAILABLE
;
1272 static RPC_STATUS
rpcrt4_protseq_ncacn_ip_tcp_open_endpoint(RpcServerProtseq
*protseq
, const char *endpoint
)
1274 RPC_STATUS status
= RPC_S_CANT_CREATE_ENDPOINT
;
1277 struct addrinfo
*ai
;
1278 struct addrinfo
*ai_cur
;
1279 struct addrinfo hints
;
1280 RpcConnection
*first_connection
= NULL
;
1282 TRACE("(%p, %s)\n", protseq
, endpoint
);
1284 hints
.ai_flags
= AI_PASSIVE
/* for non-localhost addresses */;
1285 hints
.ai_family
= PF_UNSPEC
;
1286 hints
.ai_socktype
= SOCK_STREAM
;
1287 hints
.ai_protocol
= IPPROTO_TCP
;
1288 hints
.ai_addrlen
= 0;
1289 hints
.ai_addr
= NULL
;
1290 hints
.ai_canonname
= NULL
;
1291 hints
.ai_next
= NULL
;
1293 ret
= getaddrinfo(NULL
, endpoint
? endpoint
: "0", &hints
, &ai
);
1296 ERR("getaddrinfo for port %s failed: %s\n", endpoint
,
1298 if ((ret
== EAI_SERVICE
) || (ret
== EAI_NONAME
))
1299 return RPC_S_INVALID_ENDPOINT_FORMAT
;
1300 return RPC_S_CANT_CREATE_ENDPOINT
;
1303 for (ai_cur
= ai
; ai_cur
; ai_cur
= ai_cur
->ai_next
)
1305 RpcConnection_tcp
*tcpc
;
1306 RPC_STATUS create_status
;
1307 struct sockaddr_storage sa
;
1309 char service
[NI_MAXSERV
];
1312 if (ai_cur
->ai_family
!= AF_INET
&& ai_cur
->ai_family
!= AF_INET6
)
1314 TRACE("skipping non-IP/IPv6 address family\n");
1321 getnameinfo(ai_cur
->ai_addr
, ai_cur
->ai_addrlen
,
1322 host
, sizeof(host
), service
, sizeof(service
),
1323 NI_NUMERICHOST
| NI_NUMERICSERV
);
1324 TRACE("trying %s:%s\n", host
, service
);
1327 sock
= socket(ai_cur
->ai_family
, ai_cur
->ai_socktype
, ai_cur
->ai_protocol
);
1330 WARN("socket() failed: %s\n", strerror(errno
));
1331 status
= RPC_S_CANT_CREATE_ENDPOINT
;
1335 ret
= bind(sock
, ai_cur
->ai_addr
, ai_cur
->ai_addrlen
);
1338 WARN("bind failed: %s\n", strerror(errno
));
1340 if (errno
== EADDRINUSE
)
1341 status
= RPC_S_DUPLICATE_ENDPOINT
;
1343 status
= RPC_S_CANT_CREATE_ENDPOINT
;
1347 sa_len
= sizeof(sa
);
1348 if (getsockname(sock
, (struct sockaddr
*)&sa
, &sa_len
))
1350 WARN("getsockname() failed: %s\n", strerror(errno
));
1352 status
= RPC_S_CANT_CREATE_ENDPOINT
;
1356 ret
= getnameinfo((struct sockaddr
*)&sa
, sa_len
,
1357 NULL
, 0, service
, sizeof(service
),
1361 WARN("getnameinfo failed: %s\n", gai_strerror(ret
));
1363 status
= RPC_S_CANT_CREATE_ENDPOINT
;
1367 create_status
= RPCRT4_CreateConnection((RpcConnection
**)&tcpc
, TRUE
,
1368 protseq
->Protseq
, NULL
,
1369 service
, NULL
, NULL
, NULL
, NULL
);
1370 if (create_status
!= RPC_S_OK
)
1373 status
= create_status
;
1378 ret
= listen(sock
, protseq
->MaxCalls
);
1381 WARN("listen failed: %s\n", strerror(errno
));
1382 RPCRT4_ReleaseConnection(&tcpc
->common
);
1383 status
= RPC_S_OUT_OF_RESOURCES
;
1386 /* need a non-blocking socket, otherwise accept() has a potential
1387 * race-condition (poll() says it is readable, connection drops,
1388 * and accept() blocks until the next connection comes...)
1391 ret
= ioctlsocket(sock
, FIONBIO
, &nonblocking
);
1394 WARN("couldn't make socket non-blocking, error %d\n", ret
);
1395 RPCRT4_ReleaseConnection(&tcpc
->common
);
1396 status
= RPC_S_OUT_OF_RESOURCES
;
1400 tcpc
->common
.Next
= first_connection
;
1401 first_connection
= &tcpc
->common
;
1403 /* since IPv4 and IPv6 share the same port space, we only need one
1404 * successful bind to listen for both */
1410 /* if at least one connection was created for an endpoint then
1412 if (first_connection
)
1414 RpcConnection
*conn
;
1416 /* find last element in list */
1417 for (conn
= first_connection
; conn
->Next
; conn
= conn
->Next
)
1420 EnterCriticalSection(&protseq
->cs
);
1421 conn
->Next
= protseq
->conn
;
1422 protseq
->conn
= first_connection
;
1423 LeaveCriticalSection(&protseq
->cs
);
1425 TRACE("listening on %s\n", endpoint
);
1429 ERR("couldn't listen on port %s\n", endpoint
);
1433 static RPC_STATUS
rpcrt4_conn_tcp_handoff(RpcConnection
*old_conn
, RpcConnection
*new_conn
)
1436 struct sockaddr_in address
;
1438 RpcConnection_tcp
*server
= (RpcConnection_tcp
*) old_conn
;
1439 RpcConnection_tcp
*client
= (RpcConnection_tcp
*) new_conn
;
1442 addrsize
= sizeof(address
);
1443 ret
= accept(server
->sock
, (struct sockaddr
*) &address
, &addrsize
);
1446 ERR("Failed to accept a TCP connection: error %d\n", ret
);
1447 return RPC_S_OUT_OF_RESOURCES
;
1450 ioctlsocket(ret
, FIONBIO
, &nonblocking
);
1452 TRACE("Accepted a new TCP connection\n");
1456 static int rpcrt4_conn_tcp_read(RpcConnection
*Connection
,
1457 void *buffer
, unsigned int count
)
1459 RpcConnection_tcp
*tcpc
= (RpcConnection_tcp
*) Connection
;
1461 while (bytes_read
!= count
)
1463 int r
= recv(tcpc
->sock
, (char *)buffer
+ bytes_read
, count
- bytes_read
, 0);
1468 else if (errno
== EINTR
)
1470 else if (errno
!= EAGAIN
)
1472 WARN("recv() failed: %s\n", strerror(errno
));
1477 if (!rpcrt4_sock_wait_for_recv(tcpc
))
1481 TRACE("%d %p %u -> %d\n", tcpc
->sock
, buffer
, count
, bytes_read
);
1485 static int rpcrt4_conn_tcp_write(RpcConnection
*Connection
,
1486 const void *buffer
, unsigned int count
)
1488 RpcConnection_tcp
*tcpc
= (RpcConnection_tcp
*) Connection
;
1489 int bytes_written
= 0;
1490 while (bytes_written
!= count
)
1492 int r
= send(tcpc
->sock
, (const char *)buffer
+ bytes_written
, count
- bytes_written
, 0);
1495 else if (errno
== EINTR
)
1497 else if (errno
!= EAGAIN
)
1501 if (!rpcrt4_sock_wait_for_send(tcpc
))
1505 TRACE("%d %p %u -> %d\n", tcpc
->sock
, buffer
, count
, bytes_written
);
1506 return bytes_written
;
1509 static int rpcrt4_conn_tcp_close(RpcConnection
*Connection
)
1511 RpcConnection_tcp
*tcpc
= (RpcConnection_tcp
*) Connection
;
1513 TRACE("%d\n", tcpc
->sock
);
1515 if (tcpc
->sock
!= -1)
1516 closesocket(tcpc
->sock
);
1518 rpcrt4_sock_wait_destroy(tcpc
);
1522 static void rpcrt4_conn_tcp_cancel_call(RpcConnection
*Connection
)
1524 RpcConnection_tcp
*tcpc
= (RpcConnection_tcp
*) Connection
;
1525 TRACE("%p\n", Connection
);
1526 rpcrt4_sock_wait_cancel(tcpc
);
1529 static int rpcrt4_conn_tcp_wait_for_incoming_data(RpcConnection
*Connection
)
1531 RpcConnection_tcp
*tcpc
= (RpcConnection_tcp
*) Connection
;
1533 TRACE("%p\n", Connection
);
1535 if (!rpcrt4_sock_wait_for_recv(tcpc
))
1540 static size_t rpcrt4_ncacn_ip_tcp_get_top_of_tower(unsigned char *tower_data
,
1541 const char *networkaddr
,
1542 const char *endpoint
)
1544 return rpcrt4_ip_tcp_get_top_of_tower(tower_data
, networkaddr
,
1545 EPM_PROTOCOL_TCP
, endpoint
);
1548 #ifdef HAVE_SOCKETPAIR
1550 typedef struct _RpcServerProtseq_sock
1552 RpcServerProtseq common
;
1555 } RpcServerProtseq_sock
;
1557 static RpcServerProtseq
*rpcrt4_protseq_sock_alloc(void)
1559 RpcServerProtseq_sock
*ps
= HeapAlloc(GetProcessHeap(), 0, sizeof(*ps
));
1563 if (!socketpair(PF_UNIX
, SOCK_DGRAM
, 0, fds
))
1565 fcntl(fds
[0], F_SETFL
, O_NONBLOCK
);
1566 fcntl(fds
[1], F_SETFL
, O_NONBLOCK
);
1567 ps
->mgr_event_rcv
= fds
[0];
1568 ps
->mgr_event_snd
= fds
[1];
1572 ERR("socketpair failed with error %s\n", strerror(errno
));
1573 HeapFree(GetProcessHeap(), 0, ps
);
1580 static void rpcrt4_protseq_sock_signal_state_changed(RpcServerProtseq
*protseq
)
1582 RpcServerProtseq_sock
*sockps
= CONTAINING_RECORD(protseq
, RpcServerProtseq_sock
, common
);
1584 write(sockps
->mgr_event_snd
, &dummy
, sizeof(dummy
));
1587 static void *rpcrt4_protseq_sock_get_wait_array(RpcServerProtseq
*protseq
, void *prev_array
, unsigned int *count
)
1589 struct pollfd
*poll_info
= prev_array
;
1590 RpcConnection_tcp
*conn
;
1591 RpcServerProtseq_sock
*sockps
= CONTAINING_RECORD(protseq
, RpcServerProtseq_sock
, common
);
1593 EnterCriticalSection(&protseq
->cs
);
1595 /* open and count connections */
1597 conn
= (RpcConnection_tcp
*)protseq
->conn
;
1599 if (conn
->sock
!= -1)
1601 conn
= (RpcConnection_tcp
*)conn
->common
.Next
;
1604 /* make array of connections */
1606 poll_info
= HeapReAlloc(GetProcessHeap(), 0, poll_info
, *count
*sizeof(*poll_info
));
1608 poll_info
= HeapAlloc(GetProcessHeap(), 0, *count
*sizeof(*poll_info
));
1611 ERR("couldn't allocate poll_info\n");
1612 LeaveCriticalSection(&protseq
->cs
);
1616 poll_info
[0].fd
= sockps
->mgr_event_rcv
;
1617 poll_info
[0].events
= POLLIN
;
1619 conn
= CONTAINING_RECORD(protseq
->conn
, RpcConnection_tcp
, common
);
1621 if (conn
->sock
!= -1)
1623 poll_info
[*count
].fd
= conn
->sock
;
1624 poll_info
[*count
].events
= POLLIN
;
1627 conn
= CONTAINING_RECORD(conn
->common
.Next
, RpcConnection_tcp
, common
);
1629 LeaveCriticalSection(&protseq
->cs
);
1633 static void rpcrt4_protseq_sock_free_wait_array(RpcServerProtseq
*protseq
, void *array
)
1635 HeapFree(GetProcessHeap(), 0, array
);
1638 static int rpcrt4_protseq_sock_wait_for_new_connection(RpcServerProtseq
*protseq
, unsigned int count
, void *wait_array
)
1640 struct pollfd
*poll_info
= wait_array
;
1643 RpcConnection
*cconn
;
1644 RpcConnection_tcp
*conn
;
1649 ret
= poll(poll_info
, count
, -1);
1652 ERR("poll failed with error %d\n", ret
);
1656 for (i
= 0; i
< count
; i
++)
1657 if (poll_info
[i
].revents
& POLLIN
)
1659 /* RPC server event */
1663 read(poll_info
[0].fd
, &dummy
, sizeof(dummy
));
1667 /* find which connection got a RPC */
1668 EnterCriticalSection(&protseq
->cs
);
1669 conn
= CONTAINING_RECORD(protseq
->conn
, RpcConnection_tcp
, common
);
1671 if (poll_info
[i
].fd
== conn
->sock
) break;
1672 conn
= CONTAINING_RECORD(conn
->common
.Next
, RpcConnection_tcp
, common
);
1676 RPCRT4_SpawnConnection(&cconn
, &conn
->common
);
1678 ERR("failed to locate connection for fd %d\n", poll_info
[i
].fd
);
1679 LeaveCriticalSection(&protseq
->cs
);
1681 RPCRT4_new_client(cconn
);
1689 #else /* HAVE_SOCKETPAIR */
1691 typedef struct _RpcServerProtseq_sock
1693 RpcServerProtseq common
;
1695 } RpcServerProtseq_sock
;
1697 static RpcServerProtseq
*rpcrt4_protseq_sock_alloc(void)
1699 RpcServerProtseq_sock
*ps
= HeapAlloc(GetProcessHeap(), 0, sizeof(*ps
));
1702 static BOOL wsa_inited
;
1706 WSAStartup(MAKEWORD(2, 2), &wsadata
);
1707 /* Note: WSAStartup can be called more than once so we don't bother with
1708 * making accesses to wsa_inited thread-safe */
1711 ps
->mgr_event
= CreateEventW(NULL
, FALSE
, FALSE
, NULL
);
1716 static void rpcrt4_protseq_sock_signal_state_changed(RpcServerProtseq
*protseq
)
1718 RpcServerProtseq_sock
*sockps
= CONTAINING_RECORD(protseq
, RpcServerProtseq_sock
, common
);
1719 SetEvent(sockps
->mgr_event
);
1722 static void *rpcrt4_protseq_sock_get_wait_array(RpcServerProtseq
*protseq
, void *prev_array
, unsigned int *count
)
1724 HANDLE
*objs
= prev_array
;
1725 RpcConnection_tcp
*conn
;
1726 RpcServerProtseq_sock
*sockps
= CONTAINING_RECORD(protseq
, RpcServerProtseq_sock
, common
);
1728 EnterCriticalSection(&protseq
->cs
);
1730 /* open and count connections */
1732 conn
= CONTAINING_RECORD(protseq
->conn
, RpcConnection_tcp
, common
);
1735 if (conn
->sock
!= -1)
1737 conn
= CONTAINING_RECORD(conn
->common
.Next
, RpcConnection_tcp
, common
);
1740 /* make array of connections */
1742 objs
= HeapReAlloc(GetProcessHeap(), 0, objs
, *count
*sizeof(HANDLE
));
1744 objs
= HeapAlloc(GetProcessHeap(), 0, *count
*sizeof(HANDLE
));
1747 ERR("couldn't allocate objs\n");
1748 LeaveCriticalSection(&protseq
->cs
);
1752 objs
[0] = sockps
->mgr_event
;
1754 conn
= CONTAINING_RECORD(protseq
->conn
, RpcConnection_tcp
, common
);
1757 if (conn
->sock
!= -1)
1759 int res
= WSAEventSelect(conn
->sock
, conn
->sock_event
, FD_ACCEPT
);
1760 if (res
== SOCKET_ERROR
)
1761 ERR("WSAEventSelect() failed with error %d\n", WSAGetLastError());
1764 objs
[*count
] = conn
->sock_event
;
1768 conn
= CONTAINING_RECORD(conn
->common
.Next
, RpcConnection_tcp
, common
);
1770 LeaveCriticalSection(&protseq
->cs
);
1774 static void rpcrt4_protseq_sock_free_wait_array(RpcServerProtseq
*protseq
, void *array
)
1776 HeapFree(GetProcessHeap(), 0, array
);
1779 static int rpcrt4_protseq_sock_wait_for_new_connection(RpcServerProtseq
*protseq
, unsigned int count
, void *wait_array
)
1782 HANDLE
*objs
= wait_array
;
1784 RpcConnection
*cconn
;
1785 RpcConnection_tcp
*conn
;
1792 /* an alertable wait isn't strictly necessary, but due to our
1793 * overlapped I/O implementation in Wine we need to free some memory
1794 * by the file user APC being called, even if no completion routine was
1795 * specified at the time of starting the async operation */
1796 res
= WaitForMultipleObjectsEx(count
, objs
, FALSE
, INFINITE
, TRUE
);
1797 } while (res
== WAIT_IO_COMPLETION
);
1799 if (res
== WAIT_OBJECT_0
)
1801 else if (res
== WAIT_FAILED
)
1803 ERR("wait failed with error %d\n", GetLastError());
1808 b_handle
= objs
[res
- WAIT_OBJECT_0
];
1809 /* find which connection got a RPC */
1810 EnterCriticalSection(&protseq
->cs
);
1811 conn
= CONTAINING_RECORD(protseq
->conn
, RpcConnection_tcp
, common
);
1814 if (b_handle
== conn
->sock_event
) break;
1815 conn
= CONTAINING_RECORD(conn
->common
.Next
, RpcConnection_tcp
, common
);
1819 RPCRT4_SpawnConnection(&cconn
, &conn
->common
);
1821 ERR("failed to locate connection for handle %p\n", b_handle
);
1822 LeaveCriticalSection(&protseq
->cs
);
1825 RPCRT4_new_client(cconn
);
1832 #endif /* HAVE_SOCKETPAIR */
1834 static RPC_STATUS
rpcrt4_ncacn_ip_tcp_parse_top_of_tower(const unsigned char *tower_data
,
1839 return rpcrt4_ip_tcp_parse_top_of_tower(tower_data
, tower_size
,
1840 networkaddr
, EPM_PROTOCOL_TCP
,
1844 /**** ncacn_http support ****/
1846 /* 60 seconds is the period native uses */
1847 #define HTTP_IDLE_TIME 60000
1849 /* reference counted to avoid a race between a cancelled call's connection
1850 * being destroyed and the asynchronous InternetReadFileEx call being
1852 typedef struct _RpcHttpAsyncData
1855 HANDLE completion_event
;
1857 INTERNET_BUFFERSA inet_buffers
;
1858 CRITICAL_SECTION cs
;
1861 static ULONG
RpcHttpAsyncData_AddRef(RpcHttpAsyncData
*data
)
1863 return InterlockedIncrement(&data
->refs
);
1866 static ULONG
RpcHttpAsyncData_Release(RpcHttpAsyncData
*data
)
1868 ULONG refs
= InterlockedDecrement(&data
->refs
);
1871 TRACE("destroying async data %p\n", data
);
1872 CloseHandle(data
->completion_event
);
1873 HeapFree(GetProcessHeap(), 0, data
->inet_buffers
.lpvBuffer
);
1874 data
->cs
.DebugInfo
->Spare
[0] = 0;
1875 DeleteCriticalSection(&data
->cs
);
1876 HeapFree(GetProcessHeap(), 0, data
);
1881 static void prepare_async_request(RpcHttpAsyncData
*async_data
)
1883 ResetEvent(async_data
->completion_event
);
1884 RpcHttpAsyncData_AddRef(async_data
);
1887 static RPC_STATUS
wait_async_request(RpcHttpAsyncData
*async_data
, BOOL call_ret
, HANDLE cancel_event
)
1889 HANDLE handles
[2] = { async_data
->completion_event
, cancel_event
};
1893 RpcHttpAsyncData_Release(async_data
);
1897 if(GetLastError() != ERROR_IO_PENDING
) {
1898 RpcHttpAsyncData_Release(async_data
);
1899 ERR("Request failed with error %d\n", GetLastError());
1900 return RPC_S_SERVER_UNAVAILABLE
;
1903 res
= WaitForMultipleObjects(2, handles
, FALSE
, DEFAULT_NCACN_HTTP_TIMEOUT
);
1904 if(res
!= WAIT_OBJECT_0
) {
1905 TRACE("Cancelled\n");
1906 return RPC_S_CALL_CANCELLED
;
1909 if(async_data
->async_result
) {
1910 ERR("Async request failed with error %d\n", async_data
->async_result
);
1911 return RPC_S_SERVER_UNAVAILABLE
;
1926 unsigned int data_len
;
1927 BOOL finished
; /* finished authenticating */
1930 typedef struct _RpcConnection_http
1932 RpcConnection common
;
1935 HINTERNET in_request
;
1936 HINTERNET out_request
;
1938 HANDLE timer_cancelled
;
1939 HANDLE cancel_event
;
1940 DWORD last_sent_time
;
1941 ULONG bytes_received
;
1942 ULONG flow_control_mark
; /* send a control packet to the server when this many bytes received */
1943 ULONG flow_control_increment
; /* number of bytes to increment flow_control_mark by */
1944 UUID connection_uuid
;
1947 RpcHttpAsyncData
*async_data
;
1948 } RpcConnection_http
;
1950 static RpcConnection
*rpcrt4_ncacn_http_alloc(void)
1952 RpcConnection_http
*httpc
;
1953 httpc
= HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY
, sizeof(*httpc
));
1954 if (!httpc
) return NULL
;
1955 httpc
->async_data
= HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY
, sizeof(RpcHttpAsyncData
));
1956 if (!httpc
->async_data
)
1958 HeapFree(GetProcessHeap(), 0, httpc
);
1961 TRACE("async data = %p\n", httpc
->async_data
);
1962 httpc
->cancel_event
= CreateEventW(NULL
, FALSE
, FALSE
, NULL
);
1963 httpc
->async_data
->refs
= 1;
1964 httpc
->async_data
->inet_buffers
.dwStructSize
= sizeof(INTERNET_BUFFERSA
);
1965 httpc
->async_data
->inet_buffers
.lpvBuffer
= NULL
;
1966 InitializeCriticalSection(&httpc
->async_data
->cs
);
1967 httpc
->async_data
->cs
.DebugInfo
->Spare
[0] = (DWORD_PTR
)(__FILE__
": RpcHttpAsyncData.cs");
1968 return &httpc
->common
;
1971 typedef struct _HttpTimerThreadData
1974 DWORD
*last_sent_time
;
1975 HANDLE timer_cancelled
;
1976 } HttpTimerThreadData
;
1978 static VOID
rpcrt4_http_keep_connection_active_timer_proc(PVOID param
, BOOLEAN dummy
)
1980 HINTERNET in_request
= param
;
1981 RpcPktHdr
*idle_pkt
;
1983 idle_pkt
= RPCRT4_BuildHttpHeader(NDR_LOCAL_DATA_REPRESENTATION
, 0x0001,
1987 DWORD bytes_written
;
1988 InternetWriteFile(in_request
, idle_pkt
, idle_pkt
->common
.frag_len
, &bytes_written
);
1989 RPCRT4_FreeHeader(idle_pkt
);
1993 static inline DWORD
rpcrt4_http_timer_calc_timeout(DWORD
*last_sent_time
)
1995 DWORD cur_time
= GetTickCount();
1996 DWORD cached_last_sent_time
= *last_sent_time
;
1997 return HTTP_IDLE_TIME
- (cur_time
- cached_last_sent_time
> HTTP_IDLE_TIME
? 0 : cur_time
- cached_last_sent_time
);
2000 static DWORD CALLBACK
rpcrt4_http_timer_thread(PVOID param
)
2002 HttpTimerThreadData
*data_in
= param
;
2003 HttpTimerThreadData data
;
2007 HeapFree(GetProcessHeap(), 0, data_in
);
2009 for (timeout
= HTTP_IDLE_TIME
;
2010 WaitForSingleObject(data
.timer_cancelled
, timeout
) == WAIT_TIMEOUT
;
2011 timeout
= rpcrt4_http_timer_calc_timeout(data
.last_sent_time
))
2013 /* are we too soon after last send? */
2014 if (GetTickCount() - *data
.last_sent_time
< HTTP_IDLE_TIME
)
2016 rpcrt4_http_keep_connection_active_timer_proc(data
.timer_param
, TRUE
);
2019 CloseHandle(data
.timer_cancelled
);
2023 static VOID WINAPI
rpcrt4_http_internet_callback(
2024 HINTERNET hInternet
,
2025 DWORD_PTR dwContext
,
2026 DWORD dwInternetStatus
,
2027 LPVOID lpvStatusInformation
,
2028 DWORD dwStatusInformationLength
)
2030 RpcHttpAsyncData
*async_data
= (RpcHttpAsyncData
*)dwContext
;
2032 switch (dwInternetStatus
)
2034 case INTERNET_STATUS_REQUEST_COMPLETE
:
2035 TRACE("INTERNET_STATUS_REQUEST_COMPLETED\n");
2038 INTERNET_ASYNC_RESULT
*async_result
= lpvStatusInformation
;
2040 async_data
->async_result
= async_result
->dwResult
? ERROR_SUCCESS
: async_result
->dwError
;
2041 SetEvent(async_data
->completion_event
);
2042 RpcHttpAsyncData_Release(async_data
);
2048 static RPC_STATUS
rpcrt4_http_check_response(HINTERNET hor
)
2055 WCHAR
*status_text
= buf
;
2059 size
= sizeof(status_code
);
2060 ret
= HttpQueryInfoW(hor
, HTTP_QUERY_STATUS_CODE
|HTTP_QUERY_FLAG_NUMBER
, &status_code
, &size
, &index
);
2062 return GetLastError();
2063 if (status_code
== HTTP_STATUS_OK
)
2067 ret
= HttpQueryInfoW(hor
, HTTP_QUERY_STATUS_TEXT
, status_text
, &size
, &index
);
2068 if (!ret
&& GetLastError() == ERROR_INSUFFICIENT_BUFFER
)
2070 status_text
= HeapAlloc(GetProcessHeap(), 0, size
);
2071 ret
= HttpQueryInfoW(hor
, HTTP_QUERY_STATUS_TEXT
, status_text
, &size
, &index
);
2074 ERR("server returned: %d %s\n", status_code
, ret
? debugstr_w(status_text
) : "<status text unavailable>");
2075 if(status_text
!= buf
) HeapFree(GetProcessHeap(), 0, status_text
);
2077 if (status_code
== HTTP_STATUS_DENIED
)
2078 return ERROR_ACCESS_DENIED
;
2079 return RPC_S_SERVER_UNAVAILABLE
;
2082 static RPC_STATUS
rpcrt4_http_internet_connect(RpcConnection_http
*httpc
)
2084 static const WCHAR wszUserAgent
[] = {'M','S','R','P','C',0};
2085 LPWSTR proxy
= NULL
;
2087 LPWSTR password
= NULL
;
2088 LPWSTR servername
= NULL
;
2089 const WCHAR
*option
;
2092 if (httpc
->common
.QOS
&&
2093 (httpc
->common
.QOS
->qos
->AdditionalSecurityInfoType
== RPC_C_AUTHN_INFO_TYPE_HTTP
))
2095 const RPC_HTTP_TRANSPORT_CREDENTIALS_W
*http_cred
= httpc
->common
.QOS
->qos
->u
.HttpCredentials
;
2096 if (http_cred
->TransportCredentials
)
2099 const SEC_WINNT_AUTH_IDENTITY_W
*cred
= http_cred
->TransportCredentials
;
2100 ULONG len
= cred
->DomainLength
+ 1 + cred
->UserLength
;
2101 user
= HeapAlloc(GetProcessHeap(), 0, (len
+ 1) * sizeof(WCHAR
));
2103 return RPC_S_OUT_OF_RESOURCES
;
2105 if (cred
->DomainLength
)
2107 memcpy(p
, cred
->Domain
, cred
->DomainLength
* sizeof(WCHAR
));
2108 p
+= cred
->DomainLength
;
2112 memcpy(p
, cred
->User
, cred
->UserLength
* sizeof(WCHAR
));
2113 p
[cred
->UserLength
] = 0;
2115 password
= RPCRT4_strndupW(cred
->Password
, cred
->PasswordLength
);
2119 for (option
= httpc
->common
.NetworkOptions
; option
;
2120 option
= (strchrW(option
, ',') ? strchrW(option
, ',')+1 : NULL
))
2122 static const WCHAR wszRpcProxy
[] = {'R','p','c','P','r','o','x','y','=',0};
2123 static const WCHAR wszHttpProxy
[] = {'H','t','t','p','P','r','o','x','y','=',0};
2125 if (!strncmpiW(option
, wszRpcProxy
, sizeof(wszRpcProxy
)/sizeof(wszRpcProxy
[0])-1))
2127 const WCHAR
*value_start
= option
+ sizeof(wszRpcProxy
)/sizeof(wszRpcProxy
[0])-1;
2128 const WCHAR
*value_end
;
2131 value_end
= strchrW(option
, ',');
2133 value_end
= value_start
+ strlenW(value_start
);
2134 for (p
= value_start
; p
< value_end
; p
++)
2141 TRACE("RpcProxy value is %s\n", debugstr_wn(value_start
, value_end
-value_start
));
2142 servername
= RPCRT4_strndupW(value_start
, value_end
-value_start
);
2144 else if (!strncmpiW(option
, wszHttpProxy
, sizeof(wszHttpProxy
)/sizeof(wszHttpProxy
[0])-1))
2146 const WCHAR
*value_start
= option
+ sizeof(wszHttpProxy
)/sizeof(wszHttpProxy
[0])-1;
2147 const WCHAR
*value_end
;
2149 value_end
= strchrW(option
, ',');
2151 value_end
= value_start
+ strlenW(value_start
);
2152 TRACE("HttpProxy value is %s\n", debugstr_wn(value_start
, value_end
-value_start
));
2153 proxy
= RPCRT4_strndupW(value_start
, value_end
-value_start
);
2156 FIXME("unhandled option %s\n", debugstr_w(option
));
2159 httpc
->app_info
= InternetOpenW(wszUserAgent
, proxy
? INTERNET_OPEN_TYPE_PROXY
: INTERNET_OPEN_TYPE_PRECONFIG
,
2160 NULL
, NULL
, INTERNET_FLAG_ASYNC
);
2161 if (!httpc
->app_info
)
2163 HeapFree(GetProcessHeap(), 0, password
);
2164 HeapFree(GetProcessHeap(), 0, user
);
2165 HeapFree(GetProcessHeap(), 0, proxy
);
2166 HeapFree(GetProcessHeap(), 0, servername
);
2167 ERR("InternetOpenW failed with error %d\n", GetLastError());
2168 return RPC_S_SERVER_UNAVAILABLE
;
2170 InternetSetStatusCallbackW(httpc
->app_info
, rpcrt4_http_internet_callback
);
2172 /* if no RpcProxy option specified, set the HTTP server address to the
2173 * RPC server address */
2176 servername
= HeapAlloc(GetProcessHeap(), 0, (strlen(httpc
->common
.NetworkAddr
) + 1)*sizeof(WCHAR
));
2179 HeapFree(GetProcessHeap(), 0, password
);
2180 HeapFree(GetProcessHeap(), 0, user
);
2181 HeapFree(GetProcessHeap(), 0, proxy
);
2182 return RPC_S_OUT_OF_RESOURCES
;
2184 MultiByteToWideChar(CP_ACP
, 0, httpc
->common
.NetworkAddr
, -1, servername
, strlen(httpc
->common
.NetworkAddr
) + 1);
2187 port
= (httpc
->common
.QOS
&&
2188 (httpc
->common
.QOS
->qos
->AdditionalSecurityInfoType
== RPC_C_AUTHN_INFO_TYPE_HTTP
) &&
2189 (httpc
->common
.QOS
->qos
->u
.HttpCredentials
->Flags
& RPC_C_HTTP_FLAG_USE_SSL
)) ?
2190 INTERNET_DEFAULT_HTTPS_PORT
: INTERNET_DEFAULT_HTTP_PORT
;
2192 httpc
->session
= InternetConnectW(httpc
->app_info
, servername
, port
, user
, password
,
2193 INTERNET_SERVICE_HTTP
, 0, 0);
2195 HeapFree(GetProcessHeap(), 0, password
);
2196 HeapFree(GetProcessHeap(), 0, user
);
2197 HeapFree(GetProcessHeap(), 0, proxy
);
2199 if (!httpc
->session
)
2201 ERR("InternetConnectW failed with error %d\n", GetLastError());
2202 HeapFree(GetProcessHeap(), 0, servername
);
2203 return RPC_S_SERVER_UNAVAILABLE
;
2205 httpc
->servername
= servername
;
2209 static RPC_STATUS
send_echo_request(HINTERNET req
, RpcHttpAsyncData
*async_data
, HANDLE cancel_event
)
2216 TRACE("sending echo request to server\n");
2218 prepare_async_request(async_data
);
2219 ret
= HttpSendRequestW(req
, NULL
, 0, NULL
, 0);
2220 status
= wait_async_request(async_data
, ret
, cancel_event
);
2221 if (status
!= RPC_S_OK
) return status
;
2223 status
= rpcrt4_http_check_response(req
);
2224 if (status
!= RPC_S_OK
) return status
;
2226 InternetReadFile(req
, buf
, sizeof(buf
), &bytes_read
);
2227 /* FIXME: do something with retrieved data */
2232 /* prepare the in pipe for use by RPC packets */
2233 static RPC_STATUS
rpcrt4_http_prepare_in_pipe(HINTERNET in_request
, RpcHttpAsyncData
*async_data
, HANDLE cancel_event
,
2234 const UUID
*connection_uuid
, const UUID
*in_pipe_uuid
,
2235 const UUID
*association_uuid
, BOOL authorized
)
2240 INTERNET_BUFFERSW buffers_in
;
2241 DWORD bytes_written
;
2245 /* ask wininet to authorize, if necessary */
2246 status
= send_echo_request(in_request
, async_data
, cancel_event
);
2247 if (status
!= RPC_S_OK
) return status
;
2249 memset(&buffers_in
, 0, sizeof(buffers_in
));
2250 buffers_in
.dwStructSize
= sizeof(buffers_in
);
2251 /* FIXME: get this from the registry */
2252 buffers_in
.dwBufferTotal
= 1024 * 1024 * 1024; /* 1Gb */
2253 prepare_async_request(async_data
);
2254 ret
= HttpSendRequestExW(in_request
, &buffers_in
, NULL
, 0, 0);
2255 status
= wait_async_request(async_data
, ret
, cancel_event
);
2256 if (status
!= RPC_S_OK
) return status
;
2258 TRACE("sending HTTP connect header to server\n");
2259 hdr
= RPCRT4_BuildHttpConnectHeader(FALSE
, connection_uuid
, in_pipe_uuid
, association_uuid
);
2260 if (!hdr
) return RPC_S_OUT_OF_RESOURCES
;
2261 ret
= InternetWriteFile(in_request
, hdr
, hdr
->common
.frag_len
, &bytes_written
);
2262 RPCRT4_FreeHeader(hdr
);
2265 ERR("InternetWriteFile failed with error %d\n", GetLastError());
2266 return RPC_S_SERVER_UNAVAILABLE
;
2272 static RPC_STATUS
rpcrt4_http_read_http_packet(HINTERNET request
, RpcPktHdr
*hdr
, BYTE
**data
)
2276 unsigned short data_len
;
2278 ret
= InternetReadFile(request
, hdr
, sizeof(hdr
->common
), &bytes_read
);
2280 return RPC_S_SERVER_UNAVAILABLE
;
2281 if (hdr
->common
.ptype
!= PKT_HTTP
|| hdr
->common
.frag_len
< sizeof(hdr
->http
))
2283 ERR("wrong packet type received %d or wrong frag_len %d\n",
2284 hdr
->common
.ptype
, hdr
->common
.frag_len
);
2285 return RPC_S_PROTOCOL_ERROR
;
2288 ret
= InternetReadFile(request
, &hdr
->common
+ 1, sizeof(hdr
->http
) - sizeof(hdr
->common
), &bytes_read
);
2290 return RPC_S_SERVER_UNAVAILABLE
;
2292 data_len
= hdr
->common
.frag_len
- sizeof(hdr
->http
);
2295 *data
= HeapAlloc(GetProcessHeap(), 0, data_len
);
2297 return RPC_S_OUT_OF_RESOURCES
;
2298 ret
= InternetReadFile(request
, *data
, data_len
, &bytes_read
);
2301 HeapFree(GetProcessHeap(), 0, *data
);
2302 return RPC_S_SERVER_UNAVAILABLE
;
2308 if (!RPCRT4_IsValidHttpPacket(hdr
, *data
, data_len
))
2310 ERR("invalid http packet\n");
2311 return RPC_S_PROTOCOL_ERROR
;
2317 /* prepare the out pipe for use by RPC packets */
2318 static RPC_STATUS
rpcrt4_http_prepare_out_pipe(HINTERNET out_request
, RpcHttpAsyncData
*async_data
,
2319 HANDLE cancel_event
, const UUID
*connection_uuid
,
2320 const UUID
*out_pipe_uuid
, ULONG
*flow_control_increment
,
2326 BYTE
*data_from_server
;
2327 RpcPktHdr pkt_from_server
;
2328 ULONG field1
, field3
;
2334 /* ask wininet to authorize, if necessary */
2335 status
= send_echo_request(out_request
, async_data
, cancel_event
);
2336 if (status
!= RPC_S_OK
) return status
;
2339 InternetReadFile(out_request
, buf
, sizeof(buf
), &bytes_read
);
2341 hdr
= RPCRT4_BuildHttpConnectHeader(TRUE
, connection_uuid
, out_pipe_uuid
, NULL
);
2342 if (!hdr
) return RPC_S_OUT_OF_RESOURCES
;
2344 TRACE("sending HTTP connect header to server\n");
2345 prepare_async_request(async_data
);
2346 ret
= HttpSendRequestW(out_request
, NULL
, 0, hdr
, hdr
->common
.frag_len
);
2347 status
= wait_async_request(async_data
, ret
, cancel_event
);
2348 RPCRT4_FreeHeader(hdr
);
2349 if (status
!= RPC_S_OK
) return status
;
2351 status
= rpcrt4_http_check_response(out_request
);
2352 if (status
!= RPC_S_OK
) return status
;
2354 status
= rpcrt4_http_read_http_packet(out_request
, &pkt_from_server
,
2356 if (status
!= RPC_S_OK
) return status
;
2357 status
= RPCRT4_ParseHttpPrepareHeader1(&pkt_from_server
, data_from_server
,
2359 HeapFree(GetProcessHeap(), 0, data_from_server
);
2360 if (status
!= RPC_S_OK
) return status
;
2361 TRACE("received (%d) from first prepare header\n", field1
);
2365 status
= rpcrt4_http_read_http_packet(out_request
, &pkt_from_server
,
2367 if (status
!= RPC_S_OK
) return status
;
2368 if (pkt_from_server
.http
.flags
!= 0x0001) break;
2370 TRACE("http idle packet, waiting for real packet\n");
2371 HeapFree(GetProcessHeap(), 0, data_from_server
);
2372 if (pkt_from_server
.http
.num_data_items
!= 0)
2374 ERR("HTTP idle packet should have no data items instead of %d\n",
2375 pkt_from_server
.http
.num_data_items
);
2376 return RPC_S_PROTOCOL_ERROR
;
2379 status
= RPCRT4_ParseHttpPrepareHeader2(&pkt_from_server
, data_from_server
,
2380 &field1
, flow_control_increment
,
2382 HeapFree(GetProcessHeap(), 0, data_from_server
);
2383 if (status
!= RPC_S_OK
) return status
;
2384 TRACE("received (0x%08x 0x%08x %d) from second prepare header\n", field1
, *flow_control_increment
, field3
);
2389 static UINT
encode_base64(const char *bin
, unsigned int len
, WCHAR
*base64
)
2391 static const char enc
[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
2396 /* first 6 bits, all from bin[0] */
2397 base64
[i
++] = enc
[(bin
[0] & 0xfc) >> 2];
2398 x
= (bin
[0] & 3) << 4;
2400 /* next 6 bits, 2 from bin[0] and 4 from bin[1] */
2403 base64
[i
++] = enc
[x
];
2408 base64
[i
++] = enc
[x
| ((bin
[1] & 0xf0) >> 4)];
2409 x
= (bin
[1] & 0x0f) << 2;
2411 /* next 6 bits 4 from bin[1] and 2 from bin[2] */
2414 base64
[i
++] = enc
[x
];
2418 base64
[i
++] = enc
[x
| ((bin
[2] & 0xc0) >> 6)];
2420 /* last 6 bits, all from bin [2] */
2421 base64
[i
++] = enc
[bin
[2] & 0x3f];
2429 static inline char decode_char( WCHAR c
)
2431 if (c
>= 'A' && c
<= 'Z') return c
- 'A';
2432 if (c
>= 'a' && c
<= 'z') return c
- 'a' + 26;
2433 if (c
>= '0' && c
<= '9') return c
- '0' + 52;
2434 if (c
== '+') return 62;
2435 if (c
== '/') return 63;
2439 static unsigned int decode_base64( const WCHAR
*base64
, unsigned int len
, char *buf
)
2442 char c0
, c1
, c2
, c3
;
2443 const WCHAR
*p
= base64
;
2447 if ((c0
= decode_char( p
[0] )) > 63) return 0;
2448 if ((c1
= decode_char( p
[1] )) > 63) return 0;
2449 if ((c2
= decode_char( p
[2] )) > 63) return 0;
2450 if ((c3
= decode_char( p
[3] )) > 63) return 0;
2454 buf
[i
+ 0] = (c0
<< 2) | (c1
>> 4);
2455 buf
[i
+ 1] = (c1
<< 4) | (c2
>> 2);
2456 buf
[i
+ 2] = (c2
<< 6) | c3
;
2464 if ((c0
= decode_char( p
[0] )) > 63) return 0;
2465 if ((c1
= decode_char( p
[1] )) > 63) return 0;
2467 if (buf
) buf
[i
] = (c0
<< 2) | (c1
>> 4);
2470 else if (p
[3] == '=')
2472 if ((c0
= decode_char( p
[0] )) > 63) return 0;
2473 if ((c1
= decode_char( p
[1] )) > 63) return 0;
2474 if ((c2
= decode_char( p
[2] )) > 63) return 0;
2478 buf
[i
+ 0] = (c0
<< 2) | (c1
>> 4);
2479 buf
[i
+ 1] = (c1
<< 4) | (c2
>> 2);
2485 if ((c0
= decode_char( p
[0] )) > 63) return 0;
2486 if ((c1
= decode_char( p
[1] )) > 63) return 0;
2487 if ((c2
= decode_char( p
[2] )) > 63) return 0;
2488 if ((c3
= decode_char( p
[3] )) > 63) return 0;
2492 buf
[i
+ 0] = (c0
<< 2) | (c1
>> 4);
2493 buf
[i
+ 1] = (c1
<< 4) | (c2
>> 2);
2494 buf
[i
+ 2] = (c2
<< 6) | c3
;
2501 static struct authinfo
*alloc_authinfo(void)
2503 struct authinfo
*ret
;
2505 if (!(ret
= HeapAlloc(GetProcessHeap(), 0, sizeof(*ret
) ))) return NULL
;
2507 SecInvalidateHandle(&ret
->cred
);
2508 SecInvalidateHandle(&ret
->ctx
);
2509 memset(&ret
->exp
, 0, sizeof(ret
->exp
));
2515 ret
->finished
= FALSE
;
2519 static void destroy_authinfo(struct authinfo
*info
)
2523 if (SecIsValidHandle(&info
->ctx
))
2524 DeleteSecurityContext(&info
->ctx
);
2525 if (SecIsValidHandle(&info
->cred
))
2526 FreeCredentialsHandle(&info
->cred
);
2528 HeapFree(GetProcessHeap(), 0, info
->data
);
2529 HeapFree(GetProcessHeap(), 0, info
);
2532 static const WCHAR basicW
[] = {'B','a','s','i','c',0};
2533 static const WCHAR ntlmW
[] = {'N','T','L','M',0};
2534 static const WCHAR passportW
[] = {'P','a','s','s','p','o','r','t',0};
2535 static const WCHAR digestW
[] = {'D','i','g','e','s','t',0};
2536 static const WCHAR negotiateW
[] = {'N','e','g','o','t','i','a','t','e',0};
2546 { basicW
, ARRAYSIZE(basicW
) - 1, RPC_C_HTTP_AUTHN_SCHEME_BASIC
},
2547 { ntlmW
, ARRAYSIZE(ntlmW
) - 1, RPC_C_HTTP_AUTHN_SCHEME_NTLM
},
2548 { passportW
, ARRAYSIZE(passportW
) - 1, RPC_C_HTTP_AUTHN_SCHEME_PASSPORT
},
2549 { digestW
, ARRAYSIZE(digestW
) - 1, RPC_C_HTTP_AUTHN_SCHEME_DIGEST
},
2550 { negotiateW
, ARRAYSIZE(negotiateW
) - 1, RPC_C_HTTP_AUTHN_SCHEME_NEGOTIATE
}
2552 static const unsigned int num_auth_schemes
= sizeof(auth_schemes
)/sizeof(auth_schemes
[0]);
2554 static DWORD
auth_scheme_from_header( const WCHAR
*header
)
2557 for (i
= 0; i
< num_auth_schemes
; i
++)
2559 if (!strncmpiW( header
, auth_schemes
[i
].str
, auth_schemes
[i
].len
) &&
2560 (header
[auth_schemes
[i
].len
] == ' ' || !header
[auth_schemes
[i
].len
])) return auth_schemes
[i
].scheme
;
2565 static BOOL
get_authvalue(HINTERNET request
, DWORD scheme
, WCHAR
*buffer
, DWORD buflen
)
2567 DWORD len
, index
= 0;
2571 if (!HttpQueryInfoW(request
, HTTP_QUERY_WWW_AUTHENTICATE
, buffer
, &len
, &index
)) return FALSE
;
2572 if (auth_scheme_from_header(buffer
) == scheme
) break;
2577 static RPC_STATUS
do_authorization(HINTERNET request
, SEC_WCHAR
*servername
,
2578 const RPC_HTTP_TRANSPORT_CREDENTIALS_W
*creds
, struct authinfo
**auth_ptr
)
2580 struct authinfo
*info
= *auth_ptr
;
2581 SEC_WINNT_AUTH_IDENTITY_W
*id
= creds
->TransportCredentials
;
2582 RPC_STATUS status
= RPC_S_SERVER_UNAVAILABLE
;
2584 if ((!info
&& !(info
= alloc_authinfo()))) return RPC_S_SERVER_UNAVAILABLE
;
2586 switch (creds
->AuthnSchemes
[0])
2588 case RPC_C_HTTP_AUTHN_SCHEME_BASIC
:
2590 int userlen
= WideCharToMultiByte(CP_UTF8
, 0, id
->User
, id
->UserLength
, NULL
, 0, NULL
, NULL
);
2591 int passlen
= WideCharToMultiByte(CP_UTF8
, 0, id
->Password
, id
->PasswordLength
, NULL
, 0, NULL
, NULL
);
2593 info
->data_len
= userlen
+ passlen
+ 1;
2594 if (!(info
->data
= HeapAlloc(GetProcessHeap(), 0, info
->data_len
)))
2596 status
= RPC_S_OUT_OF_MEMORY
;
2599 WideCharToMultiByte(CP_UTF8
, 0, id
->User
, id
->UserLength
, info
->data
, userlen
, NULL
, NULL
);
2600 info
->data
[userlen
] = ':';
2601 WideCharToMultiByte(CP_UTF8
, 0, id
->Password
, id
->PasswordLength
, info
->data
+ userlen
+ 1, passlen
, NULL
, NULL
);
2603 info
->scheme
= RPC_C_HTTP_AUTHN_SCHEME_BASIC
;
2604 info
->finished
= TRUE
;
2608 case RPC_C_HTTP_AUTHN_SCHEME_NTLM
:
2609 case RPC_C_HTTP_AUTHN_SCHEME_NEGOTIATE
:
2612 static SEC_WCHAR ntlmW
[] = {'N','T','L','M',0}, negotiateW
[] = {'N','e','g','o','t','i','a','t','e',0};
2613 SECURITY_STATUS ret
;
2614 SecBufferDesc out_desc
, in_desc
;
2616 ULONG flags
= ISC_REQ_CONNECTION
|ISC_REQ_USE_DCE_STYLE
|ISC_REQ_MUTUAL_AUTH
|ISC_REQ_DELEGATE
;
2620 WCHAR auth_value
[2048];
2621 DWORD size
= sizeof(auth_value
);
2624 if (creds
->AuthnSchemes
[0] == RPC_C_HTTP_AUTHN_SCHEME_NTLM
) scheme
= ntlmW
;
2625 else scheme
= negotiateW
;
2626 scheme_len
= strlenW( scheme
);
2631 SecPkgInfoW
*pkg_info
;
2633 ret
= AcquireCredentialsHandleW(NULL
, scheme
, SECPKG_CRED_OUTBOUND
, NULL
, id
, NULL
, NULL
, &info
->cred
, &exp
);
2634 if (ret
!= SEC_E_OK
) break;
2636 ret
= QuerySecurityPackageInfoW(scheme
, &pkg_info
);
2637 if (ret
!= SEC_E_OK
) break;
2639 info
->max_token
= pkg_info
->cbMaxToken
;
2640 FreeContextBuffer(pkg_info
);
2645 if (info
->finished
|| !get_authvalue(request
, creds
->AuthnSchemes
[0], auth_value
, size
)) break;
2646 if (auth_scheme_from_header(auth_value
) != info
->scheme
)
2648 ERR("authentication scheme changed\n");
2652 in
.BufferType
= SECBUFFER_TOKEN
;
2656 in_desc
.ulVersion
= 0;
2657 in_desc
.cBuffers
= 1;
2658 in_desc
.pBuffers
= &in
;
2660 p
= auth_value
+ scheme_len
;
2661 if (!first
&& *p
== ' ')
2663 int len
= strlenW(++p
);
2664 in
.cbBuffer
= decode_base64(p
, len
, NULL
);
2665 if (!(in
.pvBuffer
= HeapAlloc(GetProcessHeap(), 0, in
.cbBuffer
))) break;
2666 decode_base64(p
, len
, in
.pvBuffer
);
2668 out
.BufferType
= SECBUFFER_TOKEN
;
2669 out
.cbBuffer
= info
->max_token
;
2670 if (!(out
.pvBuffer
= HeapAlloc(GetProcessHeap(), 0, out
.cbBuffer
)))
2672 HeapFree(GetProcessHeap(), 0, in
.pvBuffer
);
2675 out_desc
.ulVersion
= 0;
2676 out_desc
.cBuffers
= 1;
2677 out_desc
.pBuffers
= &out
;
2679 ret
= InitializeSecurityContextW(first
? &info
->cred
: NULL
, first
? NULL
: &info
->ctx
,
2680 first
? servername
: NULL
, flags
, 0, SECURITY_NETWORK_DREP
,
2681 in
.pvBuffer
? &in_desc
: NULL
, 0, &info
->ctx
, &out_desc
,
2682 &info
->attr
, &info
->exp
);
2683 HeapFree(GetProcessHeap(), 0, in
.pvBuffer
);
2684 if (ret
== SEC_E_OK
)
2686 HeapFree(GetProcessHeap(), 0, info
->data
);
2687 info
->data
= out
.pvBuffer
;
2688 info
->data_len
= out
.cbBuffer
;
2689 info
->finished
= TRUE
;
2690 TRACE("sending last auth packet\n");
2693 else if (ret
== SEC_I_CONTINUE_NEEDED
)
2695 HeapFree(GetProcessHeap(), 0, info
->data
);
2696 info
->data
= out
.pvBuffer
;
2697 info
->data_len
= out
.cbBuffer
;
2698 TRACE("sending next auth packet\n");
2703 ERR("InitializeSecurityContextW failed with error 0x%08x\n", ret
);
2704 HeapFree(GetProcessHeap(), 0, out
.pvBuffer
);
2707 info
->scheme
= creds
->AuthnSchemes
[0];
2711 FIXME("scheme %u not supported\n", creds
->AuthnSchemes
[0]);
2715 if (status
!= RPC_S_OK
)
2717 destroy_authinfo(info
);
2725 static RPC_STATUS
insert_authorization_header(HINTERNET request
, ULONG scheme
, char *data
, int data_len
)
2727 static const WCHAR authW
[] = {'A','u','t','h','o','r','i','z','a','t','i','o','n',':',' '};
2728 static const WCHAR basicW
[] = {'B','a','s','i','c',' '};
2729 static const WCHAR negotiateW
[] = {'N','e','g','o','t','i','a','t','e',' '};
2730 static const WCHAR ntlmW
[] = {'N','T','L','M',' '};
2731 int scheme_len
, auth_len
= sizeof(authW
) / sizeof(authW
[0]), len
= ((data_len
+ 2) * 4) / 3;
2732 const WCHAR
*scheme_str
;
2733 WCHAR
*header
, *ptr
;
2734 RPC_STATUS status
= RPC_S_SERVER_UNAVAILABLE
;
2738 case RPC_C_HTTP_AUTHN_SCHEME_BASIC
:
2739 scheme_str
= basicW
;
2740 scheme_len
= sizeof(basicW
) / sizeof(basicW
[0]);
2742 case RPC_C_HTTP_AUTHN_SCHEME_NEGOTIATE
:
2743 scheme_str
= negotiateW
;
2744 scheme_len
= sizeof(negotiateW
) / sizeof(negotiateW
[0]);
2746 case RPC_C_HTTP_AUTHN_SCHEME_NTLM
:
2748 scheme_len
= sizeof(ntlmW
) / sizeof(ntlmW
[0]);
2751 ERR("unknown scheme %u\n", scheme
);
2752 return RPC_S_SERVER_UNAVAILABLE
;
2754 if ((header
= HeapAlloc(GetProcessHeap(), 0, (auth_len
+ scheme_len
+ len
+ 2) * sizeof(WCHAR
))))
2756 memcpy(header
, authW
, auth_len
* sizeof(WCHAR
));
2757 ptr
= header
+ auth_len
;
2758 memcpy(ptr
, scheme_str
, scheme_len
* sizeof(WCHAR
));
2760 len
= encode_base64(data
, data_len
, ptr
);
2764 if (HttpAddRequestHeadersW(request
, header
, -1, HTTP_ADDREQ_FLAG_ADD
|HTTP_ADDREQ_FLAG_REPLACE
))
2766 HeapFree(GetProcessHeap(), 0, header
);
2771 static void drain_content(HINTERNET request
)
2773 DWORD count
, len
= 0, size
= sizeof(len
);
2776 HttpQueryInfoW(request
, HTTP_QUERY_FLAG_NUMBER
|HTTP_QUERY_CONTENT_LENGTH
, &len
, &size
, NULL
);
2780 count
= min(sizeof(buf
), len
);
2781 if (!InternetReadFile(request
, buf
, count
, &count
) || !count
) return;
2786 static RPC_STATUS
authorize_request(RpcConnection_http
*httpc
, HINTERNET request
)
2788 static const WCHAR authW
[] = {'A','u','t','h','o','r','i','z','a','t','i','o','n',':','\r','\n',0};
2789 struct authinfo
*info
= NULL
;
2795 status
= do_authorization(request
, httpc
->servername
, httpc
->common
.QOS
->qos
->u
.HttpCredentials
, &info
);
2796 if (status
!= RPC_S_OK
) break;
2798 status
= insert_authorization_header(request
, info
->scheme
, info
->data
, info
->data_len
);
2799 if (status
!= RPC_S_OK
) break;
2801 prepare_async_request(httpc
->async_data
);
2802 ret
= HttpSendRequestW(request
, NULL
, 0, NULL
, 0);
2803 status
= wait_async_request(httpc
->async_data
, ret
, httpc
->cancel_event
);
2804 if (status
!= RPC_S_OK
|| info
->finished
) break;
2806 status
= rpcrt4_http_check_response(request
);
2807 if (status
!= RPC_S_OK
&& status
!= ERROR_ACCESS_DENIED
) break;
2808 drain_content(request
);
2811 if (info
->scheme
!= RPC_C_HTTP_AUTHN_SCHEME_BASIC
)
2812 HttpAddRequestHeadersW(request
, authW
, -1, HTTP_ADDREQ_FLAG_REPLACE
);
2814 destroy_authinfo(info
);
2818 static RPC_STATUS
insert_cookie_header(HINTERNET request
, const WCHAR
*value
)
2820 static const WCHAR cookieW
[] = {'C','o','o','k','i','e',':',' '};
2821 WCHAR
*header
, *ptr
;
2823 RPC_STATUS status
= RPC_S_SERVER_UNAVAILABLE
;
2825 if (!value
) return RPC_S_OK
;
2827 len
= strlenW(value
);
2828 if ((header
= HeapAlloc(GetProcessHeap(), 0, sizeof(cookieW
) + (len
+ 3) * sizeof(WCHAR
))))
2830 memcpy(header
, cookieW
, sizeof(cookieW
));
2831 ptr
= header
+ sizeof(cookieW
) / sizeof(cookieW
[0]);
2832 memcpy(ptr
, value
, len
* sizeof(WCHAR
));
2836 if ((HttpAddRequestHeadersW(request
, header
, -1, HTTP_ADDREQ_FLAG_ADD_IF_NEW
))) status
= RPC_S_OK
;
2837 HeapFree(GetProcessHeap(), 0, header
);
2842 static BOOL
has_credentials(RpcConnection_http
*httpc
)
2844 RPC_HTTP_TRANSPORT_CREDENTIALS_W
*creds
;
2845 SEC_WINNT_AUTH_IDENTITY_W
*id
;
2847 if (!httpc
->common
.QOS
|| httpc
->common
.QOS
->qos
->AdditionalSecurityInfoType
!= RPC_C_AUTHN_INFO_TYPE_HTTP
)
2850 creds
= httpc
->common
.QOS
->qos
->u
.HttpCredentials
;
2851 if (creds
->AuthenticationTarget
!= RPC_C_HTTP_AUTHN_TARGET_SERVER
|| !creds
->NumberOfAuthnSchemes
)
2854 id
= creds
->TransportCredentials
;
2855 if (!id
|| !id
->User
|| !id
->Password
) return FALSE
;
2860 static BOOL
is_secure(RpcConnection_http
*httpc
)
2862 return httpc
->common
.QOS
&&
2863 (httpc
->common
.QOS
->qos
->AdditionalSecurityInfoType
== RPC_C_AUTHN_INFO_TYPE_HTTP
) &&
2864 (httpc
->common
.QOS
->qos
->u
.HttpCredentials
->Flags
& RPC_C_HTTP_FLAG_USE_SSL
);
2867 static RPC_STATUS
rpcrt4_ncacn_http_open(RpcConnection
* Connection
)
2869 RpcConnection_http
*httpc
= (RpcConnection_http
*)Connection
;
2870 static const WCHAR wszVerbIn
[] = {'R','P','C','_','I','N','_','D','A','T','A',0};
2871 static const WCHAR wszVerbOut
[] = {'R','P','C','_','O','U','T','_','D','A','T','A',0};
2872 static const WCHAR wszRpcProxyPrefix
[] = {'/','r','p','c','/','r','p','c','p','r','o','x','y','.','d','l','l','?',0};
2873 static const WCHAR wszColon
[] = {':',0};
2874 static const WCHAR wszAcceptType
[] = {'a','p','p','l','i','c','a','t','i','o','n','/','r','p','c',0};
2875 LPCWSTR wszAcceptTypes
[] = { wszAcceptType
, NULL
};
2879 BOOL secure
, credentials
;
2880 HttpTimerThreadData
*timer_data
;
2883 TRACE("(%s, %s)\n", Connection
->NetworkAddr
, Connection
->Endpoint
);
2885 if (Connection
->server
)
2887 ERR("ncacn_http servers not supported yet\n");
2888 return RPC_S_SERVER_UNAVAILABLE
;
2891 if (httpc
->in_request
)
2894 httpc
->async_data
->completion_event
= CreateEventW(NULL
, FALSE
, FALSE
, NULL
);
2896 status
= UuidCreate(&httpc
->connection_uuid
);
2897 status
= UuidCreate(&httpc
->in_pipe_uuid
);
2898 status
= UuidCreate(&httpc
->out_pipe_uuid
);
2900 status
= rpcrt4_http_internet_connect(httpc
);
2901 if (status
!= RPC_S_OK
)
2904 url
= HeapAlloc(GetProcessHeap(), 0, sizeof(wszRpcProxyPrefix
) + (strlen(Connection
->NetworkAddr
) + 1 + strlen(Connection
->Endpoint
))*sizeof(WCHAR
));
2906 return RPC_S_OUT_OF_MEMORY
;
2907 memcpy(url
, wszRpcProxyPrefix
, sizeof(wszRpcProxyPrefix
));
2908 MultiByteToWideChar(CP_ACP
, 0, Connection
->NetworkAddr
, -1, url
+sizeof(wszRpcProxyPrefix
)/sizeof(wszRpcProxyPrefix
[0])-1, strlen(Connection
->NetworkAddr
)+1);
2909 strcatW(url
, wszColon
);
2910 MultiByteToWideChar(CP_ACP
, 0, Connection
->Endpoint
, -1, url
+strlenW(url
), strlen(Connection
->Endpoint
)+1);
2912 secure
= is_secure(httpc
);
2913 credentials
= has_credentials(httpc
);
2915 flags
= INTERNET_FLAG_KEEP_CONNECTION
| INTERNET_FLAG_PRAGMA_NOCACHE
| INTERNET_FLAG_NO_CACHE_WRITE
|
2916 INTERNET_FLAG_NO_AUTO_REDIRECT
;
2917 if (secure
) flags
|= INTERNET_FLAG_SECURE
;
2918 if (credentials
) flags
|= INTERNET_FLAG_NO_AUTH
;
2920 httpc
->in_request
= HttpOpenRequestW(httpc
->session
, wszVerbIn
, url
, NULL
, NULL
, wszAcceptTypes
,
2921 flags
, (DWORD_PTR
)httpc
->async_data
);
2922 if (!httpc
->in_request
)
2924 ERR("HttpOpenRequestW failed with error %d\n", GetLastError());
2925 HeapFree(GetProcessHeap(), 0, url
);
2926 return RPC_S_SERVER_UNAVAILABLE
;
2928 status
= insert_cookie_header(httpc
->in_request
, Connection
->CookieAuth
);
2929 if (status
!= RPC_S_OK
)
2931 HeapFree(GetProcessHeap(), 0, url
);
2936 status
= authorize_request(httpc
, httpc
->in_request
);
2937 if (status
!= RPC_S_OK
)
2939 HeapFree(GetProcessHeap(), 0, url
);
2942 status
= rpcrt4_http_check_response(httpc
->in_request
);
2943 if (status
!= RPC_S_OK
)
2945 HeapFree(GetProcessHeap(), 0, url
);
2948 drain_content(httpc
->in_request
);
2951 httpc
->out_request
= HttpOpenRequestW(httpc
->session
, wszVerbOut
, url
, NULL
, NULL
, wszAcceptTypes
,
2952 flags
, (DWORD_PTR
)httpc
->async_data
);
2953 HeapFree(GetProcessHeap(), 0, url
);
2954 if (!httpc
->out_request
)
2956 ERR("HttpOpenRequestW failed with error %d\n", GetLastError());
2957 return RPC_S_SERVER_UNAVAILABLE
;
2959 status
= insert_cookie_header(httpc
->out_request
, Connection
->CookieAuth
);
2960 if (status
!= RPC_S_OK
)
2965 status
= authorize_request(httpc
, httpc
->out_request
);
2966 if (status
!= RPC_S_OK
)
2970 status
= rpcrt4_http_prepare_in_pipe(httpc
->in_request
, httpc
->async_data
, httpc
->cancel_event
,
2971 &httpc
->connection_uuid
, &httpc
->in_pipe_uuid
,
2972 &Connection
->assoc
->http_uuid
, credentials
);
2973 if (status
!= RPC_S_OK
)
2976 status
= rpcrt4_http_prepare_out_pipe(httpc
->out_request
, httpc
->async_data
, httpc
->cancel_event
,
2977 &httpc
->connection_uuid
, &httpc
->out_pipe_uuid
,
2978 &httpc
->flow_control_increment
, credentials
);
2979 if (status
!= RPC_S_OK
)
2982 httpc
->flow_control_mark
= httpc
->flow_control_increment
/ 2;
2983 httpc
->last_sent_time
= GetTickCount();
2984 httpc
->timer_cancelled
= CreateEventW(NULL
, FALSE
, FALSE
, NULL
);
2986 timer_data
= HeapAlloc(GetProcessHeap(), 0, sizeof(*timer_data
));
2988 return ERROR_OUTOFMEMORY
;
2989 timer_data
->timer_param
= httpc
->in_request
;
2990 timer_data
->last_sent_time
= &httpc
->last_sent_time
;
2991 timer_data
->timer_cancelled
= httpc
->timer_cancelled
;
2992 /* FIXME: should use CreateTimerQueueTimer when implemented */
2993 thread
= CreateThread(NULL
, 0, rpcrt4_http_timer_thread
, timer_data
, 0, NULL
);
2996 HeapFree(GetProcessHeap(), 0, timer_data
);
2997 return GetLastError();
2999 CloseHandle(thread
);
3004 static RPC_STATUS
rpcrt4_ncacn_http_handoff(RpcConnection
*old_conn
, RpcConnection
*new_conn
)
3007 return RPC_S_SERVER_UNAVAILABLE
;
3010 static int rpcrt4_ncacn_http_read(RpcConnection
*Connection
,
3011 void *buffer
, unsigned int count
)
3013 RpcConnection_http
*httpc
= (RpcConnection_http
*) Connection
;
3016 unsigned int bytes_left
= count
;
3017 RPC_STATUS status
= RPC_S_OK
;
3019 httpc
->async_data
->inet_buffers
.lpvBuffer
= HeapAlloc(GetProcessHeap(), 0, count
);
3023 httpc
->async_data
->inet_buffers
.dwBufferLength
= bytes_left
;
3024 prepare_async_request(httpc
->async_data
);
3025 ret
= InternetReadFileExA(httpc
->out_request
, &httpc
->async_data
->inet_buffers
, IRF_ASYNC
, 0);
3026 status
= wait_async_request(httpc
->async_data
, ret
, httpc
->cancel_event
);
3027 if(status
!= RPC_S_OK
) {
3028 if(status
== RPC_S_CALL_CANCELLED
)
3029 TRACE("call cancelled\n");
3033 if(!httpc
->async_data
->inet_buffers
.dwBufferLength
)
3035 memcpy(buf
, httpc
->async_data
->inet_buffers
.lpvBuffer
,
3036 httpc
->async_data
->inet_buffers
.dwBufferLength
);
3038 bytes_left
-= httpc
->async_data
->inet_buffers
.dwBufferLength
;
3039 buf
+= httpc
->async_data
->inet_buffers
.dwBufferLength
;
3042 HeapFree(GetProcessHeap(), 0, httpc
->async_data
->inet_buffers
.lpvBuffer
);
3043 httpc
->async_data
->inet_buffers
.lpvBuffer
= NULL
;
3045 TRACE("%p %p %u -> %u\n", httpc
->out_request
, buffer
, count
, status
);
3046 return status
== RPC_S_OK
? count
: -1;
3049 static RPC_STATUS
rpcrt4_ncacn_http_receive_fragment(RpcConnection
*Connection
, RpcPktHdr
**Header
, void **Payload
)
3051 RpcConnection_http
*httpc
= (RpcConnection_http
*) Connection
;
3055 RpcPktCommonHdr common_hdr
;
3059 TRACE("(%p, %p, %p)\n", Connection
, Header
, Payload
);
3062 /* read packet common header */
3063 dwRead
= rpcrt4_ncacn_http_read(Connection
, &common_hdr
, sizeof(common_hdr
));
3064 if (dwRead
!= sizeof(common_hdr
)) {
3065 WARN("Short read of header, %d bytes\n", dwRead
);
3066 status
= RPC_S_PROTOCOL_ERROR
;
3069 if (!memcmp(&common_hdr
, "HTTP/1.1", sizeof("HTTP/1.1")) ||
3070 !memcmp(&common_hdr
, "HTTP/1.0", sizeof("HTTP/1.0")))
3072 FIXME("server returned %s\n", debugstr_a((const char *)&common_hdr
));
3073 status
= RPC_S_PROTOCOL_ERROR
;
3077 status
= RPCRT4_ValidateCommonHeader(&common_hdr
);
3078 if (status
!= RPC_S_OK
) goto fail
;
3080 hdr_length
= RPCRT4_GetHeaderSize((RpcPktHdr
*)&common_hdr
);
3081 if (hdr_length
== 0) {
3082 WARN("header length == 0\n");
3083 status
= RPC_S_PROTOCOL_ERROR
;
3087 *Header
= HeapAlloc(GetProcessHeap(), 0, hdr_length
);
3090 status
= RPC_S_OUT_OF_RESOURCES
;
3093 memcpy(*Header
, &common_hdr
, sizeof(common_hdr
));
3095 /* read the rest of packet header */
3096 dwRead
= rpcrt4_ncacn_http_read(Connection
, &(*Header
)->common
+ 1, hdr_length
- sizeof(common_hdr
));
3097 if (dwRead
!= hdr_length
- sizeof(common_hdr
)) {
3098 WARN("bad header length, %d bytes, hdr_length %d\n", dwRead
, hdr_length
);
3099 status
= RPC_S_PROTOCOL_ERROR
;
3103 if (common_hdr
.frag_len
- hdr_length
)
3105 *Payload
= HeapAlloc(GetProcessHeap(), 0, common_hdr
.frag_len
- hdr_length
);
3108 status
= RPC_S_OUT_OF_RESOURCES
;
3112 dwRead
= rpcrt4_ncacn_http_read(Connection
, *Payload
, common_hdr
.frag_len
- hdr_length
);
3113 if (dwRead
!= common_hdr
.frag_len
- hdr_length
)
3115 WARN("bad data length, %d/%d\n", dwRead
, common_hdr
.frag_len
- hdr_length
);
3116 status
= RPC_S_PROTOCOL_ERROR
;
3123 if ((*Header
)->common
.ptype
== PKT_HTTP
)
3125 if (!RPCRT4_IsValidHttpPacket(*Header
, *Payload
, common_hdr
.frag_len
- hdr_length
))
3127 ERR("invalid http packet of length %d bytes\n", (*Header
)->common
.frag_len
);
3128 status
= RPC_S_PROTOCOL_ERROR
;
3131 if ((*Header
)->http
.flags
== 0x0001)
3133 TRACE("http idle packet, waiting for real packet\n");
3134 if ((*Header
)->http
.num_data_items
!= 0)
3136 ERR("HTTP idle packet should have no data items instead of %d\n", (*Header
)->http
.num_data_items
);
3137 status
= RPC_S_PROTOCOL_ERROR
;
3141 else if ((*Header
)->http
.flags
== 0x0002)
3143 ULONG bytes_transmitted
;
3144 ULONG flow_control_increment
;
3146 status
= RPCRT4_ParseHttpFlowControlHeader(*Header
, *Payload
,
3149 &flow_control_increment
,
3151 if (status
!= RPC_S_OK
)
3153 TRACE("received http flow control header (0x%x, 0x%x, %s)\n",
3154 bytes_transmitted
, flow_control_increment
, debugstr_guid(&pipe_uuid
));
3155 /* FIXME: do something with parsed data */
3159 FIXME("unrecognised http packet with flags 0x%04x\n", (*Header
)->http
.flags
);
3160 status
= RPC_S_PROTOCOL_ERROR
;
3163 RPCRT4_FreeHeader(*Header
);
3165 HeapFree(GetProcessHeap(), 0, *Payload
);
3173 httpc
->bytes_received
+= common_hdr
.frag_len
;
3175 TRACE("httpc->bytes_received = 0x%x\n", httpc
->bytes_received
);
3177 if (httpc
->bytes_received
> httpc
->flow_control_mark
)
3179 RpcPktHdr
*hdr
= RPCRT4_BuildHttpFlowControlHeader(httpc
->common
.server
,
3180 httpc
->bytes_received
,
3181 httpc
->flow_control_increment
,
3182 &httpc
->out_pipe_uuid
);
3185 DWORD bytes_written
;
3187 TRACE("sending flow control packet at 0x%x\n", httpc
->bytes_received
);
3188 ret2
= InternetWriteFile(httpc
->in_request
, hdr
, hdr
->common
.frag_len
, &bytes_written
);
3189 RPCRT4_FreeHeader(hdr
);
3191 httpc
->flow_control_mark
= httpc
->bytes_received
+ httpc
->flow_control_increment
/ 2;
3196 if (status
!= RPC_S_OK
) {
3197 RPCRT4_FreeHeader(*Header
);
3199 HeapFree(GetProcessHeap(), 0, *Payload
);
3205 static int rpcrt4_ncacn_http_write(RpcConnection
*Connection
,
3206 const void *buffer
, unsigned int count
)
3208 RpcConnection_http
*httpc
= (RpcConnection_http
*) Connection
;
3209 DWORD bytes_written
;
3212 httpc
->last_sent_time
= ~0U; /* disable idle packet sending */
3213 ret
= InternetWriteFile(httpc
->in_request
, buffer
, count
, &bytes_written
);
3214 httpc
->last_sent_time
= GetTickCount();
3215 TRACE("%p %p %u -> %s\n", httpc
->in_request
, buffer
, count
, ret
? "TRUE" : "FALSE");
3216 return ret
? bytes_written
: -1;
3219 static int rpcrt4_ncacn_http_close(RpcConnection
*Connection
)
3221 RpcConnection_http
*httpc
= (RpcConnection_http
*) Connection
;
3225 SetEvent(httpc
->timer_cancelled
);
3226 if (httpc
->in_request
)
3227 InternetCloseHandle(httpc
->in_request
);
3228 httpc
->in_request
= NULL
;
3229 if (httpc
->out_request
)
3230 InternetCloseHandle(httpc
->out_request
);
3231 httpc
->out_request
= NULL
;
3232 if (httpc
->app_info
)
3233 InternetCloseHandle(httpc
->app_info
);
3234 httpc
->app_info
= NULL
;
3236 InternetCloseHandle(httpc
->session
);
3237 httpc
->session
= NULL
;
3238 RpcHttpAsyncData_Release(httpc
->async_data
);
3239 if (httpc
->cancel_event
)
3240 CloseHandle(httpc
->cancel_event
);
3241 HeapFree(GetProcessHeap(), 0, httpc
->servername
);
3242 httpc
->servername
= NULL
;
3247 static void rpcrt4_ncacn_http_cancel_call(RpcConnection
*Connection
)
3249 RpcConnection_http
*httpc
= (RpcConnection_http
*) Connection
;
3251 SetEvent(httpc
->cancel_event
);
3254 static int rpcrt4_ncacn_http_wait_for_incoming_data(RpcConnection
*Connection
)
3256 RpcConnection_http
*httpc
= (RpcConnection_http
*) Connection
;
3260 prepare_async_request(httpc
->async_data
);
3261 ret
= InternetQueryDataAvailable(httpc
->out_request
,
3262 &httpc
->async_data
->inet_buffers
.dwBufferLength
, IRF_ASYNC
, 0);
3263 status
= wait_async_request(httpc
->async_data
, ret
, httpc
->cancel_event
);
3264 return status
== RPC_S_OK
? 0 : -1;
3267 static size_t rpcrt4_ncacn_http_get_top_of_tower(unsigned char *tower_data
,
3268 const char *networkaddr
,
3269 const char *endpoint
)
3271 return rpcrt4_ip_tcp_get_top_of_tower(tower_data
, networkaddr
,
3272 EPM_PROTOCOL_HTTP
, endpoint
);
3275 static RPC_STATUS
rpcrt4_ncacn_http_parse_top_of_tower(const unsigned char *tower_data
,
3280 return rpcrt4_ip_tcp_parse_top_of_tower(tower_data
, tower_size
,
3281 networkaddr
, EPM_PROTOCOL_HTTP
,
3285 static const struct connection_ops conn_protseq_list
[] = {
3287 { EPM_PROTOCOL_NCACN
, EPM_PROTOCOL_SMB
},
3288 rpcrt4_conn_np_alloc
,
3289 rpcrt4_ncacn_np_open
,
3290 rpcrt4_ncacn_np_handoff
,
3291 rpcrt4_conn_np_read
,
3292 rpcrt4_conn_np_write
,
3293 rpcrt4_conn_np_close
,
3294 rpcrt4_conn_np_cancel_call
,
3295 rpcrt4_conn_np_wait_for_incoming_data
,
3296 rpcrt4_ncacn_np_get_top_of_tower
,
3297 rpcrt4_ncacn_np_parse_top_of_tower
,
3299 RPCRT4_default_is_authorized
,
3300 RPCRT4_default_authorize
,
3301 RPCRT4_default_secure_packet
,
3302 rpcrt4_conn_np_impersonate_client
,
3303 rpcrt4_conn_np_revert_to_self
,
3304 RPCRT4_default_inquire_auth_client
,
3307 { EPM_PROTOCOL_NCALRPC
, EPM_PROTOCOL_PIPE
},
3308 rpcrt4_conn_np_alloc
,
3309 rpcrt4_ncalrpc_open
,
3310 rpcrt4_ncalrpc_handoff
,
3311 rpcrt4_conn_np_read
,
3312 rpcrt4_conn_np_write
,
3313 rpcrt4_conn_np_close
,
3314 rpcrt4_conn_np_cancel_call
,
3315 rpcrt4_conn_np_wait_for_incoming_data
,
3316 rpcrt4_ncalrpc_get_top_of_tower
,
3317 rpcrt4_ncalrpc_parse_top_of_tower
,
3319 rpcrt4_ncalrpc_is_authorized
,
3320 rpcrt4_ncalrpc_authorize
,
3321 rpcrt4_ncalrpc_secure_packet
,
3322 rpcrt4_conn_np_impersonate_client
,
3323 rpcrt4_conn_np_revert_to_self
,
3324 rpcrt4_ncalrpc_inquire_auth_client
,
3327 { EPM_PROTOCOL_NCACN
, EPM_PROTOCOL_TCP
},
3328 rpcrt4_conn_tcp_alloc
,
3329 rpcrt4_ncacn_ip_tcp_open
,
3330 rpcrt4_conn_tcp_handoff
,
3331 rpcrt4_conn_tcp_read
,
3332 rpcrt4_conn_tcp_write
,
3333 rpcrt4_conn_tcp_close
,
3334 rpcrt4_conn_tcp_cancel_call
,
3335 rpcrt4_conn_tcp_wait_for_incoming_data
,
3336 rpcrt4_ncacn_ip_tcp_get_top_of_tower
,
3337 rpcrt4_ncacn_ip_tcp_parse_top_of_tower
,
3339 RPCRT4_default_is_authorized
,
3340 RPCRT4_default_authorize
,
3341 RPCRT4_default_secure_packet
,
3342 RPCRT4_default_impersonate_client
,
3343 RPCRT4_default_revert_to_self
,
3344 RPCRT4_default_inquire_auth_client
,
3347 { EPM_PROTOCOL_NCACN
, EPM_PROTOCOL_HTTP
},
3348 rpcrt4_ncacn_http_alloc
,
3349 rpcrt4_ncacn_http_open
,
3350 rpcrt4_ncacn_http_handoff
,
3351 rpcrt4_ncacn_http_read
,
3352 rpcrt4_ncacn_http_write
,
3353 rpcrt4_ncacn_http_close
,
3354 rpcrt4_ncacn_http_cancel_call
,
3355 rpcrt4_ncacn_http_wait_for_incoming_data
,
3356 rpcrt4_ncacn_http_get_top_of_tower
,
3357 rpcrt4_ncacn_http_parse_top_of_tower
,
3358 rpcrt4_ncacn_http_receive_fragment
,
3359 RPCRT4_default_is_authorized
,
3360 RPCRT4_default_authorize
,
3361 RPCRT4_default_secure_packet
,
3362 RPCRT4_default_impersonate_client
,
3363 RPCRT4_default_revert_to_self
,
3364 RPCRT4_default_inquire_auth_client
,
3369 static const struct protseq_ops protseq_list
[] =
3373 rpcrt4_protseq_np_alloc
,
3374 rpcrt4_protseq_np_signal_state_changed
,
3375 rpcrt4_protseq_np_get_wait_array
,
3376 rpcrt4_protseq_np_free_wait_array
,
3377 rpcrt4_protseq_np_wait_for_new_connection
,
3378 rpcrt4_protseq_ncacn_np_open_endpoint
,
3382 rpcrt4_protseq_np_alloc
,
3383 rpcrt4_protseq_np_signal_state_changed
,
3384 rpcrt4_protseq_np_get_wait_array
,
3385 rpcrt4_protseq_np_free_wait_array
,
3386 rpcrt4_protseq_np_wait_for_new_connection
,
3387 rpcrt4_protseq_ncalrpc_open_endpoint
,
3391 rpcrt4_protseq_sock_alloc
,
3392 rpcrt4_protseq_sock_signal_state_changed
,
3393 rpcrt4_protseq_sock_get_wait_array
,
3394 rpcrt4_protseq_sock_free_wait_array
,
3395 rpcrt4_protseq_sock_wait_for_new_connection
,
3396 rpcrt4_protseq_ncacn_ip_tcp_open_endpoint
,
3400 const struct protseq_ops
*rpcrt4_get_protseq_ops(const char *protseq
)
3403 for(i
=0; i
<ARRAYSIZE(protseq_list
); i
++)
3404 if (!strcmp(protseq_list
[i
].name
, protseq
))
3405 return &protseq_list
[i
];
3409 static const struct connection_ops
*rpcrt4_get_conn_protseq_ops(const char *protseq
)
3412 for(i
=0; i
<ARRAYSIZE(conn_protseq_list
); i
++)
3413 if (!strcmp(conn_protseq_list
[i
].name
, protseq
))
3414 return &conn_protseq_list
[i
];
3418 /**** interface to rest of code ****/
3420 RPC_STATUS
RPCRT4_OpenClientConnection(RpcConnection
* Connection
)
3422 TRACE("(Connection == ^%p)\n", Connection
);
3424 assert(!Connection
->server
);
3425 return Connection
->ops
->open_connection_client(Connection
);
3428 RPC_STATUS
RPCRT4_CloseConnection(RpcConnection
* Connection
)
3430 TRACE("(Connection == ^%p)\n", Connection
);
3431 if (SecIsValidHandle(&Connection
->ctx
))
3433 DeleteSecurityContext(&Connection
->ctx
);
3434 SecInvalidateHandle(&Connection
->ctx
);
3436 rpcrt4_conn_close(Connection
);
3440 RPC_STATUS
RPCRT4_CreateConnection(RpcConnection
** Connection
, BOOL server
,
3441 LPCSTR Protseq
, LPCSTR NetworkAddr
, LPCSTR Endpoint
,
3442 LPCWSTR NetworkOptions
, RpcAuthInfo
* AuthInfo
, RpcQualityOfService
*QOS
, LPCWSTR CookieAuth
)
3444 static LONG next_id
;
3445 const struct connection_ops
*ops
;
3446 RpcConnection
* NewConnection
;
3448 ops
= rpcrt4_get_conn_protseq_ops(Protseq
);
3451 FIXME("not supported for protseq %s\n", Protseq
);
3452 return RPC_S_PROTSEQ_NOT_SUPPORTED
;
3455 NewConnection
= ops
->alloc();
3456 NewConnection
->ref
= 1;
3457 NewConnection
->Next
= NULL
;
3458 NewConnection
->server_binding
= NULL
;
3459 NewConnection
->server
= server
;
3460 NewConnection
->ops
= ops
;
3461 NewConnection
->NetworkAddr
= RPCRT4_strdupA(NetworkAddr
);
3462 NewConnection
->Endpoint
= RPCRT4_strdupA(Endpoint
);
3463 NewConnection
->NetworkOptions
= RPCRT4_strdupW(NetworkOptions
);
3464 NewConnection
->CookieAuth
= RPCRT4_strdupW(CookieAuth
);
3465 NewConnection
->MaxTransmissionSize
= RPC_MAX_PACKET_SIZE
;
3466 memset(&NewConnection
->ActiveInterface
, 0, sizeof(NewConnection
->ActiveInterface
));
3467 NewConnection
->NextCallId
= 1;
3469 SecInvalidateHandle(&NewConnection
->ctx
);
3470 memset(&NewConnection
->exp
, 0, sizeof(NewConnection
->exp
));
3471 NewConnection
->attr
= 0;
3472 if (AuthInfo
) RpcAuthInfo_AddRef(AuthInfo
);
3473 NewConnection
->AuthInfo
= AuthInfo
;
3474 NewConnection
->auth_context_id
= InterlockedIncrement( &next_id
);
3475 NewConnection
->encryption_auth_len
= 0;
3476 NewConnection
->signature_auth_len
= 0;
3477 if (QOS
) RpcQualityOfService_AddRef(QOS
);
3478 NewConnection
->QOS
= QOS
;
3480 list_init(&NewConnection
->conn_pool_entry
);
3481 NewConnection
->async_state
= NULL
;
3483 TRACE("connection: %p\n", NewConnection
);
3484 *Connection
= NewConnection
;
3489 static RPC_STATUS
RPCRT4_SpawnConnection(RpcConnection
** Connection
, RpcConnection
* OldConnection
)
3493 err
= RPCRT4_CreateConnection(Connection
, OldConnection
->server
, rpcrt4_conn_get_name(OldConnection
),
3494 OldConnection
->NetworkAddr
, OldConnection
->Endpoint
, NULL
,
3495 OldConnection
->AuthInfo
, OldConnection
->QOS
, OldConnection
->CookieAuth
);
3496 if (err
== RPC_S_OK
)
3497 rpcrt4_conn_handoff(OldConnection
, *Connection
);
3501 RpcConnection
*RPCRT4_GrabConnection( RpcConnection
*conn
)
3503 InterlockedIncrement( &conn
->ref
);
3507 RPC_STATUS
RPCRT4_ReleaseConnection(RpcConnection
* Connection
)
3509 if (InterlockedDecrement( &Connection
->ref
) > 0) return RPC_S_OK
;
3511 TRACE("destroying connection %p\n", Connection
);
3513 RPCRT4_CloseConnection(Connection
);
3514 RPCRT4_strfree(Connection
->Endpoint
);
3515 RPCRT4_strfree(Connection
->NetworkAddr
);
3516 HeapFree(GetProcessHeap(), 0, Connection
->NetworkOptions
);
3517 HeapFree(GetProcessHeap(), 0, Connection
->CookieAuth
);
3518 if (Connection
->AuthInfo
) RpcAuthInfo_Release(Connection
->AuthInfo
);
3519 if (Connection
->QOS
) RpcQualityOfService_Release(Connection
->QOS
);
3522 if (Connection
->server_binding
) RPCRT4_ReleaseBinding(Connection
->server_binding
);
3524 HeapFree(GetProcessHeap(), 0, Connection
);
3528 RPC_STATUS
RpcTransport_GetTopOfTower(unsigned char *tower_data
,
3530 const char *protseq
,
3531 const char *networkaddr
,
3532 const char *endpoint
)
3534 twr_empty_floor_t
*protocol_floor
;
3535 const struct connection_ops
*protseq_ops
= rpcrt4_get_conn_protseq_ops(protseq
);
3540 return RPC_S_INVALID_RPC_PROTSEQ
;
3544 *tower_size
= sizeof(*protocol_floor
);
3545 *tower_size
+= protseq_ops
->get_top_of_tower(NULL
, networkaddr
, endpoint
);
3549 protocol_floor
= (twr_empty_floor_t
*)tower_data
;
3550 protocol_floor
->count_lhs
= sizeof(protocol_floor
->protid
);
3551 protocol_floor
->protid
= protseq_ops
->epm_protocols
[0];
3552 protocol_floor
->count_rhs
= 0;
3554 tower_data
+= sizeof(*protocol_floor
);
3556 *tower_size
= protseq_ops
->get_top_of_tower(tower_data
, networkaddr
, endpoint
);
3558 return EPT_S_NOT_REGISTERED
;
3560 *tower_size
+= sizeof(*protocol_floor
);
3565 RPC_STATUS
RpcTransport_ParseTopOfTower(const unsigned char *tower_data
,
3571 const twr_empty_floor_t
*protocol_floor
;
3572 const twr_empty_floor_t
*floor4
;
3573 const struct connection_ops
*protseq_ops
= NULL
;
3577 if (tower_size
< sizeof(*protocol_floor
))
3578 return EPT_S_NOT_REGISTERED
;
3580 protocol_floor
= (const twr_empty_floor_t
*)tower_data
;
3581 tower_data
+= sizeof(*protocol_floor
);
3582 tower_size
-= sizeof(*protocol_floor
);
3583 if ((protocol_floor
->count_lhs
!= sizeof(protocol_floor
->protid
)) ||
3584 (protocol_floor
->count_rhs
> tower_size
))
3585 return EPT_S_NOT_REGISTERED
;
3586 tower_data
+= protocol_floor
->count_rhs
;
3587 tower_size
-= protocol_floor
->count_rhs
;
3589 floor4
= (const twr_empty_floor_t
*)tower_data
;
3590 if ((tower_size
< sizeof(*floor4
)) ||
3591 (floor4
->count_lhs
!= sizeof(floor4
->protid
)))
3592 return EPT_S_NOT_REGISTERED
;
3594 for(i
= 0; i
< ARRAYSIZE(conn_protseq_list
); i
++)
3595 if ((protocol_floor
->protid
== conn_protseq_list
[i
].epm_protocols
[0]) &&
3596 (floor4
->protid
== conn_protseq_list
[i
].epm_protocols
[1]))
3598 protseq_ops
= &conn_protseq_list
[i
];
3603 return EPT_S_NOT_REGISTERED
;
3605 status
= protseq_ops
->parse_top_of_tower(tower_data
, tower_size
, networkaddr
, endpoint
);
3607 if ((status
== RPC_S_OK
) && protseq
)
3609 *protseq
= I_RpcAllocate(strlen(protseq_ops
->name
) + 1);
3610 strcpy(*protseq
, protseq_ops
->name
);
3616 /***********************************************************************
3617 * RpcNetworkIsProtseqValidW (RPCRT4.@)
3619 * Checks if the given protocol sequence is known by the RPC system.
3620 * If it is, returns RPC_S_OK, otherwise RPC_S_PROTSEQ_NOT_SUPPORTED.
3623 RPC_STATUS WINAPI
RpcNetworkIsProtseqValidW(RPC_WSTR protseq
)
3627 WideCharToMultiByte(CP_ACP
, 0, protseq
, -1,
3628 ps
, sizeof ps
, NULL
, NULL
);
3629 if (rpcrt4_get_conn_protseq_ops(ps
))
3632 FIXME("Unknown protseq %s\n", debugstr_w(protseq
));
3634 return RPC_S_INVALID_RPC_PROTSEQ
;
3637 /***********************************************************************
3638 * RpcNetworkIsProtseqValidA (RPCRT4.@)
3640 RPC_STATUS WINAPI
RpcNetworkIsProtseqValidA(RPC_CSTR protseq
)
3642 UNICODE_STRING protseqW
;
3644 if (RtlCreateUnicodeStringFromAsciiz(&protseqW
, (char*)protseq
))
3646 RPC_STATUS ret
= RpcNetworkIsProtseqValidW(protseqW
.Buffer
);
3647 RtlFreeUnicodeString(&protseqW
);
3650 return RPC_S_OUT_OF_MEMORY
;
3653 /***********************************************************************
3654 * RpcProtseqVectorFreeA (RPCRT4.@)
3656 RPC_STATUS WINAPI
RpcProtseqVectorFreeA(RPC_PROTSEQ_VECTORA
**protseqs
)
3658 TRACE("(%p)\n", protseqs
);
3663 for (i
= 0; i
< (*protseqs
)->Count
; i
++)
3664 HeapFree(GetProcessHeap(), 0, (*protseqs
)->Protseq
[i
]);
3665 HeapFree(GetProcessHeap(), 0, *protseqs
);
3671 /***********************************************************************
3672 * RpcProtseqVectorFreeW (RPCRT4.@)
3674 RPC_STATUS WINAPI
RpcProtseqVectorFreeW(RPC_PROTSEQ_VECTORW
**protseqs
)
3676 TRACE("(%p)\n", protseqs
);
3681 for (i
= 0; i
< (*protseqs
)->Count
; i
++)
3682 HeapFree(GetProcessHeap(), 0, (*protseqs
)->Protseq
[i
]);
3683 HeapFree(GetProcessHeap(), 0, *protseqs
);
3689 /***********************************************************************
3690 * RpcNetworkInqProtseqsW (RPCRT4.@)
3692 RPC_STATUS WINAPI
RpcNetworkInqProtseqsW( RPC_PROTSEQ_VECTORW
** protseqs
)
3694 RPC_PROTSEQ_VECTORW
*pvector
;
3696 RPC_STATUS status
= RPC_S_OUT_OF_MEMORY
;
3698 TRACE("(%p)\n", protseqs
);
3700 *protseqs
= HeapAlloc(GetProcessHeap(), 0, sizeof(RPC_PROTSEQ_VECTORW
)+(sizeof(unsigned short*)*ARRAYSIZE(protseq_list
)));
3703 pvector
= *protseqs
;
3705 for (i
= 0; i
< ARRAYSIZE(protseq_list
); i
++)
3707 pvector
->Protseq
[i
] = HeapAlloc(GetProcessHeap(), 0, (strlen(protseq_list
[i
].name
)+1)*sizeof(unsigned short));
3708 if (pvector
->Protseq
[i
] == NULL
)
3710 MultiByteToWideChar(CP_ACP
, 0, (CHAR
*)protseq_list
[i
].name
, -1,
3711 (WCHAR
*)pvector
->Protseq
[i
], strlen(protseq_list
[i
].name
) + 1);
3717 if (status
!= RPC_S_OK
)
3718 RpcProtseqVectorFreeW(protseqs
);
3722 /***********************************************************************
3723 * RpcNetworkInqProtseqsA (RPCRT4.@)
3725 RPC_STATUS WINAPI
RpcNetworkInqProtseqsA(RPC_PROTSEQ_VECTORA
** protseqs
)
3727 RPC_PROTSEQ_VECTORA
*pvector
;
3729 RPC_STATUS status
= RPC_S_OUT_OF_MEMORY
;
3731 TRACE("(%p)\n", protseqs
);
3733 *protseqs
= HeapAlloc(GetProcessHeap(), 0, sizeof(RPC_PROTSEQ_VECTORW
)+(sizeof(unsigned char*)*ARRAYSIZE(protseq_list
)));
3736 pvector
= *protseqs
;
3738 for (i
= 0; i
< ARRAYSIZE(protseq_list
); i
++)
3740 pvector
->Protseq
[i
] = HeapAlloc(GetProcessHeap(), 0, strlen(protseq_list
[i
].name
)+1);
3741 if (pvector
->Protseq
[i
] == NULL
)
3743 strcpy((char*)pvector
->Protseq
[i
], protseq_list
[i
].name
);
3749 if (status
!= RPC_S_OK
)
3750 RpcProtseqVectorFreeA(protseqs
);