msvcrt/tests: Make qsort_comp() static.
[wine.git] / dlls / rpcrt4 / rpc_transport.c
blobc073a95774326fa268ec6ed9b2e8d342d680ed24
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 <stdlib.h>
33 #include <sys/types.h>
35 #if defined(__MINGW32__) || defined (_MSC_VER)
36 # include <ws2tcpip.h>
37 # ifndef EADDRINUSE
38 # define EADDRINUSE WSAEADDRINUSE
39 # endif
40 # ifndef EAGAIN
41 # define EAGAIN WSAEWOULDBLOCK
42 # endif
43 # undef errno
44 # define errno WSAGetLastError()
45 #else
46 # include <errno.h>
47 # ifdef HAVE_UNISTD_H
48 # include <unistd.h>
49 # endif
50 # include <fcntl.h>
51 # ifdef HAVE_SYS_SOCKET_H
52 # include <sys/socket.h>
53 # endif
54 # ifdef HAVE_NETINET_IN_H
55 # include <netinet/in.h>
56 # endif
57 # ifdef HAVE_NETINET_TCP_H
58 # include <netinet/tcp.h>
59 # endif
60 # ifdef HAVE_ARPA_INET_H
61 # include <arpa/inet.h>
62 # endif
63 # ifdef HAVE_NETDB_H
64 # include <netdb.h>
65 # endif
66 # ifdef HAVE_SYS_POLL_H
67 # include <sys/poll.h>
68 # endif
69 # ifdef HAVE_SYS_FILIO_H
70 # include <sys/filio.h>
71 # endif
72 # ifdef HAVE_SYS_IOCTL_H
73 # include <sys/ioctl.h>
74 # endif
75 # define closesocket close
76 # define ioctlsocket ioctl
77 #endif /* defined(__MINGW32__) || defined (_MSC_VER) */
79 #include "windef.h"
80 #include "winbase.h"
81 #include "winnls.h"
82 #include "winerror.h"
83 #include "wininet.h"
84 #include "winternl.h"
85 #include "wine/unicode.h"
87 #include "rpc.h"
88 #include "rpcndr.h"
90 #include "wine/debug.h"
92 #include "rpc_binding.h"
93 #include "rpc_assoc.h"
94 #include "rpc_message.h"
95 #include "rpc_server.h"
96 #include "epm_towers.h"
98 #ifndef SOL_TCP
99 # define SOL_TCP IPPROTO_TCP
100 #endif
102 #define DEFAULT_NCACN_HTTP_TIMEOUT (60 * 1000)
104 #define ARRAYSIZE(a) (sizeof((a)) / sizeof((a)[0]))
106 WINE_DEFAULT_DEBUG_CHANNEL(rpc);
108 static RPC_STATUS RPCRT4_SpawnConnection(RpcConnection** Connection, RpcConnection* OldConnection);
110 /**** ncacn_np support ****/
112 typedef struct _RpcConnection_np
114 RpcConnection common;
115 HANDLE pipe;
116 HANDLE listen_thread;
117 BOOL listening;
118 } RpcConnection_np;
120 static RpcConnection *rpcrt4_conn_np_alloc(void)
122 RpcConnection_np *npc = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(RpcConnection_np));
123 return &npc->common;
126 static DWORD CALLBACK listen_thread(void *arg)
128 RpcConnection_np *npc = arg;
129 for (;;)
131 if (ConnectNamedPipe(npc->pipe, NULL))
132 return RPC_S_OK;
134 switch(GetLastError())
136 case ERROR_PIPE_CONNECTED:
137 return RPC_S_OK;
138 case ERROR_HANDLES_CLOSED:
139 /* connection closed during listen */
140 return RPC_S_NO_CONTEXT_AVAILABLE;
141 case ERROR_NO_DATA_DETECTED:
142 /* client has disconnected, retry */
143 DisconnectNamedPipe( npc->pipe );
144 break;
145 default:
146 npc->listening = FALSE;
147 WARN("Couldn't ConnectNamedPipe (error was %d)\n", GetLastError());
148 return RPC_S_OUT_OF_RESOURCES;
153 static RPC_STATUS rpcrt4_conn_listen_pipe(RpcConnection_np *npc)
155 if (npc->listening)
156 return RPC_S_OK;
158 npc->listening = TRUE;
159 npc->listen_thread = CreateThread(NULL, 0, listen_thread, npc, 0, NULL);
160 if (!npc->listen_thread)
162 npc->listening = FALSE;
163 ERR("Couldn't create listen thread (error was %d)\n", GetLastError());
164 return RPC_S_OUT_OF_RESOURCES;
166 return RPC_S_OK;
169 static RPC_STATUS rpcrt4_conn_create_pipe(RpcConnection *Connection, LPCSTR pname)
171 RpcConnection_np *npc = (RpcConnection_np *) Connection;
172 TRACE("listening on %s\n", pname);
174 npc->pipe = CreateNamedPipeA(pname, PIPE_ACCESS_DUPLEX,
175 PIPE_TYPE_MESSAGE | PIPE_READMODE_MESSAGE,
176 PIPE_UNLIMITED_INSTANCES,
177 RPC_MAX_PACKET_SIZE, RPC_MAX_PACKET_SIZE, 5000, NULL);
178 if (npc->pipe == INVALID_HANDLE_VALUE) {
179 WARN("CreateNamedPipe failed with error %d\n", GetLastError());
180 if (GetLastError() == ERROR_FILE_EXISTS)
181 return RPC_S_DUPLICATE_ENDPOINT;
182 else
183 return RPC_S_CANT_CREATE_ENDPOINT;
186 /* Note: we don't call ConnectNamedPipe here because it must be done in the
187 * server thread as the thread must be alertable */
188 return RPC_S_OK;
191 static RPC_STATUS rpcrt4_conn_open_pipe(RpcConnection *Connection, LPCSTR pname, BOOL wait)
193 RpcConnection_np *npc = (RpcConnection_np *) Connection;
194 HANDLE pipe;
195 DWORD err, dwMode;
197 TRACE("connecting to %s\n", pname);
199 while (TRUE) {
200 DWORD dwFlags = 0;
201 if (Connection->QOS)
203 dwFlags = SECURITY_SQOS_PRESENT;
204 switch (Connection->QOS->qos->ImpersonationType)
206 case RPC_C_IMP_LEVEL_DEFAULT:
207 /* FIXME: what to do here? */
208 break;
209 case RPC_C_IMP_LEVEL_ANONYMOUS:
210 dwFlags |= SECURITY_ANONYMOUS;
211 break;
212 case RPC_C_IMP_LEVEL_IDENTIFY:
213 dwFlags |= SECURITY_IDENTIFICATION;
214 break;
215 case RPC_C_IMP_LEVEL_IMPERSONATE:
216 dwFlags |= SECURITY_IMPERSONATION;
217 break;
218 case RPC_C_IMP_LEVEL_DELEGATE:
219 dwFlags |= SECURITY_DELEGATION;
220 break;
222 if (Connection->QOS->qos->IdentityTracking == RPC_C_QOS_IDENTITY_DYNAMIC)
223 dwFlags |= SECURITY_CONTEXT_TRACKING;
225 pipe = CreateFileA(pname, GENERIC_READ|GENERIC_WRITE, 0, NULL,
226 OPEN_EXISTING, dwFlags, 0);
227 if (pipe != INVALID_HANDLE_VALUE) break;
228 err = GetLastError();
229 if (err == ERROR_PIPE_BUSY) {
230 TRACE("connection failed, error=%x\n", err);
231 return RPC_S_SERVER_TOO_BUSY;
233 if (!wait || !WaitNamedPipeA(pname, NMPWAIT_WAIT_FOREVER)) {
234 err = GetLastError();
235 WARN("connection failed, error=%x\n", err);
236 return RPC_S_SERVER_UNAVAILABLE;
240 /* success */
241 /* pipe is connected; change to message-read mode. */
242 dwMode = PIPE_READMODE_MESSAGE;
243 SetNamedPipeHandleState(pipe, &dwMode, NULL, NULL);
244 npc->pipe = pipe;
246 return RPC_S_OK;
249 static RPC_STATUS rpcrt4_ncalrpc_open(RpcConnection* Connection)
251 RpcConnection_np *npc = (RpcConnection_np *) Connection;
252 static const char prefix[] = "\\\\.\\pipe\\lrpc\\";
253 RPC_STATUS r;
254 LPSTR pname;
256 /* already connected? */
257 if (npc->pipe)
258 return RPC_S_OK;
260 /* protseq=ncalrpc: supposed to use NT LPC ports,
261 * but we'll implement it with named pipes for now */
262 pname = I_RpcAllocate(strlen(prefix) + strlen(Connection->Endpoint) + 1);
263 strcat(strcpy(pname, prefix), Connection->Endpoint);
264 r = rpcrt4_conn_open_pipe(Connection, pname, TRUE);
265 I_RpcFree(pname);
267 return r;
270 static RPC_STATUS rpcrt4_protseq_ncalrpc_open_endpoint(RpcServerProtseq* protseq, const char *endpoint)
272 static const char prefix[] = "\\\\.\\pipe\\lrpc\\";
273 RPC_STATUS r;
274 LPSTR pname;
275 RpcConnection *Connection;
276 char generated_endpoint[22];
278 if (!endpoint)
280 static LONG lrpc_nameless_id;
281 DWORD process_id = GetCurrentProcessId();
282 ULONG id = InterlockedIncrement(&lrpc_nameless_id);
283 snprintf(generated_endpoint, sizeof(generated_endpoint),
284 "LRPC%08x.%08x", process_id, id);
285 endpoint = generated_endpoint;
288 r = RPCRT4_CreateConnection(&Connection, TRUE, protseq->Protseq, NULL,
289 endpoint, NULL, NULL, NULL, NULL);
290 if (r != RPC_S_OK)
291 return r;
293 /* protseq=ncalrpc: supposed to use NT LPC ports,
294 * but we'll implement it with named pipes for now */
295 pname = I_RpcAllocate(strlen(prefix) + strlen(Connection->Endpoint) + 1);
296 strcat(strcpy(pname, prefix), Connection->Endpoint);
297 r = rpcrt4_conn_create_pipe(Connection, pname);
298 I_RpcFree(pname);
300 EnterCriticalSection(&protseq->cs);
301 Connection->Next = protseq->conn;
302 protseq->conn = Connection;
303 LeaveCriticalSection(&protseq->cs);
305 return r;
308 static RPC_STATUS rpcrt4_ncacn_np_open(RpcConnection* Connection)
310 RpcConnection_np *npc = (RpcConnection_np *) Connection;
311 static const char prefix[] = "\\\\.";
312 RPC_STATUS r;
313 LPSTR pname;
315 /* already connected? */
316 if (npc->pipe)
317 return RPC_S_OK;
319 /* protseq=ncacn_np: named pipes */
320 pname = I_RpcAllocate(strlen(prefix) + strlen(Connection->Endpoint) + 1);
321 strcat(strcpy(pname, prefix), Connection->Endpoint);
322 r = rpcrt4_conn_open_pipe(Connection, pname, FALSE);
323 I_RpcFree(pname);
325 return r;
328 static RPC_STATUS rpcrt4_protseq_ncacn_np_open_endpoint(RpcServerProtseq *protseq, const char *endpoint)
330 static const char prefix[] = "\\\\.";
331 RPC_STATUS r;
332 LPSTR pname;
333 RpcConnection *Connection;
334 char generated_endpoint[21];
336 if (!endpoint)
338 static LONG np_nameless_id;
339 DWORD process_id = GetCurrentProcessId();
340 ULONG id = InterlockedExchangeAdd(&np_nameless_id, 1 );
341 snprintf(generated_endpoint, sizeof(generated_endpoint),
342 "\\\\pipe\\\\%08x.%03x", process_id, id);
343 endpoint = generated_endpoint;
346 r = RPCRT4_CreateConnection(&Connection, TRUE, protseq->Protseq, NULL,
347 endpoint, NULL, NULL, NULL, NULL);
348 if (r != RPC_S_OK)
349 return r;
351 /* protseq=ncacn_np: named pipes */
352 pname = I_RpcAllocate(strlen(prefix) + strlen(Connection->Endpoint) + 1);
353 strcat(strcpy(pname, prefix), Connection->Endpoint);
354 r = rpcrt4_conn_create_pipe(Connection, pname);
355 I_RpcFree(pname);
357 EnterCriticalSection(&protseq->cs);
358 Connection->Next = protseq->conn;
359 protseq->conn = Connection;
360 LeaveCriticalSection(&protseq->cs);
362 return r;
365 static void rpcrt4_conn_np_handoff(RpcConnection_np *old_npc, RpcConnection_np *new_npc)
367 /* because of the way named pipes work, we'll transfer the connected pipe
368 * to the child, then reopen the server binding to continue listening */
370 new_npc->pipe = old_npc->pipe;
371 new_npc->listen_thread = old_npc->listen_thread;
372 old_npc->pipe = 0;
373 old_npc->listen_thread = 0;
374 old_npc->listening = FALSE;
377 static RPC_STATUS rpcrt4_ncacn_np_handoff(RpcConnection *old_conn, RpcConnection *new_conn)
379 RPC_STATUS status;
380 LPSTR pname;
381 static const char prefix[] = "\\\\.";
383 rpcrt4_conn_np_handoff((RpcConnection_np *)old_conn, (RpcConnection_np *)new_conn);
385 pname = I_RpcAllocate(strlen(prefix) + strlen(old_conn->Endpoint) + 1);
386 strcat(strcpy(pname, prefix), old_conn->Endpoint);
387 status = rpcrt4_conn_create_pipe(old_conn, pname);
388 I_RpcFree(pname);
390 return status;
393 static RPC_STATUS rpcrt4_ncalrpc_handoff(RpcConnection *old_conn, RpcConnection *new_conn)
395 RPC_STATUS status;
396 LPSTR pname;
397 static const char prefix[] = "\\\\.\\pipe\\lrpc\\";
399 TRACE("%s\n", old_conn->Endpoint);
401 rpcrt4_conn_np_handoff((RpcConnection_np *)old_conn, (RpcConnection_np *)new_conn);
403 pname = I_RpcAllocate(strlen(prefix) + strlen(old_conn->Endpoint) + 1);
404 strcat(strcpy(pname, prefix), old_conn->Endpoint);
405 status = rpcrt4_conn_create_pipe(old_conn, pname);
406 I_RpcFree(pname);
408 return status;
411 static int rpcrt4_conn_np_read(RpcConnection *Connection,
412 void *buffer, unsigned int count)
414 RpcConnection_np *npc = (RpcConnection_np *) Connection;
415 char *buf = buffer;
416 BOOL ret = TRUE;
417 unsigned int bytes_left = count;
419 while (bytes_left)
421 DWORD bytes_read;
422 ret = ReadFile(npc->pipe, buf, bytes_left, &bytes_read, NULL);
423 if (!ret && GetLastError() == ERROR_MORE_DATA)
424 ret = TRUE;
425 if (!ret || !bytes_read)
426 break;
427 bytes_left -= bytes_read;
428 buf += bytes_read;
430 return ret ? count : -1;
433 static int rpcrt4_conn_np_write(RpcConnection *Connection,
434 const void *buffer, unsigned int count)
436 RpcConnection_np *npc = (RpcConnection_np *) Connection;
437 const char *buf = buffer;
438 BOOL ret = TRUE;
439 unsigned int bytes_left = count;
441 while (bytes_left)
443 DWORD bytes_written;
444 ret = WriteFile(npc->pipe, buf, bytes_left, &bytes_written, NULL);
445 if (!ret || !bytes_written)
446 break;
447 bytes_left -= bytes_written;
448 buf += bytes_written;
450 return ret ? count : -1;
453 static int rpcrt4_conn_np_close(RpcConnection *Connection)
455 RpcConnection_np *npc = (RpcConnection_np *) Connection;
456 if (npc->pipe) {
457 FlushFileBuffers(npc->pipe);
458 CloseHandle(npc->pipe);
459 npc->pipe = 0;
461 if (npc->listen_thread) {
462 CloseHandle(npc->listen_thread);
463 npc->listen_thread = 0;
465 return 0;
468 static void rpcrt4_conn_np_cancel_call(RpcConnection *Connection)
470 /* FIXME: implement when named pipe writes use overlapped I/O */
473 static int rpcrt4_conn_np_wait_for_incoming_data(RpcConnection *Connection)
475 /* FIXME: implement when named pipe writes use overlapped I/O */
476 return -1;
479 static size_t rpcrt4_ncacn_np_get_top_of_tower(unsigned char *tower_data,
480 const char *networkaddr,
481 const char *endpoint)
483 twr_empty_floor_t *smb_floor;
484 twr_empty_floor_t *nb_floor;
485 size_t size;
486 size_t networkaddr_size;
487 size_t endpoint_size;
489 TRACE("(%p, %s, %s)\n", tower_data, networkaddr, endpoint);
491 networkaddr_size = networkaddr ? strlen(networkaddr) + 1 : 1;
492 endpoint_size = endpoint ? strlen(endpoint) + 1 : 1;
493 size = sizeof(*smb_floor) + endpoint_size + sizeof(*nb_floor) + networkaddr_size;
495 if (!tower_data)
496 return size;
498 smb_floor = (twr_empty_floor_t *)tower_data;
500 tower_data += sizeof(*smb_floor);
502 smb_floor->count_lhs = sizeof(smb_floor->protid);
503 smb_floor->protid = EPM_PROTOCOL_SMB;
504 smb_floor->count_rhs = endpoint_size;
506 if (endpoint)
507 memcpy(tower_data, endpoint, endpoint_size);
508 else
509 tower_data[0] = 0;
510 tower_data += endpoint_size;
512 nb_floor = (twr_empty_floor_t *)tower_data;
514 tower_data += sizeof(*nb_floor);
516 nb_floor->count_lhs = sizeof(nb_floor->protid);
517 nb_floor->protid = EPM_PROTOCOL_NETBIOS;
518 nb_floor->count_rhs = networkaddr_size;
520 if (networkaddr)
521 memcpy(tower_data, networkaddr, networkaddr_size);
522 else
523 tower_data[0] = 0;
525 return size;
528 static RPC_STATUS rpcrt4_ncacn_np_parse_top_of_tower(const unsigned char *tower_data,
529 size_t tower_size,
530 char **networkaddr,
531 char **endpoint)
533 const twr_empty_floor_t *smb_floor = (const twr_empty_floor_t *)tower_data;
534 const twr_empty_floor_t *nb_floor;
536 TRACE("(%p, %d, %p, %p)\n", tower_data, (int)tower_size, networkaddr, endpoint);
538 if (tower_size < sizeof(*smb_floor))
539 return EPT_S_NOT_REGISTERED;
541 tower_data += sizeof(*smb_floor);
542 tower_size -= sizeof(*smb_floor);
544 if ((smb_floor->count_lhs != sizeof(smb_floor->protid)) ||
545 (smb_floor->protid != EPM_PROTOCOL_SMB) ||
546 (smb_floor->count_rhs > tower_size) ||
547 (tower_data[smb_floor->count_rhs - 1] != '\0'))
548 return EPT_S_NOT_REGISTERED;
550 if (endpoint)
552 *endpoint = I_RpcAllocate(smb_floor->count_rhs);
553 if (!*endpoint)
554 return RPC_S_OUT_OF_RESOURCES;
555 memcpy(*endpoint, tower_data, smb_floor->count_rhs);
557 tower_data += smb_floor->count_rhs;
558 tower_size -= smb_floor->count_rhs;
560 if (tower_size < sizeof(*nb_floor))
561 return EPT_S_NOT_REGISTERED;
563 nb_floor = (const twr_empty_floor_t *)tower_data;
565 tower_data += sizeof(*nb_floor);
566 tower_size -= sizeof(*nb_floor);
568 if ((nb_floor->count_lhs != sizeof(nb_floor->protid)) ||
569 (nb_floor->protid != EPM_PROTOCOL_NETBIOS) ||
570 (nb_floor->count_rhs > tower_size) ||
571 (tower_data[nb_floor->count_rhs - 1] != '\0'))
572 return EPT_S_NOT_REGISTERED;
574 if (networkaddr)
576 *networkaddr = I_RpcAllocate(nb_floor->count_rhs);
577 if (!*networkaddr)
579 if (endpoint)
581 I_RpcFree(*endpoint);
582 *endpoint = NULL;
584 return RPC_S_OUT_OF_RESOURCES;
586 memcpy(*networkaddr, tower_data, nb_floor->count_rhs);
589 return RPC_S_OK;
592 static RPC_STATUS rpcrt4_conn_np_impersonate_client(RpcConnection *conn)
594 RpcConnection_np *npc = (RpcConnection_np *)conn;
595 BOOL ret;
597 TRACE("(%p)\n", conn);
599 if (conn->AuthInfo && SecIsValidHandle(&conn->ctx))
600 return RPCRT4_default_impersonate_client(conn);
602 ret = ImpersonateNamedPipeClient(npc->pipe);
603 if (!ret)
605 DWORD error = GetLastError();
606 WARN("ImpersonateNamedPipeClient failed with error %u\n", error);
607 switch (error)
609 case ERROR_CANNOT_IMPERSONATE:
610 return RPC_S_NO_CONTEXT_AVAILABLE;
613 return RPC_S_OK;
616 static RPC_STATUS rpcrt4_conn_np_revert_to_self(RpcConnection *conn)
618 BOOL ret;
620 TRACE("(%p)\n", conn);
622 if (conn->AuthInfo && SecIsValidHandle(&conn->ctx))
623 return RPCRT4_default_revert_to_self(conn);
625 ret = RevertToSelf();
626 if (!ret)
628 WARN("RevertToSelf failed with error %u\n", GetLastError());
629 return RPC_S_NO_CONTEXT_AVAILABLE;
631 return RPC_S_OK;
634 typedef struct _RpcServerProtseq_np
636 RpcServerProtseq common;
637 HANDLE mgr_event;
638 } RpcServerProtseq_np;
640 static RpcServerProtseq *rpcrt4_protseq_np_alloc(void)
642 RpcServerProtseq_np *ps = HeapAlloc(GetProcessHeap(), 0, sizeof(*ps));
643 if (ps)
644 ps->mgr_event = CreateEventW(NULL, FALSE, FALSE, NULL);
645 return &ps->common;
648 static void rpcrt4_protseq_np_signal_state_changed(RpcServerProtseq *protseq)
650 RpcServerProtseq_np *npps = CONTAINING_RECORD(protseq, RpcServerProtseq_np, common);
651 SetEvent(npps->mgr_event);
654 static void *rpcrt4_protseq_np_get_wait_array(RpcServerProtseq *protseq, void *prev_array, unsigned int *count)
656 HANDLE *objs = prev_array;
657 RpcConnection_np *conn;
658 RpcServerProtseq_np *npps = CONTAINING_RECORD(protseq, RpcServerProtseq_np, common);
660 EnterCriticalSection(&protseq->cs);
662 /* open and count connections */
663 *count = 1;
664 conn = CONTAINING_RECORD(protseq->conn, RpcConnection_np, common);
665 while (conn) {
666 rpcrt4_conn_listen_pipe(conn);
667 if (conn->listen_thread)
668 (*count)++;
669 conn = CONTAINING_RECORD(conn->common.Next, RpcConnection_np, common);
672 /* make array of connections */
673 if (objs)
674 objs = HeapReAlloc(GetProcessHeap(), 0, objs, *count*sizeof(HANDLE));
675 else
676 objs = HeapAlloc(GetProcessHeap(), 0, *count*sizeof(HANDLE));
677 if (!objs)
679 ERR("couldn't allocate objs\n");
680 LeaveCriticalSection(&protseq->cs);
681 return NULL;
684 objs[0] = npps->mgr_event;
685 *count = 1;
686 conn = CONTAINING_RECORD(protseq->conn, RpcConnection_np, common);
687 while (conn) {
688 if ((objs[*count] = conn->listen_thread))
689 (*count)++;
690 conn = CONTAINING_RECORD(conn->common.Next, RpcConnection_np, common);
692 LeaveCriticalSection(&protseq->cs);
693 return objs;
696 static void rpcrt4_protseq_np_free_wait_array(RpcServerProtseq *protseq, void *array)
698 HeapFree(GetProcessHeap(), 0, array);
701 static int rpcrt4_protseq_np_wait_for_new_connection(RpcServerProtseq *protseq, unsigned int count, void *wait_array)
703 HANDLE b_handle;
704 HANDLE *objs = wait_array;
705 DWORD res;
706 RpcConnection *cconn;
707 RpcConnection_np *conn;
709 if (!objs)
710 return -1;
714 /* an alertable wait isn't strictly necessary, but due to our
715 * overlapped I/O implementation in Wine we need to free some memory
716 * by the file user APC being called, even if no completion routine was
717 * specified at the time of starting the async operation */
718 res = WaitForMultipleObjectsEx(count, objs, FALSE, INFINITE, TRUE);
719 } while (res == WAIT_IO_COMPLETION);
721 if (res == WAIT_OBJECT_0)
722 return 0;
723 else if (res == WAIT_FAILED)
725 ERR("wait failed with error %d\n", GetLastError());
726 return -1;
728 else
730 b_handle = objs[res - WAIT_OBJECT_0];
731 /* find which connection got a RPC */
732 EnterCriticalSection(&protseq->cs);
733 conn = CONTAINING_RECORD(protseq->conn, RpcConnection_np, common);
734 while (conn) {
735 if (b_handle == conn->listen_thread) break;
736 conn = CONTAINING_RECORD(conn->common.Next, RpcConnection_np, common);
738 cconn = NULL;
739 if (conn)
741 DWORD exit_code;
742 if (GetExitCodeThread(conn->listen_thread, &exit_code) && exit_code == RPC_S_OK)
743 RPCRT4_SpawnConnection(&cconn, &conn->common);
744 CloseHandle(conn->listen_thread);
745 conn->listen_thread = 0;
747 else
748 ERR("failed to locate connection for handle %p\n", b_handle);
749 LeaveCriticalSection(&protseq->cs);
750 if (cconn)
752 RPCRT4_new_client(cconn);
753 return 1;
755 else return -1;
759 static size_t rpcrt4_ncalrpc_get_top_of_tower(unsigned char *tower_data,
760 const char *networkaddr,
761 const char *endpoint)
763 twr_empty_floor_t *pipe_floor;
764 size_t size;
765 size_t endpoint_size;
767 TRACE("(%p, %s, %s)\n", tower_data, networkaddr, endpoint);
769 endpoint_size = strlen(endpoint) + 1;
770 size = sizeof(*pipe_floor) + endpoint_size;
772 if (!tower_data)
773 return size;
775 pipe_floor = (twr_empty_floor_t *)tower_data;
777 tower_data += sizeof(*pipe_floor);
779 pipe_floor->count_lhs = sizeof(pipe_floor->protid);
780 pipe_floor->protid = EPM_PROTOCOL_PIPE;
781 pipe_floor->count_rhs = endpoint_size;
783 memcpy(tower_data, endpoint, endpoint_size);
785 return size;
788 static RPC_STATUS rpcrt4_ncalrpc_parse_top_of_tower(const unsigned char *tower_data,
789 size_t tower_size,
790 char **networkaddr,
791 char **endpoint)
793 const twr_empty_floor_t *pipe_floor = (const twr_empty_floor_t *)tower_data;
795 TRACE("(%p, %d, %p, %p)\n", tower_data, (int)tower_size, networkaddr, endpoint);
797 if (tower_size < sizeof(*pipe_floor))
798 return EPT_S_NOT_REGISTERED;
800 tower_data += sizeof(*pipe_floor);
801 tower_size -= sizeof(*pipe_floor);
803 if ((pipe_floor->count_lhs != sizeof(pipe_floor->protid)) ||
804 (pipe_floor->protid != EPM_PROTOCOL_PIPE) ||
805 (pipe_floor->count_rhs > tower_size) ||
806 (tower_data[pipe_floor->count_rhs - 1] != '\0'))
807 return EPT_S_NOT_REGISTERED;
809 if (networkaddr)
810 *networkaddr = NULL;
812 if (endpoint)
814 *endpoint = I_RpcAllocate(pipe_floor->count_rhs);
815 if (!*endpoint)
816 return RPC_S_OUT_OF_RESOURCES;
817 memcpy(*endpoint, tower_data, pipe_floor->count_rhs);
820 return RPC_S_OK;
823 static BOOL rpcrt4_ncalrpc_is_authorized(RpcConnection *conn)
825 return FALSE;
828 static RPC_STATUS rpcrt4_ncalrpc_authorize(RpcConnection *conn, BOOL first_time,
829 unsigned char *in_buffer,
830 unsigned int in_size,
831 unsigned char *out_buffer,
832 unsigned int *out_size)
834 /* since this protocol is local to the machine there is no need to
835 * authenticate the caller */
836 *out_size = 0;
837 return RPC_S_OK;
840 static RPC_STATUS rpcrt4_ncalrpc_secure_packet(RpcConnection *conn,
841 enum secure_packet_direction dir,
842 RpcPktHdr *hdr, unsigned int hdr_size,
843 unsigned char *stub_data, unsigned int stub_data_size,
844 RpcAuthVerifier *auth_hdr,
845 unsigned char *auth_value, unsigned int auth_value_size)
847 /* since this protocol is local to the machine there is no need to secure
848 * the packet */
849 return RPC_S_OK;
852 static RPC_STATUS rpcrt4_ncalrpc_inquire_auth_client(
853 RpcConnection *conn, RPC_AUTHZ_HANDLE *privs, RPC_WSTR *server_princ_name,
854 ULONG *authn_level, ULONG *authn_svc, ULONG *authz_svc, ULONG flags)
856 TRACE("(%p, %p, %p, %p, %p, %p, 0x%x)\n", conn, privs,
857 server_princ_name, authn_level, authn_svc, authz_svc, flags);
859 if (privs)
861 FIXME("privs not implemented\n");
862 *privs = NULL;
864 if (server_princ_name)
866 FIXME("server_princ_name not implemented\n");
867 *server_princ_name = NULL;
869 if (authn_level) *authn_level = RPC_C_AUTHN_LEVEL_PKT_PRIVACY;
870 if (authn_svc) *authn_svc = RPC_C_AUTHN_WINNT;
871 if (authz_svc)
873 FIXME("authorization service not implemented\n");
874 *authz_svc = RPC_C_AUTHZ_NONE;
876 if (flags)
877 FIXME("flags 0x%x not implemented\n", flags);
879 return RPC_S_OK;
882 /**** ncacn_ip_tcp support ****/
884 static size_t rpcrt4_ip_tcp_get_top_of_tower(unsigned char *tower_data,
885 const char *networkaddr,
886 unsigned char tcp_protid,
887 const char *endpoint)
889 twr_tcp_floor_t *tcp_floor;
890 twr_ipv4_floor_t *ipv4_floor;
891 struct addrinfo *ai;
892 struct addrinfo hints;
893 int ret;
894 size_t size = sizeof(*tcp_floor) + sizeof(*ipv4_floor);
896 TRACE("(%p, %s, %s)\n", tower_data, networkaddr, endpoint);
898 if (!tower_data)
899 return size;
901 tcp_floor = (twr_tcp_floor_t *)tower_data;
902 tower_data += sizeof(*tcp_floor);
904 ipv4_floor = (twr_ipv4_floor_t *)tower_data;
906 tcp_floor->count_lhs = sizeof(tcp_floor->protid);
907 tcp_floor->protid = tcp_protid;
908 tcp_floor->count_rhs = sizeof(tcp_floor->port);
910 ipv4_floor->count_lhs = sizeof(ipv4_floor->protid);
911 ipv4_floor->protid = EPM_PROTOCOL_IP;
912 ipv4_floor->count_rhs = sizeof(ipv4_floor->ipv4addr);
914 hints.ai_flags = AI_NUMERICHOST;
915 /* FIXME: only support IPv4 at the moment. how is IPv6 represented by the EPM? */
916 hints.ai_family = PF_INET;
917 hints.ai_socktype = SOCK_STREAM;
918 hints.ai_protocol = IPPROTO_TCP;
919 hints.ai_addrlen = 0;
920 hints.ai_addr = NULL;
921 hints.ai_canonname = NULL;
922 hints.ai_next = NULL;
924 ret = getaddrinfo(networkaddr, endpoint, &hints, &ai);
925 if (ret)
927 ret = getaddrinfo("0.0.0.0", endpoint, &hints, &ai);
928 if (ret)
930 ERR("getaddrinfo failed: %s\n", gai_strerror(ret));
931 return 0;
935 if (ai->ai_family == PF_INET)
937 const struct sockaddr_in *sin = (const struct sockaddr_in *)ai->ai_addr;
938 tcp_floor->port = sin->sin_port;
939 ipv4_floor->ipv4addr = sin->sin_addr.s_addr;
941 else
943 ERR("unexpected protocol family %d\n", ai->ai_family);
944 return 0;
947 freeaddrinfo(ai);
949 return size;
952 static RPC_STATUS rpcrt4_ip_tcp_parse_top_of_tower(const unsigned char *tower_data,
953 size_t tower_size,
954 char **networkaddr,
955 unsigned char tcp_protid,
956 char **endpoint)
958 const twr_tcp_floor_t *tcp_floor = (const twr_tcp_floor_t *)tower_data;
959 const twr_ipv4_floor_t *ipv4_floor;
960 struct in_addr in_addr;
962 TRACE("(%p, %d, %p, %p)\n", tower_data, (int)tower_size, networkaddr, endpoint);
964 if (tower_size < sizeof(*tcp_floor))
965 return EPT_S_NOT_REGISTERED;
967 tower_data += sizeof(*tcp_floor);
968 tower_size -= sizeof(*tcp_floor);
970 if (tower_size < sizeof(*ipv4_floor))
971 return EPT_S_NOT_REGISTERED;
973 ipv4_floor = (const twr_ipv4_floor_t *)tower_data;
975 if ((tcp_floor->count_lhs != sizeof(tcp_floor->protid)) ||
976 (tcp_floor->protid != tcp_protid) ||
977 (tcp_floor->count_rhs != sizeof(tcp_floor->port)) ||
978 (ipv4_floor->count_lhs != sizeof(ipv4_floor->protid)) ||
979 (ipv4_floor->protid != EPM_PROTOCOL_IP) ||
980 (ipv4_floor->count_rhs != sizeof(ipv4_floor->ipv4addr)))
981 return EPT_S_NOT_REGISTERED;
983 if (endpoint)
985 *endpoint = I_RpcAllocate(6 /* sizeof("65535") + 1 */);
986 if (!*endpoint)
987 return RPC_S_OUT_OF_RESOURCES;
988 sprintf(*endpoint, "%u", ntohs(tcp_floor->port));
991 if (networkaddr)
993 *networkaddr = I_RpcAllocate(INET_ADDRSTRLEN);
994 if (!*networkaddr)
996 if (endpoint)
998 I_RpcFree(*endpoint);
999 *endpoint = NULL;
1001 return RPC_S_OUT_OF_RESOURCES;
1003 in_addr.s_addr = ipv4_floor->ipv4addr;
1004 if (!inet_ntop(AF_INET, &in_addr, *networkaddr, INET_ADDRSTRLEN))
1006 ERR("inet_ntop: %s\n", strerror(errno));
1007 I_RpcFree(*networkaddr);
1008 *networkaddr = NULL;
1009 if (endpoint)
1011 I_RpcFree(*endpoint);
1012 *endpoint = NULL;
1014 return EPT_S_NOT_REGISTERED;
1018 return RPC_S_OK;
1021 typedef struct _RpcConnection_tcp
1023 RpcConnection common;
1024 int sock;
1025 #ifdef HAVE_SOCKETPAIR
1026 int cancel_fds[2];
1027 #else
1028 HANDLE sock_event;
1029 HANDLE cancel_event;
1030 #endif
1031 } RpcConnection_tcp;
1033 #ifdef HAVE_SOCKETPAIR
1035 static BOOL rpcrt4_sock_wait_init(RpcConnection_tcp *tcpc)
1037 if (socketpair(PF_UNIX, SOCK_STREAM, 0, tcpc->cancel_fds) < 0)
1039 ERR("socketpair() failed: %s\n", strerror(errno));
1040 return FALSE;
1042 return TRUE;
1045 static BOOL rpcrt4_sock_wait_for_recv(RpcConnection_tcp *tcpc)
1047 struct pollfd pfds[2];
1048 pfds[0].fd = tcpc->sock;
1049 pfds[0].events = POLLIN;
1050 pfds[1].fd = tcpc->cancel_fds[0];
1051 pfds[1].events = POLLIN;
1052 if (poll(pfds, 2, -1 /* infinite */) == -1 && errno != EINTR)
1054 ERR("poll() failed: %s\n", strerror(errno));
1055 return FALSE;
1057 if (pfds[1].revents & POLLIN) /* canceled */
1059 char dummy;
1060 read(pfds[1].fd, &dummy, sizeof(dummy));
1061 return FALSE;
1063 return TRUE;
1066 static BOOL rpcrt4_sock_wait_for_send(RpcConnection_tcp *tcpc)
1068 struct pollfd pfd;
1069 pfd.fd = tcpc->sock;
1070 pfd.events = POLLOUT;
1071 if (poll(&pfd, 1, -1 /* infinite */) == -1 && errno != EINTR)
1073 ERR("poll() failed: %s\n", strerror(errno));
1074 return FALSE;
1076 return TRUE;
1079 static void rpcrt4_sock_wait_cancel(RpcConnection_tcp *tcpc)
1081 char dummy = 1;
1083 write(tcpc->cancel_fds[1], &dummy, 1);
1086 static void rpcrt4_sock_wait_destroy(RpcConnection_tcp *tcpc)
1088 close(tcpc->cancel_fds[0]);
1089 close(tcpc->cancel_fds[1]);
1092 #else /* HAVE_SOCKETPAIR */
1094 static BOOL rpcrt4_sock_wait_init(RpcConnection_tcp *tcpc)
1096 static BOOL wsa_inited;
1097 if (!wsa_inited)
1099 WSADATA wsadata;
1100 WSAStartup(MAKEWORD(2, 2), &wsadata);
1101 /* Note: WSAStartup can be called more than once so we don't bother with
1102 * making accesses to wsa_inited thread-safe */
1103 wsa_inited = TRUE;
1105 tcpc->sock_event = CreateEventW(NULL, FALSE, FALSE, NULL);
1106 tcpc->cancel_event = CreateEventW(NULL, FALSE, FALSE, NULL);
1107 if (!tcpc->sock_event || !tcpc->cancel_event)
1109 ERR("event creation failed\n");
1110 if (tcpc->sock_event) CloseHandle(tcpc->sock_event);
1111 return FALSE;
1113 return TRUE;
1116 static BOOL rpcrt4_sock_wait_for_recv(RpcConnection_tcp *tcpc)
1118 HANDLE wait_handles[2];
1119 DWORD res;
1120 if (WSAEventSelect(tcpc->sock, tcpc->sock_event, FD_READ | FD_CLOSE) == SOCKET_ERROR)
1122 ERR("WSAEventSelect() failed with error %d\n", WSAGetLastError());
1123 return FALSE;
1125 wait_handles[0] = tcpc->sock_event;
1126 wait_handles[1] = tcpc->cancel_event;
1127 res = WaitForMultipleObjects(2, wait_handles, FALSE, INFINITE);
1128 switch (res)
1130 case WAIT_OBJECT_0:
1131 return TRUE;
1132 case WAIT_OBJECT_0 + 1:
1133 return FALSE;
1134 default:
1135 ERR("WaitForMultipleObjects() failed with error %d\n", GetLastError());
1136 return FALSE;
1140 static BOOL rpcrt4_sock_wait_for_send(RpcConnection_tcp *tcpc)
1142 DWORD res;
1143 if (WSAEventSelect(tcpc->sock, tcpc->sock_event, FD_WRITE | FD_CLOSE) == SOCKET_ERROR)
1145 ERR("WSAEventSelect() failed with error %d\n", WSAGetLastError());
1146 return FALSE;
1148 res = WaitForSingleObject(tcpc->sock_event, INFINITE);
1149 switch (res)
1151 case WAIT_OBJECT_0:
1152 return TRUE;
1153 default:
1154 ERR("WaitForMultipleObjects() failed with error %d\n", GetLastError());
1155 return FALSE;
1159 static void rpcrt4_sock_wait_cancel(RpcConnection_tcp *tcpc)
1161 SetEvent(tcpc->cancel_event);
1164 static void rpcrt4_sock_wait_destroy(RpcConnection_tcp *tcpc)
1166 CloseHandle(tcpc->sock_event);
1167 CloseHandle(tcpc->cancel_event);
1170 #endif
1172 static RpcConnection *rpcrt4_conn_tcp_alloc(void)
1174 RpcConnection_tcp *tcpc;
1175 tcpc = HeapAlloc(GetProcessHeap(), 0, sizeof(RpcConnection_tcp));
1176 if (tcpc == NULL)
1177 return NULL;
1178 tcpc->sock = -1;
1179 if (!rpcrt4_sock_wait_init(tcpc))
1181 HeapFree(GetProcessHeap(), 0, tcpc);
1182 return NULL;
1184 return &tcpc->common;
1187 static RPC_STATUS rpcrt4_ncacn_ip_tcp_open(RpcConnection* Connection)
1189 RpcConnection_tcp *tcpc = (RpcConnection_tcp *) Connection;
1190 int sock;
1191 int ret;
1192 struct addrinfo *ai;
1193 struct addrinfo *ai_cur;
1194 struct addrinfo hints;
1196 TRACE("(%s, %s)\n", Connection->NetworkAddr, Connection->Endpoint);
1198 if (tcpc->sock != -1)
1199 return RPC_S_OK;
1201 hints.ai_flags = 0;
1202 hints.ai_family = PF_UNSPEC;
1203 hints.ai_socktype = SOCK_STREAM;
1204 hints.ai_protocol = IPPROTO_TCP;
1205 hints.ai_addrlen = 0;
1206 hints.ai_addr = NULL;
1207 hints.ai_canonname = NULL;
1208 hints.ai_next = NULL;
1210 ret = getaddrinfo(Connection->NetworkAddr, Connection->Endpoint, &hints, &ai);
1211 if (ret)
1213 ERR("getaddrinfo for %s:%s failed: %s\n", Connection->NetworkAddr,
1214 Connection->Endpoint, gai_strerror(ret));
1215 return RPC_S_SERVER_UNAVAILABLE;
1218 for (ai_cur = ai; ai_cur; ai_cur = ai_cur->ai_next)
1220 int val;
1221 u_long nonblocking;
1223 if (ai_cur->ai_family != AF_INET && ai_cur->ai_family != AF_INET6)
1225 TRACE("skipping non-IP/IPv6 address family\n");
1226 continue;
1229 if (TRACE_ON(rpc))
1231 char host[256];
1232 char service[256];
1233 getnameinfo(ai_cur->ai_addr, ai_cur->ai_addrlen,
1234 host, sizeof(host), service, sizeof(service),
1235 NI_NUMERICHOST | NI_NUMERICSERV);
1236 TRACE("trying %s:%s\n", host, service);
1239 sock = socket(ai_cur->ai_family, ai_cur->ai_socktype, ai_cur->ai_protocol);
1240 if (sock == -1)
1242 WARN("socket() failed: %s\n", strerror(errno));
1243 continue;
1246 if (0>connect(sock, ai_cur->ai_addr, ai_cur->ai_addrlen))
1248 WARN("connect() failed: %s\n", strerror(errno));
1249 closesocket(sock);
1250 continue;
1253 /* RPC depends on having minimal latency so disable the Nagle algorithm */
1254 val = 1;
1255 setsockopt(sock, SOL_TCP, TCP_NODELAY, (char *)&val, sizeof(val));
1256 nonblocking = 1;
1257 ioctlsocket(sock, FIONBIO, &nonblocking);
1259 tcpc->sock = sock;
1261 freeaddrinfo(ai);
1262 TRACE("connected\n");
1263 return RPC_S_OK;
1266 freeaddrinfo(ai);
1267 ERR("couldn't connect to %s:%s\n", Connection->NetworkAddr, Connection->Endpoint);
1268 return RPC_S_SERVER_UNAVAILABLE;
1271 static RPC_STATUS rpcrt4_protseq_ncacn_ip_tcp_open_endpoint(RpcServerProtseq *protseq, const char *endpoint)
1273 RPC_STATUS status = RPC_S_CANT_CREATE_ENDPOINT;
1274 int sock;
1275 int ret;
1276 struct addrinfo *ai;
1277 struct addrinfo *ai_cur;
1278 struct addrinfo hints;
1279 RpcConnection *first_connection = NULL;
1281 TRACE("(%p, %s)\n", protseq, endpoint);
1283 hints.ai_flags = AI_PASSIVE /* for non-localhost addresses */;
1284 hints.ai_family = PF_UNSPEC;
1285 hints.ai_socktype = SOCK_STREAM;
1286 hints.ai_protocol = IPPROTO_TCP;
1287 hints.ai_addrlen = 0;
1288 hints.ai_addr = NULL;
1289 hints.ai_canonname = NULL;
1290 hints.ai_next = NULL;
1292 ret = getaddrinfo(NULL, endpoint ? endpoint : "0", &hints, &ai);
1293 if (ret)
1295 ERR("getaddrinfo for port %s failed: %s\n", endpoint,
1296 gai_strerror(ret));
1297 if ((ret == EAI_SERVICE) || (ret == EAI_NONAME))
1298 return RPC_S_INVALID_ENDPOINT_FORMAT;
1299 return RPC_S_CANT_CREATE_ENDPOINT;
1302 for (ai_cur = ai; ai_cur; ai_cur = ai_cur->ai_next)
1304 RpcConnection_tcp *tcpc;
1305 RPC_STATUS create_status;
1306 struct sockaddr_storage sa;
1307 socklen_t sa_len;
1308 char service[NI_MAXSERV];
1309 u_long nonblocking;
1311 if (ai_cur->ai_family != AF_INET && ai_cur->ai_family != AF_INET6)
1313 TRACE("skipping non-IP/IPv6 address family\n");
1314 continue;
1317 if (TRACE_ON(rpc))
1319 char host[256];
1320 getnameinfo(ai_cur->ai_addr, ai_cur->ai_addrlen,
1321 host, sizeof(host), service, sizeof(service),
1322 NI_NUMERICHOST | NI_NUMERICSERV);
1323 TRACE("trying %s:%s\n", host, service);
1326 sock = socket(ai_cur->ai_family, ai_cur->ai_socktype, ai_cur->ai_protocol);
1327 if (sock == -1)
1329 WARN("socket() failed: %s\n", strerror(errno));
1330 status = RPC_S_CANT_CREATE_ENDPOINT;
1331 continue;
1334 ret = bind(sock, ai_cur->ai_addr, ai_cur->ai_addrlen);
1335 if (ret < 0)
1337 WARN("bind failed: %s\n", strerror(errno));
1338 closesocket(sock);
1339 if (errno == EADDRINUSE)
1340 status = RPC_S_DUPLICATE_ENDPOINT;
1341 else
1342 status = RPC_S_CANT_CREATE_ENDPOINT;
1343 continue;
1346 sa_len = sizeof(sa);
1347 if (getsockname(sock, (struct sockaddr *)&sa, &sa_len))
1349 WARN("getsockname() failed: %s\n", strerror(errno));
1350 closesocket(sock);
1351 status = RPC_S_CANT_CREATE_ENDPOINT;
1352 continue;
1355 ret = getnameinfo((struct sockaddr *)&sa, sa_len,
1356 NULL, 0, service, sizeof(service),
1357 NI_NUMERICSERV);
1358 if (ret)
1360 WARN("getnameinfo failed: %s\n", gai_strerror(ret));
1361 closesocket(sock);
1362 status = RPC_S_CANT_CREATE_ENDPOINT;
1363 continue;
1366 create_status = RPCRT4_CreateConnection((RpcConnection **)&tcpc, TRUE,
1367 protseq->Protseq, NULL,
1368 service, NULL, NULL, NULL, NULL);
1369 if (create_status != RPC_S_OK)
1371 closesocket(sock);
1372 status = create_status;
1373 continue;
1376 tcpc->sock = sock;
1377 ret = listen(sock, protseq->MaxCalls);
1378 if (ret < 0)
1380 WARN("listen failed: %s\n", strerror(errno));
1381 RPCRT4_ReleaseConnection(&tcpc->common);
1382 status = RPC_S_OUT_OF_RESOURCES;
1383 continue;
1385 /* need a non-blocking socket, otherwise accept() has a potential
1386 * race-condition (poll() says it is readable, connection drops,
1387 * and accept() blocks until the next connection comes...)
1389 nonblocking = 1;
1390 ret = ioctlsocket(sock, FIONBIO, &nonblocking);
1391 if (ret < 0)
1393 WARN("couldn't make socket non-blocking, error %d\n", ret);
1394 RPCRT4_ReleaseConnection(&tcpc->common);
1395 status = RPC_S_OUT_OF_RESOURCES;
1396 continue;
1399 tcpc->common.Next = first_connection;
1400 first_connection = &tcpc->common;
1402 /* since IPv4 and IPv6 share the same port space, we only need one
1403 * successful bind to listen for both */
1404 break;
1407 freeaddrinfo(ai);
1409 /* if at least one connection was created for an endpoint then
1410 * return success */
1411 if (first_connection)
1413 RpcConnection *conn;
1415 /* find last element in list */
1416 for (conn = first_connection; conn->Next; conn = conn->Next)
1419 EnterCriticalSection(&protseq->cs);
1420 conn->Next = protseq->conn;
1421 protseq->conn = first_connection;
1422 LeaveCriticalSection(&protseq->cs);
1424 TRACE("listening on %s\n", endpoint);
1425 return RPC_S_OK;
1428 ERR("couldn't listen on port %s\n", endpoint);
1429 return status;
1432 static RPC_STATUS rpcrt4_conn_tcp_handoff(RpcConnection *old_conn, RpcConnection *new_conn)
1434 int ret;
1435 struct sockaddr_in address;
1436 socklen_t addrsize;
1437 RpcConnection_tcp *server = (RpcConnection_tcp*) old_conn;
1438 RpcConnection_tcp *client = (RpcConnection_tcp*) new_conn;
1439 u_long nonblocking;
1441 addrsize = sizeof(address);
1442 ret = accept(server->sock, (struct sockaddr*) &address, &addrsize);
1443 if (ret < 0)
1445 ERR("Failed to accept a TCP connection: error %d\n", ret);
1446 return RPC_S_OUT_OF_RESOURCES;
1448 nonblocking = 1;
1449 ioctlsocket(ret, FIONBIO, &nonblocking);
1450 client->sock = ret;
1451 TRACE("Accepted a new TCP connection\n");
1452 return RPC_S_OK;
1455 static int rpcrt4_conn_tcp_read(RpcConnection *Connection,
1456 void *buffer, unsigned int count)
1458 RpcConnection_tcp *tcpc = (RpcConnection_tcp *) Connection;
1459 int bytes_read = 0;
1460 while (bytes_read != count)
1462 int r = recv(tcpc->sock, (char *)buffer + bytes_read, count - bytes_read, 0);
1463 if (!r)
1464 return -1;
1465 else if (r > 0)
1466 bytes_read += r;
1467 else if (errno != EAGAIN)
1469 WARN("recv() failed: %s\n", strerror(errno));
1470 return -1;
1472 else
1474 if (!rpcrt4_sock_wait_for_recv(tcpc))
1475 return -1;
1478 TRACE("%d %p %u -> %d\n", tcpc->sock, buffer, count, bytes_read);
1479 return bytes_read;
1482 static int rpcrt4_conn_tcp_write(RpcConnection *Connection,
1483 const void *buffer, unsigned int count)
1485 RpcConnection_tcp *tcpc = (RpcConnection_tcp *) Connection;
1486 int bytes_written = 0;
1487 while (bytes_written != count)
1489 int r = send(tcpc->sock, (const char *)buffer + bytes_written, count - bytes_written, 0);
1490 if (r >= 0)
1491 bytes_written += r;
1492 else if (errno != EAGAIN)
1493 return -1;
1494 else
1496 if (!rpcrt4_sock_wait_for_send(tcpc))
1497 return -1;
1500 TRACE("%d %p %u -> %d\n", tcpc->sock, buffer, count, bytes_written);
1501 return bytes_written;
1504 static int rpcrt4_conn_tcp_close(RpcConnection *Connection)
1506 RpcConnection_tcp *tcpc = (RpcConnection_tcp *) Connection;
1508 TRACE("%d\n", tcpc->sock);
1510 if (tcpc->sock != -1)
1511 closesocket(tcpc->sock);
1512 tcpc->sock = -1;
1513 rpcrt4_sock_wait_destroy(tcpc);
1514 return 0;
1517 static void rpcrt4_conn_tcp_cancel_call(RpcConnection *Connection)
1519 RpcConnection_tcp *tcpc = (RpcConnection_tcp *) Connection;
1520 TRACE("%p\n", Connection);
1521 rpcrt4_sock_wait_cancel(tcpc);
1524 static int rpcrt4_conn_tcp_wait_for_incoming_data(RpcConnection *Connection)
1526 RpcConnection_tcp *tcpc = (RpcConnection_tcp *) Connection;
1528 TRACE("%p\n", Connection);
1530 if (!rpcrt4_sock_wait_for_recv(tcpc))
1531 return -1;
1532 return 0;
1535 static size_t rpcrt4_ncacn_ip_tcp_get_top_of_tower(unsigned char *tower_data,
1536 const char *networkaddr,
1537 const char *endpoint)
1539 return rpcrt4_ip_tcp_get_top_of_tower(tower_data, networkaddr,
1540 EPM_PROTOCOL_TCP, endpoint);
1543 #ifdef HAVE_SOCKETPAIR
1545 typedef struct _RpcServerProtseq_sock
1547 RpcServerProtseq common;
1548 int mgr_event_rcv;
1549 int mgr_event_snd;
1550 } RpcServerProtseq_sock;
1552 static RpcServerProtseq *rpcrt4_protseq_sock_alloc(void)
1554 RpcServerProtseq_sock *ps = HeapAlloc(GetProcessHeap(), 0, sizeof(*ps));
1555 if (ps)
1557 int fds[2];
1558 if (!socketpair(PF_UNIX, SOCK_DGRAM, 0, fds))
1560 fcntl(fds[0], F_SETFL, O_NONBLOCK);
1561 fcntl(fds[1], F_SETFL, O_NONBLOCK);
1562 ps->mgr_event_rcv = fds[0];
1563 ps->mgr_event_snd = fds[1];
1565 else
1567 ERR("socketpair failed with error %s\n", strerror(errno));
1568 HeapFree(GetProcessHeap(), 0, ps);
1569 return NULL;
1572 return &ps->common;
1575 static void rpcrt4_protseq_sock_signal_state_changed(RpcServerProtseq *protseq)
1577 RpcServerProtseq_sock *sockps = CONTAINING_RECORD(protseq, RpcServerProtseq_sock, common);
1578 char dummy = 1;
1579 write(sockps->mgr_event_snd, &dummy, sizeof(dummy));
1582 static void *rpcrt4_protseq_sock_get_wait_array(RpcServerProtseq *protseq, void *prev_array, unsigned int *count)
1584 struct pollfd *poll_info = prev_array;
1585 RpcConnection_tcp *conn;
1586 RpcServerProtseq_sock *sockps = CONTAINING_RECORD(protseq, RpcServerProtseq_sock, common);
1588 EnterCriticalSection(&protseq->cs);
1590 /* open and count connections */
1591 *count = 1;
1592 conn = (RpcConnection_tcp *)protseq->conn;
1593 while (conn) {
1594 if (conn->sock != -1)
1595 (*count)++;
1596 conn = (RpcConnection_tcp *)conn->common.Next;
1599 /* make array of connections */
1600 if (poll_info)
1601 poll_info = HeapReAlloc(GetProcessHeap(), 0, poll_info, *count*sizeof(*poll_info));
1602 else
1603 poll_info = HeapAlloc(GetProcessHeap(), 0, *count*sizeof(*poll_info));
1604 if (!poll_info)
1606 ERR("couldn't allocate poll_info\n");
1607 LeaveCriticalSection(&protseq->cs);
1608 return NULL;
1611 poll_info[0].fd = sockps->mgr_event_rcv;
1612 poll_info[0].events = POLLIN;
1613 *count = 1;
1614 conn = CONTAINING_RECORD(protseq->conn, RpcConnection_tcp, common);
1615 while (conn) {
1616 if (conn->sock != -1)
1618 poll_info[*count].fd = conn->sock;
1619 poll_info[*count].events = POLLIN;
1620 (*count)++;
1622 conn = CONTAINING_RECORD(conn->common.Next, RpcConnection_tcp, common);
1624 LeaveCriticalSection(&protseq->cs);
1625 return poll_info;
1628 static void rpcrt4_protseq_sock_free_wait_array(RpcServerProtseq *protseq, void *array)
1630 HeapFree(GetProcessHeap(), 0, array);
1633 static int rpcrt4_protseq_sock_wait_for_new_connection(RpcServerProtseq *protseq, unsigned int count, void *wait_array)
1635 struct pollfd *poll_info = wait_array;
1636 int ret;
1637 unsigned int i;
1638 RpcConnection *cconn;
1639 RpcConnection_tcp *conn;
1641 if (!poll_info)
1642 return -1;
1644 ret = poll(poll_info, count, -1);
1645 if (ret < 0)
1647 ERR("poll failed with error %d\n", ret);
1648 return -1;
1651 for (i = 0; i < count; i++)
1652 if (poll_info[i].revents & POLLIN)
1654 /* RPC server event */
1655 if (i == 0)
1657 char dummy;
1658 read(poll_info[0].fd, &dummy, sizeof(dummy));
1659 return 0;
1662 /* find which connection got a RPC */
1663 EnterCriticalSection(&protseq->cs);
1664 conn = CONTAINING_RECORD(protseq->conn, RpcConnection_tcp, common);
1665 while (conn) {
1666 if (poll_info[i].fd == conn->sock) break;
1667 conn = CONTAINING_RECORD(conn->common.Next, RpcConnection_tcp, common);
1669 cconn = NULL;
1670 if (conn)
1671 RPCRT4_SpawnConnection(&cconn, &conn->common);
1672 else
1673 ERR("failed to locate connection for fd %d\n", poll_info[i].fd);
1674 LeaveCriticalSection(&protseq->cs);
1675 if (cconn)
1676 RPCRT4_new_client(cconn);
1677 else
1678 return -1;
1681 return 1;
1684 #else /* HAVE_SOCKETPAIR */
1686 typedef struct _RpcServerProtseq_sock
1688 RpcServerProtseq common;
1689 HANDLE mgr_event;
1690 } RpcServerProtseq_sock;
1692 static RpcServerProtseq *rpcrt4_protseq_sock_alloc(void)
1694 RpcServerProtseq_sock *ps = HeapAlloc(GetProcessHeap(), 0, sizeof(*ps));
1695 if (ps)
1697 static BOOL wsa_inited;
1698 if (!wsa_inited)
1700 WSADATA wsadata;
1701 WSAStartup(MAKEWORD(2, 2), &wsadata);
1702 /* Note: WSAStartup can be called more than once so we don't bother with
1703 * making accesses to wsa_inited thread-safe */
1704 wsa_inited = TRUE;
1706 ps->mgr_event = CreateEventW(NULL, FALSE, FALSE, NULL);
1708 return &ps->common;
1711 static void rpcrt4_protseq_sock_signal_state_changed(RpcServerProtseq *protseq)
1713 RpcServerProtseq_sock *sockps = CONTAINING_RECORD(protseq, RpcServerProtseq_sock, common);
1714 SetEvent(sockps->mgr_event);
1717 static void *rpcrt4_protseq_sock_get_wait_array(RpcServerProtseq *protseq, void *prev_array, unsigned int *count)
1719 HANDLE *objs = prev_array;
1720 RpcConnection_tcp *conn;
1721 RpcServerProtseq_sock *sockps = CONTAINING_RECORD(protseq, RpcServerProtseq_sock, common);
1723 EnterCriticalSection(&protseq->cs);
1725 /* open and count connections */
1726 *count = 1;
1727 conn = CONTAINING_RECORD(protseq->conn, RpcConnection_tcp, common);
1728 while (conn)
1730 if (conn->sock != -1)
1731 (*count)++;
1732 conn = CONTAINING_RECORD(conn->common.Next, RpcConnection_tcp, common);
1735 /* make array of connections */
1736 if (objs)
1737 objs = HeapReAlloc(GetProcessHeap(), 0, objs, *count*sizeof(HANDLE));
1738 else
1739 objs = HeapAlloc(GetProcessHeap(), 0, *count*sizeof(HANDLE));
1740 if (!objs)
1742 ERR("couldn't allocate objs\n");
1743 LeaveCriticalSection(&protseq->cs);
1744 return NULL;
1747 objs[0] = sockps->mgr_event;
1748 *count = 1;
1749 conn = CONTAINING_RECORD(protseq->conn, RpcConnection_tcp, common);
1750 while (conn)
1752 if (conn->sock != -1)
1754 int res = WSAEventSelect(conn->sock, conn->sock_event, FD_ACCEPT);
1755 if (res == SOCKET_ERROR)
1756 ERR("WSAEventSelect() failed with error %d\n", WSAGetLastError());
1757 else
1759 objs[*count] = conn->sock_event;
1760 (*count)++;
1763 conn = CONTAINING_RECORD(conn->common.Next, RpcConnection_tcp, common);
1765 LeaveCriticalSection(&protseq->cs);
1766 return objs;
1769 static void rpcrt4_protseq_sock_free_wait_array(RpcServerProtseq *protseq, void *array)
1771 HeapFree(GetProcessHeap(), 0, array);
1774 static int rpcrt4_protseq_sock_wait_for_new_connection(RpcServerProtseq *protseq, unsigned int count, void *wait_array)
1776 HANDLE b_handle;
1777 HANDLE *objs = wait_array;
1778 DWORD res;
1779 RpcConnection *cconn;
1780 RpcConnection_tcp *conn;
1782 if (!objs)
1783 return -1;
1787 /* an alertable wait isn't strictly necessary, but due to our
1788 * overlapped I/O implementation in Wine we need to free some memory
1789 * by the file user APC being called, even if no completion routine was
1790 * specified at the time of starting the async operation */
1791 res = WaitForMultipleObjectsEx(count, objs, FALSE, INFINITE, TRUE);
1792 } while (res == WAIT_IO_COMPLETION);
1794 if (res == WAIT_OBJECT_0)
1795 return 0;
1796 else if (res == WAIT_FAILED)
1798 ERR("wait failed with error %d\n", GetLastError());
1799 return -1;
1801 else
1803 b_handle = objs[res - WAIT_OBJECT_0];
1804 /* find which connection got a RPC */
1805 EnterCriticalSection(&protseq->cs);
1806 conn = CONTAINING_RECORD(protseq->conn, RpcConnection_tcp, common);
1807 while (conn)
1809 if (b_handle == conn->sock_event) break;
1810 conn = CONTAINING_RECORD(conn->common.Next, RpcConnection_tcp, common);
1812 cconn = NULL;
1813 if (conn)
1814 RPCRT4_SpawnConnection(&cconn, &conn->common);
1815 else
1816 ERR("failed to locate connection for handle %p\n", b_handle);
1817 LeaveCriticalSection(&protseq->cs);
1818 if (cconn)
1820 RPCRT4_new_client(cconn);
1821 return 1;
1823 else return -1;
1827 #endif /* HAVE_SOCKETPAIR */
1829 static RPC_STATUS rpcrt4_ncacn_ip_tcp_parse_top_of_tower(const unsigned char *tower_data,
1830 size_t tower_size,
1831 char **networkaddr,
1832 char **endpoint)
1834 return rpcrt4_ip_tcp_parse_top_of_tower(tower_data, tower_size,
1835 networkaddr, EPM_PROTOCOL_TCP,
1836 endpoint);
1839 /**** ncacn_http support ****/
1841 /* 60 seconds is the period native uses */
1842 #define HTTP_IDLE_TIME 60000
1844 /* reference counted to avoid a race between a cancelled call's connection
1845 * being destroyed and the asynchronous InternetReadFileEx call being
1846 * completed */
1847 typedef struct _RpcHttpAsyncData
1849 LONG refs;
1850 HANDLE completion_event;
1851 WORD async_result;
1852 INTERNET_BUFFERSA inet_buffers;
1853 CRITICAL_SECTION cs;
1854 } RpcHttpAsyncData;
1856 static ULONG RpcHttpAsyncData_AddRef(RpcHttpAsyncData *data)
1858 return InterlockedIncrement(&data->refs);
1861 static ULONG RpcHttpAsyncData_Release(RpcHttpAsyncData *data)
1863 ULONG refs = InterlockedDecrement(&data->refs);
1864 if (!refs)
1866 TRACE("destroying async data %p\n", data);
1867 CloseHandle(data->completion_event);
1868 HeapFree(GetProcessHeap(), 0, data->inet_buffers.lpvBuffer);
1869 data->cs.DebugInfo->Spare[0] = 0;
1870 DeleteCriticalSection(&data->cs);
1871 HeapFree(GetProcessHeap(), 0, data);
1873 return refs;
1876 static void prepare_async_request(RpcHttpAsyncData *async_data)
1878 ResetEvent(async_data->completion_event);
1879 RpcHttpAsyncData_AddRef(async_data);
1882 static RPC_STATUS wait_async_request(RpcHttpAsyncData *async_data, BOOL call_ret, HANDLE cancel_event)
1884 HANDLE handles[2] = { async_data->completion_event, cancel_event };
1885 DWORD res;
1887 if(call_ret) {
1888 RpcHttpAsyncData_Release(async_data);
1889 return RPC_S_OK;
1892 if(GetLastError() != ERROR_IO_PENDING) {
1893 RpcHttpAsyncData_Release(async_data);
1894 ERR("Request failed with error %d\n", GetLastError());
1895 return RPC_S_SERVER_UNAVAILABLE;
1898 res = WaitForMultipleObjects(2, handles, FALSE, DEFAULT_NCACN_HTTP_TIMEOUT);
1899 if(res != WAIT_OBJECT_0) {
1900 TRACE("Cancelled\n");
1901 return RPC_S_CALL_CANCELLED;
1904 if(async_data->async_result) {
1905 ERR("Async request failed with error %d\n", async_data->async_result);
1906 return RPC_S_SERVER_UNAVAILABLE;
1909 return RPC_S_OK;
1912 struct authinfo
1914 DWORD scheme;
1915 CredHandle cred;
1916 CtxtHandle ctx;
1917 TimeStamp exp;
1918 ULONG attr;
1919 ULONG max_token;
1920 char *data;
1921 unsigned int data_len;
1922 BOOL finished; /* finished authenticating */
1925 typedef struct _RpcConnection_http
1927 RpcConnection common;
1928 HINTERNET app_info;
1929 HINTERNET session;
1930 HINTERNET in_request;
1931 HINTERNET out_request;
1932 WCHAR *servername;
1933 HANDLE timer_cancelled;
1934 HANDLE cancel_event;
1935 DWORD last_sent_time;
1936 ULONG bytes_received;
1937 ULONG flow_control_mark; /* send a control packet to the server when this many bytes received */
1938 ULONG flow_control_increment; /* number of bytes to increment flow_control_mark by */
1939 UUID connection_uuid;
1940 UUID in_pipe_uuid;
1941 UUID out_pipe_uuid;
1942 RpcHttpAsyncData *async_data;
1943 } RpcConnection_http;
1945 static RpcConnection *rpcrt4_ncacn_http_alloc(void)
1947 RpcConnection_http *httpc;
1948 httpc = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*httpc));
1949 if (!httpc) return NULL;
1950 httpc->async_data = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(RpcHttpAsyncData));
1951 if (!httpc->async_data)
1953 HeapFree(GetProcessHeap(), 0, httpc);
1954 return NULL;
1956 TRACE("async data = %p\n", httpc->async_data);
1957 httpc->cancel_event = CreateEventW(NULL, FALSE, FALSE, NULL);
1958 httpc->async_data->refs = 1;
1959 httpc->async_data->inet_buffers.dwStructSize = sizeof(INTERNET_BUFFERSA);
1960 httpc->async_data->inet_buffers.lpvBuffer = NULL;
1961 InitializeCriticalSection(&httpc->async_data->cs);
1962 httpc->async_data->cs.DebugInfo->Spare[0] = (DWORD_PTR)(__FILE__ ": RpcHttpAsyncData.cs");
1963 return &httpc->common;
1966 typedef struct _HttpTimerThreadData
1968 PVOID timer_param;
1969 DWORD *last_sent_time;
1970 HANDLE timer_cancelled;
1971 } HttpTimerThreadData;
1973 static VOID rpcrt4_http_keep_connection_active_timer_proc(PVOID param, BOOLEAN dummy)
1975 HINTERNET in_request = param;
1976 RpcPktHdr *idle_pkt;
1978 idle_pkt = RPCRT4_BuildHttpHeader(NDR_LOCAL_DATA_REPRESENTATION, 0x0001,
1979 0, 0);
1980 if (idle_pkt)
1982 DWORD bytes_written;
1983 InternetWriteFile(in_request, idle_pkt, idle_pkt->common.frag_len, &bytes_written);
1984 RPCRT4_FreeHeader(idle_pkt);
1988 static inline DWORD rpcrt4_http_timer_calc_timeout(DWORD *last_sent_time)
1990 DWORD cur_time = GetTickCount();
1991 DWORD cached_last_sent_time = *last_sent_time;
1992 return HTTP_IDLE_TIME - (cur_time - cached_last_sent_time > HTTP_IDLE_TIME ? 0 : cur_time - cached_last_sent_time);
1995 static DWORD CALLBACK rpcrt4_http_timer_thread(PVOID param)
1997 HttpTimerThreadData *data_in = param;
1998 HttpTimerThreadData data;
1999 DWORD timeout;
2001 data = *data_in;
2002 HeapFree(GetProcessHeap(), 0, data_in);
2004 for (timeout = HTTP_IDLE_TIME;
2005 WaitForSingleObject(data.timer_cancelled, timeout) == WAIT_TIMEOUT;
2006 timeout = rpcrt4_http_timer_calc_timeout(data.last_sent_time))
2008 /* are we too soon after last send? */
2009 if (GetTickCount() - *data.last_sent_time < HTTP_IDLE_TIME)
2010 continue;
2011 rpcrt4_http_keep_connection_active_timer_proc(data.timer_param, TRUE);
2014 CloseHandle(data.timer_cancelled);
2015 return 0;
2018 static VOID WINAPI rpcrt4_http_internet_callback(
2019 HINTERNET hInternet,
2020 DWORD_PTR dwContext,
2021 DWORD dwInternetStatus,
2022 LPVOID lpvStatusInformation,
2023 DWORD dwStatusInformationLength)
2025 RpcHttpAsyncData *async_data = (RpcHttpAsyncData *)dwContext;
2027 switch (dwInternetStatus)
2029 case INTERNET_STATUS_REQUEST_COMPLETE:
2030 TRACE("INTERNET_STATUS_REQUEST_COMPLETED\n");
2031 if (async_data)
2033 INTERNET_ASYNC_RESULT *async_result = lpvStatusInformation;
2035 async_data->async_result = async_result->dwResult ? ERROR_SUCCESS : async_result->dwError;
2036 SetEvent(async_data->completion_event);
2037 RpcHttpAsyncData_Release(async_data);
2039 break;
2043 static RPC_STATUS rpcrt4_http_check_response(HINTERNET hor)
2045 BOOL ret;
2046 DWORD status_code;
2047 DWORD size;
2048 DWORD index;
2049 WCHAR buf[32];
2050 WCHAR *status_text = buf;
2051 TRACE("\n");
2053 index = 0;
2054 size = sizeof(status_code);
2055 ret = HttpQueryInfoW(hor, HTTP_QUERY_STATUS_CODE|HTTP_QUERY_FLAG_NUMBER, &status_code, &size, &index);
2056 if (!ret)
2057 return GetLastError();
2058 if (status_code == HTTP_STATUS_OK)
2059 return RPC_S_OK;
2060 index = 0;
2061 size = sizeof(buf);
2062 ret = HttpQueryInfoW(hor, HTTP_QUERY_STATUS_TEXT, status_text, &size, &index);
2063 if (!ret && GetLastError() == ERROR_INSUFFICIENT_BUFFER)
2065 status_text = HeapAlloc(GetProcessHeap(), 0, size);
2066 ret = HttpQueryInfoW(hor, HTTP_QUERY_STATUS_TEXT, status_text, &size, &index);
2069 ERR("server returned: %d %s\n", status_code, ret ? debugstr_w(status_text) : "<status text unavailable>");
2070 if(status_text != buf) HeapFree(GetProcessHeap(), 0, status_text);
2072 if (status_code == HTTP_STATUS_DENIED)
2073 return ERROR_ACCESS_DENIED;
2074 return RPC_S_SERVER_UNAVAILABLE;
2077 static RPC_STATUS rpcrt4_http_internet_connect(RpcConnection_http *httpc)
2079 static const WCHAR wszUserAgent[] = {'M','S','R','P','C',0};
2080 LPWSTR proxy = NULL;
2081 LPWSTR user = NULL;
2082 LPWSTR password = NULL;
2083 LPWSTR servername = NULL;
2084 const WCHAR *option;
2085 INTERNET_PORT port;
2087 if (httpc->common.QOS &&
2088 (httpc->common.QOS->qos->AdditionalSecurityInfoType == RPC_C_AUTHN_INFO_TYPE_HTTP))
2090 const RPC_HTTP_TRANSPORT_CREDENTIALS_W *http_cred = httpc->common.QOS->qos->u.HttpCredentials;
2091 if (http_cred->TransportCredentials)
2093 WCHAR *p;
2094 const SEC_WINNT_AUTH_IDENTITY_W *cred = http_cred->TransportCredentials;
2095 ULONG len = cred->DomainLength + 1 + cred->UserLength;
2096 user = HeapAlloc(GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR));
2097 if (!user)
2098 return RPC_S_OUT_OF_RESOURCES;
2099 p = user;
2100 if (cred->DomainLength)
2102 memcpy(p, cred->Domain, cred->DomainLength * sizeof(WCHAR));
2103 p += cred->DomainLength;
2104 *p = '\\';
2105 p++;
2107 memcpy(p, cred->User, cred->UserLength * sizeof(WCHAR));
2108 p[cred->UserLength] = 0;
2110 password = RPCRT4_strndupW(cred->Password, cred->PasswordLength);
2114 for (option = httpc->common.NetworkOptions; option;
2115 option = (strchrW(option, ',') ? strchrW(option, ',')+1 : NULL))
2117 static const WCHAR wszRpcProxy[] = {'R','p','c','P','r','o','x','y','=',0};
2118 static const WCHAR wszHttpProxy[] = {'H','t','t','p','P','r','o','x','y','=',0};
2120 if (!strncmpiW(option, wszRpcProxy, sizeof(wszRpcProxy)/sizeof(wszRpcProxy[0])-1))
2122 const WCHAR *value_start = option + sizeof(wszRpcProxy)/sizeof(wszRpcProxy[0])-1;
2123 const WCHAR *value_end;
2124 const WCHAR *p;
2126 value_end = strchrW(option, ',');
2127 if (!value_end)
2128 value_end = value_start + strlenW(value_start);
2129 for (p = value_start; p < value_end; p++)
2130 if (*p == ':')
2132 port = atoiW(p+1);
2133 value_end = p;
2134 break;
2136 TRACE("RpcProxy value is %s\n", debugstr_wn(value_start, value_end-value_start));
2137 servername = RPCRT4_strndupW(value_start, value_end-value_start);
2139 else if (!strncmpiW(option, wszHttpProxy, sizeof(wszHttpProxy)/sizeof(wszHttpProxy[0])-1))
2141 const WCHAR *value_start = option + sizeof(wszHttpProxy)/sizeof(wszHttpProxy[0])-1;
2142 const WCHAR *value_end;
2144 value_end = strchrW(option, ',');
2145 if (!value_end)
2146 value_end = value_start + strlenW(value_start);
2147 TRACE("HttpProxy value is %s\n", debugstr_wn(value_start, value_end-value_start));
2148 proxy = RPCRT4_strndupW(value_start, value_end-value_start);
2150 else
2151 FIXME("unhandled option %s\n", debugstr_w(option));
2154 httpc->app_info = InternetOpenW(wszUserAgent, proxy ? INTERNET_OPEN_TYPE_PROXY : INTERNET_OPEN_TYPE_PRECONFIG,
2155 NULL, NULL, INTERNET_FLAG_ASYNC);
2156 if (!httpc->app_info)
2158 HeapFree(GetProcessHeap(), 0, password);
2159 HeapFree(GetProcessHeap(), 0, user);
2160 HeapFree(GetProcessHeap(), 0, proxy);
2161 HeapFree(GetProcessHeap(), 0, servername);
2162 ERR("InternetOpenW failed with error %d\n", GetLastError());
2163 return RPC_S_SERVER_UNAVAILABLE;
2165 InternetSetStatusCallbackW(httpc->app_info, rpcrt4_http_internet_callback);
2167 /* if no RpcProxy option specified, set the HTTP server address to the
2168 * RPC server address */
2169 if (!servername)
2171 servername = HeapAlloc(GetProcessHeap(), 0, (strlen(httpc->common.NetworkAddr) + 1)*sizeof(WCHAR));
2172 if (!servername)
2174 HeapFree(GetProcessHeap(), 0, password);
2175 HeapFree(GetProcessHeap(), 0, user);
2176 HeapFree(GetProcessHeap(), 0, proxy);
2177 return RPC_S_OUT_OF_RESOURCES;
2179 MultiByteToWideChar(CP_ACP, 0, httpc->common.NetworkAddr, -1, servername, strlen(httpc->common.NetworkAddr) + 1);
2182 port = (httpc->common.QOS &&
2183 (httpc->common.QOS->qos->AdditionalSecurityInfoType == RPC_C_AUTHN_INFO_TYPE_HTTP) &&
2184 (httpc->common.QOS->qos->u.HttpCredentials->Flags & RPC_C_HTTP_FLAG_USE_SSL)) ?
2185 INTERNET_DEFAULT_HTTPS_PORT : INTERNET_DEFAULT_HTTP_PORT;
2187 httpc->session = InternetConnectW(httpc->app_info, servername, port, user, password,
2188 INTERNET_SERVICE_HTTP, 0, 0);
2190 HeapFree(GetProcessHeap(), 0, password);
2191 HeapFree(GetProcessHeap(), 0, user);
2192 HeapFree(GetProcessHeap(), 0, proxy);
2194 if (!httpc->session)
2196 ERR("InternetConnectW failed with error %d\n", GetLastError());
2197 HeapFree(GetProcessHeap(), 0, servername);
2198 return RPC_S_SERVER_UNAVAILABLE;
2200 httpc->servername = servername;
2201 return RPC_S_OK;
2204 static RPC_STATUS send_echo_request(HINTERNET req, RpcHttpAsyncData *async_data, HANDLE cancel_event)
2206 DWORD bytes_read;
2207 BYTE buf[20];
2208 BOOL ret;
2209 RPC_STATUS status;
2211 TRACE("sending echo request to server\n");
2213 prepare_async_request(async_data);
2214 ret = HttpSendRequestW(req, NULL, 0, NULL, 0);
2215 status = wait_async_request(async_data, ret, cancel_event);
2216 if (status != RPC_S_OK) return status;
2218 status = rpcrt4_http_check_response(req);
2219 if (status != RPC_S_OK) return status;
2221 InternetReadFile(req, buf, sizeof(buf), &bytes_read);
2222 /* FIXME: do something with retrieved data */
2224 return RPC_S_OK;
2227 /* prepare the in pipe for use by RPC packets */
2228 static RPC_STATUS rpcrt4_http_prepare_in_pipe(HINTERNET in_request, RpcHttpAsyncData *async_data, HANDLE cancel_event,
2229 const UUID *connection_uuid, const UUID *in_pipe_uuid,
2230 const UUID *association_uuid, BOOL authorized)
2232 BOOL ret;
2233 RPC_STATUS status;
2234 RpcPktHdr *hdr;
2235 INTERNET_BUFFERSW buffers_in;
2236 DWORD bytes_written;
2238 if (!authorized)
2240 /* ask wininet to authorize, if necessary */
2241 status = send_echo_request(in_request, async_data, cancel_event);
2242 if (status != RPC_S_OK) return status;
2244 memset(&buffers_in, 0, sizeof(buffers_in));
2245 buffers_in.dwStructSize = sizeof(buffers_in);
2246 /* FIXME: get this from the registry */
2247 buffers_in.dwBufferTotal = 1024 * 1024 * 1024; /* 1Gb */
2248 prepare_async_request(async_data);
2249 ret = HttpSendRequestExW(in_request, &buffers_in, NULL, 0, 0);
2250 status = wait_async_request(async_data, ret, cancel_event);
2251 if (status != RPC_S_OK) return status;
2253 TRACE("sending HTTP connect header to server\n");
2254 hdr = RPCRT4_BuildHttpConnectHeader(FALSE, connection_uuid, in_pipe_uuid, association_uuid);
2255 if (!hdr) return RPC_S_OUT_OF_RESOURCES;
2256 ret = InternetWriteFile(in_request, hdr, hdr->common.frag_len, &bytes_written);
2257 RPCRT4_FreeHeader(hdr);
2258 if (!ret)
2260 ERR("InternetWriteFile failed with error %d\n", GetLastError());
2261 return RPC_S_SERVER_UNAVAILABLE;
2264 return RPC_S_OK;
2267 static RPC_STATUS rpcrt4_http_read_http_packet(HINTERNET request, RpcPktHdr *hdr, BYTE **data)
2269 BOOL ret;
2270 DWORD bytes_read;
2271 unsigned short data_len;
2273 ret = InternetReadFile(request, hdr, sizeof(hdr->common), &bytes_read);
2274 if (!ret)
2275 return RPC_S_SERVER_UNAVAILABLE;
2276 if (hdr->common.ptype != PKT_HTTP || hdr->common.frag_len < sizeof(hdr->http))
2278 ERR("wrong packet type received %d or wrong frag_len %d\n",
2279 hdr->common.ptype, hdr->common.frag_len);
2280 return RPC_S_PROTOCOL_ERROR;
2283 ret = InternetReadFile(request, &hdr->common + 1, sizeof(hdr->http) - sizeof(hdr->common), &bytes_read);
2284 if (!ret)
2285 return RPC_S_SERVER_UNAVAILABLE;
2287 data_len = hdr->common.frag_len - sizeof(hdr->http);
2288 if (data_len)
2290 *data = HeapAlloc(GetProcessHeap(), 0, data_len);
2291 if (!*data)
2292 return RPC_S_OUT_OF_RESOURCES;
2293 ret = InternetReadFile(request, *data, data_len, &bytes_read);
2294 if (!ret)
2296 HeapFree(GetProcessHeap(), 0, *data);
2297 return RPC_S_SERVER_UNAVAILABLE;
2300 else
2301 *data = NULL;
2303 if (!RPCRT4_IsValidHttpPacket(hdr, *data, data_len))
2305 ERR("invalid http packet\n");
2306 return RPC_S_PROTOCOL_ERROR;
2309 return RPC_S_OK;
2312 /* prepare the out pipe for use by RPC packets */
2313 static RPC_STATUS rpcrt4_http_prepare_out_pipe(HINTERNET out_request, RpcHttpAsyncData *async_data,
2314 HANDLE cancel_event, const UUID *connection_uuid,
2315 const UUID *out_pipe_uuid, ULONG *flow_control_increment,
2316 BOOL authorized)
2318 BOOL ret;
2319 RPC_STATUS status;
2320 RpcPktHdr *hdr;
2321 BYTE *data_from_server;
2322 RpcPktHdr pkt_from_server;
2323 ULONG field1, field3;
2324 DWORD bytes_read;
2325 BYTE buf[20];
2327 if (!authorized)
2329 /* ask wininet to authorize, if necessary */
2330 status = send_echo_request(out_request, async_data, cancel_event);
2331 if (status != RPC_S_OK) return status;
2333 else
2334 InternetReadFile(out_request, buf, sizeof(buf), &bytes_read);
2336 hdr = RPCRT4_BuildHttpConnectHeader(TRUE, connection_uuid, out_pipe_uuid, NULL);
2337 if (!hdr) return RPC_S_OUT_OF_RESOURCES;
2339 TRACE("sending HTTP connect header to server\n");
2340 prepare_async_request(async_data);
2341 ret = HttpSendRequestW(out_request, NULL, 0, hdr, hdr->common.frag_len);
2342 status = wait_async_request(async_data, ret, cancel_event);
2343 RPCRT4_FreeHeader(hdr);
2344 if (status != RPC_S_OK) return status;
2346 status = rpcrt4_http_check_response(out_request);
2347 if (status != RPC_S_OK) return status;
2349 status = rpcrt4_http_read_http_packet(out_request, &pkt_from_server,
2350 &data_from_server);
2351 if (status != RPC_S_OK) return status;
2352 status = RPCRT4_ParseHttpPrepareHeader1(&pkt_from_server, data_from_server,
2353 &field1);
2354 HeapFree(GetProcessHeap(), 0, data_from_server);
2355 if (status != RPC_S_OK) return status;
2356 TRACE("received (%d) from first prepare header\n", field1);
2358 for (;;)
2360 status = rpcrt4_http_read_http_packet(out_request, &pkt_from_server,
2361 &data_from_server);
2362 if (status != RPC_S_OK) return status;
2363 if (pkt_from_server.http.flags != 0x0001) break;
2365 TRACE("http idle packet, waiting for real packet\n");
2366 HeapFree(GetProcessHeap(), 0, data_from_server);
2367 if (pkt_from_server.http.num_data_items != 0)
2369 ERR("HTTP idle packet should have no data items instead of %d\n",
2370 pkt_from_server.http.num_data_items);
2371 return RPC_S_PROTOCOL_ERROR;
2374 status = RPCRT4_ParseHttpPrepareHeader2(&pkt_from_server, data_from_server,
2375 &field1, flow_control_increment,
2376 &field3);
2377 HeapFree(GetProcessHeap(), 0, data_from_server);
2378 if (status != RPC_S_OK) return status;
2379 TRACE("received (0x%08x 0x%08x %d) from second prepare header\n", field1, *flow_control_increment, field3);
2381 return RPC_S_OK;
2384 static UINT encode_base64(const char *bin, unsigned int len, WCHAR *base64)
2386 static const char enc[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
2387 UINT i = 0, x;
2389 while (len > 0)
2391 /* first 6 bits, all from bin[0] */
2392 base64[i++] = enc[(bin[0] & 0xfc) >> 2];
2393 x = (bin[0] & 3) << 4;
2395 /* next 6 bits, 2 from bin[0] and 4 from bin[1] */
2396 if (len == 1)
2398 base64[i++] = enc[x];
2399 base64[i++] = '=';
2400 base64[i++] = '=';
2401 break;
2403 base64[i++] = enc[x | ((bin[1] & 0xf0) >> 4)];
2404 x = (bin[1] & 0x0f) << 2;
2406 /* next 6 bits 4 from bin[1] and 2 from bin[2] */
2407 if (len == 2)
2409 base64[i++] = enc[x];
2410 base64[i++] = '=';
2411 break;
2413 base64[i++] = enc[x | ((bin[2] & 0xc0) >> 6)];
2415 /* last 6 bits, all from bin [2] */
2416 base64[i++] = enc[bin[2] & 0x3f];
2417 bin += 3;
2418 len -= 3;
2420 base64[i] = 0;
2421 return i;
2424 static inline char decode_char( WCHAR c )
2426 if (c >= 'A' && c <= 'Z') return c - 'A';
2427 if (c >= 'a' && c <= 'z') return c - 'a' + 26;
2428 if (c >= '0' && c <= '9') return c - '0' + 52;
2429 if (c == '+') return 62;
2430 if (c == '/') return 63;
2431 return 64;
2434 static unsigned int decode_base64( const WCHAR *base64, unsigned int len, char *buf )
2436 unsigned int i = 0;
2437 char c0, c1, c2, c3;
2438 const WCHAR *p = base64;
2440 while (len > 4)
2442 if ((c0 = decode_char( p[0] )) > 63) return 0;
2443 if ((c1 = decode_char( p[1] )) > 63) return 0;
2444 if ((c2 = decode_char( p[2] )) > 63) return 0;
2445 if ((c3 = decode_char( p[3] )) > 63) return 0;
2447 if (buf)
2449 buf[i + 0] = (c0 << 2) | (c1 >> 4);
2450 buf[i + 1] = (c1 << 4) | (c2 >> 2);
2451 buf[i + 2] = (c2 << 6) | c3;
2453 len -= 4;
2454 i += 3;
2455 p += 4;
2457 if (p[2] == '=')
2459 if ((c0 = decode_char( p[0] )) > 63) return 0;
2460 if ((c1 = decode_char( p[1] )) > 63) return 0;
2462 if (buf) buf[i] = (c0 << 2) | (c1 >> 4);
2463 i++;
2465 else if (p[3] == '=')
2467 if ((c0 = decode_char( p[0] )) > 63) return 0;
2468 if ((c1 = decode_char( p[1] )) > 63) return 0;
2469 if ((c2 = decode_char( p[2] )) > 63) return 0;
2471 if (buf)
2473 buf[i + 0] = (c0 << 2) | (c1 >> 4);
2474 buf[i + 1] = (c1 << 4) | (c2 >> 2);
2476 i += 2;
2478 else
2480 if ((c0 = decode_char( p[0] )) > 63) return 0;
2481 if ((c1 = decode_char( p[1] )) > 63) return 0;
2482 if ((c2 = decode_char( p[2] )) > 63) return 0;
2483 if ((c3 = decode_char( p[3] )) > 63) return 0;
2485 if (buf)
2487 buf[i + 0] = (c0 << 2) | (c1 >> 4);
2488 buf[i + 1] = (c1 << 4) | (c2 >> 2);
2489 buf[i + 2] = (c2 << 6) | c3;
2491 i += 3;
2493 return i;
2496 static struct authinfo *alloc_authinfo(void)
2498 struct authinfo *ret;
2500 if (!(ret = HeapAlloc(GetProcessHeap(), 0, sizeof(*ret) ))) return NULL;
2502 SecInvalidateHandle(&ret->cred);
2503 SecInvalidateHandle(&ret->ctx);
2504 memset(&ret->exp, 0, sizeof(ret->exp));
2505 ret->scheme = 0;
2506 ret->attr = 0;
2507 ret->max_token = 0;
2508 ret->data = NULL;
2509 ret->data_len = 0;
2510 ret->finished = FALSE;
2511 return ret;
2514 static void destroy_authinfo(struct authinfo *info)
2516 if (!info) return;
2518 if (SecIsValidHandle(&info->ctx))
2519 DeleteSecurityContext(&info->ctx);
2520 if (SecIsValidHandle(&info->cred))
2521 FreeCredentialsHandle(&info->cred);
2523 HeapFree(GetProcessHeap(), 0, info->data);
2524 HeapFree(GetProcessHeap(), 0, info);
2527 static const WCHAR basicW[] = {'B','a','s','i','c',0};
2528 static const WCHAR ntlmW[] = {'N','T','L','M',0};
2529 static const WCHAR passportW[] = {'P','a','s','s','p','o','r','t',0};
2530 static const WCHAR digestW[] = {'D','i','g','e','s','t',0};
2531 static const WCHAR negotiateW[] = {'N','e','g','o','t','i','a','t','e',0};
2533 static const struct
2535 const WCHAR *str;
2536 unsigned int len;
2537 DWORD scheme;
2539 auth_schemes[] =
2541 { basicW, ARRAYSIZE(basicW) - 1, RPC_C_HTTP_AUTHN_SCHEME_BASIC },
2542 { ntlmW, ARRAYSIZE(ntlmW) - 1, RPC_C_HTTP_AUTHN_SCHEME_NTLM },
2543 { passportW, ARRAYSIZE(passportW) - 1, RPC_C_HTTP_AUTHN_SCHEME_PASSPORT },
2544 { digestW, ARRAYSIZE(digestW) - 1, RPC_C_HTTP_AUTHN_SCHEME_DIGEST },
2545 { negotiateW, ARRAYSIZE(negotiateW) - 1, RPC_C_HTTP_AUTHN_SCHEME_NEGOTIATE }
2547 static const unsigned int num_auth_schemes = sizeof(auth_schemes)/sizeof(auth_schemes[0]);
2549 static DWORD auth_scheme_from_header( const WCHAR *header )
2551 unsigned int i;
2552 for (i = 0; i < num_auth_schemes; i++)
2554 if (!strncmpiW( header, auth_schemes[i].str, auth_schemes[i].len ) &&
2555 (header[auth_schemes[i].len] == ' ' || !header[auth_schemes[i].len])) return auth_schemes[i].scheme;
2557 return 0;
2560 static BOOL get_authvalue(HINTERNET request, DWORD scheme, WCHAR *buffer, DWORD buflen)
2562 DWORD len, index = 0;
2563 for (;;)
2565 len = buflen;
2566 if (!HttpQueryInfoW(request, HTTP_QUERY_WWW_AUTHENTICATE, buffer, &len, &index)) return FALSE;
2567 if (auth_scheme_from_header(buffer) == scheme) break;
2569 return TRUE;
2572 static RPC_STATUS do_authorization(HINTERNET request, SEC_WCHAR *servername,
2573 const RPC_HTTP_TRANSPORT_CREDENTIALS_W *creds, struct authinfo **auth_ptr)
2575 struct authinfo *info = *auth_ptr;
2576 SEC_WINNT_AUTH_IDENTITY_W *id = creds->TransportCredentials;
2577 RPC_STATUS status = RPC_S_SERVER_UNAVAILABLE;
2579 if ((!info && !(info = alloc_authinfo()))) return RPC_S_SERVER_UNAVAILABLE;
2581 switch (creds->AuthnSchemes[0])
2583 case RPC_C_HTTP_AUTHN_SCHEME_BASIC:
2585 int userlen = WideCharToMultiByte(CP_UTF8, 0, id->User, id->UserLength, NULL, 0, NULL, NULL);
2586 int passlen = WideCharToMultiByte(CP_UTF8, 0, id->Password, id->PasswordLength, NULL, 0, NULL, NULL);
2588 info->data_len = userlen + passlen + 1;
2589 if (!(info->data = HeapAlloc(GetProcessHeap(), 0, info->data_len)))
2591 status = RPC_S_OUT_OF_MEMORY;
2592 break;
2594 WideCharToMultiByte(CP_UTF8, 0, id->User, id->UserLength, info->data, userlen, NULL, NULL);
2595 info->data[userlen] = ':';
2596 WideCharToMultiByte(CP_UTF8, 0, id->Password, id->PasswordLength, info->data + userlen + 1, passlen, NULL, NULL);
2598 info->scheme = RPC_C_HTTP_AUTHN_SCHEME_BASIC;
2599 info->finished = TRUE;
2600 status = RPC_S_OK;
2601 break;
2603 case RPC_C_HTTP_AUTHN_SCHEME_NTLM:
2604 case RPC_C_HTTP_AUTHN_SCHEME_NEGOTIATE:
2607 static SEC_WCHAR ntlmW[] = {'N','T','L','M',0}, negotiateW[] = {'N','e','g','o','t','i','a','t','e',0};
2608 SECURITY_STATUS ret;
2609 SecBufferDesc out_desc, in_desc;
2610 SecBuffer out, in;
2611 ULONG flags = ISC_REQ_CONNECTION|ISC_REQ_USE_DCE_STYLE|ISC_REQ_MUTUAL_AUTH|ISC_REQ_DELEGATE;
2612 SEC_WCHAR *scheme;
2613 int scheme_len;
2614 const WCHAR *p;
2615 WCHAR auth_value[2048];
2616 DWORD size = sizeof(auth_value);
2617 BOOL first = FALSE;
2619 if (creds->AuthnSchemes[0] == RPC_C_HTTP_AUTHN_SCHEME_NTLM) scheme = ntlmW;
2620 else scheme = negotiateW;
2621 scheme_len = strlenW( scheme );
2623 if (!*auth_ptr)
2625 TimeStamp exp;
2626 SecPkgInfoW *pkg_info;
2628 ret = AcquireCredentialsHandleW(NULL, scheme, SECPKG_CRED_OUTBOUND, NULL, id, NULL, NULL, &info->cred, &exp);
2629 if (ret != SEC_E_OK) break;
2631 ret = QuerySecurityPackageInfoW(scheme, &pkg_info);
2632 if (ret != SEC_E_OK) break;
2634 info->max_token = pkg_info->cbMaxToken;
2635 FreeContextBuffer(pkg_info);
2636 first = TRUE;
2638 else
2640 if (info->finished || !get_authvalue(request, creds->AuthnSchemes[0], auth_value, size)) break;
2641 if (auth_scheme_from_header(auth_value) != info->scheme)
2643 ERR("authentication scheme changed\n");
2644 break;
2647 in.BufferType = SECBUFFER_TOKEN;
2648 in.cbBuffer = 0;
2649 in.pvBuffer = NULL;
2651 in_desc.ulVersion = 0;
2652 in_desc.cBuffers = 1;
2653 in_desc.pBuffers = &in;
2655 p = auth_value + scheme_len;
2656 if (!first && *p == ' ')
2658 int len = strlenW(++p);
2659 in.cbBuffer = decode_base64(p, len, NULL);
2660 if (!(in.pvBuffer = HeapAlloc(GetProcessHeap(), 0, in.cbBuffer))) break;
2661 decode_base64(p, len, in.pvBuffer);
2663 out.BufferType = SECBUFFER_TOKEN;
2664 out.cbBuffer = info->max_token;
2665 if (!(out.pvBuffer = HeapAlloc(GetProcessHeap(), 0, out.cbBuffer)))
2667 HeapFree(GetProcessHeap(), 0, in.pvBuffer);
2668 break;
2670 out_desc.ulVersion = 0;
2671 out_desc.cBuffers = 1;
2672 out_desc.pBuffers = &out;
2674 ret = InitializeSecurityContextW(first ? &info->cred : NULL, first ? NULL : &info->ctx,
2675 first ? servername : NULL, flags, 0, SECURITY_NETWORK_DREP,
2676 in.pvBuffer ? &in_desc : NULL, 0, &info->ctx, &out_desc,
2677 &info->attr, &info->exp);
2678 HeapFree(GetProcessHeap(), 0, in.pvBuffer);
2679 if (ret == SEC_E_OK)
2681 HeapFree(GetProcessHeap(), 0, info->data);
2682 info->data = out.pvBuffer;
2683 info->data_len = out.cbBuffer;
2684 info->finished = TRUE;
2685 TRACE("sending last auth packet\n");
2686 status = RPC_S_OK;
2688 else if (ret == SEC_I_CONTINUE_NEEDED)
2690 HeapFree(GetProcessHeap(), 0, info->data);
2691 info->data = out.pvBuffer;
2692 info->data_len = out.cbBuffer;
2693 TRACE("sending next auth packet\n");
2694 status = RPC_S_OK;
2696 else
2698 ERR("InitializeSecurityContextW failed with error 0x%08x\n", ret);
2699 HeapFree(GetProcessHeap(), 0, out.pvBuffer);
2700 break;
2702 info->scheme = creds->AuthnSchemes[0];
2703 break;
2705 default:
2706 FIXME("scheme %u not supported\n", creds->AuthnSchemes[0]);
2707 break;
2710 if (status != RPC_S_OK)
2712 destroy_authinfo(info);
2713 *auth_ptr = NULL;
2714 return status;
2716 *auth_ptr = info;
2717 return RPC_S_OK;
2720 static RPC_STATUS insert_authorization_header(HINTERNET request, ULONG scheme, char *data, int data_len)
2722 static const WCHAR authW[] = {'A','u','t','h','o','r','i','z','a','t','i','o','n',':',' '};
2723 static const WCHAR basicW[] = {'B','a','s','i','c',' '};
2724 static const WCHAR negotiateW[] = {'N','e','g','o','t','i','a','t','e',' '};
2725 static const WCHAR ntlmW[] = {'N','T','L','M',' '};
2726 int scheme_len, auth_len = sizeof(authW) / sizeof(authW[0]), len = ((data_len + 2) * 4) / 3;
2727 const WCHAR *scheme_str;
2728 WCHAR *header, *ptr;
2729 RPC_STATUS status = RPC_S_SERVER_UNAVAILABLE;
2731 switch (scheme)
2733 case RPC_C_HTTP_AUTHN_SCHEME_BASIC:
2734 scheme_str = basicW;
2735 scheme_len = sizeof(basicW) / sizeof(basicW[0]);
2736 break;
2737 case RPC_C_HTTP_AUTHN_SCHEME_NEGOTIATE:
2738 scheme_str = negotiateW;
2739 scheme_len = sizeof(negotiateW) / sizeof(negotiateW[0]);
2740 break;
2741 case RPC_C_HTTP_AUTHN_SCHEME_NTLM:
2742 scheme_str = ntlmW;
2743 scheme_len = sizeof(ntlmW) / sizeof(ntlmW[0]);
2744 break;
2745 default:
2746 ERR("unknown scheme %u\n", scheme);
2747 return RPC_S_SERVER_UNAVAILABLE;
2749 if ((header = HeapAlloc(GetProcessHeap(), 0, (auth_len + scheme_len + len + 2) * sizeof(WCHAR))))
2751 memcpy(header, authW, auth_len * sizeof(WCHAR));
2752 ptr = header + auth_len;
2753 memcpy(ptr, scheme_str, scheme_len * sizeof(WCHAR));
2754 ptr += scheme_len;
2755 len = encode_base64(data, data_len, ptr);
2756 ptr[len++] = '\r';
2757 ptr[len++] = '\n';
2758 ptr[len] = 0;
2759 if (HttpAddRequestHeadersW(request, header, -1, HTTP_ADDREQ_FLAG_ADD|HTTP_ADDREQ_FLAG_REPLACE))
2760 status = RPC_S_OK;
2761 HeapFree(GetProcessHeap(), 0, header);
2763 return status;
2766 static void drain_content(HINTERNET request)
2768 DWORD count, len = 0, size = sizeof(len);
2769 char buf[2048];
2771 HttpQueryInfoW(request, HTTP_QUERY_FLAG_NUMBER|HTTP_QUERY_CONTENT_LENGTH, &len, &size, NULL);
2772 if (!len) return;
2773 for (;;)
2775 count = min(sizeof(buf), len);
2776 if (!InternetReadFile(request, buf, count, &count) || !count) return;
2777 len -= count;
2781 static RPC_STATUS authorize_request(RpcConnection_http *httpc, HINTERNET request)
2783 static const WCHAR authW[] = {'A','u','t','h','o','r','i','z','a','t','i','o','n',':','\r','\n',0};
2784 struct authinfo *info = NULL;
2785 RPC_STATUS status;
2786 BOOL ret;
2788 for (;;)
2790 status = do_authorization(request, httpc->servername, httpc->common.QOS->qos->u.HttpCredentials, &info);
2791 if (status != RPC_S_OK) break;
2793 status = insert_authorization_header(request, info->scheme, info->data, info->data_len);
2794 if (status != RPC_S_OK) break;
2796 prepare_async_request(httpc->async_data);
2797 ret = HttpSendRequestW(request, NULL, 0, NULL, 0);
2798 status = wait_async_request(httpc->async_data, ret, httpc->cancel_event);
2799 if (status != RPC_S_OK || info->finished) break;
2801 status = rpcrt4_http_check_response(request);
2802 if (status != RPC_S_OK && status != ERROR_ACCESS_DENIED) break;
2803 drain_content(request);
2806 if (info->scheme != RPC_C_HTTP_AUTHN_SCHEME_BASIC)
2807 HttpAddRequestHeadersW(request, authW, -1, HTTP_ADDREQ_FLAG_REPLACE);
2809 destroy_authinfo(info);
2810 return status;
2813 static RPC_STATUS insert_cookie_header(HINTERNET request, const WCHAR *value)
2815 static const WCHAR cookieW[] = {'C','o','o','k','i','e',':',' '};
2816 WCHAR *header, *ptr;
2817 int len;
2818 RPC_STATUS status = RPC_S_SERVER_UNAVAILABLE;
2820 if (!value) return RPC_S_OK;
2822 len = strlenW(value);
2823 if ((header = HeapAlloc(GetProcessHeap(), 0, sizeof(cookieW) + (len + 3) * sizeof(WCHAR))))
2825 memcpy(header, cookieW, sizeof(cookieW));
2826 ptr = header + sizeof(cookieW) / sizeof(cookieW[0]);
2827 memcpy(ptr, value, len * sizeof(WCHAR));
2828 ptr[len++] = '\r';
2829 ptr[len++] = '\n';
2830 ptr[len] = 0;
2831 if ((HttpAddRequestHeadersW(request, header, -1, HTTP_ADDREQ_FLAG_ADD_IF_NEW))) status = RPC_S_OK;
2832 HeapFree(GetProcessHeap(), 0, header);
2834 return status;
2837 static BOOL has_credentials(RpcConnection_http *httpc)
2839 RPC_HTTP_TRANSPORT_CREDENTIALS_W *creds;
2840 SEC_WINNT_AUTH_IDENTITY_W *id;
2842 if (!httpc->common.QOS || httpc->common.QOS->qos->AdditionalSecurityInfoType != RPC_C_AUTHN_INFO_TYPE_HTTP)
2843 return FALSE;
2845 creds = httpc->common.QOS->qos->u.HttpCredentials;
2846 if (creds->AuthenticationTarget != RPC_C_HTTP_AUTHN_TARGET_SERVER || !creds->NumberOfAuthnSchemes)
2847 return FALSE;
2849 id = creds->TransportCredentials;
2850 if (!id || !id->User || !id->Password) return FALSE;
2852 return TRUE;
2855 static BOOL is_secure(RpcConnection_http *httpc)
2857 return httpc->common.QOS &&
2858 (httpc->common.QOS->qos->AdditionalSecurityInfoType == RPC_C_AUTHN_INFO_TYPE_HTTP) &&
2859 (httpc->common.QOS->qos->u.HttpCredentials->Flags & RPC_C_HTTP_FLAG_USE_SSL);
2862 static RPC_STATUS rpcrt4_ncacn_http_open(RpcConnection* Connection)
2864 RpcConnection_http *httpc = (RpcConnection_http *)Connection;
2865 static const WCHAR wszVerbIn[] = {'R','P','C','_','I','N','_','D','A','T','A',0};
2866 static const WCHAR wszVerbOut[] = {'R','P','C','_','O','U','T','_','D','A','T','A',0};
2867 static const WCHAR wszRpcProxyPrefix[] = {'/','r','p','c','/','r','p','c','p','r','o','x','y','.','d','l','l','?',0};
2868 static const WCHAR wszColon[] = {':',0};
2869 static const WCHAR wszAcceptType[] = {'a','p','p','l','i','c','a','t','i','o','n','/','r','p','c',0};
2870 LPCWSTR wszAcceptTypes[] = { wszAcceptType, NULL };
2871 DWORD flags;
2872 WCHAR *url;
2873 RPC_STATUS status;
2874 BOOL secure, credentials;
2875 HttpTimerThreadData *timer_data;
2876 HANDLE thread;
2878 TRACE("(%s, %s)\n", Connection->NetworkAddr, Connection->Endpoint);
2880 if (Connection->server)
2882 ERR("ncacn_http servers not supported yet\n");
2883 return RPC_S_SERVER_UNAVAILABLE;
2886 if (httpc->in_request)
2887 return RPC_S_OK;
2889 httpc->async_data->completion_event = CreateEventW(NULL, FALSE, FALSE, NULL);
2891 status = UuidCreate(&httpc->connection_uuid);
2892 status = UuidCreate(&httpc->in_pipe_uuid);
2893 status = UuidCreate(&httpc->out_pipe_uuid);
2895 status = rpcrt4_http_internet_connect(httpc);
2896 if (status != RPC_S_OK)
2897 return status;
2899 url = HeapAlloc(GetProcessHeap(), 0, sizeof(wszRpcProxyPrefix) + (strlen(Connection->NetworkAddr) + 1 + strlen(Connection->Endpoint))*sizeof(WCHAR));
2900 if (!url)
2901 return RPC_S_OUT_OF_MEMORY;
2902 memcpy(url, wszRpcProxyPrefix, sizeof(wszRpcProxyPrefix));
2903 MultiByteToWideChar(CP_ACP, 0, Connection->NetworkAddr, -1, url+sizeof(wszRpcProxyPrefix)/sizeof(wszRpcProxyPrefix[0])-1, strlen(Connection->NetworkAddr)+1);
2904 strcatW(url, wszColon);
2905 MultiByteToWideChar(CP_ACP, 0, Connection->Endpoint, -1, url+strlenW(url), strlen(Connection->Endpoint)+1);
2907 secure = is_secure(httpc);
2908 credentials = has_credentials(httpc);
2910 flags = INTERNET_FLAG_KEEP_CONNECTION | INTERNET_FLAG_PRAGMA_NOCACHE | INTERNET_FLAG_NO_CACHE_WRITE |
2911 INTERNET_FLAG_NO_AUTO_REDIRECT;
2912 if (secure) flags |= INTERNET_FLAG_SECURE;
2913 if (credentials) flags |= INTERNET_FLAG_NO_AUTH;
2915 httpc->in_request = HttpOpenRequestW(httpc->session, wszVerbIn, url, NULL, NULL, wszAcceptTypes,
2916 flags, (DWORD_PTR)httpc->async_data);
2917 if (!httpc->in_request)
2919 ERR("HttpOpenRequestW failed with error %d\n", GetLastError());
2920 HeapFree(GetProcessHeap(), 0, url);
2921 return RPC_S_SERVER_UNAVAILABLE;
2923 status = insert_cookie_header(httpc->in_request, Connection->CookieAuth);
2924 if (status != RPC_S_OK)
2926 HeapFree(GetProcessHeap(), 0, url);
2927 return status;
2929 if (credentials)
2931 status = authorize_request(httpc, httpc->in_request);
2932 if (status != RPC_S_OK)
2934 HeapFree(GetProcessHeap(), 0, url);
2935 return status;
2937 status = rpcrt4_http_check_response(httpc->in_request);
2938 if (status != RPC_S_OK)
2940 HeapFree(GetProcessHeap(), 0, url);
2941 return status;
2943 drain_content(httpc->in_request);
2946 httpc->out_request = HttpOpenRequestW(httpc->session, wszVerbOut, url, NULL, NULL, wszAcceptTypes,
2947 flags, (DWORD_PTR)httpc->async_data);
2948 HeapFree(GetProcessHeap(), 0, url);
2949 if (!httpc->out_request)
2951 ERR("HttpOpenRequestW failed with error %d\n", GetLastError());
2952 return RPC_S_SERVER_UNAVAILABLE;
2954 status = insert_cookie_header(httpc->out_request, Connection->CookieAuth);
2955 if (status != RPC_S_OK)
2956 return status;
2958 if (credentials)
2960 status = authorize_request(httpc, httpc->out_request);
2961 if (status != RPC_S_OK)
2962 return status;
2965 status = rpcrt4_http_prepare_in_pipe(httpc->in_request, httpc->async_data, httpc->cancel_event,
2966 &httpc->connection_uuid, &httpc->in_pipe_uuid,
2967 &Connection->assoc->http_uuid, credentials);
2968 if (status != RPC_S_OK)
2969 return status;
2971 status = rpcrt4_http_prepare_out_pipe(httpc->out_request, httpc->async_data, httpc->cancel_event,
2972 &httpc->connection_uuid, &httpc->out_pipe_uuid,
2973 &httpc->flow_control_increment, credentials);
2974 if (status != RPC_S_OK)
2975 return status;
2977 httpc->flow_control_mark = httpc->flow_control_increment / 2;
2978 httpc->last_sent_time = GetTickCount();
2979 httpc->timer_cancelled = CreateEventW(NULL, FALSE, FALSE, NULL);
2981 timer_data = HeapAlloc(GetProcessHeap(), 0, sizeof(*timer_data));
2982 if (!timer_data)
2983 return ERROR_OUTOFMEMORY;
2984 timer_data->timer_param = httpc->in_request;
2985 timer_data->last_sent_time = &httpc->last_sent_time;
2986 timer_data->timer_cancelled = httpc->timer_cancelled;
2987 /* FIXME: should use CreateTimerQueueTimer when implemented */
2988 thread = CreateThread(NULL, 0, rpcrt4_http_timer_thread, timer_data, 0, NULL);
2989 if (!thread)
2991 HeapFree(GetProcessHeap(), 0, timer_data);
2992 return GetLastError();
2994 CloseHandle(thread);
2996 return RPC_S_OK;
2999 static RPC_STATUS rpcrt4_ncacn_http_handoff(RpcConnection *old_conn, RpcConnection *new_conn)
3001 assert(0);
3002 return RPC_S_SERVER_UNAVAILABLE;
3005 static int rpcrt4_ncacn_http_read(RpcConnection *Connection,
3006 void *buffer, unsigned int count)
3008 RpcConnection_http *httpc = (RpcConnection_http *) Connection;
3009 char *buf = buffer;
3010 BOOL ret;
3011 unsigned int bytes_left = count;
3012 RPC_STATUS status = RPC_S_OK;
3014 httpc->async_data->inet_buffers.lpvBuffer = HeapAlloc(GetProcessHeap(), 0, count);
3016 while (bytes_left)
3018 httpc->async_data->inet_buffers.dwBufferLength = bytes_left;
3019 prepare_async_request(httpc->async_data);
3020 ret = InternetReadFileExA(httpc->out_request, &httpc->async_data->inet_buffers, IRF_ASYNC, 0);
3021 status = wait_async_request(httpc->async_data, ret, httpc->cancel_event);
3022 if(status != RPC_S_OK) {
3023 if(status == RPC_S_CALL_CANCELLED)
3024 TRACE("call cancelled\n");
3025 break;
3028 if(!httpc->async_data->inet_buffers.dwBufferLength)
3029 break;
3030 memcpy(buf, httpc->async_data->inet_buffers.lpvBuffer,
3031 httpc->async_data->inet_buffers.dwBufferLength);
3033 bytes_left -= httpc->async_data->inet_buffers.dwBufferLength;
3034 buf += httpc->async_data->inet_buffers.dwBufferLength;
3037 HeapFree(GetProcessHeap(), 0, httpc->async_data->inet_buffers.lpvBuffer);
3038 httpc->async_data->inet_buffers.lpvBuffer = NULL;
3040 TRACE("%p %p %u -> %u\n", httpc->out_request, buffer, count, status);
3041 return status == RPC_S_OK ? count : -1;
3044 static RPC_STATUS rpcrt4_ncacn_http_receive_fragment(RpcConnection *Connection, RpcPktHdr **Header, void **Payload)
3046 RpcConnection_http *httpc = (RpcConnection_http *) Connection;
3047 RPC_STATUS status;
3048 DWORD hdr_length;
3049 LONG dwRead;
3050 RpcPktCommonHdr common_hdr;
3052 *Header = NULL;
3054 TRACE("(%p, %p, %p)\n", Connection, Header, Payload);
3056 again:
3057 /* read packet common header */
3058 dwRead = rpcrt4_ncacn_http_read(Connection, &common_hdr, sizeof(common_hdr));
3059 if (dwRead != sizeof(common_hdr)) {
3060 WARN("Short read of header, %d bytes\n", dwRead);
3061 status = RPC_S_PROTOCOL_ERROR;
3062 goto fail;
3064 if (!memcmp(&common_hdr, "HTTP/1.1", sizeof("HTTP/1.1")) ||
3065 !memcmp(&common_hdr, "HTTP/1.0", sizeof("HTTP/1.0")))
3067 FIXME("server returned %s\n", debugstr_a((const char *)&common_hdr));
3068 status = RPC_S_PROTOCOL_ERROR;
3069 goto fail;
3072 status = RPCRT4_ValidateCommonHeader(&common_hdr);
3073 if (status != RPC_S_OK) goto fail;
3075 hdr_length = RPCRT4_GetHeaderSize((RpcPktHdr*)&common_hdr);
3076 if (hdr_length == 0) {
3077 WARN("header length == 0\n");
3078 status = RPC_S_PROTOCOL_ERROR;
3079 goto fail;
3082 *Header = HeapAlloc(GetProcessHeap(), 0, hdr_length);
3083 if (!*Header)
3085 status = RPC_S_OUT_OF_RESOURCES;
3086 goto fail;
3088 memcpy(*Header, &common_hdr, sizeof(common_hdr));
3090 /* read the rest of packet header */
3091 dwRead = rpcrt4_ncacn_http_read(Connection, &(*Header)->common + 1, hdr_length - sizeof(common_hdr));
3092 if (dwRead != hdr_length - sizeof(common_hdr)) {
3093 WARN("bad header length, %d bytes, hdr_length %d\n", dwRead, hdr_length);
3094 status = RPC_S_PROTOCOL_ERROR;
3095 goto fail;
3098 if (common_hdr.frag_len - hdr_length)
3100 *Payload = HeapAlloc(GetProcessHeap(), 0, common_hdr.frag_len - hdr_length);
3101 if (!*Payload)
3103 status = RPC_S_OUT_OF_RESOURCES;
3104 goto fail;
3107 dwRead = rpcrt4_ncacn_http_read(Connection, *Payload, common_hdr.frag_len - hdr_length);
3108 if (dwRead != common_hdr.frag_len - hdr_length)
3110 WARN("bad data length, %d/%d\n", dwRead, common_hdr.frag_len - hdr_length);
3111 status = RPC_S_PROTOCOL_ERROR;
3112 goto fail;
3115 else
3116 *Payload = NULL;
3118 if ((*Header)->common.ptype == PKT_HTTP)
3120 if (!RPCRT4_IsValidHttpPacket(*Header, *Payload, common_hdr.frag_len - hdr_length))
3122 ERR("invalid http packet of length %d bytes\n", (*Header)->common.frag_len);
3123 status = RPC_S_PROTOCOL_ERROR;
3124 goto fail;
3126 if ((*Header)->http.flags == 0x0001)
3128 TRACE("http idle packet, waiting for real packet\n");
3129 if ((*Header)->http.num_data_items != 0)
3131 ERR("HTTP idle packet should have no data items instead of %d\n", (*Header)->http.num_data_items);
3132 status = RPC_S_PROTOCOL_ERROR;
3133 goto fail;
3136 else if ((*Header)->http.flags == 0x0002)
3138 ULONG bytes_transmitted;
3139 ULONG flow_control_increment;
3140 UUID pipe_uuid;
3141 status = RPCRT4_ParseHttpFlowControlHeader(*Header, *Payload,
3142 Connection->server,
3143 &bytes_transmitted,
3144 &flow_control_increment,
3145 &pipe_uuid);
3146 if (status != RPC_S_OK)
3147 goto fail;
3148 TRACE("received http flow control header (0x%x, 0x%x, %s)\n",
3149 bytes_transmitted, flow_control_increment, debugstr_guid(&pipe_uuid));
3150 /* FIXME: do something with parsed data */
3152 else
3154 FIXME("unrecognised http packet with flags 0x%04x\n", (*Header)->http.flags);
3155 status = RPC_S_PROTOCOL_ERROR;
3156 goto fail;
3158 RPCRT4_FreeHeader(*Header);
3159 *Header = NULL;
3160 HeapFree(GetProcessHeap(), 0, *Payload);
3161 *Payload = NULL;
3162 goto again;
3165 /* success */
3166 status = RPC_S_OK;
3168 httpc->bytes_received += common_hdr.frag_len;
3170 TRACE("httpc->bytes_received = 0x%x\n", httpc->bytes_received);
3172 if (httpc->bytes_received > httpc->flow_control_mark)
3174 RpcPktHdr *hdr = RPCRT4_BuildHttpFlowControlHeader(httpc->common.server,
3175 httpc->bytes_received,
3176 httpc->flow_control_increment,
3177 &httpc->out_pipe_uuid);
3178 if (hdr)
3180 DWORD bytes_written;
3181 BOOL ret2;
3182 TRACE("sending flow control packet at 0x%x\n", httpc->bytes_received);
3183 ret2 = InternetWriteFile(httpc->in_request, hdr, hdr->common.frag_len, &bytes_written);
3184 RPCRT4_FreeHeader(hdr);
3185 if (ret2)
3186 httpc->flow_control_mark = httpc->bytes_received + httpc->flow_control_increment / 2;
3190 fail:
3191 if (status != RPC_S_OK) {
3192 RPCRT4_FreeHeader(*Header);
3193 *Header = NULL;
3194 HeapFree(GetProcessHeap(), 0, *Payload);
3195 *Payload = NULL;
3197 return status;
3200 static int rpcrt4_ncacn_http_write(RpcConnection *Connection,
3201 const void *buffer, unsigned int count)
3203 RpcConnection_http *httpc = (RpcConnection_http *) Connection;
3204 DWORD bytes_written;
3205 BOOL ret;
3207 httpc->last_sent_time = ~0U; /* disable idle packet sending */
3208 ret = InternetWriteFile(httpc->in_request, buffer, count, &bytes_written);
3209 httpc->last_sent_time = GetTickCount();
3210 TRACE("%p %p %u -> %s\n", httpc->in_request, buffer, count, ret ? "TRUE" : "FALSE");
3211 return ret ? bytes_written : -1;
3214 static int rpcrt4_ncacn_http_close(RpcConnection *Connection)
3216 RpcConnection_http *httpc = (RpcConnection_http *) Connection;
3218 TRACE("\n");
3220 SetEvent(httpc->timer_cancelled);
3221 if (httpc->in_request)
3222 InternetCloseHandle(httpc->in_request);
3223 httpc->in_request = NULL;
3224 if (httpc->out_request)
3225 InternetCloseHandle(httpc->out_request);
3226 httpc->out_request = NULL;
3227 if (httpc->app_info)
3228 InternetCloseHandle(httpc->app_info);
3229 httpc->app_info = NULL;
3230 if (httpc->session)
3231 InternetCloseHandle(httpc->session);
3232 httpc->session = NULL;
3233 RpcHttpAsyncData_Release(httpc->async_data);
3234 if (httpc->cancel_event)
3235 CloseHandle(httpc->cancel_event);
3236 HeapFree(GetProcessHeap(), 0, httpc->servername);
3237 httpc->servername = NULL;
3239 return 0;
3242 static void rpcrt4_ncacn_http_cancel_call(RpcConnection *Connection)
3244 RpcConnection_http *httpc = (RpcConnection_http *) Connection;
3246 SetEvent(httpc->cancel_event);
3249 static int rpcrt4_ncacn_http_wait_for_incoming_data(RpcConnection *Connection)
3251 RpcConnection_http *httpc = (RpcConnection_http *) Connection;
3252 BOOL ret;
3253 RPC_STATUS status;
3255 prepare_async_request(httpc->async_data);
3256 ret = InternetQueryDataAvailable(httpc->out_request,
3257 &httpc->async_data->inet_buffers.dwBufferLength, IRF_ASYNC, 0);
3258 status = wait_async_request(httpc->async_data, ret, httpc->cancel_event);
3259 return status == RPC_S_OK ? 0 : -1;
3262 static size_t rpcrt4_ncacn_http_get_top_of_tower(unsigned char *tower_data,
3263 const char *networkaddr,
3264 const char *endpoint)
3266 return rpcrt4_ip_tcp_get_top_of_tower(tower_data, networkaddr,
3267 EPM_PROTOCOL_HTTP, endpoint);
3270 static RPC_STATUS rpcrt4_ncacn_http_parse_top_of_tower(const unsigned char *tower_data,
3271 size_t tower_size,
3272 char **networkaddr,
3273 char **endpoint)
3275 return rpcrt4_ip_tcp_parse_top_of_tower(tower_data, tower_size,
3276 networkaddr, EPM_PROTOCOL_HTTP,
3277 endpoint);
3280 static const struct connection_ops conn_protseq_list[] = {
3281 { "ncacn_np",
3282 { EPM_PROTOCOL_NCACN, EPM_PROTOCOL_SMB },
3283 rpcrt4_conn_np_alloc,
3284 rpcrt4_ncacn_np_open,
3285 rpcrt4_ncacn_np_handoff,
3286 rpcrt4_conn_np_read,
3287 rpcrt4_conn_np_write,
3288 rpcrt4_conn_np_close,
3289 rpcrt4_conn_np_cancel_call,
3290 rpcrt4_conn_np_wait_for_incoming_data,
3291 rpcrt4_ncacn_np_get_top_of_tower,
3292 rpcrt4_ncacn_np_parse_top_of_tower,
3293 NULL,
3294 RPCRT4_default_is_authorized,
3295 RPCRT4_default_authorize,
3296 RPCRT4_default_secure_packet,
3297 rpcrt4_conn_np_impersonate_client,
3298 rpcrt4_conn_np_revert_to_self,
3299 RPCRT4_default_inquire_auth_client,
3301 { "ncalrpc",
3302 { EPM_PROTOCOL_NCALRPC, EPM_PROTOCOL_PIPE },
3303 rpcrt4_conn_np_alloc,
3304 rpcrt4_ncalrpc_open,
3305 rpcrt4_ncalrpc_handoff,
3306 rpcrt4_conn_np_read,
3307 rpcrt4_conn_np_write,
3308 rpcrt4_conn_np_close,
3309 rpcrt4_conn_np_cancel_call,
3310 rpcrt4_conn_np_wait_for_incoming_data,
3311 rpcrt4_ncalrpc_get_top_of_tower,
3312 rpcrt4_ncalrpc_parse_top_of_tower,
3313 NULL,
3314 rpcrt4_ncalrpc_is_authorized,
3315 rpcrt4_ncalrpc_authorize,
3316 rpcrt4_ncalrpc_secure_packet,
3317 rpcrt4_conn_np_impersonate_client,
3318 rpcrt4_conn_np_revert_to_self,
3319 rpcrt4_ncalrpc_inquire_auth_client,
3321 { "ncacn_ip_tcp",
3322 { EPM_PROTOCOL_NCACN, EPM_PROTOCOL_TCP },
3323 rpcrt4_conn_tcp_alloc,
3324 rpcrt4_ncacn_ip_tcp_open,
3325 rpcrt4_conn_tcp_handoff,
3326 rpcrt4_conn_tcp_read,
3327 rpcrt4_conn_tcp_write,
3328 rpcrt4_conn_tcp_close,
3329 rpcrt4_conn_tcp_cancel_call,
3330 rpcrt4_conn_tcp_wait_for_incoming_data,
3331 rpcrt4_ncacn_ip_tcp_get_top_of_tower,
3332 rpcrt4_ncacn_ip_tcp_parse_top_of_tower,
3333 NULL,
3334 RPCRT4_default_is_authorized,
3335 RPCRT4_default_authorize,
3336 RPCRT4_default_secure_packet,
3337 RPCRT4_default_impersonate_client,
3338 RPCRT4_default_revert_to_self,
3339 RPCRT4_default_inquire_auth_client,
3341 { "ncacn_http",
3342 { EPM_PROTOCOL_NCACN, EPM_PROTOCOL_HTTP },
3343 rpcrt4_ncacn_http_alloc,
3344 rpcrt4_ncacn_http_open,
3345 rpcrt4_ncacn_http_handoff,
3346 rpcrt4_ncacn_http_read,
3347 rpcrt4_ncacn_http_write,
3348 rpcrt4_ncacn_http_close,
3349 rpcrt4_ncacn_http_cancel_call,
3350 rpcrt4_ncacn_http_wait_for_incoming_data,
3351 rpcrt4_ncacn_http_get_top_of_tower,
3352 rpcrt4_ncacn_http_parse_top_of_tower,
3353 rpcrt4_ncacn_http_receive_fragment,
3354 RPCRT4_default_is_authorized,
3355 RPCRT4_default_authorize,
3356 RPCRT4_default_secure_packet,
3357 RPCRT4_default_impersonate_client,
3358 RPCRT4_default_revert_to_self,
3359 RPCRT4_default_inquire_auth_client,
3364 static const struct protseq_ops protseq_list[] =
3367 "ncacn_np",
3368 rpcrt4_protseq_np_alloc,
3369 rpcrt4_protseq_np_signal_state_changed,
3370 rpcrt4_protseq_np_get_wait_array,
3371 rpcrt4_protseq_np_free_wait_array,
3372 rpcrt4_protseq_np_wait_for_new_connection,
3373 rpcrt4_protseq_ncacn_np_open_endpoint,
3376 "ncalrpc",
3377 rpcrt4_protseq_np_alloc,
3378 rpcrt4_protseq_np_signal_state_changed,
3379 rpcrt4_protseq_np_get_wait_array,
3380 rpcrt4_protseq_np_free_wait_array,
3381 rpcrt4_protseq_np_wait_for_new_connection,
3382 rpcrt4_protseq_ncalrpc_open_endpoint,
3385 "ncacn_ip_tcp",
3386 rpcrt4_protseq_sock_alloc,
3387 rpcrt4_protseq_sock_signal_state_changed,
3388 rpcrt4_protseq_sock_get_wait_array,
3389 rpcrt4_protseq_sock_free_wait_array,
3390 rpcrt4_protseq_sock_wait_for_new_connection,
3391 rpcrt4_protseq_ncacn_ip_tcp_open_endpoint,
3395 const struct protseq_ops *rpcrt4_get_protseq_ops(const char *protseq)
3397 unsigned int i;
3398 for(i=0; i<ARRAYSIZE(protseq_list); i++)
3399 if (!strcmp(protseq_list[i].name, protseq))
3400 return &protseq_list[i];
3401 return NULL;
3404 static const struct connection_ops *rpcrt4_get_conn_protseq_ops(const char *protseq)
3406 unsigned int i;
3407 for(i=0; i<ARRAYSIZE(conn_protseq_list); i++)
3408 if (!strcmp(conn_protseq_list[i].name, protseq))
3409 return &conn_protseq_list[i];
3410 return NULL;
3413 /**** interface to rest of code ****/
3415 RPC_STATUS RPCRT4_OpenClientConnection(RpcConnection* Connection)
3417 TRACE("(Connection == ^%p)\n", Connection);
3419 assert(!Connection->server);
3420 return Connection->ops->open_connection_client(Connection);
3423 RPC_STATUS RPCRT4_CloseConnection(RpcConnection* Connection)
3425 TRACE("(Connection == ^%p)\n", Connection);
3426 if (SecIsValidHandle(&Connection->ctx))
3428 DeleteSecurityContext(&Connection->ctx);
3429 SecInvalidateHandle(&Connection->ctx);
3431 rpcrt4_conn_close(Connection);
3432 return RPC_S_OK;
3435 RPC_STATUS RPCRT4_CreateConnection(RpcConnection** Connection, BOOL server,
3436 LPCSTR Protseq, LPCSTR NetworkAddr, LPCSTR Endpoint,
3437 LPCWSTR NetworkOptions, RpcAuthInfo* AuthInfo, RpcQualityOfService *QOS, LPCWSTR CookieAuth)
3439 static LONG next_id;
3440 const struct connection_ops *ops;
3441 RpcConnection* NewConnection;
3443 ops = rpcrt4_get_conn_protseq_ops(Protseq);
3444 if (!ops)
3446 FIXME("not supported for protseq %s\n", Protseq);
3447 return RPC_S_PROTSEQ_NOT_SUPPORTED;
3450 NewConnection = ops->alloc();
3451 NewConnection->ref = 1;
3452 NewConnection->Next = NULL;
3453 NewConnection->server_binding = NULL;
3454 NewConnection->server = server;
3455 NewConnection->ops = ops;
3456 NewConnection->NetworkAddr = RPCRT4_strdupA(NetworkAddr);
3457 NewConnection->Endpoint = RPCRT4_strdupA(Endpoint);
3458 NewConnection->NetworkOptions = RPCRT4_strdupW(NetworkOptions);
3459 NewConnection->CookieAuth = RPCRT4_strdupW(CookieAuth);
3460 NewConnection->MaxTransmissionSize = RPC_MAX_PACKET_SIZE;
3461 memset(&NewConnection->ActiveInterface, 0, sizeof(NewConnection->ActiveInterface));
3462 NewConnection->NextCallId = 1;
3464 SecInvalidateHandle(&NewConnection->ctx);
3465 memset(&NewConnection->exp, 0, sizeof(NewConnection->exp));
3466 NewConnection->attr = 0;
3467 if (AuthInfo) RpcAuthInfo_AddRef(AuthInfo);
3468 NewConnection->AuthInfo = AuthInfo;
3469 NewConnection->auth_context_id = InterlockedIncrement( &next_id );
3470 NewConnection->encryption_auth_len = 0;
3471 NewConnection->signature_auth_len = 0;
3472 if (QOS) RpcQualityOfService_AddRef(QOS);
3473 NewConnection->QOS = QOS;
3475 list_init(&NewConnection->conn_pool_entry);
3476 NewConnection->async_state = NULL;
3478 TRACE("connection: %p\n", NewConnection);
3479 *Connection = NewConnection;
3481 return RPC_S_OK;
3484 static RPC_STATUS RPCRT4_SpawnConnection(RpcConnection** Connection, RpcConnection* OldConnection)
3486 RPC_STATUS err;
3488 err = RPCRT4_CreateConnection(Connection, OldConnection->server, rpcrt4_conn_get_name(OldConnection),
3489 OldConnection->NetworkAddr, OldConnection->Endpoint, NULL,
3490 OldConnection->AuthInfo, OldConnection->QOS, OldConnection->CookieAuth);
3491 if (err == RPC_S_OK)
3492 rpcrt4_conn_handoff(OldConnection, *Connection);
3493 return err;
3496 RpcConnection *RPCRT4_GrabConnection( RpcConnection *conn )
3498 InterlockedIncrement( &conn->ref );
3499 return conn;
3502 RPC_STATUS RPCRT4_ReleaseConnection(RpcConnection* Connection)
3504 if (InterlockedDecrement( &Connection->ref ) > 0) return RPC_S_OK;
3506 TRACE("destroying connection %p\n", Connection);
3508 RPCRT4_CloseConnection(Connection);
3509 RPCRT4_strfree(Connection->Endpoint);
3510 RPCRT4_strfree(Connection->NetworkAddr);
3511 HeapFree(GetProcessHeap(), 0, Connection->NetworkOptions);
3512 HeapFree(GetProcessHeap(), 0, Connection->CookieAuth);
3513 if (Connection->AuthInfo) RpcAuthInfo_Release(Connection->AuthInfo);
3514 if (Connection->QOS) RpcQualityOfService_Release(Connection->QOS);
3516 /* server-only */
3517 if (Connection->server_binding) RPCRT4_ReleaseBinding(Connection->server_binding);
3519 HeapFree(GetProcessHeap(), 0, Connection);
3520 return RPC_S_OK;
3523 RPC_STATUS RpcTransport_GetTopOfTower(unsigned char *tower_data,
3524 size_t *tower_size,
3525 const char *protseq,
3526 const char *networkaddr,
3527 const char *endpoint)
3529 twr_empty_floor_t *protocol_floor;
3530 const struct connection_ops *protseq_ops = rpcrt4_get_conn_protseq_ops(protseq);
3532 *tower_size = 0;
3534 if (!protseq_ops)
3535 return RPC_S_INVALID_RPC_PROTSEQ;
3537 if (!tower_data)
3539 *tower_size = sizeof(*protocol_floor);
3540 *tower_size += protseq_ops->get_top_of_tower(NULL, networkaddr, endpoint);
3541 return RPC_S_OK;
3544 protocol_floor = (twr_empty_floor_t *)tower_data;
3545 protocol_floor->count_lhs = sizeof(protocol_floor->protid);
3546 protocol_floor->protid = protseq_ops->epm_protocols[0];
3547 protocol_floor->count_rhs = 0;
3549 tower_data += sizeof(*protocol_floor);
3551 *tower_size = protseq_ops->get_top_of_tower(tower_data, networkaddr, endpoint);
3552 if (!*tower_size)
3553 return EPT_S_NOT_REGISTERED;
3555 *tower_size += sizeof(*protocol_floor);
3557 return RPC_S_OK;
3560 RPC_STATUS RpcTransport_ParseTopOfTower(const unsigned char *tower_data,
3561 size_t tower_size,
3562 char **protseq,
3563 char **networkaddr,
3564 char **endpoint)
3566 const twr_empty_floor_t *protocol_floor;
3567 const twr_empty_floor_t *floor4;
3568 const struct connection_ops *protseq_ops = NULL;
3569 RPC_STATUS status;
3570 unsigned int i;
3572 if (tower_size < sizeof(*protocol_floor))
3573 return EPT_S_NOT_REGISTERED;
3575 protocol_floor = (const twr_empty_floor_t *)tower_data;
3576 tower_data += sizeof(*protocol_floor);
3577 tower_size -= sizeof(*protocol_floor);
3578 if ((protocol_floor->count_lhs != sizeof(protocol_floor->protid)) ||
3579 (protocol_floor->count_rhs > tower_size))
3580 return EPT_S_NOT_REGISTERED;
3581 tower_data += protocol_floor->count_rhs;
3582 tower_size -= protocol_floor->count_rhs;
3584 floor4 = (const twr_empty_floor_t *)tower_data;
3585 if ((tower_size < sizeof(*floor4)) ||
3586 (floor4->count_lhs != sizeof(floor4->protid)))
3587 return EPT_S_NOT_REGISTERED;
3589 for(i = 0; i < ARRAYSIZE(conn_protseq_list); i++)
3590 if ((protocol_floor->protid == conn_protseq_list[i].epm_protocols[0]) &&
3591 (floor4->protid == conn_protseq_list[i].epm_protocols[1]))
3593 protseq_ops = &conn_protseq_list[i];
3594 break;
3597 if (!protseq_ops)
3598 return EPT_S_NOT_REGISTERED;
3600 status = protseq_ops->parse_top_of_tower(tower_data, tower_size, networkaddr, endpoint);
3602 if ((status == RPC_S_OK) && protseq)
3604 *protseq = I_RpcAllocate(strlen(protseq_ops->name) + 1);
3605 strcpy(*protseq, protseq_ops->name);
3608 return status;
3611 /***********************************************************************
3612 * RpcNetworkIsProtseqValidW (RPCRT4.@)
3614 * Checks if the given protocol sequence is known by the RPC system.
3615 * If it is, returns RPC_S_OK, otherwise RPC_S_PROTSEQ_NOT_SUPPORTED.
3618 RPC_STATUS WINAPI RpcNetworkIsProtseqValidW(RPC_WSTR protseq)
3620 char ps[0x10];
3622 WideCharToMultiByte(CP_ACP, 0, protseq, -1,
3623 ps, sizeof ps, NULL, NULL);
3624 if (rpcrt4_get_conn_protseq_ops(ps))
3625 return RPC_S_OK;
3627 FIXME("Unknown protseq %s\n", debugstr_w(protseq));
3629 return RPC_S_INVALID_RPC_PROTSEQ;
3632 /***********************************************************************
3633 * RpcNetworkIsProtseqValidA (RPCRT4.@)
3635 RPC_STATUS WINAPI RpcNetworkIsProtseqValidA(RPC_CSTR protseq)
3637 UNICODE_STRING protseqW;
3639 if (RtlCreateUnicodeStringFromAsciiz(&protseqW, (char*)protseq))
3641 RPC_STATUS ret = RpcNetworkIsProtseqValidW(protseqW.Buffer);
3642 RtlFreeUnicodeString(&protseqW);
3643 return ret;
3645 return RPC_S_OUT_OF_MEMORY;
3648 /***********************************************************************
3649 * RpcProtseqVectorFreeA (RPCRT4.@)
3651 RPC_STATUS WINAPI RpcProtseqVectorFreeA(RPC_PROTSEQ_VECTORA **protseqs)
3653 TRACE("(%p)\n", protseqs);
3655 if (*protseqs)
3657 unsigned int i;
3658 for (i = 0; i < (*protseqs)->Count; i++)
3659 HeapFree(GetProcessHeap(), 0, (*protseqs)->Protseq[i]);
3660 HeapFree(GetProcessHeap(), 0, *protseqs);
3661 *protseqs = NULL;
3663 return RPC_S_OK;
3666 /***********************************************************************
3667 * RpcProtseqVectorFreeW (RPCRT4.@)
3669 RPC_STATUS WINAPI RpcProtseqVectorFreeW(RPC_PROTSEQ_VECTORW **protseqs)
3671 TRACE("(%p)\n", protseqs);
3673 if (*protseqs)
3675 unsigned int i;
3676 for (i = 0; i < (*protseqs)->Count; i++)
3677 HeapFree(GetProcessHeap(), 0, (*protseqs)->Protseq[i]);
3678 HeapFree(GetProcessHeap(), 0, *protseqs);
3679 *protseqs = NULL;
3681 return RPC_S_OK;
3684 /***********************************************************************
3685 * RpcNetworkInqProtseqsW (RPCRT4.@)
3687 RPC_STATUS WINAPI RpcNetworkInqProtseqsW( RPC_PROTSEQ_VECTORW** protseqs )
3689 RPC_PROTSEQ_VECTORW *pvector;
3690 unsigned int i;
3691 RPC_STATUS status = RPC_S_OUT_OF_MEMORY;
3693 TRACE("(%p)\n", protseqs);
3695 *protseqs = HeapAlloc(GetProcessHeap(), 0, sizeof(RPC_PROTSEQ_VECTORW)+(sizeof(unsigned short*)*ARRAYSIZE(protseq_list)));
3696 if (!*protseqs)
3697 goto end;
3698 pvector = *protseqs;
3699 pvector->Count = 0;
3700 for (i = 0; i < ARRAYSIZE(protseq_list); i++)
3702 pvector->Protseq[i] = HeapAlloc(GetProcessHeap(), 0, (strlen(protseq_list[i].name)+1)*sizeof(unsigned short));
3703 if (pvector->Protseq[i] == NULL)
3704 goto end;
3705 MultiByteToWideChar(CP_ACP, 0, (CHAR*)protseq_list[i].name, -1,
3706 (WCHAR*)pvector->Protseq[i], strlen(protseq_list[i].name) + 1);
3707 pvector->Count++;
3709 status = RPC_S_OK;
3711 end:
3712 if (status != RPC_S_OK)
3713 RpcProtseqVectorFreeW(protseqs);
3714 return status;
3717 /***********************************************************************
3718 * RpcNetworkInqProtseqsA (RPCRT4.@)
3720 RPC_STATUS WINAPI RpcNetworkInqProtseqsA(RPC_PROTSEQ_VECTORA** protseqs)
3722 RPC_PROTSEQ_VECTORA *pvector;
3723 unsigned int i;
3724 RPC_STATUS status = RPC_S_OUT_OF_MEMORY;
3726 TRACE("(%p)\n", protseqs);
3728 *protseqs = HeapAlloc(GetProcessHeap(), 0, sizeof(RPC_PROTSEQ_VECTORW)+(sizeof(unsigned char*)*ARRAYSIZE(protseq_list)));
3729 if (!*protseqs)
3730 goto end;
3731 pvector = *protseqs;
3732 pvector->Count = 0;
3733 for (i = 0; i < ARRAYSIZE(protseq_list); i++)
3735 pvector->Protseq[i] = HeapAlloc(GetProcessHeap(), 0, strlen(protseq_list[i].name)+1);
3736 if (pvector->Protseq[i] == NULL)
3737 goto end;
3738 strcpy((char*)pvector->Protseq[i], protseq_list[i].name);
3739 pvector->Count++;
3741 status = RPC_S_OK;
3743 end:
3744 if (status != RPC_S_OK)
3745 RpcProtseqVectorFreeA(protseqs);
3746 return status;