winejoystick: Fix a crash on accessing a CFArray past its end due to an off-by-one...
[wine/multimedia.git] / dlls / rpcrt4 / rpc_transport.c
blob3016d830d9bcc029719a1cf59bcbc2ea885678cd
1 /*
2 * RPC transport layer
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
26 #include "config.h"
28 #include <stdarg.h>
29 #include <stdio.h>
30 #include <string.h>
31 #include <assert.h>
32 #include <errno.h>
33 #include <stdlib.h>
34 #include <sys/types.h>
36 #if defined(__MINGW32__) || defined (_MSC_VER)
37 # include <ws2tcpip.h>
38 # ifndef EADDRINUSE
39 # define EADDRINUSE WSAEADDRINUSE
40 # endif
41 # ifndef EAGAIN
42 # define EAGAIN WSAEWOULDBLOCK
43 # endif
44 # undef errno
45 # define errno WSAGetLastError()
46 #else
47 # include <errno.h>
48 # ifdef HAVE_UNISTD_H
49 # include <unistd.h>
50 # endif
51 # include <fcntl.h>
52 # ifdef HAVE_SYS_SOCKET_H
53 # include <sys/socket.h>
54 # endif
55 # ifdef HAVE_NETINET_IN_H
56 # include <netinet/in.h>
57 # endif
58 # ifdef HAVE_NETINET_TCP_H
59 # include <netinet/tcp.h>
60 # endif
61 # ifdef HAVE_ARPA_INET_H
62 # include <arpa/inet.h>
63 # endif
64 # ifdef HAVE_NETDB_H
65 # include <netdb.h>
66 # endif
67 # ifdef HAVE_SYS_POLL_H
68 # include <sys/poll.h>
69 # endif
70 # ifdef HAVE_SYS_FILIO_H
71 # include <sys/filio.h>
72 # endif
73 # ifdef HAVE_SYS_IOCTL_H
74 # include <sys/ioctl.h>
75 # endif
76 # define closesocket close
77 # define ioctlsocket ioctl
78 #endif /* defined(__MINGW32__) || defined (_MSC_VER) */
80 #include "windef.h"
81 #include "winbase.h"
82 #include "winnls.h"
83 #include "winerror.h"
84 #include "wininet.h"
85 #include "winternl.h"
86 #include "wine/unicode.h"
88 #include "rpc.h"
89 #include "rpcndr.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"
99 #ifndef SOL_TCP
100 # define SOL_TCP IPPROTO_TCP
101 #endif
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;
116 HANDLE pipe;
117 HANDLE listen_thread;
118 BOOL listening;
119 } RpcConnection_np;
121 static RpcConnection *rpcrt4_conn_np_alloc(void)
123 RpcConnection_np *npc = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(RpcConnection_np));
124 return &npc->common;
127 static DWORD CALLBACK listen_thread(void *arg)
129 RpcConnection_np *npc = arg;
130 for (;;)
132 if (ConnectNamedPipe(npc->pipe, NULL))
133 return RPC_S_OK;
135 switch(GetLastError())
137 case ERROR_PIPE_CONNECTED:
138 return RPC_S_OK;
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 );
145 break;
146 default:
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)
156 if (npc->listening)
157 return RPC_S_OK;
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;
167 return RPC_S_OK;
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;
183 else
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 */
189 return RPC_S_OK;
192 static RPC_STATUS rpcrt4_conn_open_pipe(RpcConnection *Connection, LPCSTR pname, BOOL wait)
194 RpcConnection_np *npc = (RpcConnection_np *) Connection;
195 HANDLE pipe;
196 DWORD err, dwMode;
198 TRACE("connecting to %s\n", pname);
200 while (TRUE) {
201 DWORD dwFlags = 0;
202 if (Connection->QOS)
204 dwFlags = SECURITY_SQOS_PRESENT;
205 switch (Connection->QOS->qos->ImpersonationType)
207 case RPC_C_IMP_LEVEL_DEFAULT:
208 /* FIXME: what to do here? */
209 break;
210 case RPC_C_IMP_LEVEL_ANONYMOUS:
211 dwFlags |= SECURITY_ANONYMOUS;
212 break;
213 case RPC_C_IMP_LEVEL_IDENTIFY:
214 dwFlags |= SECURITY_IDENTIFICATION;
215 break;
216 case RPC_C_IMP_LEVEL_IMPERSONATE:
217 dwFlags |= SECURITY_IMPERSONATION;
218 break;
219 case RPC_C_IMP_LEVEL_DELEGATE:
220 dwFlags |= SECURITY_DELEGATION;
221 break;
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;
241 /* success */
242 /* pipe is connected; change to message-read mode. */
243 dwMode = PIPE_READMODE_MESSAGE;
244 SetNamedPipeHandleState(pipe, &dwMode, NULL, NULL);
245 npc->pipe = pipe;
247 return RPC_S_OK;
250 static RPC_STATUS rpcrt4_ncalrpc_open(RpcConnection* Connection)
252 RpcConnection_np *npc = (RpcConnection_np *) Connection;
253 static const char prefix[] = "\\\\.\\pipe\\lrpc\\";
254 RPC_STATUS r;
255 LPSTR pname;
257 /* already connected? */
258 if (npc->pipe)
259 return RPC_S_OK;
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);
266 I_RpcFree(pname);
268 return r;
271 static RPC_STATUS rpcrt4_protseq_ncalrpc_open_endpoint(RpcServerProtseq* protseq, const char *endpoint)
273 static const char prefix[] = "\\\\.\\pipe\\lrpc\\";
274 RPC_STATUS r;
275 LPSTR pname;
276 RpcConnection *Connection;
277 char generated_endpoint[22];
279 if (!endpoint)
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);
291 if (r != RPC_S_OK)
292 return r;
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);
299 I_RpcFree(pname);
301 EnterCriticalSection(&protseq->cs);
302 Connection->Next = protseq->conn;
303 protseq->conn = Connection;
304 LeaveCriticalSection(&protseq->cs);
306 return r;
309 static RPC_STATUS rpcrt4_ncacn_np_open(RpcConnection* Connection)
311 RpcConnection_np *npc = (RpcConnection_np *) Connection;
312 static const char prefix[] = "\\\\.";
313 RPC_STATUS r;
314 LPSTR pname;
316 /* already connected? */
317 if (npc->pipe)
318 return RPC_S_OK;
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);
324 I_RpcFree(pname);
326 return r;
329 static RPC_STATUS rpcrt4_protseq_ncacn_np_open_endpoint(RpcServerProtseq *protseq, const char *endpoint)
331 static const char prefix[] = "\\\\.";
332 RPC_STATUS r;
333 LPSTR pname;
334 RpcConnection *Connection;
335 char generated_endpoint[21];
337 if (!endpoint)
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);
349 if (r != RPC_S_OK)
350 return r;
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);
356 I_RpcFree(pname);
358 EnterCriticalSection(&protseq->cs);
359 Connection->Next = protseq->conn;
360 protseq->conn = Connection;
361 LeaveCriticalSection(&protseq->cs);
363 return r;
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;
373 old_npc->pipe = 0;
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)
380 RPC_STATUS status;
381 LPSTR pname;
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);
389 I_RpcFree(pname);
391 return status;
394 static RPC_STATUS rpcrt4_ncalrpc_handoff(RpcConnection *old_conn, RpcConnection *new_conn)
396 RPC_STATUS status;
397 LPSTR pname;
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);
407 I_RpcFree(pname);
409 return status;
412 static int rpcrt4_conn_np_read(RpcConnection *Connection,
413 void *buffer, unsigned int count)
415 RpcConnection_np *npc = (RpcConnection_np *) Connection;
416 char *buf = buffer;
417 BOOL ret = TRUE;
418 unsigned int bytes_left = count;
420 while (bytes_left)
422 DWORD bytes_read;
423 ret = ReadFile(npc->pipe, buf, bytes_left, &bytes_read, NULL);
424 if (!ret && GetLastError() == ERROR_MORE_DATA)
425 ret = TRUE;
426 if (!ret || !bytes_read)
427 break;
428 bytes_left -= bytes_read;
429 buf += 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;
439 BOOL ret = TRUE;
440 unsigned int bytes_left = count;
442 while (bytes_left)
444 DWORD bytes_written;
445 ret = WriteFile(npc->pipe, buf, bytes_left, &bytes_written, NULL);
446 if (!ret || !bytes_written)
447 break;
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;
457 if (npc->pipe) {
458 FlushFileBuffers(npc->pipe);
459 CloseHandle(npc->pipe);
460 npc->pipe = 0;
462 if (npc->listen_thread) {
463 CloseHandle(npc->listen_thread);
464 npc->listen_thread = 0;
466 return 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 */
477 return -1;
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;
486 size_t size;
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;
496 if (!tower_data)
497 return 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;
507 if (endpoint)
508 memcpy(tower_data, endpoint, endpoint_size);
509 else
510 tower_data[0] = 0;
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;
521 if (networkaddr)
522 memcpy(tower_data, networkaddr, networkaddr_size);
523 else
524 tower_data[0] = 0;
526 return size;
529 static RPC_STATUS rpcrt4_ncacn_np_parse_top_of_tower(const unsigned char *tower_data,
530 size_t tower_size,
531 char **networkaddr,
532 char **endpoint)
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;
551 if (endpoint)
553 *endpoint = I_RpcAllocate(smb_floor->count_rhs);
554 if (!*endpoint)
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;
575 if (networkaddr)
577 *networkaddr = I_RpcAllocate(nb_floor->count_rhs);
578 if (!*networkaddr)
580 if (endpoint)
582 I_RpcFree(*endpoint);
583 *endpoint = NULL;
585 return RPC_S_OUT_OF_RESOURCES;
587 memcpy(*networkaddr, tower_data, nb_floor->count_rhs);
590 return RPC_S_OK;
593 static RPC_STATUS rpcrt4_conn_np_impersonate_client(RpcConnection *conn)
595 RpcConnection_np *npc = (RpcConnection_np *)conn;
596 BOOL ret;
598 TRACE("(%p)\n", conn);
600 if (conn->AuthInfo && SecIsValidHandle(&conn->ctx))
601 return RPCRT4_default_impersonate_client(conn);
603 ret = ImpersonateNamedPipeClient(npc->pipe);
604 if (!ret)
606 DWORD error = GetLastError();
607 WARN("ImpersonateNamedPipeClient failed with error %u\n", error);
608 switch (error)
610 case ERROR_CANNOT_IMPERSONATE:
611 return RPC_S_NO_CONTEXT_AVAILABLE;
614 return RPC_S_OK;
617 static RPC_STATUS rpcrt4_conn_np_revert_to_self(RpcConnection *conn)
619 BOOL ret;
621 TRACE("(%p)\n", conn);
623 if (conn->AuthInfo && SecIsValidHandle(&conn->ctx))
624 return RPCRT4_default_revert_to_self(conn);
626 ret = RevertToSelf();
627 if (!ret)
629 WARN("RevertToSelf failed with error %u\n", GetLastError());
630 return RPC_S_NO_CONTEXT_AVAILABLE;
632 return RPC_S_OK;
635 typedef struct _RpcServerProtseq_np
637 RpcServerProtseq common;
638 HANDLE mgr_event;
639 } RpcServerProtseq_np;
641 static RpcServerProtseq *rpcrt4_protseq_np_alloc(void)
643 RpcServerProtseq_np *ps = HeapAlloc(GetProcessHeap(), 0, sizeof(*ps));
644 if (ps)
645 ps->mgr_event = CreateEventW(NULL, FALSE, FALSE, NULL);
646 return &ps->common;
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 */
664 *count = 1;
665 conn = CONTAINING_RECORD(protseq->conn, RpcConnection_np, common);
666 while (conn) {
667 rpcrt4_conn_listen_pipe(conn);
668 if (conn->listen_thread)
669 (*count)++;
670 conn = CONTAINING_RECORD(conn->common.Next, RpcConnection_np, common);
673 /* make array of connections */
674 if (objs)
675 objs = HeapReAlloc(GetProcessHeap(), 0, objs, *count*sizeof(HANDLE));
676 else
677 objs = HeapAlloc(GetProcessHeap(), 0, *count*sizeof(HANDLE));
678 if (!objs)
680 ERR("couldn't allocate objs\n");
681 LeaveCriticalSection(&protseq->cs);
682 return NULL;
685 objs[0] = npps->mgr_event;
686 *count = 1;
687 conn = CONTAINING_RECORD(protseq->conn, RpcConnection_np, common);
688 while (conn) {
689 if ((objs[*count] = conn->listen_thread))
690 (*count)++;
691 conn = CONTAINING_RECORD(conn->common.Next, RpcConnection_np, common);
693 LeaveCriticalSection(&protseq->cs);
694 return objs;
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)
704 HANDLE b_handle;
705 HANDLE *objs = wait_array;
706 DWORD res;
707 RpcConnection *cconn;
708 RpcConnection_np *conn;
710 if (!objs)
711 return -1;
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)
723 return 0;
724 else if (res == WAIT_FAILED)
726 ERR("wait failed with error %d\n", GetLastError());
727 return -1;
729 else
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);
735 while (conn) {
736 if (b_handle == conn->listen_thread) break;
737 conn = CONTAINING_RECORD(conn->common.Next, RpcConnection_np, common);
739 cconn = NULL;
740 if (conn)
742 DWORD exit_code;
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;
748 else
749 ERR("failed to locate connection for handle %p\n", b_handle);
750 LeaveCriticalSection(&protseq->cs);
751 if (cconn)
753 RPCRT4_new_client(cconn);
754 return 1;
756 else return -1;
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;
765 size_t size;
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;
773 if (!tower_data)
774 return 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);
786 return size;
789 static RPC_STATUS rpcrt4_ncalrpc_parse_top_of_tower(const unsigned char *tower_data,
790 size_t tower_size,
791 char **networkaddr,
792 char **endpoint)
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;
810 if (networkaddr)
811 *networkaddr = NULL;
813 if (endpoint)
815 *endpoint = I_RpcAllocate(pipe_floor->count_rhs);
816 if (!*endpoint)
817 return RPC_S_OUT_OF_RESOURCES;
818 memcpy(*endpoint, tower_data, pipe_floor->count_rhs);
821 return RPC_S_OK;
824 static BOOL rpcrt4_ncalrpc_is_authorized(RpcConnection *conn)
826 return FALSE;
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 */
837 *out_size = 0;
838 return RPC_S_OK;
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
849 * the packet */
850 return RPC_S_OK;
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);
860 if (privs)
862 FIXME("privs not implemented\n");
863 *privs = NULL;
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;
872 if (authz_svc)
874 FIXME("authorization service not implemented\n");
875 *authz_svc = RPC_C_AUTHZ_NONE;
877 if (flags)
878 FIXME("flags 0x%x not implemented\n", flags);
880 return RPC_S_OK;
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;
892 struct addrinfo *ai;
893 struct addrinfo hints;
894 int ret;
895 size_t size = sizeof(*tcp_floor) + sizeof(*ipv4_floor);
897 TRACE("(%p, %s, %s)\n", tower_data, networkaddr, endpoint);
899 if (!tower_data)
900 return size;
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);
926 if (ret)
928 ret = getaddrinfo("0.0.0.0", endpoint, &hints, &ai);
929 if (ret)
931 ERR("getaddrinfo failed: %s\n", gai_strerror(ret));
932 return 0;
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;
942 else
944 ERR("unexpected protocol family %d\n", ai->ai_family);
945 freeaddrinfo(ai);
946 return 0;
949 freeaddrinfo(ai);
951 return size;
954 static RPC_STATUS rpcrt4_ip_tcp_parse_top_of_tower(const unsigned char *tower_data,
955 size_t tower_size,
956 char **networkaddr,
957 unsigned char tcp_protid,
958 char **endpoint)
960 const twr_tcp_floor_t *tcp_floor = (const twr_tcp_floor_t *)tower_data;
961 const twr_ipv4_floor_t *ipv4_floor;
962 struct in_addr in_addr;
964 TRACE("(%p, %d, %p, %p)\n", tower_data, (int)tower_size, networkaddr, endpoint);
966 if (tower_size < sizeof(*tcp_floor))
967 return EPT_S_NOT_REGISTERED;
969 tower_data += sizeof(*tcp_floor);
970 tower_size -= sizeof(*tcp_floor);
972 if (tower_size < sizeof(*ipv4_floor))
973 return EPT_S_NOT_REGISTERED;
975 ipv4_floor = (const twr_ipv4_floor_t *)tower_data;
977 if ((tcp_floor->count_lhs != sizeof(tcp_floor->protid)) ||
978 (tcp_floor->protid != tcp_protid) ||
979 (tcp_floor->count_rhs != sizeof(tcp_floor->port)) ||
980 (ipv4_floor->count_lhs != sizeof(ipv4_floor->protid)) ||
981 (ipv4_floor->protid != EPM_PROTOCOL_IP) ||
982 (ipv4_floor->count_rhs != sizeof(ipv4_floor->ipv4addr)))
983 return EPT_S_NOT_REGISTERED;
985 if (endpoint)
987 *endpoint = I_RpcAllocate(6 /* sizeof("65535") + 1 */);
988 if (!*endpoint)
989 return RPC_S_OUT_OF_RESOURCES;
990 sprintf(*endpoint, "%u", ntohs(tcp_floor->port));
993 if (networkaddr)
995 *networkaddr = I_RpcAllocate(INET_ADDRSTRLEN);
996 if (!*networkaddr)
998 if (endpoint)
1000 I_RpcFree(*endpoint);
1001 *endpoint = NULL;
1003 return RPC_S_OUT_OF_RESOURCES;
1005 in_addr.s_addr = ipv4_floor->ipv4addr;
1006 if (!inet_ntop(AF_INET, &in_addr, *networkaddr, INET_ADDRSTRLEN))
1008 ERR("inet_ntop: %s\n", strerror(errno));
1009 I_RpcFree(*networkaddr);
1010 *networkaddr = NULL;
1011 if (endpoint)
1013 I_RpcFree(*endpoint);
1014 *endpoint = NULL;
1016 return EPT_S_NOT_REGISTERED;
1020 return RPC_S_OK;
1023 typedef struct _RpcConnection_tcp
1025 RpcConnection common;
1026 int sock;
1027 #ifdef HAVE_SOCKETPAIR
1028 int cancel_fds[2];
1029 #else
1030 HANDLE sock_event;
1031 HANDLE cancel_event;
1032 #endif
1033 } RpcConnection_tcp;
1035 #ifdef HAVE_SOCKETPAIR
1037 static BOOL rpcrt4_sock_wait_init(RpcConnection_tcp *tcpc)
1039 if (socketpair(PF_UNIX, SOCK_STREAM, 0, tcpc->cancel_fds) < 0)
1041 ERR("socketpair() failed: %s\n", strerror(errno));
1042 return FALSE;
1044 return TRUE;
1047 static BOOL rpcrt4_sock_wait_for_recv(RpcConnection_tcp *tcpc)
1049 struct pollfd pfds[2];
1050 pfds[0].fd = tcpc->sock;
1051 pfds[0].events = POLLIN;
1052 pfds[1].fd = tcpc->cancel_fds[0];
1053 pfds[1].events = POLLIN;
1054 if (poll(pfds, 2, -1 /* infinite */) == -1 && errno != EINTR)
1056 ERR("poll() failed: %s\n", strerror(errno));
1057 return FALSE;
1059 if (pfds[1].revents & POLLIN) /* canceled */
1061 char dummy;
1062 read(pfds[1].fd, &dummy, sizeof(dummy));
1063 return FALSE;
1065 return TRUE;
1068 static BOOL rpcrt4_sock_wait_for_send(RpcConnection_tcp *tcpc)
1070 struct pollfd pfd;
1071 pfd.fd = tcpc->sock;
1072 pfd.events = POLLOUT;
1073 if (poll(&pfd, 1, -1 /* infinite */) == -1 && errno != EINTR)
1075 ERR("poll() failed: %s\n", strerror(errno));
1076 return FALSE;
1078 return TRUE;
1081 static void rpcrt4_sock_wait_cancel(RpcConnection_tcp *tcpc)
1083 char dummy = 1;
1085 write(tcpc->cancel_fds[1], &dummy, 1);
1088 static void rpcrt4_sock_wait_destroy(RpcConnection_tcp *tcpc)
1090 close(tcpc->cancel_fds[0]);
1091 close(tcpc->cancel_fds[1]);
1094 #else /* HAVE_SOCKETPAIR */
1096 static BOOL rpcrt4_sock_wait_init(RpcConnection_tcp *tcpc)
1098 static BOOL wsa_inited;
1099 if (!wsa_inited)
1101 WSADATA wsadata;
1102 WSAStartup(MAKEWORD(2, 2), &wsadata);
1103 /* Note: WSAStartup can be called more than once so we don't bother with
1104 * making accesses to wsa_inited thread-safe */
1105 wsa_inited = TRUE;
1107 tcpc->sock_event = CreateEventW(NULL, FALSE, FALSE, NULL);
1108 tcpc->cancel_event = CreateEventW(NULL, FALSE, FALSE, NULL);
1109 if (!tcpc->sock_event || !tcpc->cancel_event)
1111 ERR("event creation failed\n");
1112 if (tcpc->sock_event) CloseHandle(tcpc->sock_event);
1113 return FALSE;
1115 return TRUE;
1118 static BOOL rpcrt4_sock_wait_for_recv(RpcConnection_tcp *tcpc)
1120 HANDLE wait_handles[2];
1121 DWORD res;
1122 if (WSAEventSelect(tcpc->sock, tcpc->sock_event, FD_READ | FD_CLOSE) == SOCKET_ERROR)
1124 ERR("WSAEventSelect() failed with error %d\n", WSAGetLastError());
1125 return FALSE;
1127 wait_handles[0] = tcpc->sock_event;
1128 wait_handles[1] = tcpc->cancel_event;
1129 res = WaitForMultipleObjects(2, wait_handles, FALSE, INFINITE);
1130 switch (res)
1132 case WAIT_OBJECT_0:
1133 return TRUE;
1134 case WAIT_OBJECT_0 + 1:
1135 return FALSE;
1136 default:
1137 ERR("WaitForMultipleObjects() failed with error %d\n", GetLastError());
1138 return FALSE;
1142 static BOOL rpcrt4_sock_wait_for_send(RpcConnection_tcp *tcpc)
1144 DWORD res;
1145 if (WSAEventSelect(tcpc->sock, tcpc->sock_event, FD_WRITE | FD_CLOSE) == SOCKET_ERROR)
1147 ERR("WSAEventSelect() failed with error %d\n", WSAGetLastError());
1148 return FALSE;
1150 res = WaitForSingleObject(tcpc->sock_event, INFINITE);
1151 switch (res)
1153 case WAIT_OBJECT_0:
1154 return TRUE;
1155 default:
1156 ERR("WaitForMultipleObjects() failed with error %d\n", GetLastError());
1157 return FALSE;
1161 static void rpcrt4_sock_wait_cancel(RpcConnection_tcp *tcpc)
1163 SetEvent(tcpc->cancel_event);
1166 static void rpcrt4_sock_wait_destroy(RpcConnection_tcp *tcpc)
1168 CloseHandle(tcpc->sock_event);
1169 CloseHandle(tcpc->cancel_event);
1172 #endif
1174 static RpcConnection *rpcrt4_conn_tcp_alloc(void)
1176 RpcConnection_tcp *tcpc;
1177 tcpc = HeapAlloc(GetProcessHeap(), 0, sizeof(RpcConnection_tcp));
1178 if (tcpc == NULL)
1179 return NULL;
1180 tcpc->sock = -1;
1181 if (!rpcrt4_sock_wait_init(tcpc))
1183 HeapFree(GetProcessHeap(), 0, tcpc);
1184 return NULL;
1186 return &tcpc->common;
1189 static RPC_STATUS rpcrt4_ncacn_ip_tcp_open(RpcConnection* Connection)
1191 RpcConnection_tcp *tcpc = (RpcConnection_tcp *) Connection;
1192 int sock;
1193 int ret;
1194 struct addrinfo *ai;
1195 struct addrinfo *ai_cur;
1196 struct addrinfo hints;
1198 TRACE("(%s, %s)\n", Connection->NetworkAddr, Connection->Endpoint);
1200 if (tcpc->sock != -1)
1201 return RPC_S_OK;
1203 hints.ai_flags = 0;
1204 hints.ai_family = PF_UNSPEC;
1205 hints.ai_socktype = SOCK_STREAM;
1206 hints.ai_protocol = IPPROTO_TCP;
1207 hints.ai_addrlen = 0;
1208 hints.ai_addr = NULL;
1209 hints.ai_canonname = NULL;
1210 hints.ai_next = NULL;
1212 ret = getaddrinfo(Connection->NetworkAddr, Connection->Endpoint, &hints, &ai);
1213 if (ret)
1215 ERR("getaddrinfo for %s:%s failed: %s\n", Connection->NetworkAddr,
1216 Connection->Endpoint, gai_strerror(ret));
1217 return RPC_S_SERVER_UNAVAILABLE;
1220 for (ai_cur = ai; ai_cur; ai_cur = ai_cur->ai_next)
1222 int val;
1223 u_long nonblocking;
1225 if (ai_cur->ai_family != AF_INET && ai_cur->ai_family != AF_INET6)
1227 TRACE("skipping non-IP/IPv6 address family\n");
1228 continue;
1231 if (TRACE_ON(rpc))
1233 char host[256];
1234 char service[256];
1235 getnameinfo(ai_cur->ai_addr, ai_cur->ai_addrlen,
1236 host, sizeof(host), service, sizeof(service),
1237 NI_NUMERICHOST | NI_NUMERICSERV);
1238 TRACE("trying %s:%s\n", host, service);
1241 sock = socket(ai_cur->ai_family, ai_cur->ai_socktype, ai_cur->ai_protocol);
1242 if (sock == -1)
1244 WARN("socket() failed: %s\n", strerror(errno));
1245 continue;
1248 if (0>connect(sock, ai_cur->ai_addr, ai_cur->ai_addrlen))
1250 WARN("connect() failed: %s\n", strerror(errno));
1251 closesocket(sock);
1252 continue;
1255 /* RPC depends on having minimal latency so disable the Nagle algorithm */
1256 val = 1;
1257 setsockopt(sock, SOL_TCP, TCP_NODELAY, (char *)&val, sizeof(val));
1258 nonblocking = 1;
1259 ioctlsocket(sock, FIONBIO, &nonblocking);
1261 tcpc->sock = sock;
1263 freeaddrinfo(ai);
1264 TRACE("connected\n");
1265 return RPC_S_OK;
1268 freeaddrinfo(ai);
1269 ERR("couldn't connect to %s:%s\n", Connection->NetworkAddr, Connection->Endpoint);
1270 return RPC_S_SERVER_UNAVAILABLE;
1273 static RPC_STATUS rpcrt4_protseq_ncacn_ip_tcp_open_endpoint(RpcServerProtseq *protseq, const char *endpoint)
1275 RPC_STATUS status = RPC_S_CANT_CREATE_ENDPOINT;
1276 int sock;
1277 int ret;
1278 struct addrinfo *ai;
1279 struct addrinfo *ai_cur;
1280 struct addrinfo hints;
1281 RpcConnection *first_connection = NULL;
1283 TRACE("(%p, %s)\n", protseq, endpoint);
1285 hints.ai_flags = AI_PASSIVE /* for non-localhost addresses */;
1286 hints.ai_family = PF_UNSPEC;
1287 hints.ai_socktype = SOCK_STREAM;
1288 hints.ai_protocol = IPPROTO_TCP;
1289 hints.ai_addrlen = 0;
1290 hints.ai_addr = NULL;
1291 hints.ai_canonname = NULL;
1292 hints.ai_next = NULL;
1294 ret = getaddrinfo(NULL, endpoint ? endpoint : "0", &hints, &ai);
1295 if (ret)
1297 ERR("getaddrinfo for port %s failed: %s\n", endpoint,
1298 gai_strerror(ret));
1299 if ((ret == EAI_SERVICE) || (ret == EAI_NONAME))
1300 return RPC_S_INVALID_ENDPOINT_FORMAT;
1301 return RPC_S_CANT_CREATE_ENDPOINT;
1304 for (ai_cur = ai; ai_cur; ai_cur = ai_cur->ai_next)
1306 RpcConnection_tcp *tcpc;
1307 RPC_STATUS create_status;
1308 struct sockaddr_storage sa;
1309 socklen_t sa_len;
1310 char service[NI_MAXSERV];
1311 u_long nonblocking;
1313 if (ai_cur->ai_family != AF_INET && ai_cur->ai_family != AF_INET6)
1315 TRACE("skipping non-IP/IPv6 address family\n");
1316 continue;
1319 if (TRACE_ON(rpc))
1321 char host[256];
1322 getnameinfo(ai_cur->ai_addr, ai_cur->ai_addrlen,
1323 host, sizeof(host), service, sizeof(service),
1324 NI_NUMERICHOST | NI_NUMERICSERV);
1325 TRACE("trying %s:%s\n", host, service);
1328 sock = socket(ai_cur->ai_family, ai_cur->ai_socktype, ai_cur->ai_protocol);
1329 if (sock == -1)
1331 WARN("socket() failed: %s\n", strerror(errno));
1332 status = RPC_S_CANT_CREATE_ENDPOINT;
1333 continue;
1336 ret = bind(sock, ai_cur->ai_addr, ai_cur->ai_addrlen);
1337 if (ret < 0)
1339 WARN("bind failed: %s\n", strerror(errno));
1340 closesocket(sock);
1341 if (errno == EADDRINUSE)
1342 status = RPC_S_DUPLICATE_ENDPOINT;
1343 else
1344 status = RPC_S_CANT_CREATE_ENDPOINT;
1345 continue;
1348 sa_len = sizeof(sa);
1349 if (getsockname(sock, (struct sockaddr *)&sa, &sa_len))
1351 WARN("getsockname() failed: %s\n", strerror(errno));
1352 closesocket(sock);
1353 status = RPC_S_CANT_CREATE_ENDPOINT;
1354 continue;
1357 ret = getnameinfo((struct sockaddr *)&sa, sa_len,
1358 NULL, 0, service, sizeof(service),
1359 NI_NUMERICSERV);
1360 if (ret)
1362 WARN("getnameinfo failed: %s\n", gai_strerror(ret));
1363 closesocket(sock);
1364 status = RPC_S_CANT_CREATE_ENDPOINT;
1365 continue;
1368 create_status = RPCRT4_CreateConnection((RpcConnection **)&tcpc, TRUE,
1369 protseq->Protseq, NULL,
1370 service, NULL, NULL, NULL, NULL);
1371 if (create_status != RPC_S_OK)
1373 closesocket(sock);
1374 status = create_status;
1375 continue;
1378 tcpc->sock = sock;
1379 ret = listen(sock, protseq->MaxCalls);
1380 if (ret < 0)
1382 WARN("listen failed: %s\n", strerror(errno));
1383 RPCRT4_ReleaseConnection(&tcpc->common);
1384 status = RPC_S_OUT_OF_RESOURCES;
1385 continue;
1387 /* need a non-blocking socket, otherwise accept() has a potential
1388 * race-condition (poll() says it is readable, connection drops,
1389 * and accept() blocks until the next connection comes...)
1391 nonblocking = 1;
1392 ret = ioctlsocket(sock, FIONBIO, &nonblocking);
1393 if (ret < 0)
1395 WARN("couldn't make socket non-blocking, error %d\n", ret);
1396 RPCRT4_ReleaseConnection(&tcpc->common);
1397 status = RPC_S_OUT_OF_RESOURCES;
1398 continue;
1401 tcpc->common.Next = first_connection;
1402 first_connection = &tcpc->common;
1404 /* since IPv4 and IPv6 share the same port space, we only need one
1405 * successful bind to listen for both */
1406 break;
1409 freeaddrinfo(ai);
1411 /* if at least one connection was created for an endpoint then
1412 * return success */
1413 if (first_connection)
1415 RpcConnection *conn;
1417 /* find last element in list */
1418 for (conn = first_connection; conn->Next; conn = conn->Next)
1421 EnterCriticalSection(&protseq->cs);
1422 conn->Next = protseq->conn;
1423 protseq->conn = first_connection;
1424 LeaveCriticalSection(&protseq->cs);
1426 TRACE("listening on %s\n", endpoint);
1427 return RPC_S_OK;
1430 ERR("couldn't listen on port %s\n", endpoint);
1431 return status;
1434 static RPC_STATUS rpcrt4_conn_tcp_handoff(RpcConnection *old_conn, RpcConnection *new_conn)
1436 int ret;
1437 struct sockaddr_in address;
1438 socklen_t addrsize;
1439 RpcConnection_tcp *server = (RpcConnection_tcp*) old_conn;
1440 RpcConnection_tcp *client = (RpcConnection_tcp*) new_conn;
1441 u_long nonblocking;
1443 addrsize = sizeof(address);
1444 ret = accept(server->sock, (struct sockaddr*) &address, &addrsize);
1445 if (ret < 0)
1447 ERR("Failed to accept a TCP connection: error %d\n", ret);
1448 return RPC_S_OUT_OF_RESOURCES;
1450 nonblocking = 1;
1451 ioctlsocket(ret, FIONBIO, &nonblocking);
1452 client->sock = ret;
1453 TRACE("Accepted a new TCP connection\n");
1454 return RPC_S_OK;
1457 static int rpcrt4_conn_tcp_read(RpcConnection *Connection,
1458 void *buffer, unsigned int count)
1460 RpcConnection_tcp *tcpc = (RpcConnection_tcp *) Connection;
1461 int bytes_read = 0;
1462 while (bytes_read != count)
1464 int r = recv(tcpc->sock, (char *)buffer + bytes_read, count - bytes_read, 0);
1465 if (!r)
1466 return -1;
1467 else if (r > 0)
1468 bytes_read += r;
1469 else if (errno == EINTR)
1470 continue;
1471 else if (errno != EAGAIN)
1473 WARN("recv() failed: %s\n", strerror(errno));
1474 return -1;
1476 else
1478 if (!rpcrt4_sock_wait_for_recv(tcpc))
1479 return -1;
1482 TRACE("%d %p %u -> %d\n", tcpc->sock, buffer, count, bytes_read);
1483 return bytes_read;
1486 static int rpcrt4_conn_tcp_write(RpcConnection *Connection,
1487 const void *buffer, unsigned int count)
1489 RpcConnection_tcp *tcpc = (RpcConnection_tcp *) Connection;
1490 int bytes_written = 0;
1491 while (bytes_written != count)
1493 int r = send(tcpc->sock, (const char *)buffer + bytes_written, count - bytes_written, 0);
1494 if (r >= 0)
1495 bytes_written += r;
1496 else if (errno == EINTR)
1497 continue;
1498 else if (errno != EAGAIN)
1499 return -1;
1500 else
1502 if (!rpcrt4_sock_wait_for_send(tcpc))
1503 return -1;
1506 TRACE("%d %p %u -> %d\n", tcpc->sock, buffer, count, bytes_written);
1507 return bytes_written;
1510 static int rpcrt4_conn_tcp_close(RpcConnection *Connection)
1512 RpcConnection_tcp *tcpc = (RpcConnection_tcp *) Connection;
1514 TRACE("%d\n", tcpc->sock);
1516 if (tcpc->sock != -1)
1517 closesocket(tcpc->sock);
1518 tcpc->sock = -1;
1519 rpcrt4_sock_wait_destroy(tcpc);
1520 return 0;
1523 static void rpcrt4_conn_tcp_cancel_call(RpcConnection *Connection)
1525 RpcConnection_tcp *tcpc = (RpcConnection_tcp *) Connection;
1526 TRACE("%p\n", Connection);
1527 rpcrt4_sock_wait_cancel(tcpc);
1530 static int rpcrt4_conn_tcp_wait_for_incoming_data(RpcConnection *Connection)
1532 RpcConnection_tcp *tcpc = (RpcConnection_tcp *) Connection;
1534 TRACE("%p\n", Connection);
1536 if (!rpcrt4_sock_wait_for_recv(tcpc))
1537 return -1;
1538 return 0;
1541 static size_t rpcrt4_ncacn_ip_tcp_get_top_of_tower(unsigned char *tower_data,
1542 const char *networkaddr,
1543 const char *endpoint)
1545 return rpcrt4_ip_tcp_get_top_of_tower(tower_data, networkaddr,
1546 EPM_PROTOCOL_TCP, endpoint);
1549 #ifdef HAVE_SOCKETPAIR
1551 typedef struct _RpcServerProtseq_sock
1553 RpcServerProtseq common;
1554 int mgr_event_rcv;
1555 int mgr_event_snd;
1556 } RpcServerProtseq_sock;
1558 static RpcServerProtseq *rpcrt4_protseq_sock_alloc(void)
1560 RpcServerProtseq_sock *ps = HeapAlloc(GetProcessHeap(), 0, sizeof(*ps));
1561 if (ps)
1563 int fds[2];
1564 if (!socketpair(PF_UNIX, SOCK_DGRAM, 0, fds))
1566 fcntl(fds[0], F_SETFL, O_NONBLOCK);
1567 fcntl(fds[1], F_SETFL, O_NONBLOCK);
1568 ps->mgr_event_rcv = fds[0];
1569 ps->mgr_event_snd = fds[1];
1571 else
1573 ERR("socketpair failed with error %s\n", strerror(errno));
1574 HeapFree(GetProcessHeap(), 0, ps);
1575 return NULL;
1578 return &ps->common;
1581 static void rpcrt4_protseq_sock_signal_state_changed(RpcServerProtseq *protseq)
1583 RpcServerProtseq_sock *sockps = CONTAINING_RECORD(protseq, RpcServerProtseq_sock, common);
1584 char dummy = 1;
1585 write(sockps->mgr_event_snd, &dummy, sizeof(dummy));
1588 static void *rpcrt4_protseq_sock_get_wait_array(RpcServerProtseq *protseq, void *prev_array, unsigned int *count)
1590 struct pollfd *poll_info = prev_array;
1591 RpcConnection_tcp *conn;
1592 RpcServerProtseq_sock *sockps = CONTAINING_RECORD(protseq, RpcServerProtseq_sock, common);
1594 EnterCriticalSection(&protseq->cs);
1596 /* open and count connections */
1597 *count = 1;
1598 conn = (RpcConnection_tcp *)protseq->conn;
1599 while (conn) {
1600 if (conn->sock != -1)
1601 (*count)++;
1602 conn = (RpcConnection_tcp *)conn->common.Next;
1605 /* make array of connections */
1606 if (poll_info)
1607 poll_info = HeapReAlloc(GetProcessHeap(), 0, poll_info, *count*sizeof(*poll_info));
1608 else
1609 poll_info = HeapAlloc(GetProcessHeap(), 0, *count*sizeof(*poll_info));
1610 if (!poll_info)
1612 ERR("couldn't allocate poll_info\n");
1613 LeaveCriticalSection(&protseq->cs);
1614 return NULL;
1617 poll_info[0].fd = sockps->mgr_event_rcv;
1618 poll_info[0].events = POLLIN;
1619 *count = 1;
1620 conn = CONTAINING_RECORD(protseq->conn, RpcConnection_tcp, common);
1621 while (conn) {
1622 if (conn->sock != -1)
1624 poll_info[*count].fd = conn->sock;
1625 poll_info[*count].events = POLLIN;
1626 (*count)++;
1628 conn = CONTAINING_RECORD(conn->common.Next, RpcConnection_tcp, common);
1630 LeaveCriticalSection(&protseq->cs);
1631 return poll_info;
1634 static void rpcrt4_protseq_sock_free_wait_array(RpcServerProtseq *protseq, void *array)
1636 HeapFree(GetProcessHeap(), 0, array);
1639 static int rpcrt4_protseq_sock_wait_for_new_connection(RpcServerProtseq *protseq, unsigned int count, void *wait_array)
1641 struct pollfd *poll_info = wait_array;
1642 int ret;
1643 unsigned int i;
1644 RpcConnection *cconn;
1645 RpcConnection_tcp *conn;
1647 if (!poll_info)
1648 return -1;
1650 ret = poll(poll_info, count, -1);
1651 if (ret < 0)
1653 ERR("poll failed with error %d\n", ret);
1654 return -1;
1657 for (i = 0; i < count; i++)
1658 if (poll_info[i].revents & POLLIN)
1660 /* RPC server event */
1661 if (i == 0)
1663 char dummy;
1664 read(poll_info[0].fd, &dummy, sizeof(dummy));
1665 return 0;
1668 /* find which connection got a RPC */
1669 EnterCriticalSection(&protseq->cs);
1670 conn = CONTAINING_RECORD(protseq->conn, RpcConnection_tcp, common);
1671 while (conn) {
1672 if (poll_info[i].fd == conn->sock) break;
1673 conn = CONTAINING_RECORD(conn->common.Next, RpcConnection_tcp, common);
1675 cconn = NULL;
1676 if (conn)
1677 RPCRT4_SpawnConnection(&cconn, &conn->common);
1678 else
1679 ERR("failed to locate connection for fd %d\n", poll_info[i].fd);
1680 LeaveCriticalSection(&protseq->cs);
1681 if (cconn)
1682 RPCRT4_new_client(cconn);
1683 else
1684 return -1;
1687 return 1;
1690 #else /* HAVE_SOCKETPAIR */
1692 typedef struct _RpcServerProtseq_sock
1694 RpcServerProtseq common;
1695 HANDLE mgr_event;
1696 } RpcServerProtseq_sock;
1698 static RpcServerProtseq *rpcrt4_protseq_sock_alloc(void)
1700 RpcServerProtseq_sock *ps = HeapAlloc(GetProcessHeap(), 0, sizeof(*ps));
1701 if (ps)
1703 static BOOL wsa_inited;
1704 if (!wsa_inited)
1706 WSADATA wsadata;
1707 WSAStartup(MAKEWORD(2, 2), &wsadata);
1708 /* Note: WSAStartup can be called more than once so we don't bother with
1709 * making accesses to wsa_inited thread-safe */
1710 wsa_inited = TRUE;
1712 ps->mgr_event = CreateEventW(NULL, FALSE, FALSE, NULL);
1714 return &ps->common;
1717 static void rpcrt4_protseq_sock_signal_state_changed(RpcServerProtseq *protseq)
1719 RpcServerProtseq_sock *sockps = CONTAINING_RECORD(protseq, RpcServerProtseq_sock, common);
1720 SetEvent(sockps->mgr_event);
1723 static void *rpcrt4_protseq_sock_get_wait_array(RpcServerProtseq *protseq, void *prev_array, unsigned int *count)
1725 HANDLE *objs = prev_array;
1726 RpcConnection_tcp *conn;
1727 RpcServerProtseq_sock *sockps = CONTAINING_RECORD(protseq, RpcServerProtseq_sock, common);
1729 EnterCriticalSection(&protseq->cs);
1731 /* open and count connections */
1732 *count = 1;
1733 conn = CONTAINING_RECORD(protseq->conn, RpcConnection_tcp, common);
1734 while (conn)
1736 if (conn->sock != -1)
1737 (*count)++;
1738 conn = CONTAINING_RECORD(conn->common.Next, RpcConnection_tcp, common);
1741 /* make array of connections */
1742 if (objs)
1743 objs = HeapReAlloc(GetProcessHeap(), 0, objs, *count*sizeof(HANDLE));
1744 else
1745 objs = HeapAlloc(GetProcessHeap(), 0, *count*sizeof(HANDLE));
1746 if (!objs)
1748 ERR("couldn't allocate objs\n");
1749 LeaveCriticalSection(&protseq->cs);
1750 return NULL;
1753 objs[0] = sockps->mgr_event;
1754 *count = 1;
1755 conn = CONTAINING_RECORD(protseq->conn, RpcConnection_tcp, common);
1756 while (conn)
1758 if (conn->sock != -1)
1760 int res = WSAEventSelect(conn->sock, conn->sock_event, FD_ACCEPT);
1761 if (res == SOCKET_ERROR)
1762 ERR("WSAEventSelect() failed with error %d\n", WSAGetLastError());
1763 else
1765 objs[*count] = conn->sock_event;
1766 (*count)++;
1769 conn = CONTAINING_RECORD(conn->common.Next, RpcConnection_tcp, common);
1771 LeaveCriticalSection(&protseq->cs);
1772 return objs;
1775 static void rpcrt4_protseq_sock_free_wait_array(RpcServerProtseq *protseq, void *array)
1777 HeapFree(GetProcessHeap(), 0, array);
1780 static int rpcrt4_protseq_sock_wait_for_new_connection(RpcServerProtseq *protseq, unsigned int count, void *wait_array)
1782 HANDLE b_handle;
1783 HANDLE *objs = wait_array;
1784 DWORD res;
1785 RpcConnection *cconn;
1786 RpcConnection_tcp *conn;
1788 if (!objs)
1789 return -1;
1793 /* an alertable wait isn't strictly necessary, but due to our
1794 * overlapped I/O implementation in Wine we need to free some memory
1795 * by the file user APC being called, even if no completion routine was
1796 * specified at the time of starting the async operation */
1797 res = WaitForMultipleObjectsEx(count, objs, FALSE, INFINITE, TRUE);
1798 } while (res == WAIT_IO_COMPLETION);
1800 if (res == WAIT_OBJECT_0)
1801 return 0;
1802 else if (res == WAIT_FAILED)
1804 ERR("wait failed with error %d\n", GetLastError());
1805 return -1;
1807 else
1809 b_handle = objs[res - WAIT_OBJECT_0];
1810 /* find which connection got a RPC */
1811 EnterCriticalSection(&protseq->cs);
1812 conn = CONTAINING_RECORD(protseq->conn, RpcConnection_tcp, common);
1813 while (conn)
1815 if (b_handle == conn->sock_event) break;
1816 conn = CONTAINING_RECORD(conn->common.Next, RpcConnection_tcp, common);
1818 cconn = NULL;
1819 if (conn)
1820 RPCRT4_SpawnConnection(&cconn, &conn->common);
1821 else
1822 ERR("failed to locate connection for handle %p\n", b_handle);
1823 LeaveCriticalSection(&protseq->cs);
1824 if (cconn)
1826 RPCRT4_new_client(cconn);
1827 return 1;
1829 else return -1;
1833 #endif /* HAVE_SOCKETPAIR */
1835 static RPC_STATUS rpcrt4_ncacn_ip_tcp_parse_top_of_tower(const unsigned char *tower_data,
1836 size_t tower_size,
1837 char **networkaddr,
1838 char **endpoint)
1840 return rpcrt4_ip_tcp_parse_top_of_tower(tower_data, tower_size,
1841 networkaddr, EPM_PROTOCOL_TCP,
1842 endpoint);
1845 /**** ncacn_http support ****/
1847 /* 60 seconds is the period native uses */
1848 #define HTTP_IDLE_TIME 60000
1850 /* reference counted to avoid a race between a cancelled call's connection
1851 * being destroyed and the asynchronous InternetReadFileEx call being
1852 * completed */
1853 typedef struct _RpcHttpAsyncData
1855 LONG refs;
1856 HANDLE completion_event;
1857 WORD async_result;
1858 INTERNET_BUFFERSA inet_buffers;
1859 CRITICAL_SECTION cs;
1860 } RpcHttpAsyncData;
1862 static ULONG RpcHttpAsyncData_AddRef(RpcHttpAsyncData *data)
1864 return InterlockedIncrement(&data->refs);
1867 static ULONG RpcHttpAsyncData_Release(RpcHttpAsyncData *data)
1869 ULONG refs = InterlockedDecrement(&data->refs);
1870 if (!refs)
1872 TRACE("destroying async data %p\n", data);
1873 CloseHandle(data->completion_event);
1874 HeapFree(GetProcessHeap(), 0, data->inet_buffers.lpvBuffer);
1875 data->cs.DebugInfo->Spare[0] = 0;
1876 DeleteCriticalSection(&data->cs);
1877 HeapFree(GetProcessHeap(), 0, data);
1879 return refs;
1882 static void prepare_async_request(RpcHttpAsyncData *async_data)
1884 ResetEvent(async_data->completion_event);
1885 RpcHttpAsyncData_AddRef(async_data);
1888 static RPC_STATUS wait_async_request(RpcHttpAsyncData *async_data, BOOL call_ret, HANDLE cancel_event)
1890 HANDLE handles[2] = { async_data->completion_event, cancel_event };
1891 DWORD res;
1893 if(call_ret) {
1894 RpcHttpAsyncData_Release(async_data);
1895 return RPC_S_OK;
1898 if(GetLastError() != ERROR_IO_PENDING) {
1899 RpcHttpAsyncData_Release(async_data);
1900 ERR("Request failed with error %d\n", GetLastError());
1901 return RPC_S_SERVER_UNAVAILABLE;
1904 res = WaitForMultipleObjects(2, handles, FALSE, DEFAULT_NCACN_HTTP_TIMEOUT);
1905 if(res != WAIT_OBJECT_0) {
1906 TRACE("Cancelled\n");
1907 return RPC_S_CALL_CANCELLED;
1910 if(async_data->async_result) {
1911 ERR("Async request failed with error %d\n", async_data->async_result);
1912 return RPC_S_SERVER_UNAVAILABLE;
1915 return RPC_S_OK;
1918 struct authinfo
1920 DWORD scheme;
1921 CredHandle cred;
1922 CtxtHandle ctx;
1923 TimeStamp exp;
1924 ULONG attr;
1925 ULONG max_token;
1926 char *data;
1927 unsigned int data_len;
1928 BOOL finished; /* finished authenticating */
1931 typedef struct _RpcConnection_http
1933 RpcConnection common;
1934 HINTERNET app_info;
1935 HINTERNET session;
1936 HINTERNET in_request;
1937 HINTERNET out_request;
1938 WCHAR *servername;
1939 HANDLE timer_cancelled;
1940 HANDLE cancel_event;
1941 DWORD last_sent_time;
1942 ULONG bytes_received;
1943 ULONG flow_control_mark; /* send a control packet to the server when this many bytes received */
1944 ULONG flow_control_increment; /* number of bytes to increment flow_control_mark by */
1945 UUID connection_uuid;
1946 UUID in_pipe_uuid;
1947 UUID out_pipe_uuid;
1948 RpcHttpAsyncData *async_data;
1949 } RpcConnection_http;
1951 static RpcConnection *rpcrt4_ncacn_http_alloc(void)
1953 RpcConnection_http *httpc;
1954 httpc = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*httpc));
1955 if (!httpc) return NULL;
1956 httpc->async_data = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(RpcHttpAsyncData));
1957 if (!httpc->async_data)
1959 HeapFree(GetProcessHeap(), 0, httpc);
1960 return NULL;
1962 TRACE("async data = %p\n", httpc->async_data);
1963 httpc->cancel_event = CreateEventW(NULL, FALSE, FALSE, NULL);
1964 httpc->async_data->refs = 1;
1965 httpc->async_data->inet_buffers.dwStructSize = sizeof(INTERNET_BUFFERSA);
1966 httpc->async_data->inet_buffers.lpvBuffer = NULL;
1967 InitializeCriticalSection(&httpc->async_data->cs);
1968 httpc->async_data->cs.DebugInfo->Spare[0] = (DWORD_PTR)(__FILE__ ": RpcHttpAsyncData.cs");
1969 return &httpc->common;
1972 typedef struct _HttpTimerThreadData
1974 PVOID timer_param;
1975 DWORD *last_sent_time;
1976 HANDLE timer_cancelled;
1977 } HttpTimerThreadData;
1979 static VOID rpcrt4_http_keep_connection_active_timer_proc(PVOID param, BOOLEAN dummy)
1981 HINTERNET in_request = param;
1982 RpcPktHdr *idle_pkt;
1984 idle_pkt = RPCRT4_BuildHttpHeader(NDR_LOCAL_DATA_REPRESENTATION, 0x0001,
1985 0, 0);
1986 if (idle_pkt)
1988 DWORD bytes_written;
1989 InternetWriteFile(in_request, idle_pkt, idle_pkt->common.frag_len, &bytes_written);
1990 RPCRT4_FreeHeader(idle_pkt);
1994 static inline DWORD rpcrt4_http_timer_calc_timeout(DWORD *last_sent_time)
1996 DWORD cur_time = GetTickCount();
1997 DWORD cached_last_sent_time = *last_sent_time;
1998 return HTTP_IDLE_TIME - (cur_time - cached_last_sent_time > HTTP_IDLE_TIME ? 0 : cur_time - cached_last_sent_time);
2001 static DWORD CALLBACK rpcrt4_http_timer_thread(PVOID param)
2003 HttpTimerThreadData *data_in = param;
2004 HttpTimerThreadData data;
2005 DWORD timeout;
2007 data = *data_in;
2008 HeapFree(GetProcessHeap(), 0, data_in);
2010 for (timeout = HTTP_IDLE_TIME;
2011 WaitForSingleObject(data.timer_cancelled, timeout) == WAIT_TIMEOUT;
2012 timeout = rpcrt4_http_timer_calc_timeout(data.last_sent_time))
2014 /* are we too soon after last send? */
2015 if (GetTickCount() - *data.last_sent_time < HTTP_IDLE_TIME)
2016 continue;
2017 rpcrt4_http_keep_connection_active_timer_proc(data.timer_param, TRUE);
2020 CloseHandle(data.timer_cancelled);
2021 return 0;
2024 static VOID WINAPI rpcrt4_http_internet_callback(
2025 HINTERNET hInternet,
2026 DWORD_PTR dwContext,
2027 DWORD dwInternetStatus,
2028 LPVOID lpvStatusInformation,
2029 DWORD dwStatusInformationLength)
2031 RpcHttpAsyncData *async_data = (RpcHttpAsyncData *)dwContext;
2033 switch (dwInternetStatus)
2035 case INTERNET_STATUS_REQUEST_COMPLETE:
2036 TRACE("INTERNET_STATUS_REQUEST_COMPLETED\n");
2037 if (async_data)
2039 INTERNET_ASYNC_RESULT *async_result = lpvStatusInformation;
2041 async_data->async_result = async_result->dwResult ? ERROR_SUCCESS : async_result->dwError;
2042 SetEvent(async_data->completion_event);
2043 RpcHttpAsyncData_Release(async_data);
2045 break;
2049 static RPC_STATUS rpcrt4_http_check_response(HINTERNET hor)
2051 BOOL ret;
2052 DWORD status_code;
2053 DWORD size;
2054 DWORD index;
2055 WCHAR buf[32];
2056 WCHAR *status_text = buf;
2057 TRACE("\n");
2059 index = 0;
2060 size = sizeof(status_code);
2061 ret = HttpQueryInfoW(hor, HTTP_QUERY_STATUS_CODE|HTTP_QUERY_FLAG_NUMBER, &status_code, &size, &index);
2062 if (!ret)
2063 return GetLastError();
2064 if (status_code == HTTP_STATUS_OK)
2065 return RPC_S_OK;
2066 index = 0;
2067 size = sizeof(buf);
2068 ret = HttpQueryInfoW(hor, HTTP_QUERY_STATUS_TEXT, status_text, &size, &index);
2069 if (!ret && GetLastError() == ERROR_INSUFFICIENT_BUFFER)
2071 status_text = HeapAlloc(GetProcessHeap(), 0, size);
2072 ret = HttpQueryInfoW(hor, HTTP_QUERY_STATUS_TEXT, status_text, &size, &index);
2075 ERR("server returned: %d %s\n", status_code, ret ? debugstr_w(status_text) : "<status text unavailable>");
2076 if(status_text != buf) HeapFree(GetProcessHeap(), 0, status_text);
2078 if (status_code == HTTP_STATUS_DENIED)
2079 return ERROR_ACCESS_DENIED;
2080 return RPC_S_SERVER_UNAVAILABLE;
2083 static RPC_STATUS rpcrt4_http_internet_connect(RpcConnection_http *httpc)
2085 static const WCHAR wszUserAgent[] = {'M','S','R','P','C',0};
2086 LPWSTR proxy = NULL;
2087 LPWSTR user = NULL;
2088 LPWSTR password = NULL;
2089 LPWSTR servername = NULL;
2090 const WCHAR *option;
2091 INTERNET_PORT port;
2093 if (httpc->common.QOS &&
2094 (httpc->common.QOS->qos->AdditionalSecurityInfoType == RPC_C_AUTHN_INFO_TYPE_HTTP))
2096 const RPC_HTTP_TRANSPORT_CREDENTIALS_W *http_cred = httpc->common.QOS->qos->u.HttpCredentials;
2097 if (http_cred->TransportCredentials)
2099 WCHAR *p;
2100 const SEC_WINNT_AUTH_IDENTITY_W *cred = http_cred->TransportCredentials;
2101 ULONG len = cred->DomainLength + 1 + cred->UserLength;
2102 user = HeapAlloc(GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR));
2103 if (!user)
2104 return RPC_S_OUT_OF_RESOURCES;
2105 p = user;
2106 if (cred->DomainLength)
2108 memcpy(p, cred->Domain, cred->DomainLength * sizeof(WCHAR));
2109 p += cred->DomainLength;
2110 *p = '\\';
2111 p++;
2113 memcpy(p, cred->User, cred->UserLength * sizeof(WCHAR));
2114 p[cred->UserLength] = 0;
2116 password = RPCRT4_strndupW(cred->Password, cred->PasswordLength);
2120 for (option = httpc->common.NetworkOptions; option;
2121 option = (strchrW(option, ',') ? strchrW(option, ',')+1 : NULL))
2123 static const WCHAR wszRpcProxy[] = {'R','p','c','P','r','o','x','y','=',0};
2124 static const WCHAR wszHttpProxy[] = {'H','t','t','p','P','r','o','x','y','=',0};
2126 if (!strncmpiW(option, wszRpcProxy, sizeof(wszRpcProxy)/sizeof(wszRpcProxy[0])-1))
2128 const WCHAR *value_start = option + sizeof(wszRpcProxy)/sizeof(wszRpcProxy[0])-1;
2129 const WCHAR *value_end;
2130 const WCHAR *p;
2132 value_end = strchrW(option, ',');
2133 if (!value_end)
2134 value_end = value_start + strlenW(value_start);
2135 for (p = value_start; p < value_end; p++)
2136 if (*p == ':')
2138 port = atoiW(p+1);
2139 value_end = p;
2140 break;
2142 TRACE("RpcProxy value is %s\n", debugstr_wn(value_start, value_end-value_start));
2143 servername = RPCRT4_strndupW(value_start, value_end-value_start);
2145 else if (!strncmpiW(option, wszHttpProxy, sizeof(wszHttpProxy)/sizeof(wszHttpProxy[0])-1))
2147 const WCHAR *value_start = option + sizeof(wszHttpProxy)/sizeof(wszHttpProxy[0])-1;
2148 const WCHAR *value_end;
2150 value_end = strchrW(option, ',');
2151 if (!value_end)
2152 value_end = value_start + strlenW(value_start);
2153 TRACE("HttpProxy value is %s\n", debugstr_wn(value_start, value_end-value_start));
2154 proxy = RPCRT4_strndupW(value_start, value_end-value_start);
2156 else
2157 FIXME("unhandled option %s\n", debugstr_w(option));
2160 httpc->app_info = InternetOpenW(wszUserAgent, proxy ? INTERNET_OPEN_TYPE_PROXY : INTERNET_OPEN_TYPE_PRECONFIG,
2161 NULL, NULL, INTERNET_FLAG_ASYNC);
2162 if (!httpc->app_info)
2164 HeapFree(GetProcessHeap(), 0, password);
2165 HeapFree(GetProcessHeap(), 0, user);
2166 HeapFree(GetProcessHeap(), 0, proxy);
2167 HeapFree(GetProcessHeap(), 0, servername);
2168 ERR("InternetOpenW failed with error %d\n", GetLastError());
2169 return RPC_S_SERVER_UNAVAILABLE;
2171 InternetSetStatusCallbackW(httpc->app_info, rpcrt4_http_internet_callback);
2173 /* if no RpcProxy option specified, set the HTTP server address to the
2174 * RPC server address */
2175 if (!servername)
2177 servername = HeapAlloc(GetProcessHeap(), 0, (strlen(httpc->common.NetworkAddr) + 1)*sizeof(WCHAR));
2178 if (!servername)
2180 HeapFree(GetProcessHeap(), 0, password);
2181 HeapFree(GetProcessHeap(), 0, user);
2182 HeapFree(GetProcessHeap(), 0, proxy);
2183 return RPC_S_OUT_OF_RESOURCES;
2185 MultiByteToWideChar(CP_ACP, 0, httpc->common.NetworkAddr, -1, servername, strlen(httpc->common.NetworkAddr) + 1);
2188 port = (httpc->common.QOS &&
2189 (httpc->common.QOS->qos->AdditionalSecurityInfoType == RPC_C_AUTHN_INFO_TYPE_HTTP) &&
2190 (httpc->common.QOS->qos->u.HttpCredentials->Flags & RPC_C_HTTP_FLAG_USE_SSL)) ?
2191 INTERNET_DEFAULT_HTTPS_PORT : INTERNET_DEFAULT_HTTP_PORT;
2193 httpc->session = InternetConnectW(httpc->app_info, servername, port, user, password,
2194 INTERNET_SERVICE_HTTP, 0, 0);
2196 HeapFree(GetProcessHeap(), 0, password);
2197 HeapFree(GetProcessHeap(), 0, user);
2198 HeapFree(GetProcessHeap(), 0, proxy);
2200 if (!httpc->session)
2202 ERR("InternetConnectW failed with error %d\n", GetLastError());
2203 HeapFree(GetProcessHeap(), 0, servername);
2204 return RPC_S_SERVER_UNAVAILABLE;
2206 httpc->servername = servername;
2207 return RPC_S_OK;
2210 static RPC_STATUS send_echo_request(HINTERNET req, RpcHttpAsyncData *async_data, HANDLE cancel_event)
2212 DWORD bytes_read;
2213 BYTE buf[20];
2214 BOOL ret;
2215 RPC_STATUS status;
2217 TRACE("sending echo request to server\n");
2219 prepare_async_request(async_data);
2220 ret = HttpSendRequestW(req, NULL, 0, NULL, 0);
2221 status = wait_async_request(async_data, ret, cancel_event);
2222 if (status != RPC_S_OK) return status;
2224 status = rpcrt4_http_check_response(req);
2225 if (status != RPC_S_OK) return status;
2227 InternetReadFile(req, buf, sizeof(buf), &bytes_read);
2228 /* FIXME: do something with retrieved data */
2230 return RPC_S_OK;
2233 /* prepare the in pipe for use by RPC packets */
2234 static RPC_STATUS rpcrt4_http_prepare_in_pipe(HINTERNET in_request, RpcHttpAsyncData *async_data, HANDLE cancel_event,
2235 const UUID *connection_uuid, const UUID *in_pipe_uuid,
2236 const UUID *association_uuid, BOOL authorized)
2238 BOOL ret;
2239 RPC_STATUS status;
2240 RpcPktHdr *hdr;
2241 INTERNET_BUFFERSW buffers_in;
2242 DWORD bytes_written;
2244 if (!authorized)
2246 /* ask wininet to authorize, if necessary */
2247 status = send_echo_request(in_request, async_data, cancel_event);
2248 if (status != RPC_S_OK) return status;
2250 memset(&buffers_in, 0, sizeof(buffers_in));
2251 buffers_in.dwStructSize = sizeof(buffers_in);
2252 /* FIXME: get this from the registry */
2253 buffers_in.dwBufferTotal = 1024 * 1024 * 1024; /* 1Gb */
2254 prepare_async_request(async_data);
2255 ret = HttpSendRequestExW(in_request, &buffers_in, NULL, 0, 0);
2256 status = wait_async_request(async_data, ret, cancel_event);
2257 if (status != RPC_S_OK) return status;
2259 TRACE("sending HTTP connect header to server\n");
2260 hdr = RPCRT4_BuildHttpConnectHeader(FALSE, connection_uuid, in_pipe_uuid, association_uuid);
2261 if (!hdr) return RPC_S_OUT_OF_RESOURCES;
2262 ret = InternetWriteFile(in_request, hdr, hdr->common.frag_len, &bytes_written);
2263 RPCRT4_FreeHeader(hdr);
2264 if (!ret)
2266 ERR("InternetWriteFile failed with error %d\n", GetLastError());
2267 return RPC_S_SERVER_UNAVAILABLE;
2270 return RPC_S_OK;
2273 static RPC_STATUS rpcrt4_http_read_http_packet(HINTERNET request, RpcPktHdr *hdr, BYTE **data)
2275 BOOL ret;
2276 DWORD bytes_read;
2277 unsigned short data_len;
2279 ret = InternetReadFile(request, hdr, sizeof(hdr->common), &bytes_read);
2280 if (!ret)
2281 return RPC_S_SERVER_UNAVAILABLE;
2282 if (hdr->common.ptype != PKT_HTTP || hdr->common.frag_len < sizeof(hdr->http))
2284 ERR("wrong packet type received %d or wrong frag_len %d\n",
2285 hdr->common.ptype, hdr->common.frag_len);
2286 return RPC_S_PROTOCOL_ERROR;
2289 ret = InternetReadFile(request, &hdr->common + 1, sizeof(hdr->http) - sizeof(hdr->common), &bytes_read);
2290 if (!ret)
2291 return RPC_S_SERVER_UNAVAILABLE;
2293 data_len = hdr->common.frag_len - sizeof(hdr->http);
2294 if (data_len)
2296 *data = HeapAlloc(GetProcessHeap(), 0, data_len);
2297 if (!*data)
2298 return RPC_S_OUT_OF_RESOURCES;
2299 ret = InternetReadFile(request, *data, data_len, &bytes_read);
2300 if (!ret)
2302 HeapFree(GetProcessHeap(), 0, *data);
2303 return RPC_S_SERVER_UNAVAILABLE;
2306 else
2307 *data = NULL;
2309 if (!RPCRT4_IsValidHttpPacket(hdr, *data, data_len))
2311 ERR("invalid http packet\n");
2312 return RPC_S_PROTOCOL_ERROR;
2315 return RPC_S_OK;
2318 /* prepare the out pipe for use by RPC packets */
2319 static RPC_STATUS rpcrt4_http_prepare_out_pipe(HINTERNET out_request, RpcHttpAsyncData *async_data,
2320 HANDLE cancel_event, const UUID *connection_uuid,
2321 const UUID *out_pipe_uuid, ULONG *flow_control_increment,
2322 BOOL authorized)
2324 static const WCHAR fmtW[] =
2325 {'C','o','n','t','e','n','t','-','L','e','n','g','t','h',':',' ','%','u','\r','\n',0};
2326 BOOL ret;
2327 RPC_STATUS status;
2328 RpcPktHdr *hdr;
2329 BYTE *data_from_server;
2330 RpcPktHdr pkt_from_server;
2331 ULONG field1, field3;
2332 DWORD bytes_read, len;
2333 BYTE buf[20];
2334 WCHAR header[sizeof(fmtW) / sizeof(fmtW[0]) + 10];
2336 if (!authorized)
2338 /* ask wininet to authorize, if necessary */
2339 status = send_echo_request(out_request, async_data, cancel_event);
2340 if (status != RPC_S_OK) return status;
2342 else
2343 InternetReadFile(out_request, buf, sizeof(buf), &bytes_read);
2345 hdr = RPCRT4_BuildHttpConnectHeader(TRUE, connection_uuid, out_pipe_uuid, NULL);
2346 if (!hdr) return RPC_S_OUT_OF_RESOURCES;
2348 TRACE("sending HTTP connect header to server\n");
2349 prepare_async_request(async_data);
2350 len = sprintfW(header, fmtW, hdr->common.frag_len);
2351 ret = HttpSendRequestW(out_request, header, len, hdr, hdr->common.frag_len);
2352 status = wait_async_request(async_data, ret, cancel_event);
2353 RPCRT4_FreeHeader(hdr);
2354 if (status != RPC_S_OK) return status;
2356 status = rpcrt4_http_check_response(out_request);
2357 if (status != RPC_S_OK) return status;
2359 status = rpcrt4_http_read_http_packet(out_request, &pkt_from_server,
2360 &data_from_server);
2361 if (status != RPC_S_OK) return status;
2362 status = RPCRT4_ParseHttpPrepareHeader1(&pkt_from_server, data_from_server,
2363 &field1);
2364 HeapFree(GetProcessHeap(), 0, data_from_server);
2365 if (status != RPC_S_OK) return status;
2366 TRACE("received (%d) from first prepare header\n", field1);
2368 for (;;)
2370 status = rpcrt4_http_read_http_packet(out_request, &pkt_from_server,
2371 &data_from_server);
2372 if (status != RPC_S_OK) return status;
2373 if (pkt_from_server.http.flags != 0x0001) break;
2375 TRACE("http idle packet, waiting for real packet\n");
2376 HeapFree(GetProcessHeap(), 0, data_from_server);
2377 if (pkt_from_server.http.num_data_items != 0)
2379 ERR("HTTP idle packet should have no data items instead of %d\n",
2380 pkt_from_server.http.num_data_items);
2381 return RPC_S_PROTOCOL_ERROR;
2384 status = RPCRT4_ParseHttpPrepareHeader2(&pkt_from_server, data_from_server,
2385 &field1, flow_control_increment,
2386 &field3);
2387 HeapFree(GetProcessHeap(), 0, data_from_server);
2388 if (status != RPC_S_OK) return status;
2389 TRACE("received (0x%08x 0x%08x %d) from second prepare header\n", field1, *flow_control_increment, field3);
2391 return RPC_S_OK;
2394 static UINT encode_base64(const char *bin, unsigned int len, WCHAR *base64)
2396 static const char enc[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
2397 UINT i = 0, x;
2399 while (len > 0)
2401 /* first 6 bits, all from bin[0] */
2402 base64[i++] = enc[(bin[0] & 0xfc) >> 2];
2403 x = (bin[0] & 3) << 4;
2405 /* next 6 bits, 2 from bin[0] and 4 from bin[1] */
2406 if (len == 1)
2408 base64[i++] = enc[x];
2409 base64[i++] = '=';
2410 base64[i++] = '=';
2411 break;
2413 base64[i++] = enc[x | ((bin[1] & 0xf0) >> 4)];
2414 x = (bin[1] & 0x0f) << 2;
2416 /* next 6 bits 4 from bin[1] and 2 from bin[2] */
2417 if (len == 2)
2419 base64[i++] = enc[x];
2420 base64[i++] = '=';
2421 break;
2423 base64[i++] = enc[x | ((bin[2] & 0xc0) >> 6)];
2425 /* last 6 bits, all from bin [2] */
2426 base64[i++] = enc[bin[2] & 0x3f];
2427 bin += 3;
2428 len -= 3;
2430 base64[i] = 0;
2431 return i;
2434 static inline char decode_char( WCHAR c )
2436 if (c >= 'A' && c <= 'Z') return c - 'A';
2437 if (c >= 'a' && c <= 'z') return c - 'a' + 26;
2438 if (c >= '0' && c <= '9') return c - '0' + 52;
2439 if (c == '+') return 62;
2440 if (c == '/') return 63;
2441 return 64;
2444 static unsigned int decode_base64( const WCHAR *base64, unsigned int len, char *buf )
2446 unsigned int i = 0;
2447 char c0, c1, c2, c3;
2448 const WCHAR *p = base64;
2450 while (len > 4)
2452 if ((c0 = decode_char( p[0] )) > 63) return 0;
2453 if ((c1 = decode_char( p[1] )) > 63) return 0;
2454 if ((c2 = decode_char( p[2] )) > 63) return 0;
2455 if ((c3 = decode_char( p[3] )) > 63) return 0;
2457 if (buf)
2459 buf[i + 0] = (c0 << 2) | (c1 >> 4);
2460 buf[i + 1] = (c1 << 4) | (c2 >> 2);
2461 buf[i + 2] = (c2 << 6) | c3;
2463 len -= 4;
2464 i += 3;
2465 p += 4;
2467 if (p[2] == '=')
2469 if ((c0 = decode_char( p[0] )) > 63) return 0;
2470 if ((c1 = decode_char( p[1] )) > 63) return 0;
2472 if (buf) buf[i] = (c0 << 2) | (c1 >> 4);
2473 i++;
2475 else if (p[3] == '=')
2477 if ((c0 = decode_char( p[0] )) > 63) return 0;
2478 if ((c1 = decode_char( p[1] )) > 63) return 0;
2479 if ((c2 = decode_char( p[2] )) > 63) return 0;
2481 if (buf)
2483 buf[i + 0] = (c0 << 2) | (c1 >> 4);
2484 buf[i + 1] = (c1 << 4) | (c2 >> 2);
2486 i += 2;
2488 else
2490 if ((c0 = decode_char( p[0] )) > 63) return 0;
2491 if ((c1 = decode_char( p[1] )) > 63) return 0;
2492 if ((c2 = decode_char( p[2] )) > 63) return 0;
2493 if ((c3 = decode_char( p[3] )) > 63) return 0;
2495 if (buf)
2497 buf[i + 0] = (c0 << 2) | (c1 >> 4);
2498 buf[i + 1] = (c1 << 4) | (c2 >> 2);
2499 buf[i + 2] = (c2 << 6) | c3;
2501 i += 3;
2503 return i;
2506 static struct authinfo *alloc_authinfo(void)
2508 struct authinfo *ret;
2510 if (!(ret = HeapAlloc(GetProcessHeap(), 0, sizeof(*ret) ))) return NULL;
2512 SecInvalidateHandle(&ret->cred);
2513 SecInvalidateHandle(&ret->ctx);
2514 memset(&ret->exp, 0, sizeof(ret->exp));
2515 ret->scheme = 0;
2516 ret->attr = 0;
2517 ret->max_token = 0;
2518 ret->data = NULL;
2519 ret->data_len = 0;
2520 ret->finished = FALSE;
2521 return ret;
2524 static void destroy_authinfo(struct authinfo *info)
2526 if (!info) return;
2528 if (SecIsValidHandle(&info->ctx))
2529 DeleteSecurityContext(&info->ctx);
2530 if (SecIsValidHandle(&info->cred))
2531 FreeCredentialsHandle(&info->cred);
2533 HeapFree(GetProcessHeap(), 0, info->data);
2534 HeapFree(GetProcessHeap(), 0, info);
2537 static const WCHAR basicW[] = {'B','a','s','i','c',0};
2538 static const WCHAR ntlmW[] = {'N','T','L','M',0};
2539 static const WCHAR passportW[] = {'P','a','s','s','p','o','r','t',0};
2540 static const WCHAR digestW[] = {'D','i','g','e','s','t',0};
2541 static const WCHAR negotiateW[] = {'N','e','g','o','t','i','a','t','e',0};
2543 static const struct
2545 const WCHAR *str;
2546 unsigned int len;
2547 DWORD scheme;
2549 auth_schemes[] =
2551 { basicW, ARRAYSIZE(basicW) - 1, RPC_C_HTTP_AUTHN_SCHEME_BASIC },
2552 { ntlmW, ARRAYSIZE(ntlmW) - 1, RPC_C_HTTP_AUTHN_SCHEME_NTLM },
2553 { passportW, ARRAYSIZE(passportW) - 1, RPC_C_HTTP_AUTHN_SCHEME_PASSPORT },
2554 { digestW, ARRAYSIZE(digestW) - 1, RPC_C_HTTP_AUTHN_SCHEME_DIGEST },
2555 { negotiateW, ARRAYSIZE(negotiateW) - 1, RPC_C_HTTP_AUTHN_SCHEME_NEGOTIATE }
2557 static const unsigned int num_auth_schemes = sizeof(auth_schemes)/sizeof(auth_schemes[0]);
2559 static DWORD auth_scheme_from_header( const WCHAR *header )
2561 unsigned int i;
2562 for (i = 0; i < num_auth_schemes; i++)
2564 if (!strncmpiW( header, auth_schemes[i].str, auth_schemes[i].len ) &&
2565 (header[auth_schemes[i].len] == ' ' || !header[auth_schemes[i].len])) return auth_schemes[i].scheme;
2567 return 0;
2570 static BOOL get_authvalue(HINTERNET request, DWORD scheme, WCHAR *buffer, DWORD buflen)
2572 DWORD len, index = 0;
2573 for (;;)
2575 len = buflen;
2576 if (!HttpQueryInfoW(request, HTTP_QUERY_WWW_AUTHENTICATE, buffer, &len, &index)) return FALSE;
2577 if (auth_scheme_from_header(buffer) == scheme) break;
2579 return TRUE;
2582 static RPC_STATUS do_authorization(HINTERNET request, SEC_WCHAR *servername,
2583 const RPC_HTTP_TRANSPORT_CREDENTIALS_W *creds, struct authinfo **auth_ptr)
2585 struct authinfo *info = *auth_ptr;
2586 SEC_WINNT_AUTH_IDENTITY_W *id = creds->TransportCredentials;
2587 RPC_STATUS status = RPC_S_SERVER_UNAVAILABLE;
2589 if ((!info && !(info = alloc_authinfo()))) return RPC_S_SERVER_UNAVAILABLE;
2591 switch (creds->AuthnSchemes[0])
2593 case RPC_C_HTTP_AUTHN_SCHEME_BASIC:
2595 int userlen = WideCharToMultiByte(CP_UTF8, 0, id->User, id->UserLength, NULL, 0, NULL, NULL);
2596 int passlen = WideCharToMultiByte(CP_UTF8, 0, id->Password, id->PasswordLength, NULL, 0, NULL, NULL);
2598 info->data_len = userlen + passlen + 1;
2599 if (!(info->data = HeapAlloc(GetProcessHeap(), 0, info->data_len)))
2601 status = RPC_S_OUT_OF_MEMORY;
2602 break;
2604 WideCharToMultiByte(CP_UTF8, 0, id->User, id->UserLength, info->data, userlen, NULL, NULL);
2605 info->data[userlen] = ':';
2606 WideCharToMultiByte(CP_UTF8, 0, id->Password, id->PasswordLength, info->data + userlen + 1, passlen, NULL, NULL);
2608 info->scheme = RPC_C_HTTP_AUTHN_SCHEME_BASIC;
2609 info->finished = TRUE;
2610 status = RPC_S_OK;
2611 break;
2613 case RPC_C_HTTP_AUTHN_SCHEME_NTLM:
2614 case RPC_C_HTTP_AUTHN_SCHEME_NEGOTIATE:
2617 static SEC_WCHAR ntlmW[] = {'N','T','L','M',0}, negotiateW[] = {'N','e','g','o','t','i','a','t','e',0};
2618 SECURITY_STATUS ret;
2619 SecBufferDesc out_desc, in_desc;
2620 SecBuffer out, in;
2621 ULONG flags = ISC_REQ_CONNECTION|ISC_REQ_USE_DCE_STYLE|ISC_REQ_MUTUAL_AUTH|ISC_REQ_DELEGATE;
2622 SEC_WCHAR *scheme;
2623 int scheme_len;
2624 const WCHAR *p;
2625 WCHAR auth_value[2048];
2626 DWORD size = sizeof(auth_value);
2627 BOOL first = FALSE;
2629 if (creds->AuthnSchemes[0] == RPC_C_HTTP_AUTHN_SCHEME_NTLM) scheme = ntlmW;
2630 else scheme = negotiateW;
2631 scheme_len = strlenW( scheme );
2633 if (!*auth_ptr)
2635 TimeStamp exp;
2636 SecPkgInfoW *pkg_info;
2638 ret = AcquireCredentialsHandleW(NULL, scheme, SECPKG_CRED_OUTBOUND, NULL, id, NULL, NULL, &info->cred, &exp);
2639 if (ret != SEC_E_OK) break;
2641 ret = QuerySecurityPackageInfoW(scheme, &pkg_info);
2642 if (ret != SEC_E_OK) break;
2644 info->max_token = pkg_info->cbMaxToken;
2645 FreeContextBuffer(pkg_info);
2646 first = TRUE;
2648 else
2650 if (info->finished || !get_authvalue(request, creds->AuthnSchemes[0], auth_value, size)) break;
2651 if (auth_scheme_from_header(auth_value) != info->scheme)
2653 ERR("authentication scheme changed\n");
2654 break;
2657 in.BufferType = SECBUFFER_TOKEN;
2658 in.cbBuffer = 0;
2659 in.pvBuffer = NULL;
2661 in_desc.ulVersion = 0;
2662 in_desc.cBuffers = 1;
2663 in_desc.pBuffers = &in;
2665 p = auth_value + scheme_len;
2666 if (!first && *p == ' ')
2668 int len = strlenW(++p);
2669 in.cbBuffer = decode_base64(p, len, NULL);
2670 if (!(in.pvBuffer = HeapAlloc(GetProcessHeap(), 0, in.cbBuffer))) break;
2671 decode_base64(p, len, in.pvBuffer);
2673 out.BufferType = SECBUFFER_TOKEN;
2674 out.cbBuffer = info->max_token;
2675 if (!(out.pvBuffer = HeapAlloc(GetProcessHeap(), 0, out.cbBuffer)))
2677 HeapFree(GetProcessHeap(), 0, in.pvBuffer);
2678 break;
2680 out_desc.ulVersion = 0;
2681 out_desc.cBuffers = 1;
2682 out_desc.pBuffers = &out;
2684 ret = InitializeSecurityContextW(first ? &info->cred : NULL, first ? NULL : &info->ctx,
2685 first ? servername : NULL, flags, 0, SECURITY_NETWORK_DREP,
2686 in.pvBuffer ? &in_desc : NULL, 0, &info->ctx, &out_desc,
2687 &info->attr, &info->exp);
2688 HeapFree(GetProcessHeap(), 0, in.pvBuffer);
2689 if (ret == SEC_E_OK)
2691 HeapFree(GetProcessHeap(), 0, info->data);
2692 info->data = out.pvBuffer;
2693 info->data_len = out.cbBuffer;
2694 info->finished = TRUE;
2695 TRACE("sending last auth packet\n");
2696 status = RPC_S_OK;
2698 else if (ret == SEC_I_CONTINUE_NEEDED)
2700 HeapFree(GetProcessHeap(), 0, info->data);
2701 info->data = out.pvBuffer;
2702 info->data_len = out.cbBuffer;
2703 TRACE("sending next auth packet\n");
2704 status = RPC_S_OK;
2706 else
2708 ERR("InitializeSecurityContextW failed with error 0x%08x\n", ret);
2709 HeapFree(GetProcessHeap(), 0, out.pvBuffer);
2710 break;
2712 info->scheme = creds->AuthnSchemes[0];
2713 break;
2715 default:
2716 FIXME("scheme %u not supported\n", creds->AuthnSchemes[0]);
2717 break;
2720 if (status != RPC_S_OK)
2722 destroy_authinfo(info);
2723 *auth_ptr = NULL;
2724 return status;
2726 *auth_ptr = info;
2727 return RPC_S_OK;
2730 static RPC_STATUS insert_authorization_header(HINTERNET request, ULONG scheme, char *data, int data_len)
2732 static const WCHAR authW[] = {'A','u','t','h','o','r','i','z','a','t','i','o','n',':',' '};
2733 static const WCHAR basicW[] = {'B','a','s','i','c',' '};
2734 static const WCHAR negotiateW[] = {'N','e','g','o','t','i','a','t','e',' '};
2735 static const WCHAR ntlmW[] = {'N','T','L','M',' '};
2736 int scheme_len, auth_len = sizeof(authW) / sizeof(authW[0]), len = ((data_len + 2) * 4) / 3;
2737 const WCHAR *scheme_str;
2738 WCHAR *header, *ptr;
2739 RPC_STATUS status = RPC_S_SERVER_UNAVAILABLE;
2741 switch (scheme)
2743 case RPC_C_HTTP_AUTHN_SCHEME_BASIC:
2744 scheme_str = basicW;
2745 scheme_len = sizeof(basicW) / sizeof(basicW[0]);
2746 break;
2747 case RPC_C_HTTP_AUTHN_SCHEME_NEGOTIATE:
2748 scheme_str = negotiateW;
2749 scheme_len = sizeof(negotiateW) / sizeof(negotiateW[0]);
2750 break;
2751 case RPC_C_HTTP_AUTHN_SCHEME_NTLM:
2752 scheme_str = ntlmW;
2753 scheme_len = sizeof(ntlmW) / sizeof(ntlmW[0]);
2754 break;
2755 default:
2756 ERR("unknown scheme %u\n", scheme);
2757 return RPC_S_SERVER_UNAVAILABLE;
2759 if ((header = HeapAlloc(GetProcessHeap(), 0, (auth_len + scheme_len + len + 2) * sizeof(WCHAR))))
2761 memcpy(header, authW, auth_len * sizeof(WCHAR));
2762 ptr = header + auth_len;
2763 memcpy(ptr, scheme_str, scheme_len * sizeof(WCHAR));
2764 ptr += scheme_len;
2765 len = encode_base64(data, data_len, ptr);
2766 ptr[len++] = '\r';
2767 ptr[len++] = '\n';
2768 ptr[len] = 0;
2769 if (HttpAddRequestHeadersW(request, header, -1, HTTP_ADDREQ_FLAG_ADD|HTTP_ADDREQ_FLAG_REPLACE))
2770 status = RPC_S_OK;
2771 HeapFree(GetProcessHeap(), 0, header);
2773 return status;
2776 static void drain_content(HINTERNET request)
2778 DWORD count, len = 0, size = sizeof(len);
2779 char buf[2048];
2781 HttpQueryInfoW(request, HTTP_QUERY_FLAG_NUMBER|HTTP_QUERY_CONTENT_LENGTH, &len, &size, NULL);
2782 if (!len) return;
2783 for (;;)
2785 count = min(sizeof(buf), len);
2786 if (!InternetReadFile(request, buf, count, &count) || !count) return;
2787 len -= count;
2791 static RPC_STATUS authorize_request(RpcConnection_http *httpc, HINTERNET request)
2793 static const WCHAR authW[] = {'A','u','t','h','o','r','i','z','a','t','i','o','n',':','\r','\n',0};
2794 struct authinfo *info = NULL;
2795 RPC_STATUS status;
2796 BOOL ret;
2798 for (;;)
2800 status = do_authorization(request, httpc->servername, httpc->common.QOS->qos->u.HttpCredentials, &info);
2801 if (status != RPC_S_OK) break;
2803 status = insert_authorization_header(request, info->scheme, info->data, info->data_len);
2804 if (status != RPC_S_OK) break;
2806 prepare_async_request(httpc->async_data);
2807 ret = HttpSendRequestW(request, NULL, 0, NULL, 0);
2808 status = wait_async_request(httpc->async_data, ret, httpc->cancel_event);
2809 if (status != RPC_S_OK || info->finished) break;
2811 status = rpcrt4_http_check_response(request);
2812 if (status != RPC_S_OK && status != ERROR_ACCESS_DENIED) break;
2813 drain_content(request);
2816 if (info->scheme != RPC_C_HTTP_AUTHN_SCHEME_BASIC)
2817 HttpAddRequestHeadersW(request, authW, -1, HTTP_ADDREQ_FLAG_REPLACE);
2819 destroy_authinfo(info);
2820 return status;
2823 static RPC_STATUS insert_cookie_header(HINTERNET request, const WCHAR *value)
2825 static const WCHAR cookieW[] = {'C','o','o','k','i','e',':',' '};
2826 WCHAR *header, *ptr;
2827 int len;
2828 RPC_STATUS status = RPC_S_SERVER_UNAVAILABLE;
2830 if (!value) return RPC_S_OK;
2832 len = strlenW(value);
2833 if ((header = HeapAlloc(GetProcessHeap(), 0, sizeof(cookieW) + (len + 3) * sizeof(WCHAR))))
2835 memcpy(header, cookieW, sizeof(cookieW));
2836 ptr = header + sizeof(cookieW) / sizeof(cookieW[0]);
2837 memcpy(ptr, value, len * sizeof(WCHAR));
2838 ptr[len++] = '\r';
2839 ptr[len++] = '\n';
2840 ptr[len] = 0;
2841 if ((HttpAddRequestHeadersW(request, header, -1, HTTP_ADDREQ_FLAG_ADD_IF_NEW))) status = RPC_S_OK;
2842 HeapFree(GetProcessHeap(), 0, header);
2844 return status;
2847 static BOOL has_credentials(RpcConnection_http *httpc)
2849 RPC_HTTP_TRANSPORT_CREDENTIALS_W *creds;
2850 SEC_WINNT_AUTH_IDENTITY_W *id;
2852 if (!httpc->common.QOS || httpc->common.QOS->qos->AdditionalSecurityInfoType != RPC_C_AUTHN_INFO_TYPE_HTTP)
2853 return FALSE;
2855 creds = httpc->common.QOS->qos->u.HttpCredentials;
2856 if (creds->AuthenticationTarget != RPC_C_HTTP_AUTHN_TARGET_SERVER || !creds->NumberOfAuthnSchemes)
2857 return FALSE;
2859 id = creds->TransportCredentials;
2860 if (!id || !id->User || !id->Password) return FALSE;
2862 return TRUE;
2865 static BOOL is_secure(RpcConnection_http *httpc)
2867 return httpc->common.QOS &&
2868 (httpc->common.QOS->qos->AdditionalSecurityInfoType == RPC_C_AUTHN_INFO_TYPE_HTTP) &&
2869 (httpc->common.QOS->qos->u.HttpCredentials->Flags & RPC_C_HTTP_FLAG_USE_SSL);
2872 static RPC_STATUS rpcrt4_ncacn_http_open(RpcConnection* Connection)
2874 RpcConnection_http *httpc = (RpcConnection_http *)Connection;
2875 static const WCHAR wszVerbIn[] = {'R','P','C','_','I','N','_','D','A','T','A',0};
2876 static const WCHAR wszVerbOut[] = {'R','P','C','_','O','U','T','_','D','A','T','A',0};
2877 static const WCHAR wszRpcProxyPrefix[] = {'/','r','p','c','/','r','p','c','p','r','o','x','y','.','d','l','l','?',0};
2878 static const WCHAR wszColon[] = {':',0};
2879 static const WCHAR wszAcceptType[] = {'a','p','p','l','i','c','a','t','i','o','n','/','r','p','c',0};
2880 LPCWSTR wszAcceptTypes[] = { wszAcceptType, NULL };
2881 DWORD flags;
2882 WCHAR *url;
2883 RPC_STATUS status;
2884 BOOL secure, credentials;
2885 HttpTimerThreadData *timer_data;
2886 HANDLE thread;
2888 TRACE("(%s, %s)\n", Connection->NetworkAddr, Connection->Endpoint);
2890 if (Connection->server)
2892 ERR("ncacn_http servers not supported yet\n");
2893 return RPC_S_SERVER_UNAVAILABLE;
2896 if (httpc->in_request)
2897 return RPC_S_OK;
2899 httpc->async_data->completion_event = CreateEventW(NULL, FALSE, FALSE, NULL);
2901 status = UuidCreate(&httpc->connection_uuid);
2902 status = UuidCreate(&httpc->in_pipe_uuid);
2903 status = UuidCreate(&httpc->out_pipe_uuid);
2905 status = rpcrt4_http_internet_connect(httpc);
2906 if (status != RPC_S_OK)
2907 return status;
2909 url = HeapAlloc(GetProcessHeap(), 0, sizeof(wszRpcProxyPrefix) + (strlen(Connection->NetworkAddr) + 1 + strlen(Connection->Endpoint))*sizeof(WCHAR));
2910 if (!url)
2911 return RPC_S_OUT_OF_MEMORY;
2912 memcpy(url, wszRpcProxyPrefix, sizeof(wszRpcProxyPrefix));
2913 MultiByteToWideChar(CP_ACP, 0, Connection->NetworkAddr, -1, url+sizeof(wszRpcProxyPrefix)/sizeof(wszRpcProxyPrefix[0])-1, strlen(Connection->NetworkAddr)+1);
2914 strcatW(url, wszColon);
2915 MultiByteToWideChar(CP_ACP, 0, Connection->Endpoint, -1, url+strlenW(url), strlen(Connection->Endpoint)+1);
2917 secure = is_secure(httpc);
2918 credentials = has_credentials(httpc);
2920 flags = INTERNET_FLAG_KEEP_CONNECTION | INTERNET_FLAG_PRAGMA_NOCACHE | INTERNET_FLAG_NO_CACHE_WRITE |
2921 INTERNET_FLAG_NO_AUTO_REDIRECT;
2922 if (secure) flags |= INTERNET_FLAG_SECURE;
2923 if (credentials) flags |= INTERNET_FLAG_NO_AUTH;
2925 httpc->in_request = HttpOpenRequestW(httpc->session, wszVerbIn, url, NULL, NULL, wszAcceptTypes,
2926 flags, (DWORD_PTR)httpc->async_data);
2927 if (!httpc->in_request)
2929 ERR("HttpOpenRequestW failed with error %d\n", GetLastError());
2930 HeapFree(GetProcessHeap(), 0, url);
2931 return RPC_S_SERVER_UNAVAILABLE;
2933 status = insert_cookie_header(httpc->in_request, Connection->CookieAuth);
2934 if (status != RPC_S_OK)
2936 HeapFree(GetProcessHeap(), 0, url);
2937 return status;
2939 if (credentials)
2941 status = authorize_request(httpc, httpc->in_request);
2942 if (status != RPC_S_OK)
2944 HeapFree(GetProcessHeap(), 0, url);
2945 return status;
2947 status = rpcrt4_http_check_response(httpc->in_request);
2948 if (status != RPC_S_OK)
2950 HeapFree(GetProcessHeap(), 0, url);
2951 return status;
2953 drain_content(httpc->in_request);
2956 httpc->out_request = HttpOpenRequestW(httpc->session, wszVerbOut, url, NULL, NULL, wszAcceptTypes,
2957 flags, (DWORD_PTR)httpc->async_data);
2958 HeapFree(GetProcessHeap(), 0, url);
2959 if (!httpc->out_request)
2961 ERR("HttpOpenRequestW failed with error %d\n", GetLastError());
2962 return RPC_S_SERVER_UNAVAILABLE;
2964 status = insert_cookie_header(httpc->out_request, Connection->CookieAuth);
2965 if (status != RPC_S_OK)
2966 return status;
2968 if (credentials)
2970 status = authorize_request(httpc, httpc->out_request);
2971 if (status != RPC_S_OK)
2972 return status;
2975 status = rpcrt4_http_prepare_in_pipe(httpc->in_request, httpc->async_data, httpc->cancel_event,
2976 &httpc->connection_uuid, &httpc->in_pipe_uuid,
2977 &Connection->assoc->http_uuid, credentials);
2978 if (status != RPC_S_OK)
2979 return status;
2981 status = rpcrt4_http_prepare_out_pipe(httpc->out_request, httpc->async_data, httpc->cancel_event,
2982 &httpc->connection_uuid, &httpc->out_pipe_uuid,
2983 &httpc->flow_control_increment, credentials);
2984 if (status != RPC_S_OK)
2985 return status;
2987 httpc->flow_control_mark = httpc->flow_control_increment / 2;
2988 httpc->last_sent_time = GetTickCount();
2989 httpc->timer_cancelled = CreateEventW(NULL, FALSE, FALSE, NULL);
2991 timer_data = HeapAlloc(GetProcessHeap(), 0, sizeof(*timer_data));
2992 if (!timer_data)
2993 return ERROR_OUTOFMEMORY;
2994 timer_data->timer_param = httpc->in_request;
2995 timer_data->last_sent_time = &httpc->last_sent_time;
2996 timer_data->timer_cancelled = httpc->timer_cancelled;
2997 /* FIXME: should use CreateTimerQueueTimer when implemented */
2998 thread = CreateThread(NULL, 0, rpcrt4_http_timer_thread, timer_data, 0, NULL);
2999 if (!thread)
3001 HeapFree(GetProcessHeap(), 0, timer_data);
3002 return GetLastError();
3004 CloseHandle(thread);
3006 return RPC_S_OK;
3009 static RPC_STATUS rpcrt4_ncacn_http_handoff(RpcConnection *old_conn, RpcConnection *new_conn)
3011 assert(0);
3012 return RPC_S_SERVER_UNAVAILABLE;
3015 static int rpcrt4_ncacn_http_read(RpcConnection *Connection,
3016 void *buffer, unsigned int count)
3018 RpcConnection_http *httpc = (RpcConnection_http *) Connection;
3019 char *buf = buffer;
3020 BOOL ret;
3021 unsigned int bytes_left = count;
3022 RPC_STATUS status = RPC_S_OK;
3024 httpc->async_data->inet_buffers.lpvBuffer = HeapAlloc(GetProcessHeap(), 0, count);
3026 while (bytes_left)
3028 httpc->async_data->inet_buffers.dwBufferLength = bytes_left;
3029 prepare_async_request(httpc->async_data);
3030 ret = InternetReadFileExA(httpc->out_request, &httpc->async_data->inet_buffers, IRF_ASYNC, 0);
3031 status = wait_async_request(httpc->async_data, ret, httpc->cancel_event);
3032 if(status != RPC_S_OK) {
3033 if(status == RPC_S_CALL_CANCELLED)
3034 TRACE("call cancelled\n");
3035 break;
3038 if(!httpc->async_data->inet_buffers.dwBufferLength)
3039 break;
3040 memcpy(buf, httpc->async_data->inet_buffers.lpvBuffer,
3041 httpc->async_data->inet_buffers.dwBufferLength);
3043 bytes_left -= httpc->async_data->inet_buffers.dwBufferLength;
3044 buf += httpc->async_data->inet_buffers.dwBufferLength;
3047 HeapFree(GetProcessHeap(), 0, httpc->async_data->inet_buffers.lpvBuffer);
3048 httpc->async_data->inet_buffers.lpvBuffer = NULL;
3050 TRACE("%p %p %u -> %u\n", httpc->out_request, buffer, count, status);
3051 return status == RPC_S_OK ? count : -1;
3054 static RPC_STATUS rpcrt4_ncacn_http_receive_fragment(RpcConnection *Connection, RpcPktHdr **Header, void **Payload)
3056 RpcConnection_http *httpc = (RpcConnection_http *) Connection;
3057 RPC_STATUS status;
3058 DWORD hdr_length;
3059 LONG dwRead;
3060 RpcPktCommonHdr common_hdr;
3062 *Header = NULL;
3064 TRACE("(%p, %p, %p)\n", Connection, Header, Payload);
3066 again:
3067 /* read packet common header */
3068 dwRead = rpcrt4_ncacn_http_read(Connection, &common_hdr, sizeof(common_hdr));
3069 if (dwRead != sizeof(common_hdr)) {
3070 WARN("Short read of header, %d bytes\n", dwRead);
3071 status = RPC_S_PROTOCOL_ERROR;
3072 goto fail;
3074 if (!memcmp(&common_hdr, "HTTP/1.1", sizeof("HTTP/1.1")) ||
3075 !memcmp(&common_hdr, "HTTP/1.0", sizeof("HTTP/1.0")))
3077 FIXME("server returned %s\n", debugstr_a((const char *)&common_hdr));
3078 status = RPC_S_PROTOCOL_ERROR;
3079 goto fail;
3082 status = RPCRT4_ValidateCommonHeader(&common_hdr);
3083 if (status != RPC_S_OK) goto fail;
3085 hdr_length = RPCRT4_GetHeaderSize((RpcPktHdr*)&common_hdr);
3086 if (hdr_length == 0) {
3087 WARN("header length == 0\n");
3088 status = RPC_S_PROTOCOL_ERROR;
3089 goto fail;
3092 *Header = HeapAlloc(GetProcessHeap(), 0, hdr_length);
3093 if (!*Header)
3095 status = RPC_S_OUT_OF_RESOURCES;
3096 goto fail;
3098 memcpy(*Header, &common_hdr, sizeof(common_hdr));
3100 /* read the rest of packet header */
3101 dwRead = rpcrt4_ncacn_http_read(Connection, &(*Header)->common + 1, hdr_length - sizeof(common_hdr));
3102 if (dwRead != hdr_length - sizeof(common_hdr)) {
3103 WARN("bad header length, %d bytes, hdr_length %d\n", dwRead, hdr_length);
3104 status = RPC_S_PROTOCOL_ERROR;
3105 goto fail;
3108 if (common_hdr.frag_len - hdr_length)
3110 *Payload = HeapAlloc(GetProcessHeap(), 0, common_hdr.frag_len - hdr_length);
3111 if (!*Payload)
3113 status = RPC_S_OUT_OF_RESOURCES;
3114 goto fail;
3117 dwRead = rpcrt4_ncacn_http_read(Connection, *Payload, common_hdr.frag_len - hdr_length);
3118 if (dwRead != common_hdr.frag_len - hdr_length)
3120 WARN("bad data length, %d/%d\n", dwRead, common_hdr.frag_len - hdr_length);
3121 status = RPC_S_PROTOCOL_ERROR;
3122 goto fail;
3125 else
3126 *Payload = NULL;
3128 if ((*Header)->common.ptype == PKT_HTTP)
3130 if (!RPCRT4_IsValidHttpPacket(*Header, *Payload, common_hdr.frag_len - hdr_length))
3132 ERR("invalid http packet of length %d bytes\n", (*Header)->common.frag_len);
3133 status = RPC_S_PROTOCOL_ERROR;
3134 goto fail;
3136 if ((*Header)->http.flags == 0x0001)
3138 TRACE("http idle packet, waiting for real packet\n");
3139 if ((*Header)->http.num_data_items != 0)
3141 ERR("HTTP idle packet should have no data items instead of %d\n", (*Header)->http.num_data_items);
3142 status = RPC_S_PROTOCOL_ERROR;
3143 goto fail;
3146 else if ((*Header)->http.flags == 0x0002)
3148 ULONG bytes_transmitted;
3149 ULONG flow_control_increment;
3150 UUID pipe_uuid;
3151 status = RPCRT4_ParseHttpFlowControlHeader(*Header, *Payload,
3152 Connection->server,
3153 &bytes_transmitted,
3154 &flow_control_increment,
3155 &pipe_uuid);
3156 if (status != RPC_S_OK)
3157 goto fail;
3158 TRACE("received http flow control header (0x%x, 0x%x, %s)\n",
3159 bytes_transmitted, flow_control_increment, debugstr_guid(&pipe_uuid));
3160 /* FIXME: do something with parsed data */
3162 else
3164 FIXME("unrecognised http packet with flags 0x%04x\n", (*Header)->http.flags);
3165 status = RPC_S_PROTOCOL_ERROR;
3166 goto fail;
3168 RPCRT4_FreeHeader(*Header);
3169 *Header = NULL;
3170 HeapFree(GetProcessHeap(), 0, *Payload);
3171 *Payload = NULL;
3172 goto again;
3175 /* success */
3176 status = RPC_S_OK;
3178 httpc->bytes_received += common_hdr.frag_len;
3180 TRACE("httpc->bytes_received = 0x%x\n", httpc->bytes_received);
3182 if (httpc->bytes_received > httpc->flow_control_mark)
3184 RpcPktHdr *hdr = RPCRT4_BuildHttpFlowControlHeader(httpc->common.server,
3185 httpc->bytes_received,
3186 httpc->flow_control_increment,
3187 &httpc->out_pipe_uuid);
3188 if (hdr)
3190 DWORD bytes_written;
3191 BOOL ret2;
3192 TRACE("sending flow control packet at 0x%x\n", httpc->bytes_received);
3193 ret2 = InternetWriteFile(httpc->in_request, hdr, hdr->common.frag_len, &bytes_written);
3194 RPCRT4_FreeHeader(hdr);
3195 if (ret2)
3196 httpc->flow_control_mark = httpc->bytes_received + httpc->flow_control_increment / 2;
3200 fail:
3201 if (status != RPC_S_OK) {
3202 RPCRT4_FreeHeader(*Header);
3203 *Header = NULL;
3204 HeapFree(GetProcessHeap(), 0, *Payload);
3205 *Payload = NULL;
3207 return status;
3210 static int rpcrt4_ncacn_http_write(RpcConnection *Connection,
3211 const void *buffer, unsigned int count)
3213 RpcConnection_http *httpc = (RpcConnection_http *) Connection;
3214 DWORD bytes_written;
3215 BOOL ret;
3217 httpc->last_sent_time = ~0U; /* disable idle packet sending */
3218 ret = InternetWriteFile(httpc->in_request, buffer, count, &bytes_written);
3219 httpc->last_sent_time = GetTickCount();
3220 TRACE("%p %p %u -> %s\n", httpc->in_request, buffer, count, ret ? "TRUE" : "FALSE");
3221 return ret ? bytes_written : -1;
3224 static int rpcrt4_ncacn_http_close(RpcConnection *Connection)
3226 RpcConnection_http *httpc = (RpcConnection_http *) Connection;
3228 TRACE("\n");
3230 SetEvent(httpc->timer_cancelled);
3231 if (httpc->in_request)
3232 InternetCloseHandle(httpc->in_request);
3233 httpc->in_request = NULL;
3234 if (httpc->out_request)
3235 InternetCloseHandle(httpc->out_request);
3236 httpc->out_request = NULL;
3237 if (httpc->app_info)
3238 InternetCloseHandle(httpc->app_info);
3239 httpc->app_info = NULL;
3240 if (httpc->session)
3241 InternetCloseHandle(httpc->session);
3242 httpc->session = NULL;
3243 RpcHttpAsyncData_Release(httpc->async_data);
3244 if (httpc->cancel_event)
3245 CloseHandle(httpc->cancel_event);
3246 HeapFree(GetProcessHeap(), 0, httpc->servername);
3247 httpc->servername = NULL;
3249 return 0;
3252 static void rpcrt4_ncacn_http_cancel_call(RpcConnection *Connection)
3254 RpcConnection_http *httpc = (RpcConnection_http *) Connection;
3256 SetEvent(httpc->cancel_event);
3259 static int rpcrt4_ncacn_http_wait_for_incoming_data(RpcConnection *Connection)
3261 RpcConnection_http *httpc = (RpcConnection_http *) Connection;
3262 BOOL ret;
3263 RPC_STATUS status;
3265 prepare_async_request(httpc->async_data);
3266 ret = InternetQueryDataAvailable(httpc->out_request,
3267 &httpc->async_data->inet_buffers.dwBufferLength, IRF_ASYNC, 0);
3268 status = wait_async_request(httpc->async_data, ret, httpc->cancel_event);
3269 return status == RPC_S_OK ? 0 : -1;
3272 static size_t rpcrt4_ncacn_http_get_top_of_tower(unsigned char *tower_data,
3273 const char *networkaddr,
3274 const char *endpoint)
3276 return rpcrt4_ip_tcp_get_top_of_tower(tower_data, networkaddr,
3277 EPM_PROTOCOL_HTTP, endpoint);
3280 static RPC_STATUS rpcrt4_ncacn_http_parse_top_of_tower(const unsigned char *tower_data,
3281 size_t tower_size,
3282 char **networkaddr,
3283 char **endpoint)
3285 return rpcrt4_ip_tcp_parse_top_of_tower(tower_data, tower_size,
3286 networkaddr, EPM_PROTOCOL_HTTP,
3287 endpoint);
3290 static const struct connection_ops conn_protseq_list[] = {
3291 { "ncacn_np",
3292 { EPM_PROTOCOL_NCACN, EPM_PROTOCOL_SMB },
3293 rpcrt4_conn_np_alloc,
3294 rpcrt4_ncacn_np_open,
3295 rpcrt4_ncacn_np_handoff,
3296 rpcrt4_conn_np_read,
3297 rpcrt4_conn_np_write,
3298 rpcrt4_conn_np_close,
3299 rpcrt4_conn_np_cancel_call,
3300 rpcrt4_conn_np_wait_for_incoming_data,
3301 rpcrt4_ncacn_np_get_top_of_tower,
3302 rpcrt4_ncacn_np_parse_top_of_tower,
3303 NULL,
3304 RPCRT4_default_is_authorized,
3305 RPCRT4_default_authorize,
3306 RPCRT4_default_secure_packet,
3307 rpcrt4_conn_np_impersonate_client,
3308 rpcrt4_conn_np_revert_to_self,
3309 RPCRT4_default_inquire_auth_client,
3311 { "ncalrpc",
3312 { EPM_PROTOCOL_NCALRPC, EPM_PROTOCOL_PIPE },
3313 rpcrt4_conn_np_alloc,
3314 rpcrt4_ncalrpc_open,
3315 rpcrt4_ncalrpc_handoff,
3316 rpcrt4_conn_np_read,
3317 rpcrt4_conn_np_write,
3318 rpcrt4_conn_np_close,
3319 rpcrt4_conn_np_cancel_call,
3320 rpcrt4_conn_np_wait_for_incoming_data,
3321 rpcrt4_ncalrpc_get_top_of_tower,
3322 rpcrt4_ncalrpc_parse_top_of_tower,
3323 NULL,
3324 rpcrt4_ncalrpc_is_authorized,
3325 rpcrt4_ncalrpc_authorize,
3326 rpcrt4_ncalrpc_secure_packet,
3327 rpcrt4_conn_np_impersonate_client,
3328 rpcrt4_conn_np_revert_to_self,
3329 rpcrt4_ncalrpc_inquire_auth_client,
3331 { "ncacn_ip_tcp",
3332 { EPM_PROTOCOL_NCACN, EPM_PROTOCOL_TCP },
3333 rpcrt4_conn_tcp_alloc,
3334 rpcrt4_ncacn_ip_tcp_open,
3335 rpcrt4_conn_tcp_handoff,
3336 rpcrt4_conn_tcp_read,
3337 rpcrt4_conn_tcp_write,
3338 rpcrt4_conn_tcp_close,
3339 rpcrt4_conn_tcp_cancel_call,
3340 rpcrt4_conn_tcp_wait_for_incoming_data,
3341 rpcrt4_ncacn_ip_tcp_get_top_of_tower,
3342 rpcrt4_ncacn_ip_tcp_parse_top_of_tower,
3343 NULL,
3344 RPCRT4_default_is_authorized,
3345 RPCRT4_default_authorize,
3346 RPCRT4_default_secure_packet,
3347 RPCRT4_default_impersonate_client,
3348 RPCRT4_default_revert_to_self,
3349 RPCRT4_default_inquire_auth_client,
3351 { "ncacn_http",
3352 { EPM_PROTOCOL_NCACN, EPM_PROTOCOL_HTTP },
3353 rpcrt4_ncacn_http_alloc,
3354 rpcrt4_ncacn_http_open,
3355 rpcrt4_ncacn_http_handoff,
3356 rpcrt4_ncacn_http_read,
3357 rpcrt4_ncacn_http_write,
3358 rpcrt4_ncacn_http_close,
3359 rpcrt4_ncacn_http_cancel_call,
3360 rpcrt4_ncacn_http_wait_for_incoming_data,
3361 rpcrt4_ncacn_http_get_top_of_tower,
3362 rpcrt4_ncacn_http_parse_top_of_tower,
3363 rpcrt4_ncacn_http_receive_fragment,
3364 RPCRT4_default_is_authorized,
3365 RPCRT4_default_authorize,
3366 RPCRT4_default_secure_packet,
3367 RPCRT4_default_impersonate_client,
3368 RPCRT4_default_revert_to_self,
3369 RPCRT4_default_inquire_auth_client,
3374 static const struct protseq_ops protseq_list[] =
3377 "ncacn_np",
3378 rpcrt4_protseq_np_alloc,
3379 rpcrt4_protseq_np_signal_state_changed,
3380 rpcrt4_protseq_np_get_wait_array,
3381 rpcrt4_protseq_np_free_wait_array,
3382 rpcrt4_protseq_np_wait_for_new_connection,
3383 rpcrt4_protseq_ncacn_np_open_endpoint,
3386 "ncalrpc",
3387 rpcrt4_protseq_np_alloc,
3388 rpcrt4_protseq_np_signal_state_changed,
3389 rpcrt4_protseq_np_get_wait_array,
3390 rpcrt4_protseq_np_free_wait_array,
3391 rpcrt4_protseq_np_wait_for_new_connection,
3392 rpcrt4_protseq_ncalrpc_open_endpoint,
3395 "ncacn_ip_tcp",
3396 rpcrt4_protseq_sock_alloc,
3397 rpcrt4_protseq_sock_signal_state_changed,
3398 rpcrt4_protseq_sock_get_wait_array,
3399 rpcrt4_protseq_sock_free_wait_array,
3400 rpcrt4_protseq_sock_wait_for_new_connection,
3401 rpcrt4_protseq_ncacn_ip_tcp_open_endpoint,
3405 const struct protseq_ops *rpcrt4_get_protseq_ops(const char *protseq)
3407 unsigned int i;
3408 for(i=0; i<ARRAYSIZE(protseq_list); i++)
3409 if (!strcmp(protseq_list[i].name, protseq))
3410 return &protseq_list[i];
3411 return NULL;
3414 static const struct connection_ops *rpcrt4_get_conn_protseq_ops(const char *protseq)
3416 unsigned int i;
3417 for(i=0; i<ARRAYSIZE(conn_protseq_list); i++)
3418 if (!strcmp(conn_protseq_list[i].name, protseq))
3419 return &conn_protseq_list[i];
3420 return NULL;
3423 /**** interface to rest of code ****/
3425 RPC_STATUS RPCRT4_OpenClientConnection(RpcConnection* Connection)
3427 TRACE("(Connection == ^%p)\n", Connection);
3429 assert(!Connection->server);
3430 return Connection->ops->open_connection_client(Connection);
3433 RPC_STATUS RPCRT4_CloseConnection(RpcConnection* Connection)
3435 TRACE("(Connection == ^%p)\n", Connection);
3436 if (SecIsValidHandle(&Connection->ctx))
3438 DeleteSecurityContext(&Connection->ctx);
3439 SecInvalidateHandle(&Connection->ctx);
3441 rpcrt4_conn_close(Connection);
3442 return RPC_S_OK;
3445 RPC_STATUS RPCRT4_CreateConnection(RpcConnection** Connection, BOOL server,
3446 LPCSTR Protseq, LPCSTR NetworkAddr, LPCSTR Endpoint,
3447 LPCWSTR NetworkOptions, RpcAuthInfo* AuthInfo, RpcQualityOfService *QOS, LPCWSTR CookieAuth)
3449 static LONG next_id;
3450 const struct connection_ops *ops;
3451 RpcConnection* NewConnection;
3453 ops = rpcrt4_get_conn_protseq_ops(Protseq);
3454 if (!ops)
3456 FIXME("not supported for protseq %s\n", Protseq);
3457 return RPC_S_PROTSEQ_NOT_SUPPORTED;
3460 NewConnection = ops->alloc();
3461 NewConnection->ref = 1;
3462 NewConnection->Next = NULL;
3463 NewConnection->server_binding = NULL;
3464 NewConnection->server = server;
3465 NewConnection->ops = ops;
3466 NewConnection->NetworkAddr = RPCRT4_strdupA(NetworkAddr);
3467 NewConnection->Endpoint = RPCRT4_strdupA(Endpoint);
3468 NewConnection->NetworkOptions = RPCRT4_strdupW(NetworkOptions);
3469 NewConnection->CookieAuth = RPCRT4_strdupW(CookieAuth);
3470 NewConnection->MaxTransmissionSize = RPC_MAX_PACKET_SIZE;
3471 memset(&NewConnection->ActiveInterface, 0, sizeof(NewConnection->ActiveInterface));
3472 NewConnection->NextCallId = 1;
3474 SecInvalidateHandle(&NewConnection->ctx);
3475 memset(&NewConnection->exp, 0, sizeof(NewConnection->exp));
3476 NewConnection->attr = 0;
3477 if (AuthInfo) RpcAuthInfo_AddRef(AuthInfo);
3478 NewConnection->AuthInfo = AuthInfo;
3479 NewConnection->auth_context_id = InterlockedIncrement( &next_id );
3480 NewConnection->encryption_auth_len = 0;
3481 NewConnection->signature_auth_len = 0;
3482 if (QOS) RpcQualityOfService_AddRef(QOS);
3483 NewConnection->QOS = QOS;
3485 list_init(&NewConnection->conn_pool_entry);
3486 NewConnection->async_state = NULL;
3488 TRACE("connection: %p\n", NewConnection);
3489 *Connection = NewConnection;
3491 return RPC_S_OK;
3494 static RPC_STATUS RPCRT4_SpawnConnection(RpcConnection** Connection, RpcConnection* OldConnection)
3496 RPC_STATUS err;
3498 err = RPCRT4_CreateConnection(Connection, OldConnection->server, rpcrt4_conn_get_name(OldConnection),
3499 OldConnection->NetworkAddr, OldConnection->Endpoint, NULL,
3500 OldConnection->AuthInfo, OldConnection->QOS, OldConnection->CookieAuth);
3501 if (err == RPC_S_OK)
3502 rpcrt4_conn_handoff(OldConnection, *Connection);
3503 return err;
3506 RpcConnection *RPCRT4_GrabConnection( RpcConnection *conn )
3508 InterlockedIncrement( &conn->ref );
3509 return conn;
3512 RPC_STATUS RPCRT4_ReleaseConnection(RpcConnection* Connection)
3514 if (InterlockedDecrement( &Connection->ref ) > 0) return RPC_S_OK;
3516 TRACE("destroying connection %p\n", Connection);
3518 RPCRT4_CloseConnection(Connection);
3519 RPCRT4_strfree(Connection->Endpoint);
3520 RPCRT4_strfree(Connection->NetworkAddr);
3521 HeapFree(GetProcessHeap(), 0, Connection->NetworkOptions);
3522 HeapFree(GetProcessHeap(), 0, Connection->CookieAuth);
3523 if (Connection->AuthInfo) RpcAuthInfo_Release(Connection->AuthInfo);
3524 if (Connection->QOS) RpcQualityOfService_Release(Connection->QOS);
3526 /* server-only */
3527 if (Connection->server_binding) RPCRT4_ReleaseBinding(Connection->server_binding);
3529 HeapFree(GetProcessHeap(), 0, Connection);
3530 return RPC_S_OK;
3533 RPC_STATUS RpcTransport_GetTopOfTower(unsigned char *tower_data,
3534 size_t *tower_size,
3535 const char *protseq,
3536 const char *networkaddr,
3537 const char *endpoint)
3539 twr_empty_floor_t *protocol_floor;
3540 const struct connection_ops *protseq_ops = rpcrt4_get_conn_protseq_ops(protseq);
3542 *tower_size = 0;
3544 if (!protseq_ops)
3545 return RPC_S_INVALID_RPC_PROTSEQ;
3547 if (!tower_data)
3549 *tower_size = sizeof(*protocol_floor);
3550 *tower_size += protseq_ops->get_top_of_tower(NULL, networkaddr, endpoint);
3551 return RPC_S_OK;
3554 protocol_floor = (twr_empty_floor_t *)tower_data;
3555 protocol_floor->count_lhs = sizeof(protocol_floor->protid);
3556 protocol_floor->protid = protseq_ops->epm_protocols[0];
3557 protocol_floor->count_rhs = 0;
3559 tower_data += sizeof(*protocol_floor);
3561 *tower_size = protseq_ops->get_top_of_tower(tower_data, networkaddr, endpoint);
3562 if (!*tower_size)
3563 return EPT_S_NOT_REGISTERED;
3565 *tower_size += sizeof(*protocol_floor);
3567 return RPC_S_OK;
3570 RPC_STATUS RpcTransport_ParseTopOfTower(const unsigned char *tower_data,
3571 size_t tower_size,
3572 char **protseq,
3573 char **networkaddr,
3574 char **endpoint)
3576 const twr_empty_floor_t *protocol_floor;
3577 const twr_empty_floor_t *floor4;
3578 const struct connection_ops *protseq_ops = NULL;
3579 RPC_STATUS status;
3580 unsigned int i;
3582 if (tower_size < sizeof(*protocol_floor))
3583 return EPT_S_NOT_REGISTERED;
3585 protocol_floor = (const twr_empty_floor_t *)tower_data;
3586 tower_data += sizeof(*protocol_floor);
3587 tower_size -= sizeof(*protocol_floor);
3588 if ((protocol_floor->count_lhs != sizeof(protocol_floor->protid)) ||
3589 (protocol_floor->count_rhs > tower_size))
3590 return EPT_S_NOT_REGISTERED;
3591 tower_data += protocol_floor->count_rhs;
3592 tower_size -= protocol_floor->count_rhs;
3594 floor4 = (const twr_empty_floor_t *)tower_data;
3595 if ((tower_size < sizeof(*floor4)) ||
3596 (floor4->count_lhs != sizeof(floor4->protid)))
3597 return EPT_S_NOT_REGISTERED;
3599 for(i = 0; i < ARRAYSIZE(conn_protseq_list); i++)
3600 if ((protocol_floor->protid == conn_protseq_list[i].epm_protocols[0]) &&
3601 (floor4->protid == conn_protseq_list[i].epm_protocols[1]))
3603 protseq_ops = &conn_protseq_list[i];
3604 break;
3607 if (!protseq_ops)
3608 return EPT_S_NOT_REGISTERED;
3610 status = protseq_ops->parse_top_of_tower(tower_data, tower_size, networkaddr, endpoint);
3612 if ((status == RPC_S_OK) && protseq)
3614 *protseq = I_RpcAllocate(strlen(protseq_ops->name) + 1);
3615 strcpy(*protseq, protseq_ops->name);
3618 return status;
3621 /***********************************************************************
3622 * RpcNetworkIsProtseqValidW (RPCRT4.@)
3624 * Checks if the given protocol sequence is known by the RPC system.
3625 * If it is, returns RPC_S_OK, otherwise RPC_S_PROTSEQ_NOT_SUPPORTED.
3628 RPC_STATUS WINAPI RpcNetworkIsProtseqValidW(RPC_WSTR protseq)
3630 char ps[0x10];
3632 WideCharToMultiByte(CP_ACP, 0, protseq, -1,
3633 ps, sizeof ps, NULL, NULL);
3634 if (rpcrt4_get_conn_protseq_ops(ps))
3635 return RPC_S_OK;
3637 FIXME("Unknown protseq %s\n", debugstr_w(protseq));
3639 return RPC_S_INVALID_RPC_PROTSEQ;
3642 /***********************************************************************
3643 * RpcNetworkIsProtseqValidA (RPCRT4.@)
3645 RPC_STATUS WINAPI RpcNetworkIsProtseqValidA(RPC_CSTR protseq)
3647 UNICODE_STRING protseqW;
3649 if (RtlCreateUnicodeStringFromAsciiz(&protseqW, (char*)protseq))
3651 RPC_STATUS ret = RpcNetworkIsProtseqValidW(protseqW.Buffer);
3652 RtlFreeUnicodeString(&protseqW);
3653 return ret;
3655 return RPC_S_OUT_OF_MEMORY;
3658 /***********************************************************************
3659 * RpcProtseqVectorFreeA (RPCRT4.@)
3661 RPC_STATUS WINAPI RpcProtseqVectorFreeA(RPC_PROTSEQ_VECTORA **protseqs)
3663 TRACE("(%p)\n", protseqs);
3665 if (*protseqs)
3667 unsigned int i;
3668 for (i = 0; i < (*protseqs)->Count; i++)
3669 HeapFree(GetProcessHeap(), 0, (*protseqs)->Protseq[i]);
3670 HeapFree(GetProcessHeap(), 0, *protseqs);
3671 *protseqs = NULL;
3673 return RPC_S_OK;
3676 /***********************************************************************
3677 * RpcProtseqVectorFreeW (RPCRT4.@)
3679 RPC_STATUS WINAPI RpcProtseqVectorFreeW(RPC_PROTSEQ_VECTORW **protseqs)
3681 TRACE("(%p)\n", protseqs);
3683 if (*protseqs)
3685 unsigned int i;
3686 for (i = 0; i < (*protseqs)->Count; i++)
3687 HeapFree(GetProcessHeap(), 0, (*protseqs)->Protseq[i]);
3688 HeapFree(GetProcessHeap(), 0, *protseqs);
3689 *protseqs = NULL;
3691 return RPC_S_OK;
3694 /***********************************************************************
3695 * RpcNetworkInqProtseqsW (RPCRT4.@)
3697 RPC_STATUS WINAPI RpcNetworkInqProtseqsW( RPC_PROTSEQ_VECTORW** protseqs )
3699 RPC_PROTSEQ_VECTORW *pvector;
3700 unsigned int i;
3701 RPC_STATUS status = RPC_S_OUT_OF_MEMORY;
3703 TRACE("(%p)\n", protseqs);
3705 *protseqs = HeapAlloc(GetProcessHeap(), 0, sizeof(RPC_PROTSEQ_VECTORW)+(sizeof(unsigned short*)*ARRAYSIZE(protseq_list)));
3706 if (!*protseqs)
3707 goto end;
3708 pvector = *protseqs;
3709 pvector->Count = 0;
3710 for (i = 0; i < ARRAYSIZE(protseq_list); i++)
3712 pvector->Protseq[i] = HeapAlloc(GetProcessHeap(), 0, (strlen(protseq_list[i].name)+1)*sizeof(unsigned short));
3713 if (pvector->Protseq[i] == NULL)
3714 goto end;
3715 MultiByteToWideChar(CP_ACP, 0, (CHAR*)protseq_list[i].name, -1,
3716 (WCHAR*)pvector->Protseq[i], strlen(protseq_list[i].name) + 1);
3717 pvector->Count++;
3719 status = RPC_S_OK;
3721 end:
3722 if (status != RPC_S_OK)
3723 RpcProtseqVectorFreeW(protseqs);
3724 return status;
3727 /***********************************************************************
3728 * RpcNetworkInqProtseqsA (RPCRT4.@)
3730 RPC_STATUS WINAPI RpcNetworkInqProtseqsA(RPC_PROTSEQ_VECTORA** protseqs)
3732 RPC_PROTSEQ_VECTORA *pvector;
3733 unsigned int i;
3734 RPC_STATUS status = RPC_S_OUT_OF_MEMORY;
3736 TRACE("(%p)\n", protseqs);
3738 *protseqs = HeapAlloc(GetProcessHeap(), 0, sizeof(RPC_PROTSEQ_VECTORW)+(sizeof(unsigned char*)*ARRAYSIZE(protseq_list)));
3739 if (!*protseqs)
3740 goto end;
3741 pvector = *protseqs;
3742 pvector->Count = 0;
3743 for (i = 0; i < ARRAYSIZE(protseq_list); i++)
3745 pvector->Protseq[i] = HeapAlloc(GetProcessHeap(), 0, strlen(protseq_list[i].name)+1);
3746 if (pvector->Protseq[i] == NULL)
3747 goto end;
3748 strcpy((char*)pvector->Protseq[i], protseq_list[i].name);
3749 pvector->Count++;
3751 status = RPC_S_OK;
3753 end:
3754 if (status != RPC_S_OK)
3755 RpcProtseqVectorFreeA(protseqs);
3756 return status;