tools: Only allow the absolute difference in bracket pairs to be less than 128, since...
[wine/multimedia.git] / dlls / rpcrt4 / rpc_transport.c
blobb28330147ec941fd0cfdb6496460ab67ca5b4004
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 return 0;
948 freeaddrinfo(ai);
950 return size;
953 static RPC_STATUS rpcrt4_ip_tcp_parse_top_of_tower(const unsigned char *tower_data,
954 size_t tower_size,
955 char **networkaddr,
956 unsigned char tcp_protid,
957 char **endpoint)
959 const twr_tcp_floor_t *tcp_floor = (const twr_tcp_floor_t *)tower_data;
960 const twr_ipv4_floor_t *ipv4_floor;
961 struct in_addr in_addr;
963 TRACE("(%p, %d, %p, %p)\n", tower_data, (int)tower_size, networkaddr, endpoint);
965 if (tower_size < sizeof(*tcp_floor))
966 return EPT_S_NOT_REGISTERED;
968 tower_data += sizeof(*tcp_floor);
969 tower_size -= sizeof(*tcp_floor);
971 if (tower_size < sizeof(*ipv4_floor))
972 return EPT_S_NOT_REGISTERED;
974 ipv4_floor = (const twr_ipv4_floor_t *)tower_data;
976 if ((tcp_floor->count_lhs != sizeof(tcp_floor->protid)) ||
977 (tcp_floor->protid != tcp_protid) ||
978 (tcp_floor->count_rhs != sizeof(tcp_floor->port)) ||
979 (ipv4_floor->count_lhs != sizeof(ipv4_floor->protid)) ||
980 (ipv4_floor->protid != EPM_PROTOCOL_IP) ||
981 (ipv4_floor->count_rhs != sizeof(ipv4_floor->ipv4addr)))
982 return EPT_S_NOT_REGISTERED;
984 if (endpoint)
986 *endpoint = I_RpcAllocate(6 /* sizeof("65535") + 1 */);
987 if (!*endpoint)
988 return RPC_S_OUT_OF_RESOURCES;
989 sprintf(*endpoint, "%u", ntohs(tcp_floor->port));
992 if (networkaddr)
994 *networkaddr = I_RpcAllocate(INET_ADDRSTRLEN);
995 if (!*networkaddr)
997 if (endpoint)
999 I_RpcFree(*endpoint);
1000 *endpoint = NULL;
1002 return RPC_S_OUT_OF_RESOURCES;
1004 in_addr.s_addr = ipv4_floor->ipv4addr;
1005 if (!inet_ntop(AF_INET, &in_addr, *networkaddr, INET_ADDRSTRLEN))
1007 ERR("inet_ntop: %s\n", strerror(errno));
1008 I_RpcFree(*networkaddr);
1009 *networkaddr = NULL;
1010 if (endpoint)
1012 I_RpcFree(*endpoint);
1013 *endpoint = NULL;
1015 return EPT_S_NOT_REGISTERED;
1019 return RPC_S_OK;
1022 typedef struct _RpcConnection_tcp
1024 RpcConnection common;
1025 int sock;
1026 #ifdef HAVE_SOCKETPAIR
1027 int cancel_fds[2];
1028 #else
1029 HANDLE sock_event;
1030 HANDLE cancel_event;
1031 #endif
1032 } RpcConnection_tcp;
1034 #ifdef HAVE_SOCKETPAIR
1036 static BOOL rpcrt4_sock_wait_init(RpcConnection_tcp *tcpc)
1038 if (socketpair(PF_UNIX, SOCK_STREAM, 0, tcpc->cancel_fds) < 0)
1040 ERR("socketpair() failed: %s\n", strerror(errno));
1041 return FALSE;
1043 return TRUE;
1046 static BOOL rpcrt4_sock_wait_for_recv(RpcConnection_tcp *tcpc)
1048 struct pollfd pfds[2];
1049 pfds[0].fd = tcpc->sock;
1050 pfds[0].events = POLLIN;
1051 pfds[1].fd = tcpc->cancel_fds[0];
1052 pfds[1].events = POLLIN;
1053 if (poll(pfds, 2, -1 /* infinite */) == -1 && errno != EINTR)
1055 ERR("poll() failed: %s\n", strerror(errno));
1056 return FALSE;
1058 if (pfds[1].revents & POLLIN) /* canceled */
1060 char dummy;
1061 read(pfds[1].fd, &dummy, sizeof(dummy));
1062 return FALSE;
1064 return TRUE;
1067 static BOOL rpcrt4_sock_wait_for_send(RpcConnection_tcp *tcpc)
1069 struct pollfd pfd;
1070 pfd.fd = tcpc->sock;
1071 pfd.events = POLLOUT;
1072 if (poll(&pfd, 1, -1 /* infinite */) == -1 && errno != EINTR)
1074 ERR("poll() failed: %s\n", strerror(errno));
1075 return FALSE;
1077 return TRUE;
1080 static void rpcrt4_sock_wait_cancel(RpcConnection_tcp *tcpc)
1082 char dummy = 1;
1084 write(tcpc->cancel_fds[1], &dummy, 1);
1087 static void rpcrt4_sock_wait_destroy(RpcConnection_tcp *tcpc)
1089 close(tcpc->cancel_fds[0]);
1090 close(tcpc->cancel_fds[1]);
1093 #else /* HAVE_SOCKETPAIR */
1095 static BOOL rpcrt4_sock_wait_init(RpcConnection_tcp *tcpc)
1097 static BOOL wsa_inited;
1098 if (!wsa_inited)
1100 WSADATA wsadata;
1101 WSAStartup(MAKEWORD(2, 2), &wsadata);
1102 /* Note: WSAStartup can be called more than once so we don't bother with
1103 * making accesses to wsa_inited thread-safe */
1104 wsa_inited = TRUE;
1106 tcpc->sock_event = CreateEventW(NULL, FALSE, FALSE, NULL);
1107 tcpc->cancel_event = CreateEventW(NULL, FALSE, FALSE, NULL);
1108 if (!tcpc->sock_event || !tcpc->cancel_event)
1110 ERR("event creation failed\n");
1111 if (tcpc->sock_event) CloseHandle(tcpc->sock_event);
1112 return FALSE;
1114 return TRUE;
1117 static BOOL rpcrt4_sock_wait_for_recv(RpcConnection_tcp *tcpc)
1119 HANDLE wait_handles[2];
1120 DWORD res;
1121 if (WSAEventSelect(tcpc->sock, tcpc->sock_event, FD_READ | FD_CLOSE) == SOCKET_ERROR)
1123 ERR("WSAEventSelect() failed with error %d\n", WSAGetLastError());
1124 return FALSE;
1126 wait_handles[0] = tcpc->sock_event;
1127 wait_handles[1] = tcpc->cancel_event;
1128 res = WaitForMultipleObjects(2, wait_handles, FALSE, INFINITE);
1129 switch (res)
1131 case WAIT_OBJECT_0:
1132 return TRUE;
1133 case WAIT_OBJECT_0 + 1:
1134 return FALSE;
1135 default:
1136 ERR("WaitForMultipleObjects() failed with error %d\n", GetLastError());
1137 return FALSE;
1141 static BOOL rpcrt4_sock_wait_for_send(RpcConnection_tcp *tcpc)
1143 DWORD res;
1144 if (WSAEventSelect(tcpc->sock, tcpc->sock_event, FD_WRITE | FD_CLOSE) == SOCKET_ERROR)
1146 ERR("WSAEventSelect() failed with error %d\n", WSAGetLastError());
1147 return FALSE;
1149 res = WaitForSingleObject(tcpc->sock_event, INFINITE);
1150 switch (res)
1152 case WAIT_OBJECT_0:
1153 return TRUE;
1154 default:
1155 ERR("WaitForMultipleObjects() failed with error %d\n", GetLastError());
1156 return FALSE;
1160 static void rpcrt4_sock_wait_cancel(RpcConnection_tcp *tcpc)
1162 SetEvent(tcpc->cancel_event);
1165 static void rpcrt4_sock_wait_destroy(RpcConnection_tcp *tcpc)
1167 CloseHandle(tcpc->sock_event);
1168 CloseHandle(tcpc->cancel_event);
1171 #endif
1173 static RpcConnection *rpcrt4_conn_tcp_alloc(void)
1175 RpcConnection_tcp *tcpc;
1176 tcpc = HeapAlloc(GetProcessHeap(), 0, sizeof(RpcConnection_tcp));
1177 if (tcpc == NULL)
1178 return NULL;
1179 tcpc->sock = -1;
1180 if (!rpcrt4_sock_wait_init(tcpc))
1182 HeapFree(GetProcessHeap(), 0, tcpc);
1183 return NULL;
1185 return &tcpc->common;
1188 static RPC_STATUS rpcrt4_ncacn_ip_tcp_open(RpcConnection* Connection)
1190 RpcConnection_tcp *tcpc = (RpcConnection_tcp *) Connection;
1191 int sock;
1192 int ret;
1193 struct addrinfo *ai;
1194 struct addrinfo *ai_cur;
1195 struct addrinfo hints;
1197 TRACE("(%s, %s)\n", Connection->NetworkAddr, Connection->Endpoint);
1199 if (tcpc->sock != -1)
1200 return RPC_S_OK;
1202 hints.ai_flags = 0;
1203 hints.ai_family = PF_UNSPEC;
1204 hints.ai_socktype = SOCK_STREAM;
1205 hints.ai_protocol = IPPROTO_TCP;
1206 hints.ai_addrlen = 0;
1207 hints.ai_addr = NULL;
1208 hints.ai_canonname = NULL;
1209 hints.ai_next = NULL;
1211 ret = getaddrinfo(Connection->NetworkAddr, Connection->Endpoint, &hints, &ai);
1212 if (ret)
1214 ERR("getaddrinfo for %s:%s failed: %s\n", Connection->NetworkAddr,
1215 Connection->Endpoint, gai_strerror(ret));
1216 return RPC_S_SERVER_UNAVAILABLE;
1219 for (ai_cur = ai; ai_cur; ai_cur = ai_cur->ai_next)
1221 int val;
1222 u_long nonblocking;
1224 if (ai_cur->ai_family != AF_INET && ai_cur->ai_family != AF_INET6)
1226 TRACE("skipping non-IP/IPv6 address family\n");
1227 continue;
1230 if (TRACE_ON(rpc))
1232 char host[256];
1233 char service[256];
1234 getnameinfo(ai_cur->ai_addr, ai_cur->ai_addrlen,
1235 host, sizeof(host), service, sizeof(service),
1236 NI_NUMERICHOST | NI_NUMERICSERV);
1237 TRACE("trying %s:%s\n", host, service);
1240 sock = socket(ai_cur->ai_family, ai_cur->ai_socktype, ai_cur->ai_protocol);
1241 if (sock == -1)
1243 WARN("socket() failed: %s\n", strerror(errno));
1244 continue;
1247 if (0>connect(sock, ai_cur->ai_addr, ai_cur->ai_addrlen))
1249 WARN("connect() failed: %s\n", strerror(errno));
1250 closesocket(sock);
1251 continue;
1254 /* RPC depends on having minimal latency so disable the Nagle algorithm */
1255 val = 1;
1256 setsockopt(sock, SOL_TCP, TCP_NODELAY, (char *)&val, sizeof(val));
1257 nonblocking = 1;
1258 ioctlsocket(sock, FIONBIO, &nonblocking);
1260 tcpc->sock = sock;
1262 freeaddrinfo(ai);
1263 TRACE("connected\n");
1264 return RPC_S_OK;
1267 freeaddrinfo(ai);
1268 ERR("couldn't connect to %s:%s\n", Connection->NetworkAddr, Connection->Endpoint);
1269 return RPC_S_SERVER_UNAVAILABLE;
1272 static RPC_STATUS rpcrt4_protseq_ncacn_ip_tcp_open_endpoint(RpcServerProtseq *protseq, const char *endpoint)
1274 RPC_STATUS status = RPC_S_CANT_CREATE_ENDPOINT;
1275 int sock;
1276 int ret;
1277 struct addrinfo *ai;
1278 struct addrinfo *ai_cur;
1279 struct addrinfo hints;
1280 RpcConnection *first_connection = NULL;
1282 TRACE("(%p, %s)\n", protseq, endpoint);
1284 hints.ai_flags = AI_PASSIVE /* for non-localhost addresses */;
1285 hints.ai_family = PF_UNSPEC;
1286 hints.ai_socktype = SOCK_STREAM;
1287 hints.ai_protocol = IPPROTO_TCP;
1288 hints.ai_addrlen = 0;
1289 hints.ai_addr = NULL;
1290 hints.ai_canonname = NULL;
1291 hints.ai_next = NULL;
1293 ret = getaddrinfo(NULL, endpoint ? endpoint : "0", &hints, &ai);
1294 if (ret)
1296 ERR("getaddrinfo for port %s failed: %s\n", endpoint,
1297 gai_strerror(ret));
1298 if ((ret == EAI_SERVICE) || (ret == EAI_NONAME))
1299 return RPC_S_INVALID_ENDPOINT_FORMAT;
1300 return RPC_S_CANT_CREATE_ENDPOINT;
1303 for (ai_cur = ai; ai_cur; ai_cur = ai_cur->ai_next)
1305 RpcConnection_tcp *tcpc;
1306 RPC_STATUS create_status;
1307 struct sockaddr_storage sa;
1308 socklen_t sa_len;
1309 char service[NI_MAXSERV];
1310 u_long nonblocking;
1312 if (ai_cur->ai_family != AF_INET && ai_cur->ai_family != AF_INET6)
1314 TRACE("skipping non-IP/IPv6 address family\n");
1315 continue;
1318 if (TRACE_ON(rpc))
1320 char host[256];
1321 getnameinfo(ai_cur->ai_addr, ai_cur->ai_addrlen,
1322 host, sizeof(host), service, sizeof(service),
1323 NI_NUMERICHOST | NI_NUMERICSERV);
1324 TRACE("trying %s:%s\n", host, service);
1327 sock = socket(ai_cur->ai_family, ai_cur->ai_socktype, ai_cur->ai_protocol);
1328 if (sock == -1)
1330 WARN("socket() failed: %s\n", strerror(errno));
1331 status = RPC_S_CANT_CREATE_ENDPOINT;
1332 continue;
1335 ret = bind(sock, ai_cur->ai_addr, ai_cur->ai_addrlen);
1336 if (ret < 0)
1338 WARN("bind failed: %s\n", strerror(errno));
1339 closesocket(sock);
1340 if (errno == EADDRINUSE)
1341 status = RPC_S_DUPLICATE_ENDPOINT;
1342 else
1343 status = RPC_S_CANT_CREATE_ENDPOINT;
1344 continue;
1347 sa_len = sizeof(sa);
1348 if (getsockname(sock, (struct sockaddr *)&sa, &sa_len))
1350 WARN("getsockname() failed: %s\n", strerror(errno));
1351 closesocket(sock);
1352 status = RPC_S_CANT_CREATE_ENDPOINT;
1353 continue;
1356 ret = getnameinfo((struct sockaddr *)&sa, sa_len,
1357 NULL, 0, service, sizeof(service),
1358 NI_NUMERICSERV);
1359 if (ret)
1361 WARN("getnameinfo failed: %s\n", gai_strerror(ret));
1362 closesocket(sock);
1363 status = RPC_S_CANT_CREATE_ENDPOINT;
1364 continue;
1367 create_status = RPCRT4_CreateConnection((RpcConnection **)&tcpc, TRUE,
1368 protseq->Protseq, NULL,
1369 service, NULL, NULL, NULL, NULL);
1370 if (create_status != RPC_S_OK)
1372 closesocket(sock);
1373 status = create_status;
1374 continue;
1377 tcpc->sock = sock;
1378 ret = listen(sock, protseq->MaxCalls);
1379 if (ret < 0)
1381 WARN("listen failed: %s\n", strerror(errno));
1382 RPCRT4_ReleaseConnection(&tcpc->common);
1383 status = RPC_S_OUT_OF_RESOURCES;
1384 continue;
1386 /* need a non-blocking socket, otherwise accept() has a potential
1387 * race-condition (poll() says it is readable, connection drops,
1388 * and accept() blocks until the next connection comes...)
1390 nonblocking = 1;
1391 ret = ioctlsocket(sock, FIONBIO, &nonblocking);
1392 if (ret < 0)
1394 WARN("couldn't make socket non-blocking, error %d\n", ret);
1395 RPCRT4_ReleaseConnection(&tcpc->common);
1396 status = RPC_S_OUT_OF_RESOURCES;
1397 continue;
1400 tcpc->common.Next = first_connection;
1401 first_connection = &tcpc->common;
1403 /* since IPv4 and IPv6 share the same port space, we only need one
1404 * successful bind to listen for both */
1405 break;
1408 freeaddrinfo(ai);
1410 /* if at least one connection was created for an endpoint then
1411 * return success */
1412 if (first_connection)
1414 RpcConnection *conn;
1416 /* find last element in list */
1417 for (conn = first_connection; conn->Next; conn = conn->Next)
1420 EnterCriticalSection(&protseq->cs);
1421 conn->Next = protseq->conn;
1422 protseq->conn = first_connection;
1423 LeaveCriticalSection(&protseq->cs);
1425 TRACE("listening on %s\n", endpoint);
1426 return RPC_S_OK;
1429 ERR("couldn't listen on port %s\n", endpoint);
1430 return status;
1433 static RPC_STATUS rpcrt4_conn_tcp_handoff(RpcConnection *old_conn, RpcConnection *new_conn)
1435 int ret;
1436 struct sockaddr_in address;
1437 socklen_t addrsize;
1438 RpcConnection_tcp *server = (RpcConnection_tcp*) old_conn;
1439 RpcConnection_tcp *client = (RpcConnection_tcp*) new_conn;
1440 u_long nonblocking;
1442 addrsize = sizeof(address);
1443 ret = accept(server->sock, (struct sockaddr*) &address, &addrsize);
1444 if (ret < 0)
1446 ERR("Failed to accept a TCP connection: error %d\n", ret);
1447 return RPC_S_OUT_OF_RESOURCES;
1449 nonblocking = 1;
1450 ioctlsocket(ret, FIONBIO, &nonblocking);
1451 client->sock = ret;
1452 TRACE("Accepted a new TCP connection\n");
1453 return RPC_S_OK;
1456 static int rpcrt4_conn_tcp_read(RpcConnection *Connection,
1457 void *buffer, unsigned int count)
1459 RpcConnection_tcp *tcpc = (RpcConnection_tcp *) Connection;
1460 int bytes_read = 0;
1461 while (bytes_read != count)
1463 int r = recv(tcpc->sock, (char *)buffer + bytes_read, count - bytes_read, 0);
1464 if (!r)
1465 return -1;
1466 else if (r > 0)
1467 bytes_read += r;
1468 else if (errno == EINTR)
1469 continue;
1470 else if (errno != EAGAIN)
1472 WARN("recv() failed: %s\n", strerror(errno));
1473 return -1;
1475 else
1477 if (!rpcrt4_sock_wait_for_recv(tcpc))
1478 return -1;
1481 TRACE("%d %p %u -> %d\n", tcpc->sock, buffer, count, bytes_read);
1482 return bytes_read;
1485 static int rpcrt4_conn_tcp_write(RpcConnection *Connection,
1486 const void *buffer, unsigned int count)
1488 RpcConnection_tcp *tcpc = (RpcConnection_tcp *) Connection;
1489 int bytes_written = 0;
1490 while (bytes_written != count)
1492 int r = send(tcpc->sock, (const char *)buffer + bytes_written, count - bytes_written, 0);
1493 if (r >= 0)
1494 bytes_written += r;
1495 else if (errno == EINTR)
1496 continue;
1497 else if (errno != EAGAIN)
1498 return -1;
1499 else
1501 if (!rpcrt4_sock_wait_for_send(tcpc))
1502 return -1;
1505 TRACE("%d %p %u -> %d\n", tcpc->sock, buffer, count, bytes_written);
1506 return bytes_written;
1509 static int rpcrt4_conn_tcp_close(RpcConnection *Connection)
1511 RpcConnection_tcp *tcpc = (RpcConnection_tcp *) Connection;
1513 TRACE("%d\n", tcpc->sock);
1515 if (tcpc->sock != -1)
1516 closesocket(tcpc->sock);
1517 tcpc->sock = -1;
1518 rpcrt4_sock_wait_destroy(tcpc);
1519 return 0;
1522 static void rpcrt4_conn_tcp_cancel_call(RpcConnection *Connection)
1524 RpcConnection_tcp *tcpc = (RpcConnection_tcp *) Connection;
1525 TRACE("%p\n", Connection);
1526 rpcrt4_sock_wait_cancel(tcpc);
1529 static int rpcrt4_conn_tcp_wait_for_incoming_data(RpcConnection *Connection)
1531 RpcConnection_tcp *tcpc = (RpcConnection_tcp *) Connection;
1533 TRACE("%p\n", Connection);
1535 if (!rpcrt4_sock_wait_for_recv(tcpc))
1536 return -1;
1537 return 0;
1540 static size_t rpcrt4_ncacn_ip_tcp_get_top_of_tower(unsigned char *tower_data,
1541 const char *networkaddr,
1542 const char *endpoint)
1544 return rpcrt4_ip_tcp_get_top_of_tower(tower_data, networkaddr,
1545 EPM_PROTOCOL_TCP, endpoint);
1548 #ifdef HAVE_SOCKETPAIR
1550 typedef struct _RpcServerProtseq_sock
1552 RpcServerProtseq common;
1553 int mgr_event_rcv;
1554 int mgr_event_snd;
1555 } RpcServerProtseq_sock;
1557 static RpcServerProtseq *rpcrt4_protseq_sock_alloc(void)
1559 RpcServerProtseq_sock *ps = HeapAlloc(GetProcessHeap(), 0, sizeof(*ps));
1560 if (ps)
1562 int fds[2];
1563 if (!socketpair(PF_UNIX, SOCK_DGRAM, 0, fds))
1565 fcntl(fds[0], F_SETFL, O_NONBLOCK);
1566 fcntl(fds[1], F_SETFL, O_NONBLOCK);
1567 ps->mgr_event_rcv = fds[0];
1568 ps->mgr_event_snd = fds[1];
1570 else
1572 ERR("socketpair failed with error %s\n", strerror(errno));
1573 HeapFree(GetProcessHeap(), 0, ps);
1574 return NULL;
1577 return &ps->common;
1580 static void rpcrt4_protseq_sock_signal_state_changed(RpcServerProtseq *protseq)
1582 RpcServerProtseq_sock *sockps = CONTAINING_RECORD(protseq, RpcServerProtseq_sock, common);
1583 char dummy = 1;
1584 write(sockps->mgr_event_snd, &dummy, sizeof(dummy));
1587 static void *rpcrt4_protseq_sock_get_wait_array(RpcServerProtseq *protseq, void *prev_array, unsigned int *count)
1589 struct pollfd *poll_info = prev_array;
1590 RpcConnection_tcp *conn;
1591 RpcServerProtseq_sock *sockps = CONTAINING_RECORD(protseq, RpcServerProtseq_sock, common);
1593 EnterCriticalSection(&protseq->cs);
1595 /* open and count connections */
1596 *count = 1;
1597 conn = (RpcConnection_tcp *)protseq->conn;
1598 while (conn) {
1599 if (conn->sock != -1)
1600 (*count)++;
1601 conn = (RpcConnection_tcp *)conn->common.Next;
1604 /* make array of connections */
1605 if (poll_info)
1606 poll_info = HeapReAlloc(GetProcessHeap(), 0, poll_info, *count*sizeof(*poll_info));
1607 else
1608 poll_info = HeapAlloc(GetProcessHeap(), 0, *count*sizeof(*poll_info));
1609 if (!poll_info)
1611 ERR("couldn't allocate poll_info\n");
1612 LeaveCriticalSection(&protseq->cs);
1613 return NULL;
1616 poll_info[0].fd = sockps->mgr_event_rcv;
1617 poll_info[0].events = POLLIN;
1618 *count = 1;
1619 conn = CONTAINING_RECORD(protseq->conn, RpcConnection_tcp, common);
1620 while (conn) {
1621 if (conn->sock != -1)
1623 poll_info[*count].fd = conn->sock;
1624 poll_info[*count].events = POLLIN;
1625 (*count)++;
1627 conn = CONTAINING_RECORD(conn->common.Next, RpcConnection_tcp, common);
1629 LeaveCriticalSection(&protseq->cs);
1630 return poll_info;
1633 static void rpcrt4_protseq_sock_free_wait_array(RpcServerProtseq *protseq, void *array)
1635 HeapFree(GetProcessHeap(), 0, array);
1638 static int rpcrt4_protseq_sock_wait_for_new_connection(RpcServerProtseq *protseq, unsigned int count, void *wait_array)
1640 struct pollfd *poll_info = wait_array;
1641 int ret;
1642 unsigned int i;
1643 RpcConnection *cconn;
1644 RpcConnection_tcp *conn;
1646 if (!poll_info)
1647 return -1;
1649 ret = poll(poll_info, count, -1);
1650 if (ret < 0)
1652 ERR("poll failed with error %d\n", ret);
1653 return -1;
1656 for (i = 0; i < count; i++)
1657 if (poll_info[i].revents & POLLIN)
1659 /* RPC server event */
1660 if (i == 0)
1662 char dummy;
1663 read(poll_info[0].fd, &dummy, sizeof(dummy));
1664 return 0;
1667 /* find which connection got a RPC */
1668 EnterCriticalSection(&protseq->cs);
1669 conn = CONTAINING_RECORD(protseq->conn, RpcConnection_tcp, common);
1670 while (conn) {
1671 if (poll_info[i].fd == conn->sock) break;
1672 conn = CONTAINING_RECORD(conn->common.Next, RpcConnection_tcp, common);
1674 cconn = NULL;
1675 if (conn)
1676 RPCRT4_SpawnConnection(&cconn, &conn->common);
1677 else
1678 ERR("failed to locate connection for fd %d\n", poll_info[i].fd);
1679 LeaveCriticalSection(&protseq->cs);
1680 if (cconn)
1681 RPCRT4_new_client(cconn);
1682 else
1683 return -1;
1686 return 1;
1689 #else /* HAVE_SOCKETPAIR */
1691 typedef struct _RpcServerProtseq_sock
1693 RpcServerProtseq common;
1694 HANDLE mgr_event;
1695 } RpcServerProtseq_sock;
1697 static RpcServerProtseq *rpcrt4_protseq_sock_alloc(void)
1699 RpcServerProtseq_sock *ps = HeapAlloc(GetProcessHeap(), 0, sizeof(*ps));
1700 if (ps)
1702 static BOOL wsa_inited;
1703 if (!wsa_inited)
1705 WSADATA wsadata;
1706 WSAStartup(MAKEWORD(2, 2), &wsadata);
1707 /* Note: WSAStartup can be called more than once so we don't bother with
1708 * making accesses to wsa_inited thread-safe */
1709 wsa_inited = TRUE;
1711 ps->mgr_event = CreateEventW(NULL, FALSE, FALSE, NULL);
1713 return &ps->common;
1716 static void rpcrt4_protseq_sock_signal_state_changed(RpcServerProtseq *protseq)
1718 RpcServerProtseq_sock *sockps = CONTAINING_RECORD(protseq, RpcServerProtseq_sock, common);
1719 SetEvent(sockps->mgr_event);
1722 static void *rpcrt4_protseq_sock_get_wait_array(RpcServerProtseq *protseq, void *prev_array, unsigned int *count)
1724 HANDLE *objs = prev_array;
1725 RpcConnection_tcp *conn;
1726 RpcServerProtseq_sock *sockps = CONTAINING_RECORD(protseq, RpcServerProtseq_sock, common);
1728 EnterCriticalSection(&protseq->cs);
1730 /* open and count connections */
1731 *count = 1;
1732 conn = CONTAINING_RECORD(protseq->conn, RpcConnection_tcp, common);
1733 while (conn)
1735 if (conn->sock != -1)
1736 (*count)++;
1737 conn = CONTAINING_RECORD(conn->common.Next, RpcConnection_tcp, common);
1740 /* make array of connections */
1741 if (objs)
1742 objs = HeapReAlloc(GetProcessHeap(), 0, objs, *count*sizeof(HANDLE));
1743 else
1744 objs = HeapAlloc(GetProcessHeap(), 0, *count*sizeof(HANDLE));
1745 if (!objs)
1747 ERR("couldn't allocate objs\n");
1748 LeaveCriticalSection(&protseq->cs);
1749 return NULL;
1752 objs[0] = sockps->mgr_event;
1753 *count = 1;
1754 conn = CONTAINING_RECORD(protseq->conn, RpcConnection_tcp, common);
1755 while (conn)
1757 if (conn->sock != -1)
1759 int res = WSAEventSelect(conn->sock, conn->sock_event, FD_ACCEPT);
1760 if (res == SOCKET_ERROR)
1761 ERR("WSAEventSelect() failed with error %d\n", WSAGetLastError());
1762 else
1764 objs[*count] = conn->sock_event;
1765 (*count)++;
1768 conn = CONTAINING_RECORD(conn->common.Next, RpcConnection_tcp, common);
1770 LeaveCriticalSection(&protseq->cs);
1771 return objs;
1774 static void rpcrt4_protseq_sock_free_wait_array(RpcServerProtseq *protseq, void *array)
1776 HeapFree(GetProcessHeap(), 0, array);
1779 static int rpcrt4_protseq_sock_wait_for_new_connection(RpcServerProtseq *protseq, unsigned int count, void *wait_array)
1781 HANDLE b_handle;
1782 HANDLE *objs = wait_array;
1783 DWORD res;
1784 RpcConnection *cconn;
1785 RpcConnection_tcp *conn;
1787 if (!objs)
1788 return -1;
1792 /* an alertable wait isn't strictly necessary, but due to our
1793 * overlapped I/O implementation in Wine we need to free some memory
1794 * by the file user APC being called, even if no completion routine was
1795 * specified at the time of starting the async operation */
1796 res = WaitForMultipleObjectsEx(count, objs, FALSE, INFINITE, TRUE);
1797 } while (res == WAIT_IO_COMPLETION);
1799 if (res == WAIT_OBJECT_0)
1800 return 0;
1801 else if (res == WAIT_FAILED)
1803 ERR("wait failed with error %d\n", GetLastError());
1804 return -1;
1806 else
1808 b_handle = objs[res - WAIT_OBJECT_0];
1809 /* find which connection got a RPC */
1810 EnterCriticalSection(&protseq->cs);
1811 conn = CONTAINING_RECORD(protseq->conn, RpcConnection_tcp, common);
1812 while (conn)
1814 if (b_handle == conn->sock_event) break;
1815 conn = CONTAINING_RECORD(conn->common.Next, RpcConnection_tcp, common);
1817 cconn = NULL;
1818 if (conn)
1819 RPCRT4_SpawnConnection(&cconn, &conn->common);
1820 else
1821 ERR("failed to locate connection for handle %p\n", b_handle);
1822 LeaveCriticalSection(&protseq->cs);
1823 if (cconn)
1825 RPCRT4_new_client(cconn);
1826 return 1;
1828 else return -1;
1832 #endif /* HAVE_SOCKETPAIR */
1834 static RPC_STATUS rpcrt4_ncacn_ip_tcp_parse_top_of_tower(const unsigned char *tower_data,
1835 size_t tower_size,
1836 char **networkaddr,
1837 char **endpoint)
1839 return rpcrt4_ip_tcp_parse_top_of_tower(tower_data, tower_size,
1840 networkaddr, EPM_PROTOCOL_TCP,
1841 endpoint);
1844 /**** ncacn_http support ****/
1846 /* 60 seconds is the period native uses */
1847 #define HTTP_IDLE_TIME 60000
1849 /* reference counted to avoid a race between a cancelled call's connection
1850 * being destroyed and the asynchronous InternetReadFileEx call being
1851 * completed */
1852 typedef struct _RpcHttpAsyncData
1854 LONG refs;
1855 HANDLE completion_event;
1856 WORD async_result;
1857 INTERNET_BUFFERSA inet_buffers;
1858 CRITICAL_SECTION cs;
1859 } RpcHttpAsyncData;
1861 static ULONG RpcHttpAsyncData_AddRef(RpcHttpAsyncData *data)
1863 return InterlockedIncrement(&data->refs);
1866 static ULONG RpcHttpAsyncData_Release(RpcHttpAsyncData *data)
1868 ULONG refs = InterlockedDecrement(&data->refs);
1869 if (!refs)
1871 TRACE("destroying async data %p\n", data);
1872 CloseHandle(data->completion_event);
1873 HeapFree(GetProcessHeap(), 0, data->inet_buffers.lpvBuffer);
1874 data->cs.DebugInfo->Spare[0] = 0;
1875 DeleteCriticalSection(&data->cs);
1876 HeapFree(GetProcessHeap(), 0, data);
1878 return refs;
1881 static void prepare_async_request(RpcHttpAsyncData *async_data)
1883 ResetEvent(async_data->completion_event);
1884 RpcHttpAsyncData_AddRef(async_data);
1887 static RPC_STATUS wait_async_request(RpcHttpAsyncData *async_data, BOOL call_ret, HANDLE cancel_event)
1889 HANDLE handles[2] = { async_data->completion_event, cancel_event };
1890 DWORD res;
1892 if(call_ret) {
1893 RpcHttpAsyncData_Release(async_data);
1894 return RPC_S_OK;
1897 if(GetLastError() != ERROR_IO_PENDING) {
1898 RpcHttpAsyncData_Release(async_data);
1899 ERR("Request failed with error %d\n", GetLastError());
1900 return RPC_S_SERVER_UNAVAILABLE;
1903 res = WaitForMultipleObjects(2, handles, FALSE, DEFAULT_NCACN_HTTP_TIMEOUT);
1904 if(res != WAIT_OBJECT_0) {
1905 TRACE("Cancelled\n");
1906 return RPC_S_CALL_CANCELLED;
1909 if(async_data->async_result) {
1910 ERR("Async request failed with error %d\n", async_data->async_result);
1911 return RPC_S_SERVER_UNAVAILABLE;
1914 return RPC_S_OK;
1917 struct authinfo
1919 DWORD scheme;
1920 CredHandle cred;
1921 CtxtHandle ctx;
1922 TimeStamp exp;
1923 ULONG attr;
1924 ULONG max_token;
1925 char *data;
1926 unsigned int data_len;
1927 BOOL finished; /* finished authenticating */
1930 typedef struct _RpcConnection_http
1932 RpcConnection common;
1933 HINTERNET app_info;
1934 HINTERNET session;
1935 HINTERNET in_request;
1936 HINTERNET out_request;
1937 WCHAR *servername;
1938 HANDLE timer_cancelled;
1939 HANDLE cancel_event;
1940 DWORD last_sent_time;
1941 ULONG bytes_received;
1942 ULONG flow_control_mark; /* send a control packet to the server when this many bytes received */
1943 ULONG flow_control_increment; /* number of bytes to increment flow_control_mark by */
1944 UUID connection_uuid;
1945 UUID in_pipe_uuid;
1946 UUID out_pipe_uuid;
1947 RpcHttpAsyncData *async_data;
1948 } RpcConnection_http;
1950 static RpcConnection *rpcrt4_ncacn_http_alloc(void)
1952 RpcConnection_http *httpc;
1953 httpc = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*httpc));
1954 if (!httpc) return NULL;
1955 httpc->async_data = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(RpcHttpAsyncData));
1956 if (!httpc->async_data)
1958 HeapFree(GetProcessHeap(), 0, httpc);
1959 return NULL;
1961 TRACE("async data = %p\n", httpc->async_data);
1962 httpc->cancel_event = CreateEventW(NULL, FALSE, FALSE, NULL);
1963 httpc->async_data->refs = 1;
1964 httpc->async_data->inet_buffers.dwStructSize = sizeof(INTERNET_BUFFERSA);
1965 httpc->async_data->inet_buffers.lpvBuffer = NULL;
1966 InitializeCriticalSection(&httpc->async_data->cs);
1967 httpc->async_data->cs.DebugInfo->Spare[0] = (DWORD_PTR)(__FILE__ ": RpcHttpAsyncData.cs");
1968 return &httpc->common;
1971 typedef struct _HttpTimerThreadData
1973 PVOID timer_param;
1974 DWORD *last_sent_time;
1975 HANDLE timer_cancelled;
1976 } HttpTimerThreadData;
1978 static VOID rpcrt4_http_keep_connection_active_timer_proc(PVOID param, BOOLEAN dummy)
1980 HINTERNET in_request = param;
1981 RpcPktHdr *idle_pkt;
1983 idle_pkt = RPCRT4_BuildHttpHeader(NDR_LOCAL_DATA_REPRESENTATION, 0x0001,
1984 0, 0);
1985 if (idle_pkt)
1987 DWORD bytes_written;
1988 InternetWriteFile(in_request, idle_pkt, idle_pkt->common.frag_len, &bytes_written);
1989 RPCRT4_FreeHeader(idle_pkt);
1993 static inline DWORD rpcrt4_http_timer_calc_timeout(DWORD *last_sent_time)
1995 DWORD cur_time = GetTickCount();
1996 DWORD cached_last_sent_time = *last_sent_time;
1997 return HTTP_IDLE_TIME - (cur_time - cached_last_sent_time > HTTP_IDLE_TIME ? 0 : cur_time - cached_last_sent_time);
2000 static DWORD CALLBACK rpcrt4_http_timer_thread(PVOID param)
2002 HttpTimerThreadData *data_in = param;
2003 HttpTimerThreadData data;
2004 DWORD timeout;
2006 data = *data_in;
2007 HeapFree(GetProcessHeap(), 0, data_in);
2009 for (timeout = HTTP_IDLE_TIME;
2010 WaitForSingleObject(data.timer_cancelled, timeout) == WAIT_TIMEOUT;
2011 timeout = rpcrt4_http_timer_calc_timeout(data.last_sent_time))
2013 /* are we too soon after last send? */
2014 if (GetTickCount() - *data.last_sent_time < HTTP_IDLE_TIME)
2015 continue;
2016 rpcrt4_http_keep_connection_active_timer_proc(data.timer_param, TRUE);
2019 CloseHandle(data.timer_cancelled);
2020 return 0;
2023 static VOID WINAPI rpcrt4_http_internet_callback(
2024 HINTERNET hInternet,
2025 DWORD_PTR dwContext,
2026 DWORD dwInternetStatus,
2027 LPVOID lpvStatusInformation,
2028 DWORD dwStatusInformationLength)
2030 RpcHttpAsyncData *async_data = (RpcHttpAsyncData *)dwContext;
2032 switch (dwInternetStatus)
2034 case INTERNET_STATUS_REQUEST_COMPLETE:
2035 TRACE("INTERNET_STATUS_REQUEST_COMPLETED\n");
2036 if (async_data)
2038 INTERNET_ASYNC_RESULT *async_result = lpvStatusInformation;
2040 async_data->async_result = async_result->dwResult ? ERROR_SUCCESS : async_result->dwError;
2041 SetEvent(async_data->completion_event);
2042 RpcHttpAsyncData_Release(async_data);
2044 break;
2048 static RPC_STATUS rpcrt4_http_check_response(HINTERNET hor)
2050 BOOL ret;
2051 DWORD status_code;
2052 DWORD size;
2053 DWORD index;
2054 WCHAR buf[32];
2055 WCHAR *status_text = buf;
2056 TRACE("\n");
2058 index = 0;
2059 size = sizeof(status_code);
2060 ret = HttpQueryInfoW(hor, HTTP_QUERY_STATUS_CODE|HTTP_QUERY_FLAG_NUMBER, &status_code, &size, &index);
2061 if (!ret)
2062 return GetLastError();
2063 if (status_code == HTTP_STATUS_OK)
2064 return RPC_S_OK;
2065 index = 0;
2066 size = sizeof(buf);
2067 ret = HttpQueryInfoW(hor, HTTP_QUERY_STATUS_TEXT, status_text, &size, &index);
2068 if (!ret && GetLastError() == ERROR_INSUFFICIENT_BUFFER)
2070 status_text = HeapAlloc(GetProcessHeap(), 0, size);
2071 ret = HttpQueryInfoW(hor, HTTP_QUERY_STATUS_TEXT, status_text, &size, &index);
2074 ERR("server returned: %d %s\n", status_code, ret ? debugstr_w(status_text) : "<status text unavailable>");
2075 if(status_text != buf) HeapFree(GetProcessHeap(), 0, status_text);
2077 if (status_code == HTTP_STATUS_DENIED)
2078 return ERROR_ACCESS_DENIED;
2079 return RPC_S_SERVER_UNAVAILABLE;
2082 static RPC_STATUS rpcrt4_http_internet_connect(RpcConnection_http *httpc)
2084 static const WCHAR wszUserAgent[] = {'M','S','R','P','C',0};
2085 LPWSTR proxy = NULL;
2086 LPWSTR user = NULL;
2087 LPWSTR password = NULL;
2088 LPWSTR servername = NULL;
2089 const WCHAR *option;
2090 INTERNET_PORT port;
2092 if (httpc->common.QOS &&
2093 (httpc->common.QOS->qos->AdditionalSecurityInfoType == RPC_C_AUTHN_INFO_TYPE_HTTP))
2095 const RPC_HTTP_TRANSPORT_CREDENTIALS_W *http_cred = httpc->common.QOS->qos->u.HttpCredentials;
2096 if (http_cred->TransportCredentials)
2098 WCHAR *p;
2099 const SEC_WINNT_AUTH_IDENTITY_W *cred = http_cred->TransportCredentials;
2100 ULONG len = cred->DomainLength + 1 + cred->UserLength;
2101 user = HeapAlloc(GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR));
2102 if (!user)
2103 return RPC_S_OUT_OF_RESOURCES;
2104 p = user;
2105 if (cred->DomainLength)
2107 memcpy(p, cred->Domain, cred->DomainLength * sizeof(WCHAR));
2108 p += cred->DomainLength;
2109 *p = '\\';
2110 p++;
2112 memcpy(p, cred->User, cred->UserLength * sizeof(WCHAR));
2113 p[cred->UserLength] = 0;
2115 password = RPCRT4_strndupW(cred->Password, cred->PasswordLength);
2119 for (option = httpc->common.NetworkOptions; option;
2120 option = (strchrW(option, ',') ? strchrW(option, ',')+1 : NULL))
2122 static const WCHAR wszRpcProxy[] = {'R','p','c','P','r','o','x','y','=',0};
2123 static const WCHAR wszHttpProxy[] = {'H','t','t','p','P','r','o','x','y','=',0};
2125 if (!strncmpiW(option, wszRpcProxy, sizeof(wszRpcProxy)/sizeof(wszRpcProxy[0])-1))
2127 const WCHAR *value_start = option + sizeof(wszRpcProxy)/sizeof(wszRpcProxy[0])-1;
2128 const WCHAR *value_end;
2129 const WCHAR *p;
2131 value_end = strchrW(option, ',');
2132 if (!value_end)
2133 value_end = value_start + strlenW(value_start);
2134 for (p = value_start; p < value_end; p++)
2135 if (*p == ':')
2137 port = atoiW(p+1);
2138 value_end = p;
2139 break;
2141 TRACE("RpcProxy value is %s\n", debugstr_wn(value_start, value_end-value_start));
2142 servername = RPCRT4_strndupW(value_start, value_end-value_start);
2144 else if (!strncmpiW(option, wszHttpProxy, sizeof(wszHttpProxy)/sizeof(wszHttpProxy[0])-1))
2146 const WCHAR *value_start = option + sizeof(wszHttpProxy)/sizeof(wszHttpProxy[0])-1;
2147 const WCHAR *value_end;
2149 value_end = strchrW(option, ',');
2150 if (!value_end)
2151 value_end = value_start + strlenW(value_start);
2152 TRACE("HttpProxy value is %s\n", debugstr_wn(value_start, value_end-value_start));
2153 proxy = RPCRT4_strndupW(value_start, value_end-value_start);
2155 else
2156 FIXME("unhandled option %s\n", debugstr_w(option));
2159 httpc->app_info = InternetOpenW(wszUserAgent, proxy ? INTERNET_OPEN_TYPE_PROXY : INTERNET_OPEN_TYPE_PRECONFIG,
2160 NULL, NULL, INTERNET_FLAG_ASYNC);
2161 if (!httpc->app_info)
2163 HeapFree(GetProcessHeap(), 0, password);
2164 HeapFree(GetProcessHeap(), 0, user);
2165 HeapFree(GetProcessHeap(), 0, proxy);
2166 HeapFree(GetProcessHeap(), 0, servername);
2167 ERR("InternetOpenW failed with error %d\n", GetLastError());
2168 return RPC_S_SERVER_UNAVAILABLE;
2170 InternetSetStatusCallbackW(httpc->app_info, rpcrt4_http_internet_callback);
2172 /* if no RpcProxy option specified, set the HTTP server address to the
2173 * RPC server address */
2174 if (!servername)
2176 servername = HeapAlloc(GetProcessHeap(), 0, (strlen(httpc->common.NetworkAddr) + 1)*sizeof(WCHAR));
2177 if (!servername)
2179 HeapFree(GetProcessHeap(), 0, password);
2180 HeapFree(GetProcessHeap(), 0, user);
2181 HeapFree(GetProcessHeap(), 0, proxy);
2182 return RPC_S_OUT_OF_RESOURCES;
2184 MultiByteToWideChar(CP_ACP, 0, httpc->common.NetworkAddr, -1, servername, strlen(httpc->common.NetworkAddr) + 1);
2187 port = (httpc->common.QOS &&
2188 (httpc->common.QOS->qos->AdditionalSecurityInfoType == RPC_C_AUTHN_INFO_TYPE_HTTP) &&
2189 (httpc->common.QOS->qos->u.HttpCredentials->Flags & RPC_C_HTTP_FLAG_USE_SSL)) ?
2190 INTERNET_DEFAULT_HTTPS_PORT : INTERNET_DEFAULT_HTTP_PORT;
2192 httpc->session = InternetConnectW(httpc->app_info, servername, port, user, password,
2193 INTERNET_SERVICE_HTTP, 0, 0);
2195 HeapFree(GetProcessHeap(), 0, password);
2196 HeapFree(GetProcessHeap(), 0, user);
2197 HeapFree(GetProcessHeap(), 0, proxy);
2199 if (!httpc->session)
2201 ERR("InternetConnectW failed with error %d\n", GetLastError());
2202 HeapFree(GetProcessHeap(), 0, servername);
2203 return RPC_S_SERVER_UNAVAILABLE;
2205 httpc->servername = servername;
2206 return RPC_S_OK;
2209 static RPC_STATUS send_echo_request(HINTERNET req, RpcHttpAsyncData *async_data, HANDLE cancel_event)
2211 DWORD bytes_read;
2212 BYTE buf[20];
2213 BOOL ret;
2214 RPC_STATUS status;
2216 TRACE("sending echo request to server\n");
2218 prepare_async_request(async_data);
2219 ret = HttpSendRequestW(req, NULL, 0, NULL, 0);
2220 status = wait_async_request(async_data, ret, cancel_event);
2221 if (status != RPC_S_OK) return status;
2223 status = rpcrt4_http_check_response(req);
2224 if (status != RPC_S_OK) return status;
2226 InternetReadFile(req, buf, sizeof(buf), &bytes_read);
2227 /* FIXME: do something with retrieved data */
2229 return RPC_S_OK;
2232 /* prepare the in pipe for use by RPC packets */
2233 static RPC_STATUS rpcrt4_http_prepare_in_pipe(HINTERNET in_request, RpcHttpAsyncData *async_data, HANDLE cancel_event,
2234 const UUID *connection_uuid, const UUID *in_pipe_uuid,
2235 const UUID *association_uuid, BOOL authorized)
2237 BOOL ret;
2238 RPC_STATUS status;
2239 RpcPktHdr *hdr;
2240 INTERNET_BUFFERSW buffers_in;
2241 DWORD bytes_written;
2243 if (!authorized)
2245 /* ask wininet to authorize, if necessary */
2246 status = send_echo_request(in_request, async_data, cancel_event);
2247 if (status != RPC_S_OK) return status;
2249 memset(&buffers_in, 0, sizeof(buffers_in));
2250 buffers_in.dwStructSize = sizeof(buffers_in);
2251 /* FIXME: get this from the registry */
2252 buffers_in.dwBufferTotal = 1024 * 1024 * 1024; /* 1Gb */
2253 prepare_async_request(async_data);
2254 ret = HttpSendRequestExW(in_request, &buffers_in, NULL, 0, 0);
2255 status = wait_async_request(async_data, ret, cancel_event);
2256 if (status != RPC_S_OK) return status;
2258 TRACE("sending HTTP connect header to server\n");
2259 hdr = RPCRT4_BuildHttpConnectHeader(FALSE, connection_uuid, in_pipe_uuid, association_uuid);
2260 if (!hdr) return RPC_S_OUT_OF_RESOURCES;
2261 ret = InternetWriteFile(in_request, hdr, hdr->common.frag_len, &bytes_written);
2262 RPCRT4_FreeHeader(hdr);
2263 if (!ret)
2265 ERR("InternetWriteFile failed with error %d\n", GetLastError());
2266 return RPC_S_SERVER_UNAVAILABLE;
2269 return RPC_S_OK;
2272 static RPC_STATUS rpcrt4_http_read_http_packet(HINTERNET request, RpcPktHdr *hdr, BYTE **data)
2274 BOOL ret;
2275 DWORD bytes_read;
2276 unsigned short data_len;
2278 ret = InternetReadFile(request, hdr, sizeof(hdr->common), &bytes_read);
2279 if (!ret)
2280 return RPC_S_SERVER_UNAVAILABLE;
2281 if (hdr->common.ptype != PKT_HTTP || hdr->common.frag_len < sizeof(hdr->http))
2283 ERR("wrong packet type received %d or wrong frag_len %d\n",
2284 hdr->common.ptype, hdr->common.frag_len);
2285 return RPC_S_PROTOCOL_ERROR;
2288 ret = InternetReadFile(request, &hdr->common + 1, sizeof(hdr->http) - sizeof(hdr->common), &bytes_read);
2289 if (!ret)
2290 return RPC_S_SERVER_UNAVAILABLE;
2292 data_len = hdr->common.frag_len - sizeof(hdr->http);
2293 if (data_len)
2295 *data = HeapAlloc(GetProcessHeap(), 0, data_len);
2296 if (!*data)
2297 return RPC_S_OUT_OF_RESOURCES;
2298 ret = InternetReadFile(request, *data, data_len, &bytes_read);
2299 if (!ret)
2301 HeapFree(GetProcessHeap(), 0, *data);
2302 return RPC_S_SERVER_UNAVAILABLE;
2305 else
2306 *data = NULL;
2308 if (!RPCRT4_IsValidHttpPacket(hdr, *data, data_len))
2310 ERR("invalid http packet\n");
2311 return RPC_S_PROTOCOL_ERROR;
2314 return RPC_S_OK;
2317 /* prepare the out pipe for use by RPC packets */
2318 static RPC_STATUS rpcrt4_http_prepare_out_pipe(HINTERNET out_request, RpcHttpAsyncData *async_data,
2319 HANDLE cancel_event, const UUID *connection_uuid,
2320 const UUID *out_pipe_uuid, ULONG *flow_control_increment,
2321 BOOL authorized)
2323 BOOL ret;
2324 RPC_STATUS status;
2325 RpcPktHdr *hdr;
2326 BYTE *data_from_server;
2327 RpcPktHdr pkt_from_server;
2328 ULONG field1, field3;
2329 DWORD bytes_read;
2330 BYTE buf[20];
2332 if (!authorized)
2334 /* ask wininet to authorize, if necessary */
2335 status = send_echo_request(out_request, async_data, cancel_event);
2336 if (status != RPC_S_OK) return status;
2338 else
2339 InternetReadFile(out_request, buf, sizeof(buf), &bytes_read);
2341 hdr = RPCRT4_BuildHttpConnectHeader(TRUE, connection_uuid, out_pipe_uuid, NULL);
2342 if (!hdr) return RPC_S_OUT_OF_RESOURCES;
2344 TRACE("sending HTTP connect header to server\n");
2345 prepare_async_request(async_data);
2346 ret = HttpSendRequestW(out_request, NULL, 0, hdr, hdr->common.frag_len);
2347 status = wait_async_request(async_data, ret, cancel_event);
2348 RPCRT4_FreeHeader(hdr);
2349 if (status != RPC_S_OK) return status;
2351 status = rpcrt4_http_check_response(out_request);
2352 if (status != RPC_S_OK) return status;
2354 status = rpcrt4_http_read_http_packet(out_request, &pkt_from_server,
2355 &data_from_server);
2356 if (status != RPC_S_OK) return status;
2357 status = RPCRT4_ParseHttpPrepareHeader1(&pkt_from_server, data_from_server,
2358 &field1);
2359 HeapFree(GetProcessHeap(), 0, data_from_server);
2360 if (status != RPC_S_OK) return status;
2361 TRACE("received (%d) from first prepare header\n", field1);
2363 for (;;)
2365 status = rpcrt4_http_read_http_packet(out_request, &pkt_from_server,
2366 &data_from_server);
2367 if (status != RPC_S_OK) return status;
2368 if (pkt_from_server.http.flags != 0x0001) break;
2370 TRACE("http idle packet, waiting for real packet\n");
2371 HeapFree(GetProcessHeap(), 0, data_from_server);
2372 if (pkt_from_server.http.num_data_items != 0)
2374 ERR("HTTP idle packet should have no data items instead of %d\n",
2375 pkt_from_server.http.num_data_items);
2376 return RPC_S_PROTOCOL_ERROR;
2379 status = RPCRT4_ParseHttpPrepareHeader2(&pkt_from_server, data_from_server,
2380 &field1, flow_control_increment,
2381 &field3);
2382 HeapFree(GetProcessHeap(), 0, data_from_server);
2383 if (status != RPC_S_OK) return status;
2384 TRACE("received (0x%08x 0x%08x %d) from second prepare header\n", field1, *flow_control_increment, field3);
2386 return RPC_S_OK;
2389 static UINT encode_base64(const char *bin, unsigned int len, WCHAR *base64)
2391 static const char enc[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
2392 UINT i = 0, x;
2394 while (len > 0)
2396 /* first 6 bits, all from bin[0] */
2397 base64[i++] = enc[(bin[0] & 0xfc) >> 2];
2398 x = (bin[0] & 3) << 4;
2400 /* next 6 bits, 2 from bin[0] and 4 from bin[1] */
2401 if (len == 1)
2403 base64[i++] = enc[x];
2404 base64[i++] = '=';
2405 base64[i++] = '=';
2406 break;
2408 base64[i++] = enc[x | ((bin[1] & 0xf0) >> 4)];
2409 x = (bin[1] & 0x0f) << 2;
2411 /* next 6 bits 4 from bin[1] and 2 from bin[2] */
2412 if (len == 2)
2414 base64[i++] = enc[x];
2415 base64[i++] = '=';
2416 break;
2418 base64[i++] = enc[x | ((bin[2] & 0xc0) >> 6)];
2420 /* last 6 bits, all from bin [2] */
2421 base64[i++] = enc[bin[2] & 0x3f];
2422 bin += 3;
2423 len -= 3;
2425 base64[i] = 0;
2426 return i;
2429 static inline char decode_char( WCHAR c )
2431 if (c >= 'A' && c <= 'Z') return c - 'A';
2432 if (c >= 'a' && c <= 'z') return c - 'a' + 26;
2433 if (c >= '0' && c <= '9') return c - '0' + 52;
2434 if (c == '+') return 62;
2435 if (c == '/') return 63;
2436 return 64;
2439 static unsigned int decode_base64( const WCHAR *base64, unsigned int len, char *buf )
2441 unsigned int i = 0;
2442 char c0, c1, c2, c3;
2443 const WCHAR *p = base64;
2445 while (len > 4)
2447 if ((c0 = decode_char( p[0] )) > 63) return 0;
2448 if ((c1 = decode_char( p[1] )) > 63) return 0;
2449 if ((c2 = decode_char( p[2] )) > 63) return 0;
2450 if ((c3 = decode_char( p[3] )) > 63) return 0;
2452 if (buf)
2454 buf[i + 0] = (c0 << 2) | (c1 >> 4);
2455 buf[i + 1] = (c1 << 4) | (c2 >> 2);
2456 buf[i + 2] = (c2 << 6) | c3;
2458 len -= 4;
2459 i += 3;
2460 p += 4;
2462 if (p[2] == '=')
2464 if ((c0 = decode_char( p[0] )) > 63) return 0;
2465 if ((c1 = decode_char( p[1] )) > 63) return 0;
2467 if (buf) buf[i] = (c0 << 2) | (c1 >> 4);
2468 i++;
2470 else if (p[3] == '=')
2472 if ((c0 = decode_char( p[0] )) > 63) return 0;
2473 if ((c1 = decode_char( p[1] )) > 63) return 0;
2474 if ((c2 = decode_char( p[2] )) > 63) return 0;
2476 if (buf)
2478 buf[i + 0] = (c0 << 2) | (c1 >> 4);
2479 buf[i + 1] = (c1 << 4) | (c2 >> 2);
2481 i += 2;
2483 else
2485 if ((c0 = decode_char( p[0] )) > 63) return 0;
2486 if ((c1 = decode_char( p[1] )) > 63) return 0;
2487 if ((c2 = decode_char( p[2] )) > 63) return 0;
2488 if ((c3 = decode_char( p[3] )) > 63) return 0;
2490 if (buf)
2492 buf[i + 0] = (c0 << 2) | (c1 >> 4);
2493 buf[i + 1] = (c1 << 4) | (c2 >> 2);
2494 buf[i + 2] = (c2 << 6) | c3;
2496 i += 3;
2498 return i;
2501 static struct authinfo *alloc_authinfo(void)
2503 struct authinfo *ret;
2505 if (!(ret = HeapAlloc(GetProcessHeap(), 0, sizeof(*ret) ))) return NULL;
2507 SecInvalidateHandle(&ret->cred);
2508 SecInvalidateHandle(&ret->ctx);
2509 memset(&ret->exp, 0, sizeof(ret->exp));
2510 ret->scheme = 0;
2511 ret->attr = 0;
2512 ret->max_token = 0;
2513 ret->data = NULL;
2514 ret->data_len = 0;
2515 ret->finished = FALSE;
2516 return ret;
2519 static void destroy_authinfo(struct authinfo *info)
2521 if (!info) return;
2523 if (SecIsValidHandle(&info->ctx))
2524 DeleteSecurityContext(&info->ctx);
2525 if (SecIsValidHandle(&info->cred))
2526 FreeCredentialsHandle(&info->cred);
2528 HeapFree(GetProcessHeap(), 0, info->data);
2529 HeapFree(GetProcessHeap(), 0, info);
2532 static const WCHAR basicW[] = {'B','a','s','i','c',0};
2533 static const WCHAR ntlmW[] = {'N','T','L','M',0};
2534 static const WCHAR passportW[] = {'P','a','s','s','p','o','r','t',0};
2535 static const WCHAR digestW[] = {'D','i','g','e','s','t',0};
2536 static const WCHAR negotiateW[] = {'N','e','g','o','t','i','a','t','e',0};
2538 static const struct
2540 const WCHAR *str;
2541 unsigned int len;
2542 DWORD scheme;
2544 auth_schemes[] =
2546 { basicW, ARRAYSIZE(basicW) - 1, RPC_C_HTTP_AUTHN_SCHEME_BASIC },
2547 { ntlmW, ARRAYSIZE(ntlmW) - 1, RPC_C_HTTP_AUTHN_SCHEME_NTLM },
2548 { passportW, ARRAYSIZE(passportW) - 1, RPC_C_HTTP_AUTHN_SCHEME_PASSPORT },
2549 { digestW, ARRAYSIZE(digestW) - 1, RPC_C_HTTP_AUTHN_SCHEME_DIGEST },
2550 { negotiateW, ARRAYSIZE(negotiateW) - 1, RPC_C_HTTP_AUTHN_SCHEME_NEGOTIATE }
2552 static const unsigned int num_auth_schemes = sizeof(auth_schemes)/sizeof(auth_schemes[0]);
2554 static DWORD auth_scheme_from_header( const WCHAR *header )
2556 unsigned int i;
2557 for (i = 0; i < num_auth_schemes; i++)
2559 if (!strncmpiW( header, auth_schemes[i].str, auth_schemes[i].len ) &&
2560 (header[auth_schemes[i].len] == ' ' || !header[auth_schemes[i].len])) return auth_schemes[i].scheme;
2562 return 0;
2565 static BOOL get_authvalue(HINTERNET request, DWORD scheme, WCHAR *buffer, DWORD buflen)
2567 DWORD len, index = 0;
2568 for (;;)
2570 len = buflen;
2571 if (!HttpQueryInfoW(request, HTTP_QUERY_WWW_AUTHENTICATE, buffer, &len, &index)) return FALSE;
2572 if (auth_scheme_from_header(buffer) == scheme) break;
2574 return TRUE;
2577 static RPC_STATUS do_authorization(HINTERNET request, SEC_WCHAR *servername,
2578 const RPC_HTTP_TRANSPORT_CREDENTIALS_W *creds, struct authinfo **auth_ptr)
2580 struct authinfo *info = *auth_ptr;
2581 SEC_WINNT_AUTH_IDENTITY_W *id = creds->TransportCredentials;
2582 RPC_STATUS status = RPC_S_SERVER_UNAVAILABLE;
2584 if ((!info && !(info = alloc_authinfo()))) return RPC_S_SERVER_UNAVAILABLE;
2586 switch (creds->AuthnSchemes[0])
2588 case RPC_C_HTTP_AUTHN_SCHEME_BASIC:
2590 int userlen = WideCharToMultiByte(CP_UTF8, 0, id->User, id->UserLength, NULL, 0, NULL, NULL);
2591 int passlen = WideCharToMultiByte(CP_UTF8, 0, id->Password, id->PasswordLength, NULL, 0, NULL, NULL);
2593 info->data_len = userlen + passlen + 1;
2594 if (!(info->data = HeapAlloc(GetProcessHeap(), 0, info->data_len)))
2596 status = RPC_S_OUT_OF_MEMORY;
2597 break;
2599 WideCharToMultiByte(CP_UTF8, 0, id->User, id->UserLength, info->data, userlen, NULL, NULL);
2600 info->data[userlen] = ':';
2601 WideCharToMultiByte(CP_UTF8, 0, id->Password, id->PasswordLength, info->data + userlen + 1, passlen, NULL, NULL);
2603 info->scheme = RPC_C_HTTP_AUTHN_SCHEME_BASIC;
2604 info->finished = TRUE;
2605 status = RPC_S_OK;
2606 break;
2608 case RPC_C_HTTP_AUTHN_SCHEME_NTLM:
2609 case RPC_C_HTTP_AUTHN_SCHEME_NEGOTIATE:
2612 static SEC_WCHAR ntlmW[] = {'N','T','L','M',0}, negotiateW[] = {'N','e','g','o','t','i','a','t','e',0};
2613 SECURITY_STATUS ret;
2614 SecBufferDesc out_desc, in_desc;
2615 SecBuffer out, in;
2616 ULONG flags = ISC_REQ_CONNECTION|ISC_REQ_USE_DCE_STYLE|ISC_REQ_MUTUAL_AUTH|ISC_REQ_DELEGATE;
2617 SEC_WCHAR *scheme;
2618 int scheme_len;
2619 const WCHAR *p;
2620 WCHAR auth_value[2048];
2621 DWORD size = sizeof(auth_value);
2622 BOOL first = FALSE;
2624 if (creds->AuthnSchemes[0] == RPC_C_HTTP_AUTHN_SCHEME_NTLM) scheme = ntlmW;
2625 else scheme = negotiateW;
2626 scheme_len = strlenW( scheme );
2628 if (!*auth_ptr)
2630 TimeStamp exp;
2631 SecPkgInfoW *pkg_info;
2633 ret = AcquireCredentialsHandleW(NULL, scheme, SECPKG_CRED_OUTBOUND, NULL, id, NULL, NULL, &info->cred, &exp);
2634 if (ret != SEC_E_OK) break;
2636 ret = QuerySecurityPackageInfoW(scheme, &pkg_info);
2637 if (ret != SEC_E_OK) break;
2639 info->max_token = pkg_info->cbMaxToken;
2640 FreeContextBuffer(pkg_info);
2641 first = TRUE;
2643 else
2645 if (info->finished || !get_authvalue(request, creds->AuthnSchemes[0], auth_value, size)) break;
2646 if (auth_scheme_from_header(auth_value) != info->scheme)
2648 ERR("authentication scheme changed\n");
2649 break;
2652 in.BufferType = SECBUFFER_TOKEN;
2653 in.cbBuffer = 0;
2654 in.pvBuffer = NULL;
2656 in_desc.ulVersion = 0;
2657 in_desc.cBuffers = 1;
2658 in_desc.pBuffers = &in;
2660 p = auth_value + scheme_len;
2661 if (!first && *p == ' ')
2663 int len = strlenW(++p);
2664 in.cbBuffer = decode_base64(p, len, NULL);
2665 if (!(in.pvBuffer = HeapAlloc(GetProcessHeap(), 0, in.cbBuffer))) break;
2666 decode_base64(p, len, in.pvBuffer);
2668 out.BufferType = SECBUFFER_TOKEN;
2669 out.cbBuffer = info->max_token;
2670 if (!(out.pvBuffer = HeapAlloc(GetProcessHeap(), 0, out.cbBuffer)))
2672 HeapFree(GetProcessHeap(), 0, in.pvBuffer);
2673 break;
2675 out_desc.ulVersion = 0;
2676 out_desc.cBuffers = 1;
2677 out_desc.pBuffers = &out;
2679 ret = InitializeSecurityContextW(first ? &info->cred : NULL, first ? NULL : &info->ctx,
2680 first ? servername : NULL, flags, 0, SECURITY_NETWORK_DREP,
2681 in.pvBuffer ? &in_desc : NULL, 0, &info->ctx, &out_desc,
2682 &info->attr, &info->exp);
2683 HeapFree(GetProcessHeap(), 0, in.pvBuffer);
2684 if (ret == SEC_E_OK)
2686 HeapFree(GetProcessHeap(), 0, info->data);
2687 info->data = out.pvBuffer;
2688 info->data_len = out.cbBuffer;
2689 info->finished = TRUE;
2690 TRACE("sending last auth packet\n");
2691 status = RPC_S_OK;
2693 else if (ret == SEC_I_CONTINUE_NEEDED)
2695 HeapFree(GetProcessHeap(), 0, info->data);
2696 info->data = out.pvBuffer;
2697 info->data_len = out.cbBuffer;
2698 TRACE("sending next auth packet\n");
2699 status = RPC_S_OK;
2701 else
2703 ERR("InitializeSecurityContextW failed with error 0x%08x\n", ret);
2704 HeapFree(GetProcessHeap(), 0, out.pvBuffer);
2705 break;
2707 info->scheme = creds->AuthnSchemes[0];
2708 break;
2710 default:
2711 FIXME("scheme %u not supported\n", creds->AuthnSchemes[0]);
2712 break;
2715 if (status != RPC_S_OK)
2717 destroy_authinfo(info);
2718 *auth_ptr = NULL;
2719 return status;
2721 *auth_ptr = info;
2722 return RPC_S_OK;
2725 static RPC_STATUS insert_authorization_header(HINTERNET request, ULONG scheme, char *data, int data_len)
2727 static const WCHAR authW[] = {'A','u','t','h','o','r','i','z','a','t','i','o','n',':',' '};
2728 static const WCHAR basicW[] = {'B','a','s','i','c',' '};
2729 static const WCHAR negotiateW[] = {'N','e','g','o','t','i','a','t','e',' '};
2730 static const WCHAR ntlmW[] = {'N','T','L','M',' '};
2731 int scheme_len, auth_len = sizeof(authW) / sizeof(authW[0]), len = ((data_len + 2) * 4) / 3;
2732 const WCHAR *scheme_str;
2733 WCHAR *header, *ptr;
2734 RPC_STATUS status = RPC_S_SERVER_UNAVAILABLE;
2736 switch (scheme)
2738 case RPC_C_HTTP_AUTHN_SCHEME_BASIC:
2739 scheme_str = basicW;
2740 scheme_len = sizeof(basicW) / sizeof(basicW[0]);
2741 break;
2742 case RPC_C_HTTP_AUTHN_SCHEME_NEGOTIATE:
2743 scheme_str = negotiateW;
2744 scheme_len = sizeof(negotiateW) / sizeof(negotiateW[0]);
2745 break;
2746 case RPC_C_HTTP_AUTHN_SCHEME_NTLM:
2747 scheme_str = ntlmW;
2748 scheme_len = sizeof(ntlmW) / sizeof(ntlmW[0]);
2749 break;
2750 default:
2751 ERR("unknown scheme %u\n", scheme);
2752 return RPC_S_SERVER_UNAVAILABLE;
2754 if ((header = HeapAlloc(GetProcessHeap(), 0, (auth_len + scheme_len + len + 2) * sizeof(WCHAR))))
2756 memcpy(header, authW, auth_len * sizeof(WCHAR));
2757 ptr = header + auth_len;
2758 memcpy(ptr, scheme_str, scheme_len * sizeof(WCHAR));
2759 ptr += scheme_len;
2760 len = encode_base64(data, data_len, ptr);
2761 ptr[len++] = '\r';
2762 ptr[len++] = '\n';
2763 ptr[len] = 0;
2764 if (HttpAddRequestHeadersW(request, header, -1, HTTP_ADDREQ_FLAG_ADD|HTTP_ADDREQ_FLAG_REPLACE))
2765 status = RPC_S_OK;
2766 HeapFree(GetProcessHeap(), 0, header);
2768 return status;
2771 static void drain_content(HINTERNET request)
2773 DWORD count, len = 0, size = sizeof(len);
2774 char buf[2048];
2776 HttpQueryInfoW(request, HTTP_QUERY_FLAG_NUMBER|HTTP_QUERY_CONTENT_LENGTH, &len, &size, NULL);
2777 if (!len) return;
2778 for (;;)
2780 count = min(sizeof(buf), len);
2781 if (!InternetReadFile(request, buf, count, &count) || !count) return;
2782 len -= count;
2786 static RPC_STATUS authorize_request(RpcConnection_http *httpc, HINTERNET request)
2788 static const WCHAR authW[] = {'A','u','t','h','o','r','i','z','a','t','i','o','n',':','\r','\n',0};
2789 struct authinfo *info = NULL;
2790 RPC_STATUS status;
2791 BOOL ret;
2793 for (;;)
2795 status = do_authorization(request, httpc->servername, httpc->common.QOS->qos->u.HttpCredentials, &info);
2796 if (status != RPC_S_OK) break;
2798 status = insert_authorization_header(request, info->scheme, info->data, info->data_len);
2799 if (status != RPC_S_OK) break;
2801 prepare_async_request(httpc->async_data);
2802 ret = HttpSendRequestW(request, NULL, 0, NULL, 0);
2803 status = wait_async_request(httpc->async_data, ret, httpc->cancel_event);
2804 if (status != RPC_S_OK || info->finished) break;
2806 status = rpcrt4_http_check_response(request);
2807 if (status != RPC_S_OK && status != ERROR_ACCESS_DENIED) break;
2808 drain_content(request);
2811 if (info->scheme != RPC_C_HTTP_AUTHN_SCHEME_BASIC)
2812 HttpAddRequestHeadersW(request, authW, -1, HTTP_ADDREQ_FLAG_REPLACE);
2814 destroy_authinfo(info);
2815 return status;
2818 static RPC_STATUS insert_cookie_header(HINTERNET request, const WCHAR *value)
2820 static const WCHAR cookieW[] = {'C','o','o','k','i','e',':',' '};
2821 WCHAR *header, *ptr;
2822 int len;
2823 RPC_STATUS status = RPC_S_SERVER_UNAVAILABLE;
2825 if (!value) return RPC_S_OK;
2827 len = strlenW(value);
2828 if ((header = HeapAlloc(GetProcessHeap(), 0, sizeof(cookieW) + (len + 3) * sizeof(WCHAR))))
2830 memcpy(header, cookieW, sizeof(cookieW));
2831 ptr = header + sizeof(cookieW) / sizeof(cookieW[0]);
2832 memcpy(ptr, value, len * sizeof(WCHAR));
2833 ptr[len++] = '\r';
2834 ptr[len++] = '\n';
2835 ptr[len] = 0;
2836 if ((HttpAddRequestHeadersW(request, header, -1, HTTP_ADDREQ_FLAG_ADD_IF_NEW))) status = RPC_S_OK;
2837 HeapFree(GetProcessHeap(), 0, header);
2839 return status;
2842 static BOOL has_credentials(RpcConnection_http *httpc)
2844 RPC_HTTP_TRANSPORT_CREDENTIALS_W *creds;
2845 SEC_WINNT_AUTH_IDENTITY_W *id;
2847 if (!httpc->common.QOS || httpc->common.QOS->qos->AdditionalSecurityInfoType != RPC_C_AUTHN_INFO_TYPE_HTTP)
2848 return FALSE;
2850 creds = httpc->common.QOS->qos->u.HttpCredentials;
2851 if (creds->AuthenticationTarget != RPC_C_HTTP_AUTHN_TARGET_SERVER || !creds->NumberOfAuthnSchemes)
2852 return FALSE;
2854 id = creds->TransportCredentials;
2855 if (!id || !id->User || !id->Password) return FALSE;
2857 return TRUE;
2860 static BOOL is_secure(RpcConnection_http *httpc)
2862 return httpc->common.QOS &&
2863 (httpc->common.QOS->qos->AdditionalSecurityInfoType == RPC_C_AUTHN_INFO_TYPE_HTTP) &&
2864 (httpc->common.QOS->qos->u.HttpCredentials->Flags & RPC_C_HTTP_FLAG_USE_SSL);
2867 static RPC_STATUS rpcrt4_ncacn_http_open(RpcConnection* Connection)
2869 RpcConnection_http *httpc = (RpcConnection_http *)Connection;
2870 static const WCHAR wszVerbIn[] = {'R','P','C','_','I','N','_','D','A','T','A',0};
2871 static const WCHAR wszVerbOut[] = {'R','P','C','_','O','U','T','_','D','A','T','A',0};
2872 static const WCHAR wszRpcProxyPrefix[] = {'/','r','p','c','/','r','p','c','p','r','o','x','y','.','d','l','l','?',0};
2873 static const WCHAR wszColon[] = {':',0};
2874 static const WCHAR wszAcceptType[] = {'a','p','p','l','i','c','a','t','i','o','n','/','r','p','c',0};
2875 LPCWSTR wszAcceptTypes[] = { wszAcceptType, NULL };
2876 DWORD flags;
2877 WCHAR *url;
2878 RPC_STATUS status;
2879 BOOL secure, credentials;
2880 HttpTimerThreadData *timer_data;
2881 HANDLE thread;
2883 TRACE("(%s, %s)\n", Connection->NetworkAddr, Connection->Endpoint);
2885 if (Connection->server)
2887 ERR("ncacn_http servers not supported yet\n");
2888 return RPC_S_SERVER_UNAVAILABLE;
2891 if (httpc->in_request)
2892 return RPC_S_OK;
2894 httpc->async_data->completion_event = CreateEventW(NULL, FALSE, FALSE, NULL);
2896 status = UuidCreate(&httpc->connection_uuid);
2897 status = UuidCreate(&httpc->in_pipe_uuid);
2898 status = UuidCreate(&httpc->out_pipe_uuid);
2900 status = rpcrt4_http_internet_connect(httpc);
2901 if (status != RPC_S_OK)
2902 return status;
2904 url = HeapAlloc(GetProcessHeap(), 0, sizeof(wszRpcProxyPrefix) + (strlen(Connection->NetworkAddr) + 1 + strlen(Connection->Endpoint))*sizeof(WCHAR));
2905 if (!url)
2906 return RPC_S_OUT_OF_MEMORY;
2907 memcpy(url, wszRpcProxyPrefix, sizeof(wszRpcProxyPrefix));
2908 MultiByteToWideChar(CP_ACP, 0, Connection->NetworkAddr, -1, url+sizeof(wszRpcProxyPrefix)/sizeof(wszRpcProxyPrefix[0])-1, strlen(Connection->NetworkAddr)+1);
2909 strcatW(url, wszColon);
2910 MultiByteToWideChar(CP_ACP, 0, Connection->Endpoint, -1, url+strlenW(url), strlen(Connection->Endpoint)+1);
2912 secure = is_secure(httpc);
2913 credentials = has_credentials(httpc);
2915 flags = INTERNET_FLAG_KEEP_CONNECTION | INTERNET_FLAG_PRAGMA_NOCACHE | INTERNET_FLAG_NO_CACHE_WRITE |
2916 INTERNET_FLAG_NO_AUTO_REDIRECT;
2917 if (secure) flags |= INTERNET_FLAG_SECURE;
2918 if (credentials) flags |= INTERNET_FLAG_NO_AUTH;
2920 httpc->in_request = HttpOpenRequestW(httpc->session, wszVerbIn, url, NULL, NULL, wszAcceptTypes,
2921 flags, (DWORD_PTR)httpc->async_data);
2922 if (!httpc->in_request)
2924 ERR("HttpOpenRequestW failed with error %d\n", GetLastError());
2925 HeapFree(GetProcessHeap(), 0, url);
2926 return RPC_S_SERVER_UNAVAILABLE;
2928 status = insert_cookie_header(httpc->in_request, Connection->CookieAuth);
2929 if (status != RPC_S_OK)
2931 HeapFree(GetProcessHeap(), 0, url);
2932 return status;
2934 if (credentials)
2936 status = authorize_request(httpc, httpc->in_request);
2937 if (status != RPC_S_OK)
2939 HeapFree(GetProcessHeap(), 0, url);
2940 return status;
2942 status = rpcrt4_http_check_response(httpc->in_request);
2943 if (status != RPC_S_OK)
2945 HeapFree(GetProcessHeap(), 0, url);
2946 return status;
2948 drain_content(httpc->in_request);
2951 httpc->out_request = HttpOpenRequestW(httpc->session, wszVerbOut, url, NULL, NULL, wszAcceptTypes,
2952 flags, (DWORD_PTR)httpc->async_data);
2953 HeapFree(GetProcessHeap(), 0, url);
2954 if (!httpc->out_request)
2956 ERR("HttpOpenRequestW failed with error %d\n", GetLastError());
2957 return RPC_S_SERVER_UNAVAILABLE;
2959 status = insert_cookie_header(httpc->out_request, Connection->CookieAuth);
2960 if (status != RPC_S_OK)
2961 return status;
2963 if (credentials)
2965 status = authorize_request(httpc, httpc->out_request);
2966 if (status != RPC_S_OK)
2967 return status;
2970 status = rpcrt4_http_prepare_in_pipe(httpc->in_request, httpc->async_data, httpc->cancel_event,
2971 &httpc->connection_uuid, &httpc->in_pipe_uuid,
2972 &Connection->assoc->http_uuid, credentials);
2973 if (status != RPC_S_OK)
2974 return status;
2976 status = rpcrt4_http_prepare_out_pipe(httpc->out_request, httpc->async_data, httpc->cancel_event,
2977 &httpc->connection_uuid, &httpc->out_pipe_uuid,
2978 &httpc->flow_control_increment, credentials);
2979 if (status != RPC_S_OK)
2980 return status;
2982 httpc->flow_control_mark = httpc->flow_control_increment / 2;
2983 httpc->last_sent_time = GetTickCount();
2984 httpc->timer_cancelled = CreateEventW(NULL, FALSE, FALSE, NULL);
2986 timer_data = HeapAlloc(GetProcessHeap(), 0, sizeof(*timer_data));
2987 if (!timer_data)
2988 return ERROR_OUTOFMEMORY;
2989 timer_data->timer_param = httpc->in_request;
2990 timer_data->last_sent_time = &httpc->last_sent_time;
2991 timer_data->timer_cancelled = httpc->timer_cancelled;
2992 /* FIXME: should use CreateTimerQueueTimer when implemented */
2993 thread = CreateThread(NULL, 0, rpcrt4_http_timer_thread, timer_data, 0, NULL);
2994 if (!thread)
2996 HeapFree(GetProcessHeap(), 0, timer_data);
2997 return GetLastError();
2999 CloseHandle(thread);
3001 return RPC_S_OK;
3004 static RPC_STATUS rpcrt4_ncacn_http_handoff(RpcConnection *old_conn, RpcConnection *new_conn)
3006 assert(0);
3007 return RPC_S_SERVER_UNAVAILABLE;
3010 static int rpcrt4_ncacn_http_read(RpcConnection *Connection,
3011 void *buffer, unsigned int count)
3013 RpcConnection_http *httpc = (RpcConnection_http *) Connection;
3014 char *buf = buffer;
3015 BOOL ret;
3016 unsigned int bytes_left = count;
3017 RPC_STATUS status = RPC_S_OK;
3019 httpc->async_data->inet_buffers.lpvBuffer = HeapAlloc(GetProcessHeap(), 0, count);
3021 while (bytes_left)
3023 httpc->async_data->inet_buffers.dwBufferLength = bytes_left;
3024 prepare_async_request(httpc->async_data);
3025 ret = InternetReadFileExA(httpc->out_request, &httpc->async_data->inet_buffers, IRF_ASYNC, 0);
3026 status = wait_async_request(httpc->async_data, ret, httpc->cancel_event);
3027 if(status != RPC_S_OK) {
3028 if(status == RPC_S_CALL_CANCELLED)
3029 TRACE("call cancelled\n");
3030 break;
3033 if(!httpc->async_data->inet_buffers.dwBufferLength)
3034 break;
3035 memcpy(buf, httpc->async_data->inet_buffers.lpvBuffer,
3036 httpc->async_data->inet_buffers.dwBufferLength);
3038 bytes_left -= httpc->async_data->inet_buffers.dwBufferLength;
3039 buf += httpc->async_data->inet_buffers.dwBufferLength;
3042 HeapFree(GetProcessHeap(), 0, httpc->async_data->inet_buffers.lpvBuffer);
3043 httpc->async_data->inet_buffers.lpvBuffer = NULL;
3045 TRACE("%p %p %u -> %u\n", httpc->out_request, buffer, count, status);
3046 return status == RPC_S_OK ? count : -1;
3049 static RPC_STATUS rpcrt4_ncacn_http_receive_fragment(RpcConnection *Connection, RpcPktHdr **Header, void **Payload)
3051 RpcConnection_http *httpc = (RpcConnection_http *) Connection;
3052 RPC_STATUS status;
3053 DWORD hdr_length;
3054 LONG dwRead;
3055 RpcPktCommonHdr common_hdr;
3057 *Header = NULL;
3059 TRACE("(%p, %p, %p)\n", Connection, Header, Payload);
3061 again:
3062 /* read packet common header */
3063 dwRead = rpcrt4_ncacn_http_read(Connection, &common_hdr, sizeof(common_hdr));
3064 if (dwRead != sizeof(common_hdr)) {
3065 WARN("Short read of header, %d bytes\n", dwRead);
3066 status = RPC_S_PROTOCOL_ERROR;
3067 goto fail;
3069 if (!memcmp(&common_hdr, "HTTP/1.1", sizeof("HTTP/1.1")) ||
3070 !memcmp(&common_hdr, "HTTP/1.0", sizeof("HTTP/1.0")))
3072 FIXME("server returned %s\n", debugstr_a((const char *)&common_hdr));
3073 status = RPC_S_PROTOCOL_ERROR;
3074 goto fail;
3077 status = RPCRT4_ValidateCommonHeader(&common_hdr);
3078 if (status != RPC_S_OK) goto fail;
3080 hdr_length = RPCRT4_GetHeaderSize((RpcPktHdr*)&common_hdr);
3081 if (hdr_length == 0) {
3082 WARN("header length == 0\n");
3083 status = RPC_S_PROTOCOL_ERROR;
3084 goto fail;
3087 *Header = HeapAlloc(GetProcessHeap(), 0, hdr_length);
3088 if (!*Header)
3090 status = RPC_S_OUT_OF_RESOURCES;
3091 goto fail;
3093 memcpy(*Header, &common_hdr, sizeof(common_hdr));
3095 /* read the rest of packet header */
3096 dwRead = rpcrt4_ncacn_http_read(Connection, &(*Header)->common + 1, hdr_length - sizeof(common_hdr));
3097 if (dwRead != hdr_length - sizeof(common_hdr)) {
3098 WARN("bad header length, %d bytes, hdr_length %d\n", dwRead, hdr_length);
3099 status = RPC_S_PROTOCOL_ERROR;
3100 goto fail;
3103 if (common_hdr.frag_len - hdr_length)
3105 *Payload = HeapAlloc(GetProcessHeap(), 0, common_hdr.frag_len - hdr_length);
3106 if (!*Payload)
3108 status = RPC_S_OUT_OF_RESOURCES;
3109 goto fail;
3112 dwRead = rpcrt4_ncacn_http_read(Connection, *Payload, common_hdr.frag_len - hdr_length);
3113 if (dwRead != common_hdr.frag_len - hdr_length)
3115 WARN("bad data length, %d/%d\n", dwRead, common_hdr.frag_len - hdr_length);
3116 status = RPC_S_PROTOCOL_ERROR;
3117 goto fail;
3120 else
3121 *Payload = NULL;
3123 if ((*Header)->common.ptype == PKT_HTTP)
3125 if (!RPCRT4_IsValidHttpPacket(*Header, *Payload, common_hdr.frag_len - hdr_length))
3127 ERR("invalid http packet of length %d bytes\n", (*Header)->common.frag_len);
3128 status = RPC_S_PROTOCOL_ERROR;
3129 goto fail;
3131 if ((*Header)->http.flags == 0x0001)
3133 TRACE("http idle packet, waiting for real packet\n");
3134 if ((*Header)->http.num_data_items != 0)
3136 ERR("HTTP idle packet should have no data items instead of %d\n", (*Header)->http.num_data_items);
3137 status = RPC_S_PROTOCOL_ERROR;
3138 goto fail;
3141 else if ((*Header)->http.flags == 0x0002)
3143 ULONG bytes_transmitted;
3144 ULONG flow_control_increment;
3145 UUID pipe_uuid;
3146 status = RPCRT4_ParseHttpFlowControlHeader(*Header, *Payload,
3147 Connection->server,
3148 &bytes_transmitted,
3149 &flow_control_increment,
3150 &pipe_uuid);
3151 if (status != RPC_S_OK)
3152 goto fail;
3153 TRACE("received http flow control header (0x%x, 0x%x, %s)\n",
3154 bytes_transmitted, flow_control_increment, debugstr_guid(&pipe_uuid));
3155 /* FIXME: do something with parsed data */
3157 else
3159 FIXME("unrecognised http packet with flags 0x%04x\n", (*Header)->http.flags);
3160 status = RPC_S_PROTOCOL_ERROR;
3161 goto fail;
3163 RPCRT4_FreeHeader(*Header);
3164 *Header = NULL;
3165 HeapFree(GetProcessHeap(), 0, *Payload);
3166 *Payload = NULL;
3167 goto again;
3170 /* success */
3171 status = RPC_S_OK;
3173 httpc->bytes_received += common_hdr.frag_len;
3175 TRACE("httpc->bytes_received = 0x%x\n", httpc->bytes_received);
3177 if (httpc->bytes_received > httpc->flow_control_mark)
3179 RpcPktHdr *hdr = RPCRT4_BuildHttpFlowControlHeader(httpc->common.server,
3180 httpc->bytes_received,
3181 httpc->flow_control_increment,
3182 &httpc->out_pipe_uuid);
3183 if (hdr)
3185 DWORD bytes_written;
3186 BOOL ret2;
3187 TRACE("sending flow control packet at 0x%x\n", httpc->bytes_received);
3188 ret2 = InternetWriteFile(httpc->in_request, hdr, hdr->common.frag_len, &bytes_written);
3189 RPCRT4_FreeHeader(hdr);
3190 if (ret2)
3191 httpc->flow_control_mark = httpc->bytes_received + httpc->flow_control_increment / 2;
3195 fail:
3196 if (status != RPC_S_OK) {
3197 RPCRT4_FreeHeader(*Header);
3198 *Header = NULL;
3199 HeapFree(GetProcessHeap(), 0, *Payload);
3200 *Payload = NULL;
3202 return status;
3205 static int rpcrt4_ncacn_http_write(RpcConnection *Connection,
3206 const void *buffer, unsigned int count)
3208 RpcConnection_http *httpc = (RpcConnection_http *) Connection;
3209 DWORD bytes_written;
3210 BOOL ret;
3212 httpc->last_sent_time = ~0U; /* disable idle packet sending */
3213 ret = InternetWriteFile(httpc->in_request, buffer, count, &bytes_written);
3214 httpc->last_sent_time = GetTickCount();
3215 TRACE("%p %p %u -> %s\n", httpc->in_request, buffer, count, ret ? "TRUE" : "FALSE");
3216 return ret ? bytes_written : -1;
3219 static int rpcrt4_ncacn_http_close(RpcConnection *Connection)
3221 RpcConnection_http *httpc = (RpcConnection_http *) Connection;
3223 TRACE("\n");
3225 SetEvent(httpc->timer_cancelled);
3226 if (httpc->in_request)
3227 InternetCloseHandle(httpc->in_request);
3228 httpc->in_request = NULL;
3229 if (httpc->out_request)
3230 InternetCloseHandle(httpc->out_request);
3231 httpc->out_request = NULL;
3232 if (httpc->app_info)
3233 InternetCloseHandle(httpc->app_info);
3234 httpc->app_info = NULL;
3235 if (httpc->session)
3236 InternetCloseHandle(httpc->session);
3237 httpc->session = NULL;
3238 RpcHttpAsyncData_Release(httpc->async_data);
3239 if (httpc->cancel_event)
3240 CloseHandle(httpc->cancel_event);
3241 HeapFree(GetProcessHeap(), 0, httpc->servername);
3242 httpc->servername = NULL;
3244 return 0;
3247 static void rpcrt4_ncacn_http_cancel_call(RpcConnection *Connection)
3249 RpcConnection_http *httpc = (RpcConnection_http *) Connection;
3251 SetEvent(httpc->cancel_event);
3254 static int rpcrt4_ncacn_http_wait_for_incoming_data(RpcConnection *Connection)
3256 RpcConnection_http *httpc = (RpcConnection_http *) Connection;
3257 BOOL ret;
3258 RPC_STATUS status;
3260 prepare_async_request(httpc->async_data);
3261 ret = InternetQueryDataAvailable(httpc->out_request,
3262 &httpc->async_data->inet_buffers.dwBufferLength, IRF_ASYNC, 0);
3263 status = wait_async_request(httpc->async_data, ret, httpc->cancel_event);
3264 return status == RPC_S_OK ? 0 : -1;
3267 static size_t rpcrt4_ncacn_http_get_top_of_tower(unsigned char *tower_data,
3268 const char *networkaddr,
3269 const char *endpoint)
3271 return rpcrt4_ip_tcp_get_top_of_tower(tower_data, networkaddr,
3272 EPM_PROTOCOL_HTTP, endpoint);
3275 static RPC_STATUS rpcrt4_ncacn_http_parse_top_of_tower(const unsigned char *tower_data,
3276 size_t tower_size,
3277 char **networkaddr,
3278 char **endpoint)
3280 return rpcrt4_ip_tcp_parse_top_of_tower(tower_data, tower_size,
3281 networkaddr, EPM_PROTOCOL_HTTP,
3282 endpoint);
3285 static const struct connection_ops conn_protseq_list[] = {
3286 { "ncacn_np",
3287 { EPM_PROTOCOL_NCACN, EPM_PROTOCOL_SMB },
3288 rpcrt4_conn_np_alloc,
3289 rpcrt4_ncacn_np_open,
3290 rpcrt4_ncacn_np_handoff,
3291 rpcrt4_conn_np_read,
3292 rpcrt4_conn_np_write,
3293 rpcrt4_conn_np_close,
3294 rpcrt4_conn_np_cancel_call,
3295 rpcrt4_conn_np_wait_for_incoming_data,
3296 rpcrt4_ncacn_np_get_top_of_tower,
3297 rpcrt4_ncacn_np_parse_top_of_tower,
3298 NULL,
3299 RPCRT4_default_is_authorized,
3300 RPCRT4_default_authorize,
3301 RPCRT4_default_secure_packet,
3302 rpcrt4_conn_np_impersonate_client,
3303 rpcrt4_conn_np_revert_to_self,
3304 RPCRT4_default_inquire_auth_client,
3306 { "ncalrpc",
3307 { EPM_PROTOCOL_NCALRPC, EPM_PROTOCOL_PIPE },
3308 rpcrt4_conn_np_alloc,
3309 rpcrt4_ncalrpc_open,
3310 rpcrt4_ncalrpc_handoff,
3311 rpcrt4_conn_np_read,
3312 rpcrt4_conn_np_write,
3313 rpcrt4_conn_np_close,
3314 rpcrt4_conn_np_cancel_call,
3315 rpcrt4_conn_np_wait_for_incoming_data,
3316 rpcrt4_ncalrpc_get_top_of_tower,
3317 rpcrt4_ncalrpc_parse_top_of_tower,
3318 NULL,
3319 rpcrt4_ncalrpc_is_authorized,
3320 rpcrt4_ncalrpc_authorize,
3321 rpcrt4_ncalrpc_secure_packet,
3322 rpcrt4_conn_np_impersonate_client,
3323 rpcrt4_conn_np_revert_to_self,
3324 rpcrt4_ncalrpc_inquire_auth_client,
3326 { "ncacn_ip_tcp",
3327 { EPM_PROTOCOL_NCACN, EPM_PROTOCOL_TCP },
3328 rpcrt4_conn_tcp_alloc,
3329 rpcrt4_ncacn_ip_tcp_open,
3330 rpcrt4_conn_tcp_handoff,
3331 rpcrt4_conn_tcp_read,
3332 rpcrt4_conn_tcp_write,
3333 rpcrt4_conn_tcp_close,
3334 rpcrt4_conn_tcp_cancel_call,
3335 rpcrt4_conn_tcp_wait_for_incoming_data,
3336 rpcrt4_ncacn_ip_tcp_get_top_of_tower,
3337 rpcrt4_ncacn_ip_tcp_parse_top_of_tower,
3338 NULL,
3339 RPCRT4_default_is_authorized,
3340 RPCRT4_default_authorize,
3341 RPCRT4_default_secure_packet,
3342 RPCRT4_default_impersonate_client,
3343 RPCRT4_default_revert_to_self,
3344 RPCRT4_default_inquire_auth_client,
3346 { "ncacn_http",
3347 { EPM_PROTOCOL_NCACN, EPM_PROTOCOL_HTTP },
3348 rpcrt4_ncacn_http_alloc,
3349 rpcrt4_ncacn_http_open,
3350 rpcrt4_ncacn_http_handoff,
3351 rpcrt4_ncacn_http_read,
3352 rpcrt4_ncacn_http_write,
3353 rpcrt4_ncacn_http_close,
3354 rpcrt4_ncacn_http_cancel_call,
3355 rpcrt4_ncacn_http_wait_for_incoming_data,
3356 rpcrt4_ncacn_http_get_top_of_tower,
3357 rpcrt4_ncacn_http_parse_top_of_tower,
3358 rpcrt4_ncacn_http_receive_fragment,
3359 RPCRT4_default_is_authorized,
3360 RPCRT4_default_authorize,
3361 RPCRT4_default_secure_packet,
3362 RPCRT4_default_impersonate_client,
3363 RPCRT4_default_revert_to_self,
3364 RPCRT4_default_inquire_auth_client,
3369 static const struct protseq_ops protseq_list[] =
3372 "ncacn_np",
3373 rpcrt4_protseq_np_alloc,
3374 rpcrt4_protseq_np_signal_state_changed,
3375 rpcrt4_protseq_np_get_wait_array,
3376 rpcrt4_protseq_np_free_wait_array,
3377 rpcrt4_protseq_np_wait_for_new_connection,
3378 rpcrt4_protseq_ncacn_np_open_endpoint,
3381 "ncalrpc",
3382 rpcrt4_protseq_np_alloc,
3383 rpcrt4_protseq_np_signal_state_changed,
3384 rpcrt4_protseq_np_get_wait_array,
3385 rpcrt4_protseq_np_free_wait_array,
3386 rpcrt4_protseq_np_wait_for_new_connection,
3387 rpcrt4_protseq_ncalrpc_open_endpoint,
3390 "ncacn_ip_tcp",
3391 rpcrt4_protseq_sock_alloc,
3392 rpcrt4_protseq_sock_signal_state_changed,
3393 rpcrt4_protseq_sock_get_wait_array,
3394 rpcrt4_protseq_sock_free_wait_array,
3395 rpcrt4_protseq_sock_wait_for_new_connection,
3396 rpcrt4_protseq_ncacn_ip_tcp_open_endpoint,
3400 const struct protseq_ops *rpcrt4_get_protseq_ops(const char *protseq)
3402 unsigned int i;
3403 for(i=0; i<ARRAYSIZE(protseq_list); i++)
3404 if (!strcmp(protseq_list[i].name, protseq))
3405 return &protseq_list[i];
3406 return NULL;
3409 static const struct connection_ops *rpcrt4_get_conn_protseq_ops(const char *protseq)
3411 unsigned int i;
3412 for(i=0; i<ARRAYSIZE(conn_protseq_list); i++)
3413 if (!strcmp(conn_protseq_list[i].name, protseq))
3414 return &conn_protseq_list[i];
3415 return NULL;
3418 /**** interface to rest of code ****/
3420 RPC_STATUS RPCRT4_OpenClientConnection(RpcConnection* Connection)
3422 TRACE("(Connection == ^%p)\n", Connection);
3424 assert(!Connection->server);
3425 return Connection->ops->open_connection_client(Connection);
3428 RPC_STATUS RPCRT4_CloseConnection(RpcConnection* Connection)
3430 TRACE("(Connection == ^%p)\n", Connection);
3431 if (SecIsValidHandle(&Connection->ctx))
3433 DeleteSecurityContext(&Connection->ctx);
3434 SecInvalidateHandle(&Connection->ctx);
3436 rpcrt4_conn_close(Connection);
3437 return RPC_S_OK;
3440 RPC_STATUS RPCRT4_CreateConnection(RpcConnection** Connection, BOOL server,
3441 LPCSTR Protseq, LPCSTR NetworkAddr, LPCSTR Endpoint,
3442 LPCWSTR NetworkOptions, RpcAuthInfo* AuthInfo, RpcQualityOfService *QOS, LPCWSTR CookieAuth)
3444 static LONG next_id;
3445 const struct connection_ops *ops;
3446 RpcConnection* NewConnection;
3448 ops = rpcrt4_get_conn_protseq_ops(Protseq);
3449 if (!ops)
3451 FIXME("not supported for protseq %s\n", Protseq);
3452 return RPC_S_PROTSEQ_NOT_SUPPORTED;
3455 NewConnection = ops->alloc();
3456 NewConnection->ref = 1;
3457 NewConnection->Next = NULL;
3458 NewConnection->server_binding = NULL;
3459 NewConnection->server = server;
3460 NewConnection->ops = ops;
3461 NewConnection->NetworkAddr = RPCRT4_strdupA(NetworkAddr);
3462 NewConnection->Endpoint = RPCRT4_strdupA(Endpoint);
3463 NewConnection->NetworkOptions = RPCRT4_strdupW(NetworkOptions);
3464 NewConnection->CookieAuth = RPCRT4_strdupW(CookieAuth);
3465 NewConnection->MaxTransmissionSize = RPC_MAX_PACKET_SIZE;
3466 memset(&NewConnection->ActiveInterface, 0, sizeof(NewConnection->ActiveInterface));
3467 NewConnection->NextCallId = 1;
3469 SecInvalidateHandle(&NewConnection->ctx);
3470 memset(&NewConnection->exp, 0, sizeof(NewConnection->exp));
3471 NewConnection->attr = 0;
3472 if (AuthInfo) RpcAuthInfo_AddRef(AuthInfo);
3473 NewConnection->AuthInfo = AuthInfo;
3474 NewConnection->auth_context_id = InterlockedIncrement( &next_id );
3475 NewConnection->encryption_auth_len = 0;
3476 NewConnection->signature_auth_len = 0;
3477 if (QOS) RpcQualityOfService_AddRef(QOS);
3478 NewConnection->QOS = QOS;
3480 list_init(&NewConnection->conn_pool_entry);
3481 NewConnection->async_state = NULL;
3483 TRACE("connection: %p\n", NewConnection);
3484 *Connection = NewConnection;
3486 return RPC_S_OK;
3489 static RPC_STATUS RPCRT4_SpawnConnection(RpcConnection** Connection, RpcConnection* OldConnection)
3491 RPC_STATUS err;
3493 err = RPCRT4_CreateConnection(Connection, OldConnection->server, rpcrt4_conn_get_name(OldConnection),
3494 OldConnection->NetworkAddr, OldConnection->Endpoint, NULL,
3495 OldConnection->AuthInfo, OldConnection->QOS, OldConnection->CookieAuth);
3496 if (err == RPC_S_OK)
3497 rpcrt4_conn_handoff(OldConnection, *Connection);
3498 return err;
3501 RpcConnection *RPCRT4_GrabConnection( RpcConnection *conn )
3503 InterlockedIncrement( &conn->ref );
3504 return conn;
3507 RPC_STATUS RPCRT4_ReleaseConnection(RpcConnection* Connection)
3509 if (InterlockedDecrement( &Connection->ref ) > 0) return RPC_S_OK;
3511 TRACE("destroying connection %p\n", Connection);
3513 RPCRT4_CloseConnection(Connection);
3514 RPCRT4_strfree(Connection->Endpoint);
3515 RPCRT4_strfree(Connection->NetworkAddr);
3516 HeapFree(GetProcessHeap(), 0, Connection->NetworkOptions);
3517 HeapFree(GetProcessHeap(), 0, Connection->CookieAuth);
3518 if (Connection->AuthInfo) RpcAuthInfo_Release(Connection->AuthInfo);
3519 if (Connection->QOS) RpcQualityOfService_Release(Connection->QOS);
3521 /* server-only */
3522 if (Connection->server_binding) RPCRT4_ReleaseBinding(Connection->server_binding);
3524 HeapFree(GetProcessHeap(), 0, Connection);
3525 return RPC_S_OK;
3528 RPC_STATUS RpcTransport_GetTopOfTower(unsigned char *tower_data,
3529 size_t *tower_size,
3530 const char *protseq,
3531 const char *networkaddr,
3532 const char *endpoint)
3534 twr_empty_floor_t *protocol_floor;
3535 const struct connection_ops *protseq_ops = rpcrt4_get_conn_protseq_ops(protseq);
3537 *tower_size = 0;
3539 if (!protseq_ops)
3540 return RPC_S_INVALID_RPC_PROTSEQ;
3542 if (!tower_data)
3544 *tower_size = sizeof(*protocol_floor);
3545 *tower_size += protseq_ops->get_top_of_tower(NULL, networkaddr, endpoint);
3546 return RPC_S_OK;
3549 protocol_floor = (twr_empty_floor_t *)tower_data;
3550 protocol_floor->count_lhs = sizeof(protocol_floor->protid);
3551 protocol_floor->protid = protseq_ops->epm_protocols[0];
3552 protocol_floor->count_rhs = 0;
3554 tower_data += sizeof(*protocol_floor);
3556 *tower_size = protseq_ops->get_top_of_tower(tower_data, networkaddr, endpoint);
3557 if (!*tower_size)
3558 return EPT_S_NOT_REGISTERED;
3560 *tower_size += sizeof(*protocol_floor);
3562 return RPC_S_OK;
3565 RPC_STATUS RpcTransport_ParseTopOfTower(const unsigned char *tower_data,
3566 size_t tower_size,
3567 char **protseq,
3568 char **networkaddr,
3569 char **endpoint)
3571 const twr_empty_floor_t *protocol_floor;
3572 const twr_empty_floor_t *floor4;
3573 const struct connection_ops *protseq_ops = NULL;
3574 RPC_STATUS status;
3575 unsigned int i;
3577 if (tower_size < sizeof(*protocol_floor))
3578 return EPT_S_NOT_REGISTERED;
3580 protocol_floor = (const twr_empty_floor_t *)tower_data;
3581 tower_data += sizeof(*protocol_floor);
3582 tower_size -= sizeof(*protocol_floor);
3583 if ((protocol_floor->count_lhs != sizeof(protocol_floor->protid)) ||
3584 (protocol_floor->count_rhs > tower_size))
3585 return EPT_S_NOT_REGISTERED;
3586 tower_data += protocol_floor->count_rhs;
3587 tower_size -= protocol_floor->count_rhs;
3589 floor4 = (const twr_empty_floor_t *)tower_data;
3590 if ((tower_size < sizeof(*floor4)) ||
3591 (floor4->count_lhs != sizeof(floor4->protid)))
3592 return EPT_S_NOT_REGISTERED;
3594 for(i = 0; i < ARRAYSIZE(conn_protseq_list); i++)
3595 if ((protocol_floor->protid == conn_protseq_list[i].epm_protocols[0]) &&
3596 (floor4->protid == conn_protseq_list[i].epm_protocols[1]))
3598 protseq_ops = &conn_protseq_list[i];
3599 break;
3602 if (!protseq_ops)
3603 return EPT_S_NOT_REGISTERED;
3605 status = protseq_ops->parse_top_of_tower(tower_data, tower_size, networkaddr, endpoint);
3607 if ((status == RPC_S_OK) && protseq)
3609 *protseq = I_RpcAllocate(strlen(protseq_ops->name) + 1);
3610 strcpy(*protseq, protseq_ops->name);
3613 return status;
3616 /***********************************************************************
3617 * RpcNetworkIsProtseqValidW (RPCRT4.@)
3619 * Checks if the given protocol sequence is known by the RPC system.
3620 * If it is, returns RPC_S_OK, otherwise RPC_S_PROTSEQ_NOT_SUPPORTED.
3623 RPC_STATUS WINAPI RpcNetworkIsProtseqValidW(RPC_WSTR protseq)
3625 char ps[0x10];
3627 WideCharToMultiByte(CP_ACP, 0, protseq, -1,
3628 ps, sizeof ps, NULL, NULL);
3629 if (rpcrt4_get_conn_protseq_ops(ps))
3630 return RPC_S_OK;
3632 FIXME("Unknown protseq %s\n", debugstr_w(protseq));
3634 return RPC_S_INVALID_RPC_PROTSEQ;
3637 /***********************************************************************
3638 * RpcNetworkIsProtseqValidA (RPCRT4.@)
3640 RPC_STATUS WINAPI RpcNetworkIsProtseqValidA(RPC_CSTR protseq)
3642 UNICODE_STRING protseqW;
3644 if (RtlCreateUnicodeStringFromAsciiz(&protseqW, (char*)protseq))
3646 RPC_STATUS ret = RpcNetworkIsProtseqValidW(protseqW.Buffer);
3647 RtlFreeUnicodeString(&protseqW);
3648 return ret;
3650 return RPC_S_OUT_OF_MEMORY;
3653 /***********************************************************************
3654 * RpcProtseqVectorFreeA (RPCRT4.@)
3656 RPC_STATUS WINAPI RpcProtseqVectorFreeA(RPC_PROTSEQ_VECTORA **protseqs)
3658 TRACE("(%p)\n", protseqs);
3660 if (*protseqs)
3662 unsigned int i;
3663 for (i = 0; i < (*protseqs)->Count; i++)
3664 HeapFree(GetProcessHeap(), 0, (*protseqs)->Protseq[i]);
3665 HeapFree(GetProcessHeap(), 0, *protseqs);
3666 *protseqs = NULL;
3668 return RPC_S_OK;
3671 /***********************************************************************
3672 * RpcProtseqVectorFreeW (RPCRT4.@)
3674 RPC_STATUS WINAPI RpcProtseqVectorFreeW(RPC_PROTSEQ_VECTORW **protseqs)
3676 TRACE("(%p)\n", protseqs);
3678 if (*protseqs)
3680 unsigned int i;
3681 for (i = 0; i < (*protseqs)->Count; i++)
3682 HeapFree(GetProcessHeap(), 0, (*protseqs)->Protseq[i]);
3683 HeapFree(GetProcessHeap(), 0, *protseqs);
3684 *protseqs = NULL;
3686 return RPC_S_OK;
3689 /***********************************************************************
3690 * RpcNetworkInqProtseqsW (RPCRT4.@)
3692 RPC_STATUS WINAPI RpcNetworkInqProtseqsW( RPC_PROTSEQ_VECTORW** protseqs )
3694 RPC_PROTSEQ_VECTORW *pvector;
3695 unsigned int i;
3696 RPC_STATUS status = RPC_S_OUT_OF_MEMORY;
3698 TRACE("(%p)\n", protseqs);
3700 *protseqs = HeapAlloc(GetProcessHeap(), 0, sizeof(RPC_PROTSEQ_VECTORW)+(sizeof(unsigned short*)*ARRAYSIZE(protseq_list)));
3701 if (!*protseqs)
3702 goto end;
3703 pvector = *protseqs;
3704 pvector->Count = 0;
3705 for (i = 0; i < ARRAYSIZE(protseq_list); i++)
3707 pvector->Protseq[i] = HeapAlloc(GetProcessHeap(), 0, (strlen(protseq_list[i].name)+1)*sizeof(unsigned short));
3708 if (pvector->Protseq[i] == NULL)
3709 goto end;
3710 MultiByteToWideChar(CP_ACP, 0, (CHAR*)protseq_list[i].name, -1,
3711 (WCHAR*)pvector->Protseq[i], strlen(protseq_list[i].name) + 1);
3712 pvector->Count++;
3714 status = RPC_S_OK;
3716 end:
3717 if (status != RPC_S_OK)
3718 RpcProtseqVectorFreeW(protseqs);
3719 return status;
3722 /***********************************************************************
3723 * RpcNetworkInqProtseqsA (RPCRT4.@)
3725 RPC_STATUS WINAPI RpcNetworkInqProtseqsA(RPC_PROTSEQ_VECTORA** protseqs)
3727 RPC_PROTSEQ_VECTORA *pvector;
3728 unsigned int i;
3729 RPC_STATUS status = RPC_S_OUT_OF_MEMORY;
3731 TRACE("(%p)\n", protseqs);
3733 *protseqs = HeapAlloc(GetProcessHeap(), 0, sizeof(RPC_PROTSEQ_VECTORW)+(sizeof(unsigned char*)*ARRAYSIZE(protseq_list)));
3734 if (!*protseqs)
3735 goto end;
3736 pvector = *protseqs;
3737 pvector->Count = 0;
3738 for (i = 0; i < ARRAYSIZE(protseq_list); i++)
3740 pvector->Protseq[i] = HeapAlloc(GetProcessHeap(), 0, strlen(protseq_list[i].name)+1);
3741 if (pvector->Protseq[i] == NULL)
3742 goto end;
3743 strcpy((char*)pvector->Protseq[i], protseq_list[i].name);
3744 pvector->Count++;
3746 status = RPC_S_OK;
3748 end:
3749 if (status != RPC_S_OK)
3750 RpcProtseqVectorFreeA(protseqs);
3751 return status;