msi: Correctly parse double quotes in the token value.
[wine/multimedia.git] / dlls / rpcrt4 / rpc_transport.c
blobfbc2ad75f5eb43ed5058efd52089e7f3caf52b25
1 /*
2 * RPC transport layer
4 * Copyright 2001 Ove Kåven, TransGaming Technologies
5 * Copyright 2003 Mike Hearn
6 * Copyright 2004 Filip Navara
7 * Copyright 2006 Mike McCormack
8 * Copyright 2006 Damjan Jovanovic
10 * This library is free software; you can redistribute it and/or
11 * modify it under the terms of the GNU Lesser General Public
12 * License as published by the Free Software Foundation; either
13 * version 2.1 of the License, or (at your option) any later version.
15 * This library is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
18 * Lesser General Public License for more details.
20 * You should have received a copy of the GNU Lesser General Public
21 * License along with this library; if not, write to the Free Software
22 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
26 #include "config.h"
28 #include <stdarg.h>
29 #include <stdio.h>
30 #include <string.h>
31 #include <assert.h>
32 #include <errno.h>
33 #include <stdlib.h>
34 #include <sys/types.h>
36 #if defined(__MINGW32__) || defined (_MSC_VER)
37 # include <ws2tcpip.h>
38 # ifndef EADDRINUSE
39 # define EADDRINUSE WSAEADDRINUSE
40 # endif
41 # ifndef EAGAIN
42 # define EAGAIN WSAEWOULDBLOCK
43 # endif
44 # undef errno
45 # define errno WSAGetLastError()
46 #else
47 # include <errno.h>
48 # ifdef HAVE_UNISTD_H
49 # include <unistd.h>
50 # endif
51 # include <fcntl.h>
52 # ifdef HAVE_SYS_SOCKET_H
53 # include <sys/socket.h>
54 # endif
55 # ifdef HAVE_NETINET_IN_H
56 # include <netinet/in.h>
57 # endif
58 # ifdef HAVE_NETINET_TCP_H
59 # include <netinet/tcp.h>
60 # endif
61 # ifdef HAVE_ARPA_INET_H
62 # include <arpa/inet.h>
63 # endif
64 # ifdef HAVE_NETDB_H
65 # include <netdb.h>
66 # endif
67 # ifdef HAVE_SYS_POLL_H
68 # include <sys/poll.h>
69 # endif
70 # ifdef HAVE_SYS_FILIO_H
71 # include <sys/filio.h>
72 # endif
73 # ifdef HAVE_SYS_IOCTL_H
74 # include <sys/ioctl.h>
75 # endif
76 # define closesocket close
77 # define ioctlsocket ioctl
78 #endif /* defined(__MINGW32__) || defined (_MSC_VER) */
80 #include "windef.h"
81 #include "winbase.h"
82 #include "winnls.h"
83 #include "winerror.h"
84 #include "wininet.h"
85 #include "winternl.h"
86 #include "wine/unicode.h"
88 #include "rpc.h"
89 #include "rpcndr.h"
91 #include "wine/debug.h"
93 #include "rpc_binding.h"
94 #include "rpc_assoc.h"
95 #include "rpc_message.h"
96 #include "rpc_server.h"
97 #include "epm_towers.h"
99 #ifndef SOL_TCP
100 # define SOL_TCP IPPROTO_TCP
101 #endif
103 #define DEFAULT_NCACN_HTTP_TIMEOUT (60 * 1000)
105 #define ARRAYSIZE(a) (sizeof((a)) / sizeof((a)[0]))
107 WINE_DEFAULT_DEBUG_CHANNEL(rpc);
109 static RPC_STATUS RPCRT4_SpawnConnection(RpcConnection** Connection, RpcConnection* OldConnection);
111 /**** ncacn_np support ****/
113 typedef struct _RpcConnection_np
115 RpcConnection common;
116 HANDLE pipe;
117 HANDLE listen_thread;
118 BOOL listening;
119 } RpcConnection_np;
121 static RpcConnection *rpcrt4_conn_np_alloc(void)
123 RpcConnection_np *npc = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(RpcConnection_np));
124 return &npc->common;
127 static DWORD CALLBACK listen_thread(void *arg)
129 RpcConnection_np *npc = arg;
130 for (;;)
132 if (ConnectNamedPipe(npc->pipe, NULL))
133 return RPC_S_OK;
135 switch(GetLastError())
137 case ERROR_PIPE_CONNECTED:
138 return RPC_S_OK;
139 case ERROR_HANDLES_CLOSED:
140 /* connection closed during listen */
141 return RPC_S_NO_CONTEXT_AVAILABLE;
142 case ERROR_NO_DATA_DETECTED:
143 /* client has disconnected, retry */
144 DisconnectNamedPipe( npc->pipe );
145 break;
146 default:
147 npc->listening = FALSE;
148 WARN("Couldn't ConnectNamedPipe (error was %d)\n", GetLastError());
149 return RPC_S_OUT_OF_RESOURCES;
154 static RPC_STATUS rpcrt4_conn_listen_pipe(RpcConnection_np *npc)
156 if (npc->listening)
157 return RPC_S_OK;
159 npc->listening = TRUE;
160 npc->listen_thread = CreateThread(NULL, 0, listen_thread, npc, 0, NULL);
161 if (!npc->listen_thread)
163 npc->listening = FALSE;
164 ERR("Couldn't create listen thread (error was %d)\n", GetLastError());
165 return RPC_S_OUT_OF_RESOURCES;
167 return RPC_S_OK;
170 static RPC_STATUS rpcrt4_conn_create_pipe(RpcConnection *Connection, LPCSTR pname)
172 RpcConnection_np *npc = (RpcConnection_np *) Connection;
173 TRACE("listening on %s\n", pname);
175 npc->pipe = CreateNamedPipeA(pname, PIPE_ACCESS_DUPLEX,
176 PIPE_TYPE_MESSAGE | PIPE_READMODE_MESSAGE,
177 PIPE_UNLIMITED_INSTANCES,
178 RPC_MAX_PACKET_SIZE, RPC_MAX_PACKET_SIZE, 5000, NULL);
179 if (npc->pipe == INVALID_HANDLE_VALUE) {
180 WARN("CreateNamedPipe failed with error %d\n", GetLastError());
181 if (GetLastError() == ERROR_FILE_EXISTS)
182 return RPC_S_DUPLICATE_ENDPOINT;
183 else
184 return RPC_S_CANT_CREATE_ENDPOINT;
187 /* Note: we don't call ConnectNamedPipe here because it must be done in the
188 * server thread as the thread must be alertable */
189 return RPC_S_OK;
192 static RPC_STATUS rpcrt4_conn_open_pipe(RpcConnection *Connection, LPCSTR pname, BOOL wait)
194 RpcConnection_np *npc = (RpcConnection_np *) Connection;
195 HANDLE pipe;
196 DWORD err, dwMode;
198 TRACE("connecting to %s\n", pname);
200 while (TRUE) {
201 DWORD dwFlags = 0;
202 if (Connection->QOS)
204 dwFlags = SECURITY_SQOS_PRESENT;
205 switch (Connection->QOS->qos->ImpersonationType)
207 case RPC_C_IMP_LEVEL_DEFAULT:
208 /* FIXME: what to do here? */
209 break;
210 case RPC_C_IMP_LEVEL_ANONYMOUS:
211 dwFlags |= SECURITY_ANONYMOUS;
212 break;
213 case RPC_C_IMP_LEVEL_IDENTIFY:
214 dwFlags |= SECURITY_IDENTIFICATION;
215 break;
216 case RPC_C_IMP_LEVEL_IMPERSONATE:
217 dwFlags |= SECURITY_IMPERSONATION;
218 break;
219 case RPC_C_IMP_LEVEL_DELEGATE:
220 dwFlags |= SECURITY_DELEGATION;
221 break;
223 if (Connection->QOS->qos->IdentityTracking == RPC_C_QOS_IDENTITY_DYNAMIC)
224 dwFlags |= SECURITY_CONTEXT_TRACKING;
226 pipe = CreateFileA(pname, GENERIC_READ|GENERIC_WRITE, 0, NULL,
227 OPEN_EXISTING, dwFlags, 0);
228 if (pipe != INVALID_HANDLE_VALUE) break;
229 err = GetLastError();
230 if (err == ERROR_PIPE_BUSY) {
231 TRACE("connection failed, error=%x\n", err);
232 return RPC_S_SERVER_TOO_BUSY;
234 if (!wait || !WaitNamedPipeA(pname, NMPWAIT_WAIT_FOREVER)) {
235 err = GetLastError();
236 WARN("connection failed, error=%x\n", err);
237 return RPC_S_SERVER_UNAVAILABLE;
241 /* success */
242 /* pipe is connected; change to message-read mode. */
243 dwMode = PIPE_READMODE_MESSAGE;
244 SetNamedPipeHandleState(pipe, &dwMode, NULL, NULL);
245 npc->pipe = pipe;
247 return RPC_S_OK;
250 static RPC_STATUS rpcrt4_ncalrpc_open(RpcConnection* Connection)
252 RpcConnection_np *npc = (RpcConnection_np *) Connection;
253 static const char prefix[] = "\\\\.\\pipe\\lrpc\\";
254 RPC_STATUS r;
255 LPSTR pname;
257 /* already connected? */
258 if (npc->pipe)
259 return RPC_S_OK;
261 /* protseq=ncalrpc: supposed to use NT LPC ports,
262 * but we'll implement it with named pipes for now */
263 pname = I_RpcAllocate(strlen(prefix) + strlen(Connection->Endpoint) + 1);
264 strcat(strcpy(pname, prefix), Connection->Endpoint);
265 r = rpcrt4_conn_open_pipe(Connection, pname, TRUE);
266 I_RpcFree(pname);
268 return r;
271 static RPC_STATUS rpcrt4_protseq_ncalrpc_open_endpoint(RpcServerProtseq* protseq, const char *endpoint)
273 static const char prefix[] = "\\\\.\\pipe\\lrpc\\";
274 RPC_STATUS r;
275 LPSTR pname;
276 RpcConnection *Connection;
277 char generated_endpoint[22];
279 if (!endpoint)
281 static LONG lrpc_nameless_id;
282 DWORD process_id = GetCurrentProcessId();
283 ULONG id = InterlockedIncrement(&lrpc_nameless_id);
284 snprintf(generated_endpoint, sizeof(generated_endpoint),
285 "LRPC%08x.%08x", process_id, id);
286 endpoint = generated_endpoint;
289 r = RPCRT4_CreateConnection(&Connection, TRUE, protseq->Protseq, NULL,
290 endpoint, NULL, NULL, NULL, NULL);
291 if (r != RPC_S_OK)
292 return r;
294 /* protseq=ncalrpc: supposed to use NT LPC ports,
295 * but we'll implement it with named pipes for now */
296 pname = I_RpcAllocate(strlen(prefix) + strlen(Connection->Endpoint) + 1);
297 strcat(strcpy(pname, prefix), Connection->Endpoint);
298 r = rpcrt4_conn_create_pipe(Connection, pname);
299 I_RpcFree(pname);
301 EnterCriticalSection(&protseq->cs);
302 Connection->Next = protseq->conn;
303 protseq->conn = Connection;
304 LeaveCriticalSection(&protseq->cs);
306 return r;
309 static RPC_STATUS rpcrt4_ncacn_np_open(RpcConnection* Connection)
311 RpcConnection_np *npc = (RpcConnection_np *) Connection;
312 static const char prefix[] = "\\\\.";
313 RPC_STATUS r;
314 LPSTR pname;
316 /* already connected? */
317 if (npc->pipe)
318 return RPC_S_OK;
320 /* protseq=ncacn_np: named pipes */
321 pname = I_RpcAllocate(strlen(prefix) + strlen(Connection->Endpoint) + 1);
322 strcat(strcpy(pname, prefix), Connection->Endpoint);
323 r = rpcrt4_conn_open_pipe(Connection, pname, FALSE);
324 I_RpcFree(pname);
326 return r;
329 static RPC_STATUS rpcrt4_protseq_ncacn_np_open_endpoint(RpcServerProtseq *protseq, const char *endpoint)
331 static const char prefix[] = "\\\\.";
332 RPC_STATUS r;
333 LPSTR pname;
334 RpcConnection *Connection;
335 char generated_endpoint[21];
337 if (!endpoint)
339 static LONG np_nameless_id;
340 DWORD process_id = GetCurrentProcessId();
341 ULONG id = InterlockedExchangeAdd(&np_nameless_id, 1 );
342 snprintf(generated_endpoint, sizeof(generated_endpoint),
343 "\\\\pipe\\\\%08x.%03x", process_id, id);
344 endpoint = generated_endpoint;
347 r = RPCRT4_CreateConnection(&Connection, TRUE, protseq->Protseq, NULL,
348 endpoint, NULL, NULL, NULL, NULL);
349 if (r != RPC_S_OK)
350 return r;
352 /* protseq=ncacn_np: named pipes */
353 pname = I_RpcAllocate(strlen(prefix) + strlen(Connection->Endpoint) + 1);
354 strcat(strcpy(pname, prefix), Connection->Endpoint);
355 r = rpcrt4_conn_create_pipe(Connection, pname);
356 I_RpcFree(pname);
358 EnterCriticalSection(&protseq->cs);
359 Connection->Next = protseq->conn;
360 protseq->conn = Connection;
361 LeaveCriticalSection(&protseq->cs);
363 return r;
366 static void rpcrt4_conn_np_handoff(RpcConnection_np *old_npc, RpcConnection_np *new_npc)
368 /* because of the way named pipes work, we'll transfer the connected pipe
369 * to the child, then reopen the server binding to continue listening */
371 new_npc->pipe = old_npc->pipe;
372 new_npc->listen_thread = old_npc->listen_thread;
373 old_npc->pipe = 0;
374 old_npc->listen_thread = 0;
375 old_npc->listening = FALSE;
378 static RPC_STATUS rpcrt4_ncacn_np_handoff(RpcConnection *old_conn, RpcConnection *new_conn)
380 RPC_STATUS status;
381 LPSTR pname;
382 static const char prefix[] = "\\\\.";
384 rpcrt4_conn_np_handoff((RpcConnection_np *)old_conn, (RpcConnection_np *)new_conn);
386 pname = I_RpcAllocate(strlen(prefix) + strlen(old_conn->Endpoint) + 1);
387 strcat(strcpy(pname, prefix), old_conn->Endpoint);
388 status = rpcrt4_conn_create_pipe(old_conn, pname);
389 I_RpcFree(pname);
391 return status;
394 static RPC_STATUS rpcrt4_ncalrpc_handoff(RpcConnection *old_conn, RpcConnection *new_conn)
396 RPC_STATUS status;
397 LPSTR pname;
398 static const char prefix[] = "\\\\.\\pipe\\lrpc\\";
400 TRACE("%s\n", old_conn->Endpoint);
402 rpcrt4_conn_np_handoff((RpcConnection_np *)old_conn, (RpcConnection_np *)new_conn);
404 pname = I_RpcAllocate(strlen(prefix) + strlen(old_conn->Endpoint) + 1);
405 strcat(strcpy(pname, prefix), old_conn->Endpoint);
406 status = rpcrt4_conn_create_pipe(old_conn, pname);
407 I_RpcFree(pname);
409 return status;
412 static int rpcrt4_conn_np_read(RpcConnection *Connection,
413 void *buffer, unsigned int count)
415 RpcConnection_np *npc = (RpcConnection_np *) Connection;
416 char *buf = buffer;
417 BOOL ret = TRUE;
418 unsigned int bytes_left = count;
420 while (bytes_left)
422 DWORD bytes_read;
423 ret = ReadFile(npc->pipe, buf, bytes_left, &bytes_read, NULL);
424 if (!ret && GetLastError() == ERROR_MORE_DATA)
425 ret = TRUE;
426 if (!ret || !bytes_read)
427 break;
428 bytes_left -= bytes_read;
429 buf += bytes_read;
431 return ret ? count : -1;
434 static int rpcrt4_conn_np_write(RpcConnection *Connection,
435 const void *buffer, unsigned int count)
437 RpcConnection_np *npc = (RpcConnection_np *) Connection;
438 const char *buf = buffer;
439 BOOL ret = TRUE;
440 unsigned int bytes_left = count;
442 while (bytes_left)
444 DWORD bytes_written;
445 ret = WriteFile(npc->pipe, buf, bytes_left, &bytes_written, NULL);
446 if (!ret || !bytes_written)
447 break;
448 bytes_left -= bytes_written;
449 buf += bytes_written;
451 return ret ? count : -1;
454 static int rpcrt4_conn_np_close(RpcConnection *Connection)
456 RpcConnection_np *npc = (RpcConnection_np *) Connection;
457 if (npc->pipe) {
458 FlushFileBuffers(npc->pipe);
459 CloseHandle(npc->pipe);
460 npc->pipe = 0;
462 if (npc->listen_thread) {
463 CloseHandle(npc->listen_thread);
464 npc->listen_thread = 0;
466 return 0;
469 static void rpcrt4_conn_np_cancel_call(RpcConnection *Connection)
471 /* FIXME: implement when named pipe writes use overlapped I/O */
474 static int rpcrt4_conn_np_wait_for_incoming_data(RpcConnection *Connection)
476 /* FIXME: implement when named pipe writes use overlapped I/O */
477 return -1;
480 static size_t rpcrt4_ncacn_np_get_top_of_tower(unsigned char *tower_data,
481 const char *networkaddr,
482 const char *endpoint)
484 twr_empty_floor_t *smb_floor;
485 twr_empty_floor_t *nb_floor;
486 size_t size;
487 size_t networkaddr_size;
488 size_t endpoint_size;
490 TRACE("(%p, %s, %s)\n", tower_data, networkaddr, endpoint);
492 networkaddr_size = networkaddr ? strlen(networkaddr) + 1 : 1;
493 endpoint_size = endpoint ? strlen(endpoint) + 1 : 1;
494 size = sizeof(*smb_floor) + endpoint_size + sizeof(*nb_floor) + networkaddr_size;
496 if (!tower_data)
497 return size;
499 smb_floor = (twr_empty_floor_t *)tower_data;
501 tower_data += sizeof(*smb_floor);
503 smb_floor->count_lhs = sizeof(smb_floor->protid);
504 smb_floor->protid = EPM_PROTOCOL_SMB;
505 smb_floor->count_rhs = endpoint_size;
507 if (endpoint)
508 memcpy(tower_data, endpoint, endpoint_size);
509 else
510 tower_data[0] = 0;
511 tower_data += endpoint_size;
513 nb_floor = (twr_empty_floor_t *)tower_data;
515 tower_data += sizeof(*nb_floor);
517 nb_floor->count_lhs = sizeof(nb_floor->protid);
518 nb_floor->protid = EPM_PROTOCOL_NETBIOS;
519 nb_floor->count_rhs = networkaddr_size;
521 if (networkaddr)
522 memcpy(tower_data, networkaddr, networkaddr_size);
523 else
524 tower_data[0] = 0;
526 return size;
529 static RPC_STATUS rpcrt4_ncacn_np_parse_top_of_tower(const unsigned char *tower_data,
530 size_t tower_size,
531 char **networkaddr,
532 char **endpoint)
534 const twr_empty_floor_t *smb_floor = (const twr_empty_floor_t *)tower_data;
535 const twr_empty_floor_t *nb_floor;
537 TRACE("(%p, %d, %p, %p)\n", tower_data, (int)tower_size, networkaddr, endpoint);
539 if (tower_size < sizeof(*smb_floor))
540 return EPT_S_NOT_REGISTERED;
542 tower_data += sizeof(*smb_floor);
543 tower_size -= sizeof(*smb_floor);
545 if ((smb_floor->count_lhs != sizeof(smb_floor->protid)) ||
546 (smb_floor->protid != EPM_PROTOCOL_SMB) ||
547 (smb_floor->count_rhs > tower_size) ||
548 (tower_data[smb_floor->count_rhs - 1] != '\0'))
549 return EPT_S_NOT_REGISTERED;
551 if (endpoint)
553 *endpoint = I_RpcAllocate(smb_floor->count_rhs);
554 if (!*endpoint)
555 return RPC_S_OUT_OF_RESOURCES;
556 memcpy(*endpoint, tower_data, smb_floor->count_rhs);
558 tower_data += smb_floor->count_rhs;
559 tower_size -= smb_floor->count_rhs;
561 if (tower_size < sizeof(*nb_floor))
562 return EPT_S_NOT_REGISTERED;
564 nb_floor = (const twr_empty_floor_t *)tower_data;
566 tower_data += sizeof(*nb_floor);
567 tower_size -= sizeof(*nb_floor);
569 if ((nb_floor->count_lhs != sizeof(nb_floor->protid)) ||
570 (nb_floor->protid != EPM_PROTOCOL_NETBIOS) ||
571 (nb_floor->count_rhs > tower_size) ||
572 (tower_data[nb_floor->count_rhs - 1] != '\0'))
573 return EPT_S_NOT_REGISTERED;
575 if (networkaddr)
577 *networkaddr = I_RpcAllocate(nb_floor->count_rhs);
578 if (!*networkaddr)
580 if (endpoint)
582 I_RpcFree(*endpoint);
583 *endpoint = NULL;
585 return RPC_S_OUT_OF_RESOURCES;
587 memcpy(*networkaddr, tower_data, nb_floor->count_rhs);
590 return RPC_S_OK;
593 static RPC_STATUS rpcrt4_conn_np_impersonate_client(RpcConnection *conn)
595 RpcConnection_np *npc = (RpcConnection_np *)conn;
596 BOOL ret;
598 TRACE("(%p)\n", conn);
600 if (conn->AuthInfo && SecIsValidHandle(&conn->ctx))
601 return RPCRT4_default_impersonate_client(conn);
603 ret = ImpersonateNamedPipeClient(npc->pipe);
604 if (!ret)
606 DWORD error = GetLastError();
607 WARN("ImpersonateNamedPipeClient failed with error %u\n", error);
608 switch (error)
610 case ERROR_CANNOT_IMPERSONATE:
611 return RPC_S_NO_CONTEXT_AVAILABLE;
614 return RPC_S_OK;
617 static RPC_STATUS rpcrt4_conn_np_revert_to_self(RpcConnection *conn)
619 BOOL ret;
621 TRACE("(%p)\n", conn);
623 if (conn->AuthInfo && SecIsValidHandle(&conn->ctx))
624 return RPCRT4_default_revert_to_self(conn);
626 ret = RevertToSelf();
627 if (!ret)
629 WARN("RevertToSelf failed with error %u\n", GetLastError());
630 return RPC_S_NO_CONTEXT_AVAILABLE;
632 return RPC_S_OK;
635 typedef struct _RpcServerProtseq_np
637 RpcServerProtseq common;
638 HANDLE mgr_event;
639 } RpcServerProtseq_np;
641 static RpcServerProtseq *rpcrt4_protseq_np_alloc(void)
643 RpcServerProtseq_np *ps = HeapAlloc(GetProcessHeap(), 0, sizeof(*ps));
644 if (ps)
645 ps->mgr_event = CreateEventW(NULL, FALSE, FALSE, NULL);
646 return &ps->common;
649 static void rpcrt4_protseq_np_signal_state_changed(RpcServerProtseq *protseq)
651 RpcServerProtseq_np *npps = CONTAINING_RECORD(protseq, RpcServerProtseq_np, common);
652 SetEvent(npps->mgr_event);
655 static void *rpcrt4_protseq_np_get_wait_array(RpcServerProtseq *protseq, void *prev_array, unsigned int *count)
657 HANDLE *objs = prev_array;
658 RpcConnection_np *conn;
659 RpcServerProtseq_np *npps = CONTAINING_RECORD(protseq, RpcServerProtseq_np, common);
661 EnterCriticalSection(&protseq->cs);
663 /* open and count connections */
664 *count = 1;
665 conn = CONTAINING_RECORD(protseq->conn, RpcConnection_np, common);
666 while (conn) {
667 rpcrt4_conn_listen_pipe(conn);
668 if (conn->listen_thread)
669 (*count)++;
670 conn = CONTAINING_RECORD(conn->common.Next, RpcConnection_np, common);
673 /* make array of connections */
674 if (objs)
675 objs = HeapReAlloc(GetProcessHeap(), 0, objs, *count*sizeof(HANDLE));
676 else
677 objs = HeapAlloc(GetProcessHeap(), 0, *count*sizeof(HANDLE));
678 if (!objs)
680 ERR("couldn't allocate objs\n");
681 LeaveCriticalSection(&protseq->cs);
682 return NULL;
685 objs[0] = npps->mgr_event;
686 *count = 1;
687 conn = CONTAINING_RECORD(protseq->conn, RpcConnection_np, common);
688 while (conn) {
689 if ((objs[*count] = conn->listen_thread))
690 (*count)++;
691 conn = CONTAINING_RECORD(conn->common.Next, RpcConnection_np, common);
693 LeaveCriticalSection(&protseq->cs);
694 return objs;
697 static void rpcrt4_protseq_np_free_wait_array(RpcServerProtseq *protseq, void *array)
699 HeapFree(GetProcessHeap(), 0, array);
702 static int rpcrt4_protseq_np_wait_for_new_connection(RpcServerProtseq *protseq, unsigned int count, void *wait_array)
704 HANDLE b_handle;
705 HANDLE *objs = wait_array;
706 DWORD res;
707 RpcConnection *cconn;
708 RpcConnection_np *conn;
710 if (!objs)
711 return -1;
715 /* an alertable wait isn't strictly necessary, but due to our
716 * overlapped I/O implementation in Wine we need to free some memory
717 * by the file user APC being called, even if no completion routine was
718 * specified at the time of starting the async operation */
719 res = WaitForMultipleObjectsEx(count, objs, FALSE, INFINITE, TRUE);
720 } while (res == WAIT_IO_COMPLETION);
722 if (res == WAIT_OBJECT_0)
723 return 0;
724 else if (res == WAIT_FAILED)
726 ERR("wait failed with error %d\n", GetLastError());
727 return -1;
729 else
731 b_handle = objs[res - WAIT_OBJECT_0];
732 /* find which connection got a RPC */
733 EnterCriticalSection(&protseq->cs);
734 conn = CONTAINING_RECORD(protseq->conn, RpcConnection_np, common);
735 while (conn) {
736 if (b_handle == conn->listen_thread) break;
737 conn = CONTAINING_RECORD(conn->common.Next, RpcConnection_np, common);
739 cconn = NULL;
740 if (conn)
742 DWORD exit_code;
743 if (GetExitCodeThread(conn->listen_thread, &exit_code) && exit_code == RPC_S_OK)
744 RPCRT4_SpawnConnection(&cconn, &conn->common);
745 CloseHandle(conn->listen_thread);
746 conn->listen_thread = 0;
748 else
749 ERR("failed to locate connection for handle %p\n", b_handle);
750 LeaveCriticalSection(&protseq->cs);
751 if (cconn)
753 RPCRT4_new_client(cconn);
754 return 1;
756 else return -1;
760 static size_t rpcrt4_ncalrpc_get_top_of_tower(unsigned char *tower_data,
761 const char *networkaddr,
762 const char *endpoint)
764 twr_empty_floor_t *pipe_floor;
765 size_t size;
766 size_t endpoint_size;
768 TRACE("(%p, %s, %s)\n", tower_data, networkaddr, endpoint);
770 endpoint_size = strlen(endpoint) + 1;
771 size = sizeof(*pipe_floor) + endpoint_size;
773 if (!tower_data)
774 return size;
776 pipe_floor = (twr_empty_floor_t *)tower_data;
778 tower_data += sizeof(*pipe_floor);
780 pipe_floor->count_lhs = sizeof(pipe_floor->protid);
781 pipe_floor->protid = EPM_PROTOCOL_PIPE;
782 pipe_floor->count_rhs = endpoint_size;
784 memcpy(tower_data, endpoint, endpoint_size);
786 return size;
789 static RPC_STATUS rpcrt4_ncalrpc_parse_top_of_tower(const unsigned char *tower_data,
790 size_t tower_size,
791 char **networkaddr,
792 char **endpoint)
794 const twr_empty_floor_t *pipe_floor = (const twr_empty_floor_t *)tower_data;
796 TRACE("(%p, %d, %p, %p)\n", tower_data, (int)tower_size, networkaddr, endpoint);
798 if (tower_size < sizeof(*pipe_floor))
799 return EPT_S_NOT_REGISTERED;
801 tower_data += sizeof(*pipe_floor);
802 tower_size -= sizeof(*pipe_floor);
804 if ((pipe_floor->count_lhs != sizeof(pipe_floor->protid)) ||
805 (pipe_floor->protid != EPM_PROTOCOL_PIPE) ||
806 (pipe_floor->count_rhs > tower_size) ||
807 (tower_data[pipe_floor->count_rhs - 1] != '\0'))
808 return EPT_S_NOT_REGISTERED;
810 if (networkaddr)
811 *networkaddr = NULL;
813 if (endpoint)
815 *endpoint = I_RpcAllocate(pipe_floor->count_rhs);
816 if (!*endpoint)
817 return RPC_S_OUT_OF_RESOURCES;
818 memcpy(*endpoint, tower_data, pipe_floor->count_rhs);
821 return RPC_S_OK;
824 static BOOL rpcrt4_ncalrpc_is_authorized(RpcConnection *conn)
826 return FALSE;
829 static RPC_STATUS rpcrt4_ncalrpc_authorize(RpcConnection *conn, BOOL first_time,
830 unsigned char *in_buffer,
831 unsigned int in_size,
832 unsigned char *out_buffer,
833 unsigned int *out_size)
835 /* since this protocol is local to the machine there is no need to
836 * authenticate the caller */
837 *out_size = 0;
838 return RPC_S_OK;
841 static RPC_STATUS rpcrt4_ncalrpc_secure_packet(RpcConnection *conn,
842 enum secure_packet_direction dir,
843 RpcPktHdr *hdr, unsigned int hdr_size,
844 unsigned char *stub_data, unsigned int stub_data_size,
845 RpcAuthVerifier *auth_hdr,
846 unsigned char *auth_value, unsigned int auth_value_size)
848 /* since this protocol is local to the machine there is no need to secure
849 * the packet */
850 return RPC_S_OK;
853 static RPC_STATUS rpcrt4_ncalrpc_inquire_auth_client(
854 RpcConnection *conn, RPC_AUTHZ_HANDLE *privs, RPC_WSTR *server_princ_name,
855 ULONG *authn_level, ULONG *authn_svc, ULONG *authz_svc, ULONG flags)
857 TRACE("(%p, %p, %p, %p, %p, %p, 0x%x)\n", conn, privs,
858 server_princ_name, authn_level, authn_svc, authz_svc, flags);
860 if (privs)
862 FIXME("privs not implemented\n");
863 *privs = NULL;
865 if (server_princ_name)
867 FIXME("server_princ_name not implemented\n");
868 *server_princ_name = NULL;
870 if (authn_level) *authn_level = RPC_C_AUTHN_LEVEL_PKT_PRIVACY;
871 if (authn_svc) *authn_svc = RPC_C_AUTHN_WINNT;
872 if (authz_svc)
874 FIXME("authorization service not implemented\n");
875 *authz_svc = RPC_C_AUTHZ_NONE;
877 if (flags)
878 FIXME("flags 0x%x not implemented\n", flags);
880 return RPC_S_OK;
883 /**** ncacn_ip_tcp support ****/
885 static size_t rpcrt4_ip_tcp_get_top_of_tower(unsigned char *tower_data,
886 const char *networkaddr,
887 unsigned char tcp_protid,
888 const char *endpoint)
890 twr_tcp_floor_t *tcp_floor;
891 twr_ipv4_floor_t *ipv4_floor;
892 struct addrinfo *ai;
893 struct addrinfo hints;
894 int ret;
895 size_t size = sizeof(*tcp_floor) + sizeof(*ipv4_floor);
897 TRACE("(%p, %s, %s)\n", tower_data, networkaddr, endpoint);
899 if (!tower_data)
900 return size;
902 tcp_floor = (twr_tcp_floor_t *)tower_data;
903 tower_data += sizeof(*tcp_floor);
905 ipv4_floor = (twr_ipv4_floor_t *)tower_data;
907 tcp_floor->count_lhs = sizeof(tcp_floor->protid);
908 tcp_floor->protid = tcp_protid;
909 tcp_floor->count_rhs = sizeof(tcp_floor->port);
911 ipv4_floor->count_lhs = sizeof(ipv4_floor->protid);
912 ipv4_floor->protid = EPM_PROTOCOL_IP;
913 ipv4_floor->count_rhs = sizeof(ipv4_floor->ipv4addr);
915 hints.ai_flags = AI_NUMERICHOST;
916 /* FIXME: only support IPv4 at the moment. how is IPv6 represented by the EPM? */
917 hints.ai_family = PF_INET;
918 hints.ai_socktype = SOCK_STREAM;
919 hints.ai_protocol = IPPROTO_TCP;
920 hints.ai_addrlen = 0;
921 hints.ai_addr = NULL;
922 hints.ai_canonname = NULL;
923 hints.ai_next = NULL;
925 ret = getaddrinfo(networkaddr, endpoint, &hints, &ai);
926 if (ret)
928 ret = getaddrinfo("0.0.0.0", endpoint, &hints, &ai);
929 if (ret)
931 ERR("getaddrinfo failed: %s\n", gai_strerror(ret));
932 return 0;
936 if (ai->ai_family == PF_INET)
938 const struct sockaddr_in *sin = (const struct sockaddr_in *)ai->ai_addr;
939 tcp_floor->port = sin->sin_port;
940 ipv4_floor->ipv4addr = sin->sin_addr.s_addr;
942 else
944 ERR("unexpected protocol family %d\n", ai->ai_family);
945 freeaddrinfo(ai);
946 return 0;
949 freeaddrinfo(ai);
951 return size;
954 static RPC_STATUS rpcrt4_ip_tcp_parse_top_of_tower(const unsigned char *tower_data,
955 size_t tower_size,
956 char **networkaddr,
957 unsigned char tcp_protid,
958 char **endpoint)
960 const twr_tcp_floor_t *tcp_floor = (const twr_tcp_floor_t *)tower_data;
961 const twr_ipv4_floor_t *ipv4_floor;
962 struct in_addr in_addr;
964 TRACE("(%p, %d, %p, %p)\n", tower_data, (int)tower_size, networkaddr, endpoint);
966 if (tower_size < sizeof(*tcp_floor))
967 return EPT_S_NOT_REGISTERED;
969 tower_data += sizeof(*tcp_floor);
970 tower_size -= sizeof(*tcp_floor);
972 if (tower_size < sizeof(*ipv4_floor))
973 return EPT_S_NOT_REGISTERED;
975 ipv4_floor = (const twr_ipv4_floor_t *)tower_data;
977 if ((tcp_floor->count_lhs != sizeof(tcp_floor->protid)) ||
978 (tcp_floor->protid != tcp_protid) ||
979 (tcp_floor->count_rhs != sizeof(tcp_floor->port)) ||
980 (ipv4_floor->count_lhs != sizeof(ipv4_floor->protid)) ||
981 (ipv4_floor->protid != EPM_PROTOCOL_IP) ||
982 (ipv4_floor->count_rhs != sizeof(ipv4_floor->ipv4addr)))
983 return EPT_S_NOT_REGISTERED;
985 if (endpoint)
987 *endpoint = I_RpcAllocate(6 /* sizeof("65535") + 1 */);
988 if (!*endpoint)
989 return RPC_S_OUT_OF_RESOURCES;
990 sprintf(*endpoint, "%u", ntohs(tcp_floor->port));
993 if (networkaddr)
995 *networkaddr = I_RpcAllocate(INET_ADDRSTRLEN);
996 if (!*networkaddr)
998 if (endpoint)
1000 I_RpcFree(*endpoint);
1001 *endpoint = NULL;
1003 return RPC_S_OUT_OF_RESOURCES;
1005 in_addr.s_addr = ipv4_floor->ipv4addr;
1006 if (!inet_ntop(AF_INET, &in_addr, *networkaddr, INET_ADDRSTRLEN))
1008 ERR("inet_ntop: %s\n", strerror(errno));
1009 I_RpcFree(*networkaddr);
1010 *networkaddr = NULL;
1011 if (endpoint)
1013 I_RpcFree(*endpoint);
1014 *endpoint = NULL;
1016 return EPT_S_NOT_REGISTERED;
1020 return RPC_S_OK;
1023 typedef struct _RpcConnection_tcp
1025 RpcConnection common;
1026 int sock;
1027 #ifdef HAVE_SOCKETPAIR
1028 int cancel_fds[2];
1029 #else
1030 HANDLE sock_event;
1031 HANDLE cancel_event;
1032 #endif
1033 } RpcConnection_tcp;
1035 #ifdef HAVE_SOCKETPAIR
1037 static BOOL rpcrt4_sock_wait_init(RpcConnection_tcp *tcpc)
1039 if (socketpair(PF_UNIX, SOCK_STREAM, 0, tcpc->cancel_fds) < 0)
1041 ERR("socketpair() failed: %s\n", strerror(errno));
1042 return FALSE;
1044 return TRUE;
1047 static BOOL rpcrt4_sock_wait_for_recv(RpcConnection_tcp *tcpc)
1049 struct pollfd pfds[2];
1050 pfds[0].fd = tcpc->sock;
1051 pfds[0].events = POLLIN;
1052 pfds[1].fd = tcpc->cancel_fds[0];
1053 pfds[1].events = POLLIN;
1054 if (poll(pfds, 2, -1 /* infinite */) == -1 && errno != EINTR)
1056 ERR("poll() failed: %s\n", strerror(errno));
1057 return FALSE;
1059 if (pfds[1].revents & POLLIN) /* canceled */
1061 char dummy;
1062 read(pfds[1].fd, &dummy, sizeof(dummy));
1063 return FALSE;
1065 return TRUE;
1068 static BOOL rpcrt4_sock_wait_for_send(RpcConnection_tcp *tcpc)
1070 struct pollfd pfd;
1071 pfd.fd = tcpc->sock;
1072 pfd.events = POLLOUT;
1073 if (poll(&pfd, 1, -1 /* infinite */) == -1 && errno != EINTR)
1075 ERR("poll() failed: %s\n", strerror(errno));
1076 return FALSE;
1078 return TRUE;
1081 static void rpcrt4_sock_wait_cancel(RpcConnection_tcp *tcpc)
1083 char dummy = 1;
1085 write(tcpc->cancel_fds[1], &dummy, 1);
1088 static void rpcrt4_sock_wait_destroy(RpcConnection_tcp *tcpc)
1090 close(tcpc->cancel_fds[0]);
1091 close(tcpc->cancel_fds[1]);
1094 #else /* HAVE_SOCKETPAIR */
1096 static BOOL rpcrt4_sock_wait_init(RpcConnection_tcp *tcpc)
1098 static BOOL wsa_inited;
1099 if (!wsa_inited)
1101 WSADATA wsadata;
1102 WSAStartup(MAKEWORD(2, 2), &wsadata);
1103 /* Note: WSAStartup can be called more than once so we don't bother with
1104 * making accesses to wsa_inited thread-safe */
1105 wsa_inited = TRUE;
1107 tcpc->sock_event = CreateEventW(NULL, FALSE, FALSE, NULL);
1108 tcpc->cancel_event = CreateEventW(NULL, FALSE, FALSE, NULL);
1109 if (!tcpc->sock_event || !tcpc->cancel_event)
1111 ERR("event creation failed\n");
1112 if (tcpc->sock_event) CloseHandle(tcpc->sock_event);
1113 return FALSE;
1115 return TRUE;
1118 static BOOL rpcrt4_sock_wait_for_recv(RpcConnection_tcp *tcpc)
1120 HANDLE wait_handles[2];
1121 DWORD res;
1122 if (WSAEventSelect(tcpc->sock, tcpc->sock_event, FD_READ | FD_CLOSE) == SOCKET_ERROR)
1124 ERR("WSAEventSelect() failed with error %d\n", WSAGetLastError());
1125 return FALSE;
1127 wait_handles[0] = tcpc->sock_event;
1128 wait_handles[1] = tcpc->cancel_event;
1129 res = WaitForMultipleObjects(2, wait_handles, FALSE, INFINITE);
1130 switch (res)
1132 case WAIT_OBJECT_0:
1133 return TRUE;
1134 case WAIT_OBJECT_0 + 1:
1135 return FALSE;
1136 default:
1137 ERR("WaitForMultipleObjects() failed with error %d\n", GetLastError());
1138 return FALSE;
1142 static BOOL rpcrt4_sock_wait_for_send(RpcConnection_tcp *tcpc)
1144 DWORD res;
1145 if (WSAEventSelect(tcpc->sock, tcpc->sock_event, FD_WRITE | FD_CLOSE) == SOCKET_ERROR)
1147 ERR("WSAEventSelect() failed with error %d\n", WSAGetLastError());
1148 return FALSE;
1150 res = WaitForSingleObject(tcpc->sock_event, INFINITE);
1151 switch (res)
1153 case WAIT_OBJECT_0:
1154 return TRUE;
1155 default:
1156 ERR("WaitForMultipleObjects() failed with error %d\n", GetLastError());
1157 return FALSE;
1161 static void rpcrt4_sock_wait_cancel(RpcConnection_tcp *tcpc)
1163 SetEvent(tcpc->cancel_event);
1166 static void rpcrt4_sock_wait_destroy(RpcConnection_tcp *tcpc)
1168 CloseHandle(tcpc->sock_event);
1169 CloseHandle(tcpc->cancel_event);
1172 #endif
1174 static RpcConnection *rpcrt4_conn_tcp_alloc(void)
1176 RpcConnection_tcp *tcpc;
1177 tcpc = HeapAlloc(GetProcessHeap(), 0, sizeof(RpcConnection_tcp));
1178 if (tcpc == NULL)
1179 return NULL;
1180 tcpc->sock = -1;
1181 if (!rpcrt4_sock_wait_init(tcpc))
1183 HeapFree(GetProcessHeap(), 0, tcpc);
1184 return NULL;
1186 return &tcpc->common;
1189 static RPC_STATUS rpcrt4_ncacn_ip_tcp_open(RpcConnection* Connection)
1191 RpcConnection_tcp *tcpc = (RpcConnection_tcp *) Connection;
1192 int sock;
1193 int ret;
1194 struct addrinfo *ai;
1195 struct addrinfo *ai_cur;
1196 struct addrinfo hints;
1198 TRACE("(%s, %s)\n", Connection->NetworkAddr, Connection->Endpoint);
1200 if (tcpc->sock != -1)
1201 return RPC_S_OK;
1203 hints.ai_flags = 0;
1204 hints.ai_family = PF_UNSPEC;
1205 hints.ai_socktype = SOCK_STREAM;
1206 hints.ai_protocol = IPPROTO_TCP;
1207 hints.ai_addrlen = 0;
1208 hints.ai_addr = NULL;
1209 hints.ai_canonname = NULL;
1210 hints.ai_next = NULL;
1212 ret = getaddrinfo(Connection->NetworkAddr, Connection->Endpoint, &hints, &ai);
1213 if (ret)
1215 ERR("getaddrinfo for %s:%s failed: %s\n", Connection->NetworkAddr,
1216 Connection->Endpoint, gai_strerror(ret));
1217 return RPC_S_SERVER_UNAVAILABLE;
1220 for (ai_cur = ai; ai_cur; ai_cur = ai_cur->ai_next)
1222 int val;
1223 u_long nonblocking;
1225 if (ai_cur->ai_family != AF_INET && ai_cur->ai_family != AF_INET6)
1227 TRACE("skipping non-IP/IPv6 address family\n");
1228 continue;
1231 if (TRACE_ON(rpc))
1233 char host[256];
1234 char service[256];
1235 getnameinfo(ai_cur->ai_addr, ai_cur->ai_addrlen,
1236 host, sizeof(host), service, sizeof(service),
1237 NI_NUMERICHOST | NI_NUMERICSERV);
1238 TRACE("trying %s:%s\n", host, service);
1241 sock = socket(ai_cur->ai_family, ai_cur->ai_socktype, ai_cur->ai_protocol);
1242 if (sock == -1)
1244 WARN("socket() failed: %s\n", strerror(errno));
1245 continue;
1248 if (0>connect(sock, ai_cur->ai_addr, ai_cur->ai_addrlen))
1250 WARN("connect() failed: %s\n", strerror(errno));
1251 closesocket(sock);
1252 continue;
1255 /* RPC depends on having minimal latency so disable the Nagle algorithm */
1256 val = 1;
1257 setsockopt(sock, SOL_TCP, TCP_NODELAY, (char *)&val, sizeof(val));
1258 nonblocking = 1;
1259 ioctlsocket(sock, FIONBIO, &nonblocking);
1261 tcpc->sock = sock;
1263 freeaddrinfo(ai);
1264 TRACE("connected\n");
1265 return RPC_S_OK;
1268 freeaddrinfo(ai);
1269 ERR("couldn't connect to %s:%s\n", Connection->NetworkAddr, Connection->Endpoint);
1270 return RPC_S_SERVER_UNAVAILABLE;
1273 static RPC_STATUS rpcrt4_protseq_ncacn_ip_tcp_open_endpoint(RpcServerProtseq *protseq, const char *endpoint)
1275 RPC_STATUS status = RPC_S_CANT_CREATE_ENDPOINT;
1276 int sock;
1277 int ret;
1278 struct addrinfo *ai;
1279 struct addrinfo *ai_cur;
1280 struct addrinfo hints;
1281 RpcConnection *first_connection = NULL;
1283 TRACE("(%p, %s)\n", protseq, endpoint);
1285 hints.ai_flags = AI_PASSIVE /* for non-localhost addresses */;
1286 hints.ai_family = PF_UNSPEC;
1287 hints.ai_socktype = SOCK_STREAM;
1288 hints.ai_protocol = IPPROTO_TCP;
1289 hints.ai_addrlen = 0;
1290 hints.ai_addr = NULL;
1291 hints.ai_canonname = NULL;
1292 hints.ai_next = NULL;
1294 ret = getaddrinfo(NULL, endpoint ? endpoint : "0", &hints, &ai);
1295 if (ret)
1297 ERR("getaddrinfo for port %s failed: %s\n", endpoint,
1298 gai_strerror(ret));
1299 if ((ret == EAI_SERVICE) || (ret == EAI_NONAME))
1300 return RPC_S_INVALID_ENDPOINT_FORMAT;
1301 return RPC_S_CANT_CREATE_ENDPOINT;
1304 for (ai_cur = ai; ai_cur; ai_cur = ai_cur->ai_next)
1306 RpcConnection_tcp *tcpc;
1307 RPC_STATUS create_status;
1308 struct sockaddr_storage sa;
1309 socklen_t sa_len;
1310 char service[NI_MAXSERV];
1311 u_long nonblocking;
1313 if (ai_cur->ai_family != AF_INET && ai_cur->ai_family != AF_INET6)
1315 TRACE("skipping non-IP/IPv6 address family\n");
1316 continue;
1319 if (TRACE_ON(rpc))
1321 char host[256];
1322 getnameinfo(ai_cur->ai_addr, ai_cur->ai_addrlen,
1323 host, sizeof(host), service, sizeof(service),
1324 NI_NUMERICHOST | NI_NUMERICSERV);
1325 TRACE("trying %s:%s\n", host, service);
1328 sock = socket(ai_cur->ai_family, ai_cur->ai_socktype, ai_cur->ai_protocol);
1329 if (sock == -1)
1331 WARN("socket() failed: %s\n", strerror(errno));
1332 status = RPC_S_CANT_CREATE_ENDPOINT;
1333 continue;
1336 ret = bind(sock, ai_cur->ai_addr, ai_cur->ai_addrlen);
1337 if (ret < 0)
1339 WARN("bind failed: %s\n", strerror(errno));
1340 closesocket(sock);
1341 if (errno == EADDRINUSE)
1342 status = RPC_S_DUPLICATE_ENDPOINT;
1343 else
1344 status = RPC_S_CANT_CREATE_ENDPOINT;
1345 continue;
1348 sa_len = sizeof(sa);
1349 if (getsockname(sock, (struct sockaddr *)&sa, &sa_len))
1351 WARN("getsockname() failed: %s\n", strerror(errno));
1352 closesocket(sock);
1353 status = RPC_S_CANT_CREATE_ENDPOINT;
1354 continue;
1357 ret = getnameinfo((struct sockaddr *)&sa, sa_len,
1358 NULL, 0, service, sizeof(service),
1359 NI_NUMERICSERV);
1360 if (ret)
1362 WARN("getnameinfo failed: %s\n", gai_strerror(ret));
1363 closesocket(sock);
1364 status = RPC_S_CANT_CREATE_ENDPOINT;
1365 continue;
1368 create_status = RPCRT4_CreateConnection((RpcConnection **)&tcpc, TRUE,
1369 protseq->Protseq, NULL,
1370 service, NULL, NULL, NULL, NULL);
1371 if (create_status != RPC_S_OK)
1373 closesocket(sock);
1374 status = create_status;
1375 continue;
1378 tcpc->sock = sock;
1379 ret = listen(sock, protseq->MaxCalls);
1380 if (ret < 0)
1382 WARN("listen failed: %s\n", strerror(errno));
1383 RPCRT4_ReleaseConnection(&tcpc->common);
1384 status = RPC_S_OUT_OF_RESOURCES;
1385 continue;
1387 /* need a non-blocking socket, otherwise accept() has a potential
1388 * race-condition (poll() says it is readable, connection drops,
1389 * and accept() blocks until the next connection comes...)
1391 nonblocking = 1;
1392 ret = ioctlsocket(sock, FIONBIO, &nonblocking);
1393 if (ret < 0)
1395 WARN("couldn't make socket non-blocking, error %d\n", ret);
1396 RPCRT4_ReleaseConnection(&tcpc->common);
1397 status = RPC_S_OUT_OF_RESOURCES;
1398 continue;
1401 tcpc->common.Next = first_connection;
1402 first_connection = &tcpc->common;
1404 /* since IPv4 and IPv6 share the same port space, we only need one
1405 * successful bind to listen for both */
1406 break;
1409 freeaddrinfo(ai);
1411 /* if at least one connection was created for an endpoint then
1412 * return success */
1413 if (first_connection)
1415 RpcConnection *conn;
1417 /* find last element in list */
1418 for (conn = first_connection; conn->Next; conn = conn->Next)
1421 EnterCriticalSection(&protseq->cs);
1422 conn->Next = protseq->conn;
1423 protseq->conn = first_connection;
1424 LeaveCriticalSection(&protseq->cs);
1426 TRACE("listening on %s\n", endpoint);
1427 return RPC_S_OK;
1430 ERR("couldn't listen on port %s\n", endpoint);
1431 return status;
1434 static RPC_STATUS rpcrt4_conn_tcp_handoff(RpcConnection *old_conn, RpcConnection *new_conn)
1436 int ret;
1437 struct sockaddr_in address;
1438 socklen_t addrsize;
1439 RpcConnection_tcp *server = (RpcConnection_tcp*) old_conn;
1440 RpcConnection_tcp *client = (RpcConnection_tcp*) new_conn;
1441 u_long nonblocking;
1443 addrsize = sizeof(address);
1444 ret = accept(server->sock, (struct sockaddr*) &address, &addrsize);
1445 if (ret < 0)
1447 ERR("Failed to accept a TCP connection: error %d\n", ret);
1448 return RPC_S_OUT_OF_RESOURCES;
1450 nonblocking = 1;
1451 ioctlsocket(ret, FIONBIO, &nonblocking);
1452 client->sock = ret;
1453 TRACE("Accepted a new TCP connection\n");
1454 return RPC_S_OK;
1457 static int rpcrt4_conn_tcp_read(RpcConnection *Connection,
1458 void *buffer, unsigned int count)
1460 RpcConnection_tcp *tcpc = (RpcConnection_tcp *) Connection;
1461 int bytes_read = 0;
1462 while (bytes_read != count)
1464 int r = recv(tcpc->sock, (char *)buffer + bytes_read, count - bytes_read, 0);
1465 if (!r)
1466 return -1;
1467 else if (r > 0)
1468 bytes_read += r;
1469 else if (errno == EINTR)
1470 continue;
1471 else if (errno != EAGAIN)
1473 WARN("recv() failed: %s\n", strerror(errno));
1474 return -1;
1476 else
1478 if (!rpcrt4_sock_wait_for_recv(tcpc))
1479 return -1;
1482 TRACE("%d %p %u -> %d\n", tcpc->sock, buffer, count, bytes_read);
1483 return bytes_read;
1486 static int rpcrt4_conn_tcp_write(RpcConnection *Connection,
1487 const void *buffer, unsigned int count)
1489 RpcConnection_tcp *tcpc = (RpcConnection_tcp *) Connection;
1490 int bytes_written = 0;
1491 while (bytes_written != count)
1493 int r = send(tcpc->sock, (const char *)buffer + bytes_written, count - bytes_written, 0);
1494 if (r >= 0)
1495 bytes_written += r;
1496 else if (errno == EINTR)
1497 continue;
1498 else if (errno != EAGAIN)
1499 return -1;
1500 else
1502 if (!rpcrt4_sock_wait_for_send(tcpc))
1503 return -1;
1506 TRACE("%d %p %u -> %d\n", tcpc->sock, buffer, count, bytes_written);
1507 return bytes_written;
1510 static int rpcrt4_conn_tcp_close(RpcConnection *Connection)
1512 RpcConnection_tcp *tcpc = (RpcConnection_tcp *) Connection;
1514 TRACE("%d\n", tcpc->sock);
1516 if (tcpc->sock != -1)
1517 closesocket(tcpc->sock);
1518 tcpc->sock = -1;
1519 rpcrt4_sock_wait_destroy(tcpc);
1520 return 0;
1523 static void rpcrt4_conn_tcp_cancel_call(RpcConnection *Connection)
1525 RpcConnection_tcp *tcpc = (RpcConnection_tcp *) Connection;
1526 TRACE("%p\n", Connection);
1527 rpcrt4_sock_wait_cancel(tcpc);
1530 static int rpcrt4_conn_tcp_wait_for_incoming_data(RpcConnection *Connection)
1532 RpcConnection_tcp *tcpc = (RpcConnection_tcp *) Connection;
1534 TRACE("%p\n", Connection);
1536 if (!rpcrt4_sock_wait_for_recv(tcpc))
1537 return -1;
1538 return 0;
1541 static size_t rpcrt4_ncacn_ip_tcp_get_top_of_tower(unsigned char *tower_data,
1542 const char *networkaddr,
1543 const char *endpoint)
1545 return rpcrt4_ip_tcp_get_top_of_tower(tower_data, networkaddr,
1546 EPM_PROTOCOL_TCP, endpoint);
1549 #ifdef HAVE_SOCKETPAIR
1551 typedef struct _RpcServerProtseq_sock
1553 RpcServerProtseq common;
1554 int mgr_event_rcv;
1555 int mgr_event_snd;
1556 } RpcServerProtseq_sock;
1558 static RpcServerProtseq *rpcrt4_protseq_sock_alloc(void)
1560 RpcServerProtseq_sock *ps = HeapAlloc(GetProcessHeap(), 0, sizeof(*ps));
1561 if (ps)
1563 int fds[2];
1564 if (!socketpair(PF_UNIX, SOCK_DGRAM, 0, fds))
1566 fcntl(fds[0], F_SETFL, O_NONBLOCK);
1567 fcntl(fds[1], F_SETFL, O_NONBLOCK);
1568 ps->mgr_event_rcv = fds[0];
1569 ps->mgr_event_snd = fds[1];
1571 else
1573 ERR("socketpair failed with error %s\n", strerror(errno));
1574 HeapFree(GetProcessHeap(), 0, ps);
1575 return NULL;
1578 return &ps->common;
1581 static void rpcrt4_protseq_sock_signal_state_changed(RpcServerProtseq *protseq)
1583 RpcServerProtseq_sock *sockps = CONTAINING_RECORD(protseq, RpcServerProtseq_sock, common);
1584 char dummy = 1;
1585 write(sockps->mgr_event_snd, &dummy, sizeof(dummy));
1588 static void *rpcrt4_protseq_sock_get_wait_array(RpcServerProtseq *protseq, void *prev_array, unsigned int *count)
1590 struct pollfd *poll_info = prev_array;
1591 RpcConnection_tcp *conn;
1592 RpcServerProtseq_sock *sockps = CONTAINING_RECORD(protseq, RpcServerProtseq_sock, common);
1594 EnterCriticalSection(&protseq->cs);
1596 /* open and count connections */
1597 *count = 1;
1598 conn = (RpcConnection_tcp *)protseq->conn;
1599 while (conn) {
1600 if (conn->sock != -1)
1601 (*count)++;
1602 conn = (RpcConnection_tcp *)conn->common.Next;
1605 /* make array of connections */
1606 if (poll_info)
1607 poll_info = HeapReAlloc(GetProcessHeap(), 0, poll_info, *count*sizeof(*poll_info));
1608 else
1609 poll_info = HeapAlloc(GetProcessHeap(), 0, *count*sizeof(*poll_info));
1610 if (!poll_info)
1612 ERR("couldn't allocate poll_info\n");
1613 LeaveCriticalSection(&protseq->cs);
1614 return NULL;
1617 poll_info[0].fd = sockps->mgr_event_rcv;
1618 poll_info[0].events = POLLIN;
1619 *count = 1;
1620 conn = CONTAINING_RECORD(protseq->conn, RpcConnection_tcp, common);
1621 while (conn) {
1622 if (conn->sock != -1)
1624 poll_info[*count].fd = conn->sock;
1625 poll_info[*count].events = POLLIN;
1626 (*count)++;
1628 conn = CONTAINING_RECORD(conn->common.Next, RpcConnection_tcp, common);
1630 LeaveCriticalSection(&protseq->cs);
1631 return poll_info;
1634 static void rpcrt4_protseq_sock_free_wait_array(RpcServerProtseq *protseq, void *array)
1636 HeapFree(GetProcessHeap(), 0, array);
1639 static int rpcrt4_protseq_sock_wait_for_new_connection(RpcServerProtseq *protseq, unsigned int count, void *wait_array)
1641 struct pollfd *poll_info = wait_array;
1642 int ret;
1643 unsigned int i;
1644 RpcConnection *cconn;
1645 RpcConnection_tcp *conn;
1647 if (!poll_info)
1648 return -1;
1650 ret = poll(poll_info, count, -1);
1651 if (ret < 0)
1653 ERR("poll failed with error %d\n", ret);
1654 return -1;
1657 for (i = 0; i < count; i++)
1658 if (poll_info[i].revents & POLLIN)
1660 /* RPC server event */
1661 if (i == 0)
1663 char dummy;
1664 read(poll_info[0].fd, &dummy, sizeof(dummy));
1665 return 0;
1668 /* find which connection got a RPC */
1669 EnterCriticalSection(&protseq->cs);
1670 conn = CONTAINING_RECORD(protseq->conn, RpcConnection_tcp, common);
1671 while (conn) {
1672 if (poll_info[i].fd == conn->sock) break;
1673 conn = CONTAINING_RECORD(conn->common.Next, RpcConnection_tcp, common);
1675 cconn = NULL;
1676 if (conn)
1677 RPCRT4_SpawnConnection(&cconn, &conn->common);
1678 else
1679 ERR("failed to locate connection for fd %d\n", poll_info[i].fd);
1680 LeaveCriticalSection(&protseq->cs);
1681 if (cconn)
1682 RPCRT4_new_client(cconn);
1683 else
1684 return -1;
1687 return 1;
1690 #else /* HAVE_SOCKETPAIR */
1692 typedef struct _RpcServerProtseq_sock
1694 RpcServerProtseq common;
1695 HANDLE mgr_event;
1696 } RpcServerProtseq_sock;
1698 static RpcServerProtseq *rpcrt4_protseq_sock_alloc(void)
1700 RpcServerProtseq_sock *ps = HeapAlloc(GetProcessHeap(), 0, sizeof(*ps));
1701 if (ps)
1703 static BOOL wsa_inited;
1704 if (!wsa_inited)
1706 WSADATA wsadata;
1707 WSAStartup(MAKEWORD(2, 2), &wsadata);
1708 /* Note: WSAStartup can be called more than once so we don't bother with
1709 * making accesses to wsa_inited thread-safe */
1710 wsa_inited = TRUE;
1712 ps->mgr_event = CreateEventW(NULL, FALSE, FALSE, NULL);
1714 return &ps->common;
1717 static void rpcrt4_protseq_sock_signal_state_changed(RpcServerProtseq *protseq)
1719 RpcServerProtseq_sock *sockps = CONTAINING_RECORD(protseq, RpcServerProtseq_sock, common);
1720 SetEvent(sockps->mgr_event);
1723 static void *rpcrt4_protseq_sock_get_wait_array(RpcServerProtseq *protseq, void *prev_array, unsigned int *count)
1725 HANDLE *objs = prev_array;
1726 RpcConnection_tcp *conn;
1727 RpcServerProtseq_sock *sockps = CONTAINING_RECORD(protseq, RpcServerProtseq_sock, common);
1729 EnterCriticalSection(&protseq->cs);
1731 /* open and count connections */
1732 *count = 1;
1733 conn = CONTAINING_RECORD(protseq->conn, RpcConnection_tcp, common);
1734 while (conn)
1736 if (conn->sock != -1)
1737 (*count)++;
1738 conn = CONTAINING_RECORD(conn->common.Next, RpcConnection_tcp, common);
1741 /* make array of connections */
1742 if (objs)
1743 objs = HeapReAlloc(GetProcessHeap(), 0, objs, *count*sizeof(HANDLE));
1744 else
1745 objs = HeapAlloc(GetProcessHeap(), 0, *count*sizeof(HANDLE));
1746 if (!objs)
1748 ERR("couldn't allocate objs\n");
1749 LeaveCriticalSection(&protseq->cs);
1750 return NULL;
1753 objs[0] = sockps->mgr_event;
1754 *count = 1;
1755 conn = CONTAINING_RECORD(protseq->conn, RpcConnection_tcp, common);
1756 while (conn)
1758 if (conn->sock != -1)
1760 int res = WSAEventSelect(conn->sock, conn->sock_event, FD_ACCEPT);
1761 if (res == SOCKET_ERROR)
1762 ERR("WSAEventSelect() failed with error %d\n", WSAGetLastError());
1763 else
1765 objs[*count] = conn->sock_event;
1766 (*count)++;
1769 conn = CONTAINING_RECORD(conn->common.Next, RpcConnection_tcp, common);
1771 LeaveCriticalSection(&protseq->cs);
1772 return objs;
1775 static void rpcrt4_protseq_sock_free_wait_array(RpcServerProtseq *protseq, void *array)
1777 HeapFree(GetProcessHeap(), 0, array);
1780 static int rpcrt4_protseq_sock_wait_for_new_connection(RpcServerProtseq *protseq, unsigned int count, void *wait_array)
1782 HANDLE b_handle;
1783 HANDLE *objs = wait_array;
1784 DWORD res;
1785 RpcConnection *cconn;
1786 RpcConnection_tcp *conn;
1788 if (!objs)
1789 return -1;
1793 /* an alertable wait isn't strictly necessary, but due to our
1794 * overlapped I/O implementation in Wine we need to free some memory
1795 * by the file user APC being called, even if no completion routine was
1796 * specified at the time of starting the async operation */
1797 res = WaitForMultipleObjectsEx(count, objs, FALSE, INFINITE, TRUE);
1798 } while (res == WAIT_IO_COMPLETION);
1800 if (res == WAIT_OBJECT_0)
1801 return 0;
1802 else if (res == WAIT_FAILED)
1804 ERR("wait failed with error %d\n", GetLastError());
1805 return -1;
1807 else
1809 b_handle = objs[res - WAIT_OBJECT_0];
1810 /* find which connection got a RPC */
1811 EnterCriticalSection(&protseq->cs);
1812 conn = CONTAINING_RECORD(protseq->conn, RpcConnection_tcp, common);
1813 while (conn)
1815 if (b_handle == conn->sock_event) break;
1816 conn = CONTAINING_RECORD(conn->common.Next, RpcConnection_tcp, common);
1818 cconn = NULL;
1819 if (conn)
1820 RPCRT4_SpawnConnection(&cconn, &conn->common);
1821 else
1822 ERR("failed to locate connection for handle %p\n", b_handle);
1823 LeaveCriticalSection(&protseq->cs);
1824 if (cconn)
1826 RPCRT4_new_client(cconn);
1827 return 1;
1829 else return -1;
1833 #endif /* HAVE_SOCKETPAIR */
1835 static RPC_STATUS rpcrt4_ncacn_ip_tcp_parse_top_of_tower(const unsigned char *tower_data,
1836 size_t tower_size,
1837 char **networkaddr,
1838 char **endpoint)
1840 return rpcrt4_ip_tcp_parse_top_of_tower(tower_data, tower_size,
1841 networkaddr, EPM_PROTOCOL_TCP,
1842 endpoint);
1845 /**** ncacn_http support ****/
1847 /* 60 seconds is the period native uses */
1848 #define HTTP_IDLE_TIME 60000
1850 /* reference counted to avoid a race between a cancelled call's connection
1851 * being destroyed and the asynchronous InternetReadFileEx call being
1852 * completed */
1853 typedef struct _RpcHttpAsyncData
1855 LONG refs;
1856 HANDLE completion_event;
1857 WORD async_result;
1858 INTERNET_BUFFERSW inet_buffers;
1859 CRITICAL_SECTION cs;
1860 } RpcHttpAsyncData;
1862 static ULONG RpcHttpAsyncData_AddRef(RpcHttpAsyncData *data)
1864 return InterlockedIncrement(&data->refs);
1867 static ULONG RpcHttpAsyncData_Release(RpcHttpAsyncData *data)
1869 ULONG refs = InterlockedDecrement(&data->refs);
1870 if (!refs)
1872 TRACE("destroying async data %p\n", data);
1873 CloseHandle(data->completion_event);
1874 HeapFree(GetProcessHeap(), 0, data->inet_buffers.lpvBuffer);
1875 data->cs.DebugInfo->Spare[0] = 0;
1876 DeleteCriticalSection(&data->cs);
1877 HeapFree(GetProcessHeap(), 0, data);
1879 return refs;
1882 static void prepare_async_request(RpcHttpAsyncData *async_data)
1884 ResetEvent(async_data->completion_event);
1885 RpcHttpAsyncData_AddRef(async_data);
1888 static RPC_STATUS wait_async_request(RpcHttpAsyncData *async_data, BOOL call_ret, HANDLE cancel_event)
1890 HANDLE handles[2] = { async_data->completion_event, cancel_event };
1891 DWORD res;
1893 if(call_ret) {
1894 RpcHttpAsyncData_Release(async_data);
1895 return RPC_S_OK;
1898 if(GetLastError() != ERROR_IO_PENDING) {
1899 RpcHttpAsyncData_Release(async_data);
1900 ERR("Request failed with error %d\n", GetLastError());
1901 return RPC_S_SERVER_UNAVAILABLE;
1904 res = WaitForMultipleObjects(2, handles, FALSE, DEFAULT_NCACN_HTTP_TIMEOUT);
1905 if(res != WAIT_OBJECT_0) {
1906 TRACE("Cancelled\n");
1907 return RPC_S_CALL_CANCELLED;
1910 if(async_data->async_result) {
1911 ERR("Async request failed with error %d\n", async_data->async_result);
1912 return RPC_S_SERVER_UNAVAILABLE;
1915 return RPC_S_OK;
1918 struct authinfo
1920 DWORD scheme;
1921 CredHandle cred;
1922 CtxtHandle ctx;
1923 TimeStamp exp;
1924 ULONG attr;
1925 ULONG max_token;
1926 char *data;
1927 unsigned int data_len;
1928 BOOL finished; /* finished authenticating */
1931 typedef struct _RpcConnection_http
1933 RpcConnection common;
1934 HINTERNET app_info;
1935 HINTERNET session;
1936 HINTERNET in_request;
1937 HINTERNET out_request;
1938 WCHAR *servername;
1939 HANDLE timer_cancelled;
1940 HANDLE cancel_event;
1941 DWORD last_sent_time;
1942 ULONG bytes_received;
1943 ULONG flow_control_mark; /* send a control packet to the server when this many bytes received */
1944 ULONG flow_control_increment; /* number of bytes to increment flow_control_mark by */
1945 UUID connection_uuid;
1946 UUID in_pipe_uuid;
1947 UUID out_pipe_uuid;
1948 RpcHttpAsyncData *async_data;
1949 } RpcConnection_http;
1951 static RpcConnection *rpcrt4_ncacn_http_alloc(void)
1953 RpcConnection_http *httpc;
1954 httpc = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*httpc));
1955 if (!httpc) return NULL;
1956 httpc->async_data = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(RpcHttpAsyncData));
1957 if (!httpc->async_data)
1959 HeapFree(GetProcessHeap(), 0, httpc);
1960 return NULL;
1962 TRACE("async data = %p\n", httpc->async_data);
1963 httpc->cancel_event = CreateEventW(NULL, FALSE, FALSE, NULL);
1964 httpc->async_data->refs = 1;
1965 httpc->async_data->inet_buffers.dwStructSize = sizeof(INTERNET_BUFFERSW);
1966 httpc->async_data->inet_buffers.lpvBuffer = NULL;
1967 InitializeCriticalSection(&httpc->async_data->cs);
1968 httpc->async_data->cs.DebugInfo->Spare[0] = (DWORD_PTR)(__FILE__ ": RpcHttpAsyncData.cs");
1969 return &httpc->common;
1972 typedef struct _HttpTimerThreadData
1974 PVOID timer_param;
1975 DWORD *last_sent_time;
1976 HANDLE timer_cancelled;
1977 } HttpTimerThreadData;
1979 static VOID rpcrt4_http_keep_connection_active_timer_proc(PVOID param, BOOLEAN dummy)
1981 HINTERNET in_request = param;
1982 RpcPktHdr *idle_pkt;
1984 idle_pkt = RPCRT4_BuildHttpHeader(NDR_LOCAL_DATA_REPRESENTATION, 0x0001,
1985 0, 0);
1986 if (idle_pkt)
1988 DWORD bytes_written;
1989 InternetWriteFile(in_request, idle_pkt, idle_pkt->common.frag_len, &bytes_written);
1990 RPCRT4_FreeHeader(idle_pkt);
1994 static inline DWORD rpcrt4_http_timer_calc_timeout(DWORD *last_sent_time)
1996 DWORD cur_time = GetTickCount();
1997 DWORD cached_last_sent_time = *last_sent_time;
1998 return HTTP_IDLE_TIME - (cur_time - cached_last_sent_time > HTTP_IDLE_TIME ? 0 : cur_time - cached_last_sent_time);
2001 static DWORD CALLBACK rpcrt4_http_timer_thread(PVOID param)
2003 HttpTimerThreadData *data_in = param;
2004 HttpTimerThreadData data;
2005 DWORD timeout;
2007 data = *data_in;
2008 HeapFree(GetProcessHeap(), 0, data_in);
2010 for (timeout = HTTP_IDLE_TIME;
2011 WaitForSingleObject(data.timer_cancelled, timeout) == WAIT_TIMEOUT;
2012 timeout = rpcrt4_http_timer_calc_timeout(data.last_sent_time))
2014 /* are we too soon after last send? */
2015 if (GetTickCount() - *data.last_sent_time < HTTP_IDLE_TIME)
2016 continue;
2017 rpcrt4_http_keep_connection_active_timer_proc(data.timer_param, TRUE);
2020 CloseHandle(data.timer_cancelled);
2021 return 0;
2024 static VOID WINAPI rpcrt4_http_internet_callback(
2025 HINTERNET hInternet,
2026 DWORD_PTR dwContext,
2027 DWORD dwInternetStatus,
2028 LPVOID lpvStatusInformation,
2029 DWORD dwStatusInformationLength)
2031 RpcHttpAsyncData *async_data = (RpcHttpAsyncData *)dwContext;
2033 switch (dwInternetStatus)
2035 case INTERNET_STATUS_REQUEST_COMPLETE:
2036 TRACE("INTERNET_STATUS_REQUEST_COMPLETED\n");
2037 if (async_data)
2039 INTERNET_ASYNC_RESULT *async_result = lpvStatusInformation;
2041 async_data->async_result = async_result->dwResult ? ERROR_SUCCESS : async_result->dwError;
2042 SetEvent(async_data->completion_event);
2043 RpcHttpAsyncData_Release(async_data);
2045 break;
2049 static RPC_STATUS rpcrt4_http_check_response(HINTERNET hor)
2051 BOOL ret;
2052 DWORD status_code;
2053 DWORD size;
2054 DWORD index;
2055 WCHAR buf[32];
2056 WCHAR *status_text = buf;
2057 TRACE("\n");
2059 index = 0;
2060 size = sizeof(status_code);
2061 ret = HttpQueryInfoW(hor, HTTP_QUERY_STATUS_CODE|HTTP_QUERY_FLAG_NUMBER, &status_code, &size, &index);
2062 if (!ret)
2063 return GetLastError();
2064 if (status_code == HTTP_STATUS_OK)
2065 return RPC_S_OK;
2066 index = 0;
2067 size = sizeof(buf);
2068 ret = HttpQueryInfoW(hor, HTTP_QUERY_STATUS_TEXT, status_text, &size, &index);
2069 if (!ret && GetLastError() == ERROR_INSUFFICIENT_BUFFER)
2071 status_text = HeapAlloc(GetProcessHeap(), 0, size);
2072 ret = HttpQueryInfoW(hor, HTTP_QUERY_STATUS_TEXT, status_text, &size, &index);
2075 ERR("server returned: %d %s\n", status_code, ret ? debugstr_w(status_text) : "<status text unavailable>");
2076 if(status_text != buf) HeapFree(GetProcessHeap(), 0, status_text);
2078 if (status_code == HTTP_STATUS_DENIED)
2079 return ERROR_ACCESS_DENIED;
2080 return RPC_S_SERVER_UNAVAILABLE;
2083 static RPC_STATUS rpcrt4_http_internet_connect(RpcConnection_http *httpc)
2085 static const WCHAR wszUserAgent[] = {'M','S','R','P','C',0};
2086 LPWSTR proxy = NULL;
2087 LPWSTR user = NULL;
2088 LPWSTR password = NULL;
2089 LPWSTR servername = NULL;
2090 const WCHAR *option;
2091 INTERNET_PORT port;
2093 if (httpc->common.QOS &&
2094 (httpc->common.QOS->qos->AdditionalSecurityInfoType == RPC_C_AUTHN_INFO_TYPE_HTTP))
2096 const RPC_HTTP_TRANSPORT_CREDENTIALS_W *http_cred = httpc->common.QOS->qos->u.HttpCredentials;
2097 if (http_cred->TransportCredentials)
2099 WCHAR *p;
2100 const SEC_WINNT_AUTH_IDENTITY_W *cred = http_cred->TransportCredentials;
2101 ULONG len = cred->DomainLength + 1 + cred->UserLength;
2102 user = HeapAlloc(GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR));
2103 if (!user)
2104 return RPC_S_OUT_OF_RESOURCES;
2105 p = user;
2106 if (cred->DomainLength)
2108 memcpy(p, cred->Domain, cred->DomainLength * sizeof(WCHAR));
2109 p += cred->DomainLength;
2110 *p = '\\';
2111 p++;
2113 memcpy(p, cred->User, cred->UserLength * sizeof(WCHAR));
2114 p[cred->UserLength] = 0;
2116 password = RPCRT4_strndupW(cred->Password, cred->PasswordLength);
2120 for (option = httpc->common.NetworkOptions; option;
2121 option = (strchrW(option, ',') ? strchrW(option, ',')+1 : NULL))
2123 static const WCHAR wszRpcProxy[] = {'R','p','c','P','r','o','x','y','=',0};
2124 static const WCHAR wszHttpProxy[] = {'H','t','t','p','P','r','o','x','y','=',0};
2126 if (!strncmpiW(option, wszRpcProxy, sizeof(wszRpcProxy)/sizeof(wszRpcProxy[0])-1))
2128 const WCHAR *value_start = option + sizeof(wszRpcProxy)/sizeof(wszRpcProxy[0])-1;
2129 const WCHAR *value_end;
2130 const WCHAR *p;
2132 value_end = strchrW(option, ',');
2133 if (!value_end)
2134 value_end = value_start + strlenW(value_start);
2135 for (p = value_start; p < value_end; p++)
2136 if (*p == ':')
2138 port = atoiW(p+1);
2139 value_end = p;
2140 break;
2142 TRACE("RpcProxy value is %s\n", debugstr_wn(value_start, value_end-value_start));
2143 servername = RPCRT4_strndupW(value_start, value_end-value_start);
2145 else if (!strncmpiW(option, wszHttpProxy, sizeof(wszHttpProxy)/sizeof(wszHttpProxy[0])-1))
2147 const WCHAR *value_start = option + sizeof(wszHttpProxy)/sizeof(wszHttpProxy[0])-1;
2148 const WCHAR *value_end;
2150 value_end = strchrW(option, ',');
2151 if (!value_end)
2152 value_end = value_start + strlenW(value_start);
2153 TRACE("HttpProxy value is %s\n", debugstr_wn(value_start, value_end-value_start));
2154 proxy = RPCRT4_strndupW(value_start, value_end-value_start);
2156 else
2157 FIXME("unhandled option %s\n", debugstr_w(option));
2160 httpc->app_info = InternetOpenW(wszUserAgent, proxy ? INTERNET_OPEN_TYPE_PROXY : INTERNET_OPEN_TYPE_PRECONFIG,
2161 NULL, NULL, INTERNET_FLAG_ASYNC);
2162 if (!httpc->app_info)
2164 HeapFree(GetProcessHeap(), 0, password);
2165 HeapFree(GetProcessHeap(), 0, user);
2166 HeapFree(GetProcessHeap(), 0, proxy);
2167 HeapFree(GetProcessHeap(), 0, servername);
2168 ERR("InternetOpenW failed with error %d\n", GetLastError());
2169 return RPC_S_SERVER_UNAVAILABLE;
2171 InternetSetStatusCallbackW(httpc->app_info, rpcrt4_http_internet_callback);
2173 /* if no RpcProxy option specified, set the HTTP server address to the
2174 * RPC server address */
2175 if (!servername)
2177 servername = HeapAlloc(GetProcessHeap(), 0, (strlen(httpc->common.NetworkAddr) + 1)*sizeof(WCHAR));
2178 if (!servername)
2180 HeapFree(GetProcessHeap(), 0, password);
2181 HeapFree(GetProcessHeap(), 0, user);
2182 HeapFree(GetProcessHeap(), 0, proxy);
2183 return RPC_S_OUT_OF_RESOURCES;
2185 MultiByteToWideChar(CP_ACP, 0, httpc->common.NetworkAddr, -1, servername, strlen(httpc->common.NetworkAddr) + 1);
2188 port = (httpc->common.QOS &&
2189 (httpc->common.QOS->qos->AdditionalSecurityInfoType == RPC_C_AUTHN_INFO_TYPE_HTTP) &&
2190 (httpc->common.QOS->qos->u.HttpCredentials->Flags & RPC_C_HTTP_FLAG_USE_SSL)) ?
2191 INTERNET_DEFAULT_HTTPS_PORT : INTERNET_DEFAULT_HTTP_PORT;
2193 httpc->session = InternetConnectW(httpc->app_info, servername, port, user, password,
2194 INTERNET_SERVICE_HTTP, 0, 0);
2196 HeapFree(GetProcessHeap(), 0, password);
2197 HeapFree(GetProcessHeap(), 0, user);
2198 HeapFree(GetProcessHeap(), 0, proxy);
2200 if (!httpc->session)
2202 ERR("InternetConnectW failed with error %d\n", GetLastError());
2203 HeapFree(GetProcessHeap(), 0, servername);
2204 return RPC_S_SERVER_UNAVAILABLE;
2206 httpc->servername = servername;
2207 return RPC_S_OK;
2210 static int rpcrt4_http_async_read(HINTERNET req, RpcHttpAsyncData *async_data, HANDLE cancel_event,
2211 void *buffer, unsigned int count)
2213 char *buf = buffer;
2214 BOOL ret;
2215 unsigned int bytes_left = count;
2216 RPC_STATUS status = RPC_S_OK;
2218 async_data->inet_buffers.lpvBuffer = HeapAlloc(GetProcessHeap(), 0, count);
2220 while (bytes_left)
2222 async_data->inet_buffers.dwBufferLength = bytes_left;
2223 prepare_async_request(async_data);
2224 ret = InternetReadFileExW(req, &async_data->inet_buffers, IRF_ASYNC, 0);
2225 status = wait_async_request(async_data, ret, cancel_event);
2226 if (status != RPC_S_OK)
2228 if (status == RPC_S_CALL_CANCELLED)
2229 TRACE("call cancelled\n");
2230 break;
2233 if (!async_data->inet_buffers.dwBufferLength)
2234 break;
2235 memcpy(buf, async_data->inet_buffers.lpvBuffer,
2236 async_data->inet_buffers.dwBufferLength);
2238 bytes_left -= async_data->inet_buffers.dwBufferLength;
2239 buf += async_data->inet_buffers.dwBufferLength;
2242 HeapFree(GetProcessHeap(), 0, async_data->inet_buffers.lpvBuffer);
2243 async_data->inet_buffers.lpvBuffer = NULL;
2245 TRACE("%p %p %u -> %u\n", req, buffer, count, status);
2246 return status == RPC_S_OK ? count : -1;
2249 static RPC_STATUS send_echo_request(HINTERNET req, RpcHttpAsyncData *async_data, HANDLE cancel_event)
2251 BYTE buf[20];
2252 BOOL ret;
2253 RPC_STATUS status;
2255 TRACE("sending echo request to server\n");
2257 prepare_async_request(async_data);
2258 ret = HttpSendRequestW(req, NULL, 0, NULL, 0);
2259 status = wait_async_request(async_data, ret, cancel_event);
2260 if (status != RPC_S_OK) return status;
2262 status = rpcrt4_http_check_response(req);
2263 if (status != RPC_S_OK) return status;
2265 rpcrt4_http_async_read(req, async_data, cancel_event, buf, sizeof(buf));
2266 /* FIXME: do something with retrieved data */
2268 return RPC_S_OK;
2271 static RPC_STATUS insert_content_length_header(HINTERNET request, DWORD len)
2273 static const WCHAR fmtW[] =
2274 {'C','o','n','t','e','n','t','-','L','e','n','g','t','h',':',' ','%','u','\r','\n',0};
2275 WCHAR header[sizeof(fmtW) / sizeof(fmtW[0]) + 10];
2277 sprintfW(header, fmtW, len);
2278 if ((HttpAddRequestHeadersW(request, header, -1, HTTP_ADDREQ_FLAG_REPLACE | HTTP_ADDREQ_FLAG_ADD))) return RPC_S_OK;
2279 return RPC_S_SERVER_UNAVAILABLE;
2282 /* prepare the in pipe for use by RPC packets */
2283 static RPC_STATUS rpcrt4_http_prepare_in_pipe(HINTERNET in_request, RpcHttpAsyncData *async_data, HANDLE cancel_event,
2284 const UUID *connection_uuid, const UUID *in_pipe_uuid,
2285 const UUID *association_uuid, BOOL authorized)
2287 BOOL ret;
2288 RPC_STATUS status;
2289 RpcPktHdr *hdr;
2290 INTERNET_BUFFERSW buffers_in;
2291 DWORD bytes_written;
2293 if (!authorized)
2295 /* ask wininet to authorize, if necessary */
2296 status = send_echo_request(in_request, async_data, cancel_event);
2297 if (status != RPC_S_OK) return status;
2299 memset(&buffers_in, 0, sizeof(buffers_in));
2300 buffers_in.dwStructSize = sizeof(buffers_in);
2301 /* FIXME: get this from the registry */
2302 buffers_in.dwBufferTotal = 1024 * 1024 * 1024; /* 1Gb */
2303 status = insert_content_length_header(in_request, buffers_in.dwBufferTotal);
2304 if (status != RPC_S_OK) return status;
2306 prepare_async_request(async_data);
2307 ret = HttpSendRequestExW(in_request, &buffers_in, NULL, 0, 0);
2308 status = wait_async_request(async_data, ret, cancel_event);
2309 if (status != RPC_S_OK) return status;
2311 TRACE("sending HTTP connect header to server\n");
2312 hdr = RPCRT4_BuildHttpConnectHeader(FALSE, connection_uuid, in_pipe_uuid, association_uuid);
2313 if (!hdr) return RPC_S_OUT_OF_RESOURCES;
2314 ret = InternetWriteFile(in_request, hdr, hdr->common.frag_len, &bytes_written);
2315 RPCRT4_FreeHeader(hdr);
2316 if (!ret)
2318 ERR("InternetWriteFile failed with error %d\n", GetLastError());
2319 return RPC_S_SERVER_UNAVAILABLE;
2322 return RPC_S_OK;
2325 static RPC_STATUS rpcrt4_http_read_http_packet(HINTERNET request, RpcHttpAsyncData *async_data,
2326 HANDLE cancel_event, RpcPktHdr *hdr, BYTE **data)
2328 unsigned short data_len;
2329 unsigned int size;
2331 if (rpcrt4_http_async_read(request, async_data, cancel_event, hdr, sizeof(hdr->common)) < 0)
2332 return RPC_S_SERVER_UNAVAILABLE;
2333 if (hdr->common.ptype != PKT_HTTP || hdr->common.frag_len < sizeof(hdr->http))
2335 ERR("wrong packet type received %d or wrong frag_len %d\n",
2336 hdr->common.ptype, hdr->common.frag_len);
2337 return RPC_S_PROTOCOL_ERROR;
2340 size = sizeof(hdr->http) - sizeof(hdr->common);
2341 if (rpcrt4_http_async_read(request, async_data, cancel_event, &hdr->common + 1, size) < 0)
2342 return RPC_S_SERVER_UNAVAILABLE;
2344 data_len = hdr->common.frag_len - sizeof(hdr->http);
2345 if (data_len)
2347 *data = HeapAlloc(GetProcessHeap(), 0, data_len);
2348 if (!*data)
2349 return RPC_S_OUT_OF_RESOURCES;
2350 if (rpcrt4_http_async_read(request, async_data, cancel_event, *data, data_len) < 0)
2352 HeapFree(GetProcessHeap(), 0, *data);
2353 return RPC_S_SERVER_UNAVAILABLE;
2356 else
2357 *data = NULL;
2359 if (!RPCRT4_IsValidHttpPacket(hdr, *data, data_len))
2361 ERR("invalid http packet\n");
2362 HeapFree(GetProcessHeap(), 0, *data);
2363 return RPC_S_PROTOCOL_ERROR;
2366 return RPC_S_OK;
2369 /* prepare the out pipe for use by RPC packets */
2370 static RPC_STATUS rpcrt4_http_prepare_out_pipe(HINTERNET out_request, RpcHttpAsyncData *async_data,
2371 HANDLE cancel_event, const UUID *connection_uuid,
2372 const UUID *out_pipe_uuid, ULONG *flow_control_increment,
2373 BOOL authorized)
2375 BOOL ret;
2376 RPC_STATUS status;
2377 RpcPktHdr *hdr;
2378 BYTE *data_from_server;
2379 RpcPktHdr pkt_from_server;
2380 ULONG field1, field3;
2381 BYTE buf[20];
2383 if (!authorized)
2385 /* ask wininet to authorize, if necessary */
2386 status = send_echo_request(out_request, async_data, cancel_event);
2387 if (status != RPC_S_OK) return status;
2389 else
2390 rpcrt4_http_async_read(out_request, async_data, cancel_event, buf, sizeof(buf));
2392 hdr = RPCRT4_BuildHttpConnectHeader(TRUE, connection_uuid, out_pipe_uuid, NULL);
2393 if (!hdr) return RPC_S_OUT_OF_RESOURCES;
2395 status = insert_content_length_header(out_request, hdr->common.frag_len);
2396 if (status != RPC_S_OK)
2398 RPCRT4_FreeHeader(hdr);
2399 return status;
2402 TRACE("sending HTTP connect header to server\n");
2403 prepare_async_request(async_data);
2404 ret = HttpSendRequestW(out_request, NULL, 0, hdr, hdr->common.frag_len);
2405 status = wait_async_request(async_data, ret, cancel_event);
2406 RPCRT4_FreeHeader(hdr);
2407 if (status != RPC_S_OK) return status;
2409 status = rpcrt4_http_check_response(out_request);
2410 if (status != RPC_S_OK) return status;
2412 status = rpcrt4_http_read_http_packet(out_request, async_data, cancel_event,
2413 &pkt_from_server, &data_from_server);
2414 if (status != RPC_S_OK) return status;
2415 status = RPCRT4_ParseHttpPrepareHeader1(&pkt_from_server, data_from_server,
2416 &field1);
2417 HeapFree(GetProcessHeap(), 0, data_from_server);
2418 if (status != RPC_S_OK) return status;
2419 TRACE("received (%d) from first prepare header\n", field1);
2421 for (;;)
2423 status = rpcrt4_http_read_http_packet(out_request, async_data, cancel_event,
2424 &pkt_from_server, &data_from_server);
2425 if (status != RPC_S_OK) return status;
2426 if (pkt_from_server.http.flags != 0x0001) break;
2428 TRACE("http idle packet, waiting for real packet\n");
2429 HeapFree(GetProcessHeap(), 0, data_from_server);
2430 if (pkt_from_server.http.num_data_items != 0)
2432 ERR("HTTP idle packet should have no data items instead of %d\n",
2433 pkt_from_server.http.num_data_items);
2434 return RPC_S_PROTOCOL_ERROR;
2437 status = RPCRT4_ParseHttpPrepareHeader2(&pkt_from_server, data_from_server,
2438 &field1, flow_control_increment,
2439 &field3);
2440 HeapFree(GetProcessHeap(), 0, data_from_server);
2441 if (status != RPC_S_OK) return status;
2442 TRACE("received (0x%08x 0x%08x %d) from second prepare header\n", field1, *flow_control_increment, field3);
2444 return RPC_S_OK;
2447 static UINT encode_base64(const char *bin, unsigned int len, WCHAR *base64)
2449 static const char enc[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
2450 UINT i = 0, x;
2452 while (len > 0)
2454 /* first 6 bits, all from bin[0] */
2455 base64[i++] = enc[(bin[0] & 0xfc) >> 2];
2456 x = (bin[0] & 3) << 4;
2458 /* next 6 bits, 2 from bin[0] and 4 from bin[1] */
2459 if (len == 1)
2461 base64[i++] = enc[x];
2462 base64[i++] = '=';
2463 base64[i++] = '=';
2464 break;
2466 base64[i++] = enc[x | ((bin[1] & 0xf0) >> 4)];
2467 x = (bin[1] & 0x0f) << 2;
2469 /* next 6 bits 4 from bin[1] and 2 from bin[2] */
2470 if (len == 2)
2472 base64[i++] = enc[x];
2473 base64[i++] = '=';
2474 break;
2476 base64[i++] = enc[x | ((bin[2] & 0xc0) >> 6)];
2478 /* last 6 bits, all from bin [2] */
2479 base64[i++] = enc[bin[2] & 0x3f];
2480 bin += 3;
2481 len -= 3;
2483 base64[i] = 0;
2484 return i;
2487 static inline char decode_char( WCHAR c )
2489 if (c >= 'A' && c <= 'Z') return c - 'A';
2490 if (c >= 'a' && c <= 'z') return c - 'a' + 26;
2491 if (c >= '0' && c <= '9') return c - '0' + 52;
2492 if (c == '+') return 62;
2493 if (c == '/') return 63;
2494 return 64;
2497 static unsigned int decode_base64( const WCHAR *base64, unsigned int len, char *buf )
2499 unsigned int i = 0;
2500 char c0, c1, c2, c3;
2501 const WCHAR *p = base64;
2503 while (len > 4)
2505 if ((c0 = decode_char( p[0] )) > 63) return 0;
2506 if ((c1 = decode_char( p[1] )) > 63) return 0;
2507 if ((c2 = decode_char( p[2] )) > 63) return 0;
2508 if ((c3 = decode_char( p[3] )) > 63) return 0;
2510 if (buf)
2512 buf[i + 0] = (c0 << 2) | (c1 >> 4);
2513 buf[i + 1] = (c1 << 4) | (c2 >> 2);
2514 buf[i + 2] = (c2 << 6) | c3;
2516 len -= 4;
2517 i += 3;
2518 p += 4;
2520 if (p[2] == '=')
2522 if ((c0 = decode_char( p[0] )) > 63) return 0;
2523 if ((c1 = decode_char( p[1] )) > 63) return 0;
2525 if (buf) buf[i] = (c0 << 2) | (c1 >> 4);
2526 i++;
2528 else if (p[3] == '=')
2530 if ((c0 = decode_char( p[0] )) > 63) return 0;
2531 if ((c1 = decode_char( p[1] )) > 63) return 0;
2532 if ((c2 = decode_char( p[2] )) > 63) return 0;
2534 if (buf)
2536 buf[i + 0] = (c0 << 2) | (c1 >> 4);
2537 buf[i + 1] = (c1 << 4) | (c2 >> 2);
2539 i += 2;
2541 else
2543 if ((c0 = decode_char( p[0] )) > 63) return 0;
2544 if ((c1 = decode_char( p[1] )) > 63) return 0;
2545 if ((c2 = decode_char( p[2] )) > 63) return 0;
2546 if ((c3 = decode_char( p[3] )) > 63) return 0;
2548 if (buf)
2550 buf[i + 0] = (c0 << 2) | (c1 >> 4);
2551 buf[i + 1] = (c1 << 4) | (c2 >> 2);
2552 buf[i + 2] = (c2 << 6) | c3;
2554 i += 3;
2556 return i;
2559 static struct authinfo *alloc_authinfo(void)
2561 struct authinfo *ret;
2563 if (!(ret = HeapAlloc(GetProcessHeap(), 0, sizeof(*ret) ))) return NULL;
2565 SecInvalidateHandle(&ret->cred);
2566 SecInvalidateHandle(&ret->ctx);
2567 memset(&ret->exp, 0, sizeof(ret->exp));
2568 ret->scheme = 0;
2569 ret->attr = 0;
2570 ret->max_token = 0;
2571 ret->data = NULL;
2572 ret->data_len = 0;
2573 ret->finished = FALSE;
2574 return ret;
2577 static void destroy_authinfo(struct authinfo *info)
2579 if (!info) return;
2581 if (SecIsValidHandle(&info->ctx))
2582 DeleteSecurityContext(&info->ctx);
2583 if (SecIsValidHandle(&info->cred))
2584 FreeCredentialsHandle(&info->cred);
2586 HeapFree(GetProcessHeap(), 0, info->data);
2587 HeapFree(GetProcessHeap(), 0, info);
2590 static const WCHAR basicW[] = {'B','a','s','i','c',0};
2591 static const WCHAR ntlmW[] = {'N','T','L','M',0};
2592 static const WCHAR passportW[] = {'P','a','s','s','p','o','r','t',0};
2593 static const WCHAR digestW[] = {'D','i','g','e','s','t',0};
2594 static const WCHAR negotiateW[] = {'N','e','g','o','t','i','a','t','e',0};
2596 static const struct
2598 const WCHAR *str;
2599 unsigned int len;
2600 DWORD scheme;
2602 auth_schemes[] =
2604 { basicW, ARRAYSIZE(basicW) - 1, RPC_C_HTTP_AUTHN_SCHEME_BASIC },
2605 { ntlmW, ARRAYSIZE(ntlmW) - 1, RPC_C_HTTP_AUTHN_SCHEME_NTLM },
2606 { passportW, ARRAYSIZE(passportW) - 1, RPC_C_HTTP_AUTHN_SCHEME_PASSPORT },
2607 { digestW, ARRAYSIZE(digestW) - 1, RPC_C_HTTP_AUTHN_SCHEME_DIGEST },
2608 { negotiateW, ARRAYSIZE(negotiateW) - 1, RPC_C_HTTP_AUTHN_SCHEME_NEGOTIATE }
2610 static const unsigned int num_auth_schemes = sizeof(auth_schemes)/sizeof(auth_schemes[0]);
2612 static DWORD auth_scheme_from_header( const WCHAR *header )
2614 unsigned int i;
2615 for (i = 0; i < num_auth_schemes; i++)
2617 if (!strncmpiW( header, auth_schemes[i].str, auth_schemes[i].len ) &&
2618 (header[auth_schemes[i].len] == ' ' || !header[auth_schemes[i].len])) return auth_schemes[i].scheme;
2620 return 0;
2623 static BOOL get_authvalue(HINTERNET request, DWORD scheme, WCHAR *buffer, DWORD buflen)
2625 DWORD len, index = 0;
2626 for (;;)
2628 len = buflen;
2629 if (!HttpQueryInfoW(request, HTTP_QUERY_WWW_AUTHENTICATE, buffer, &len, &index)) return FALSE;
2630 if (auth_scheme_from_header(buffer) == scheme) break;
2632 return TRUE;
2635 static RPC_STATUS do_authorization(HINTERNET request, SEC_WCHAR *servername,
2636 const RPC_HTTP_TRANSPORT_CREDENTIALS_W *creds, struct authinfo **auth_ptr)
2638 struct authinfo *info = *auth_ptr;
2639 SEC_WINNT_AUTH_IDENTITY_W *id = creds->TransportCredentials;
2640 RPC_STATUS status = RPC_S_SERVER_UNAVAILABLE;
2642 if ((!info && !(info = alloc_authinfo()))) return RPC_S_SERVER_UNAVAILABLE;
2644 switch (creds->AuthnSchemes[0])
2646 case RPC_C_HTTP_AUTHN_SCHEME_BASIC:
2648 int userlen = WideCharToMultiByte(CP_UTF8, 0, id->User, id->UserLength, NULL, 0, NULL, NULL);
2649 int passlen = WideCharToMultiByte(CP_UTF8, 0, id->Password, id->PasswordLength, NULL, 0, NULL, NULL);
2651 info->data_len = userlen + passlen + 1;
2652 if (!(info->data = HeapAlloc(GetProcessHeap(), 0, info->data_len)))
2654 status = RPC_S_OUT_OF_MEMORY;
2655 break;
2657 WideCharToMultiByte(CP_UTF8, 0, id->User, id->UserLength, info->data, userlen, NULL, NULL);
2658 info->data[userlen] = ':';
2659 WideCharToMultiByte(CP_UTF8, 0, id->Password, id->PasswordLength, info->data + userlen + 1, passlen, NULL, NULL);
2661 info->scheme = RPC_C_HTTP_AUTHN_SCHEME_BASIC;
2662 info->finished = TRUE;
2663 status = RPC_S_OK;
2664 break;
2666 case RPC_C_HTTP_AUTHN_SCHEME_NTLM:
2667 case RPC_C_HTTP_AUTHN_SCHEME_NEGOTIATE:
2670 static SEC_WCHAR ntlmW[] = {'N','T','L','M',0}, negotiateW[] = {'N','e','g','o','t','i','a','t','e',0};
2671 SECURITY_STATUS ret;
2672 SecBufferDesc out_desc, in_desc;
2673 SecBuffer out, in;
2674 ULONG flags = ISC_REQ_CONNECTION|ISC_REQ_USE_DCE_STYLE|ISC_REQ_MUTUAL_AUTH|ISC_REQ_DELEGATE;
2675 SEC_WCHAR *scheme;
2676 int scheme_len;
2677 const WCHAR *p;
2678 WCHAR auth_value[2048];
2679 DWORD size = sizeof(auth_value);
2680 BOOL first = FALSE;
2682 if (creds->AuthnSchemes[0] == RPC_C_HTTP_AUTHN_SCHEME_NTLM) scheme = ntlmW;
2683 else scheme = negotiateW;
2684 scheme_len = strlenW( scheme );
2686 if (!*auth_ptr)
2688 TimeStamp exp;
2689 SecPkgInfoW *pkg_info;
2691 ret = AcquireCredentialsHandleW(NULL, scheme, SECPKG_CRED_OUTBOUND, NULL, id, NULL, NULL, &info->cred, &exp);
2692 if (ret != SEC_E_OK) break;
2694 ret = QuerySecurityPackageInfoW(scheme, &pkg_info);
2695 if (ret != SEC_E_OK) break;
2697 info->max_token = pkg_info->cbMaxToken;
2698 FreeContextBuffer(pkg_info);
2699 first = TRUE;
2701 else
2703 if (info->finished || !get_authvalue(request, creds->AuthnSchemes[0], auth_value, size)) break;
2704 if (auth_scheme_from_header(auth_value) != info->scheme)
2706 ERR("authentication scheme changed\n");
2707 break;
2710 in.BufferType = SECBUFFER_TOKEN;
2711 in.cbBuffer = 0;
2712 in.pvBuffer = NULL;
2714 in_desc.ulVersion = 0;
2715 in_desc.cBuffers = 1;
2716 in_desc.pBuffers = &in;
2718 p = auth_value + scheme_len;
2719 if (!first && *p == ' ')
2721 int len = strlenW(++p);
2722 in.cbBuffer = decode_base64(p, len, NULL);
2723 if (!(in.pvBuffer = HeapAlloc(GetProcessHeap(), 0, in.cbBuffer))) break;
2724 decode_base64(p, len, in.pvBuffer);
2726 out.BufferType = SECBUFFER_TOKEN;
2727 out.cbBuffer = info->max_token;
2728 if (!(out.pvBuffer = HeapAlloc(GetProcessHeap(), 0, out.cbBuffer)))
2730 HeapFree(GetProcessHeap(), 0, in.pvBuffer);
2731 break;
2733 out_desc.ulVersion = 0;
2734 out_desc.cBuffers = 1;
2735 out_desc.pBuffers = &out;
2737 ret = InitializeSecurityContextW(first ? &info->cred : NULL, first ? NULL : &info->ctx,
2738 first ? servername : NULL, flags, 0, SECURITY_NETWORK_DREP,
2739 in.pvBuffer ? &in_desc : NULL, 0, &info->ctx, &out_desc,
2740 &info->attr, &info->exp);
2741 HeapFree(GetProcessHeap(), 0, in.pvBuffer);
2742 if (ret == SEC_E_OK)
2744 HeapFree(GetProcessHeap(), 0, info->data);
2745 info->data = out.pvBuffer;
2746 info->data_len = out.cbBuffer;
2747 info->finished = TRUE;
2748 TRACE("sending last auth packet\n");
2749 status = RPC_S_OK;
2751 else if (ret == SEC_I_CONTINUE_NEEDED)
2753 HeapFree(GetProcessHeap(), 0, info->data);
2754 info->data = out.pvBuffer;
2755 info->data_len = out.cbBuffer;
2756 TRACE("sending next auth packet\n");
2757 status = RPC_S_OK;
2759 else
2761 ERR("InitializeSecurityContextW failed with error 0x%08x\n", ret);
2762 HeapFree(GetProcessHeap(), 0, out.pvBuffer);
2763 break;
2765 info->scheme = creds->AuthnSchemes[0];
2766 break;
2768 default:
2769 FIXME("scheme %u not supported\n", creds->AuthnSchemes[0]);
2770 break;
2773 if (status != RPC_S_OK)
2775 destroy_authinfo(info);
2776 *auth_ptr = NULL;
2777 return status;
2779 *auth_ptr = info;
2780 return RPC_S_OK;
2783 static RPC_STATUS insert_authorization_header(HINTERNET request, ULONG scheme, char *data, int data_len)
2785 static const WCHAR authW[] = {'A','u','t','h','o','r','i','z','a','t','i','o','n',':',' '};
2786 static const WCHAR basicW[] = {'B','a','s','i','c',' '};
2787 static const WCHAR negotiateW[] = {'N','e','g','o','t','i','a','t','e',' '};
2788 static const WCHAR ntlmW[] = {'N','T','L','M',' '};
2789 int scheme_len, auth_len = sizeof(authW) / sizeof(authW[0]), len = ((data_len + 2) * 4) / 3;
2790 const WCHAR *scheme_str;
2791 WCHAR *header, *ptr;
2792 RPC_STATUS status = RPC_S_SERVER_UNAVAILABLE;
2794 switch (scheme)
2796 case RPC_C_HTTP_AUTHN_SCHEME_BASIC:
2797 scheme_str = basicW;
2798 scheme_len = sizeof(basicW) / sizeof(basicW[0]);
2799 break;
2800 case RPC_C_HTTP_AUTHN_SCHEME_NEGOTIATE:
2801 scheme_str = negotiateW;
2802 scheme_len = sizeof(negotiateW) / sizeof(negotiateW[0]);
2803 break;
2804 case RPC_C_HTTP_AUTHN_SCHEME_NTLM:
2805 scheme_str = ntlmW;
2806 scheme_len = sizeof(ntlmW) / sizeof(ntlmW[0]);
2807 break;
2808 default:
2809 ERR("unknown scheme %u\n", scheme);
2810 return RPC_S_SERVER_UNAVAILABLE;
2812 if ((header = HeapAlloc(GetProcessHeap(), 0, (auth_len + scheme_len + len + 2) * sizeof(WCHAR))))
2814 memcpy(header, authW, auth_len * sizeof(WCHAR));
2815 ptr = header + auth_len;
2816 memcpy(ptr, scheme_str, scheme_len * sizeof(WCHAR));
2817 ptr += scheme_len;
2818 len = encode_base64(data, data_len, ptr);
2819 ptr[len++] = '\r';
2820 ptr[len++] = '\n';
2821 ptr[len] = 0;
2822 if (HttpAddRequestHeadersW(request, header, -1, HTTP_ADDREQ_FLAG_ADD|HTTP_ADDREQ_FLAG_REPLACE))
2823 status = RPC_S_OK;
2824 HeapFree(GetProcessHeap(), 0, header);
2826 return status;
2829 static void drain_content(HINTERNET request, RpcHttpAsyncData *async_data, HANDLE cancel_event)
2831 DWORD count, len = 0, size = sizeof(len);
2832 char buf[2048];
2834 HttpQueryInfoW(request, HTTP_QUERY_FLAG_NUMBER|HTTP_QUERY_CONTENT_LENGTH, &len, &size, NULL);
2835 if (!len) return;
2836 for (;;)
2838 count = min(sizeof(buf), len);
2839 if (rpcrt4_http_async_read(request, async_data, cancel_event, buf, count) <= 0) return;
2840 len -= count;
2844 static RPC_STATUS authorize_request(RpcConnection_http *httpc, HINTERNET request)
2846 static const WCHAR authW[] = {'A','u','t','h','o','r','i','z','a','t','i','o','n',':','\r','\n',0};
2847 struct authinfo *info = NULL;
2848 RPC_STATUS status;
2849 BOOL ret;
2851 for (;;)
2853 status = do_authorization(request, httpc->servername, httpc->common.QOS->qos->u.HttpCredentials, &info);
2854 if (status != RPC_S_OK) break;
2856 status = insert_authorization_header(request, info->scheme, info->data, info->data_len);
2857 if (status != RPC_S_OK) break;
2859 prepare_async_request(httpc->async_data);
2860 ret = HttpSendRequestW(request, NULL, 0, NULL, 0);
2861 status = wait_async_request(httpc->async_data, ret, httpc->cancel_event);
2862 if (status != RPC_S_OK || info->finished) break;
2864 status = rpcrt4_http_check_response(request);
2865 if (status != RPC_S_OK && status != ERROR_ACCESS_DENIED) break;
2866 drain_content(request, httpc->async_data, httpc->cancel_event);
2869 if (info->scheme != RPC_C_HTTP_AUTHN_SCHEME_BASIC)
2870 HttpAddRequestHeadersW(request, authW, -1, HTTP_ADDREQ_FLAG_REPLACE | HTTP_ADDREQ_FLAG_ADD);
2872 destroy_authinfo(info);
2873 return status;
2876 static BOOL has_credentials(RpcConnection_http *httpc)
2878 RPC_HTTP_TRANSPORT_CREDENTIALS_W *creds;
2879 SEC_WINNT_AUTH_IDENTITY_W *id;
2881 if (!httpc->common.QOS || httpc->common.QOS->qos->AdditionalSecurityInfoType != RPC_C_AUTHN_INFO_TYPE_HTTP)
2882 return FALSE;
2884 creds = httpc->common.QOS->qos->u.HttpCredentials;
2885 if (creds->AuthenticationTarget != RPC_C_HTTP_AUTHN_TARGET_SERVER || !creds->NumberOfAuthnSchemes)
2886 return FALSE;
2888 id = creds->TransportCredentials;
2889 if (!id || !id->User || !id->Password) return FALSE;
2891 return TRUE;
2894 static BOOL is_secure(RpcConnection_http *httpc)
2896 return httpc->common.QOS &&
2897 (httpc->common.QOS->qos->AdditionalSecurityInfoType == RPC_C_AUTHN_INFO_TYPE_HTTP) &&
2898 (httpc->common.QOS->qos->u.HttpCredentials->Flags & RPC_C_HTTP_FLAG_USE_SSL);
2901 static RPC_STATUS set_auth_cookie(RpcConnection_http *httpc, const WCHAR *value)
2903 static WCHAR httpW[] = {'h','t','t','p',0};
2904 static WCHAR httpsW[] = {'h','t','t','p','s',0};
2905 URL_COMPONENTSW uc;
2906 DWORD len;
2907 WCHAR *url;
2908 BOOL ret;
2910 if (!value) return RPC_S_OK;
2912 uc.dwStructSize = sizeof(uc);
2913 uc.lpszScheme = is_secure(httpc) ? httpsW : httpW;
2914 uc.dwSchemeLength = 0;
2915 uc.lpszHostName = httpc->servername;
2916 uc.dwHostNameLength = 0;
2917 uc.nPort = 0;
2918 uc.lpszUserName = NULL;
2919 uc.dwUserNameLength = 0;
2920 uc.lpszPassword = NULL;
2921 uc.dwPasswordLength = 0;
2922 uc.lpszUrlPath = NULL;
2923 uc.dwUrlPathLength = 0;
2924 uc.lpszExtraInfo = NULL;
2925 uc.dwExtraInfoLength = 0;
2927 if (!InternetCreateUrlW(&uc, 0, NULL, &len) && (GetLastError() != ERROR_INSUFFICIENT_BUFFER))
2928 return RPC_S_SERVER_UNAVAILABLE;
2930 if (!(url = HeapAlloc(GetProcessHeap(), 0, len))) return RPC_S_OUT_OF_MEMORY;
2932 len = len / sizeof(WCHAR) - 1;
2933 if (!InternetCreateUrlW(&uc, 0, url, &len))
2935 HeapFree(GetProcessHeap(), 0, url);
2936 return RPC_S_SERVER_UNAVAILABLE;
2939 ret = InternetSetCookieW(url, NULL, value);
2940 HeapFree(GetProcessHeap(), 0, url);
2941 if (!ret) return RPC_S_SERVER_UNAVAILABLE;
2943 return RPC_S_OK;
2946 static RPC_STATUS rpcrt4_ncacn_http_open(RpcConnection* Connection)
2948 RpcConnection_http *httpc = (RpcConnection_http *)Connection;
2949 static const WCHAR wszVerbIn[] = {'R','P','C','_','I','N','_','D','A','T','A',0};
2950 static const WCHAR wszVerbOut[] = {'R','P','C','_','O','U','T','_','D','A','T','A',0};
2951 static const WCHAR wszRpcProxyPrefix[] = {'/','r','p','c','/','r','p','c','p','r','o','x','y','.','d','l','l','?',0};
2952 static const WCHAR wszColon[] = {':',0};
2953 static const WCHAR wszAcceptType[] = {'a','p','p','l','i','c','a','t','i','o','n','/','r','p','c',0};
2954 LPCWSTR wszAcceptTypes[] = { wszAcceptType, NULL };
2955 DWORD flags;
2956 WCHAR *url;
2957 RPC_STATUS status;
2958 BOOL secure, credentials;
2959 HttpTimerThreadData *timer_data;
2960 HANDLE thread;
2962 TRACE("(%s, %s)\n", Connection->NetworkAddr, Connection->Endpoint);
2964 if (Connection->server)
2966 ERR("ncacn_http servers not supported yet\n");
2967 return RPC_S_SERVER_UNAVAILABLE;
2970 if (httpc->in_request)
2971 return RPC_S_OK;
2973 httpc->async_data->completion_event = CreateEventW(NULL, FALSE, FALSE, NULL);
2975 UuidCreate(&httpc->connection_uuid);
2976 UuidCreate(&httpc->in_pipe_uuid);
2977 UuidCreate(&httpc->out_pipe_uuid);
2979 status = rpcrt4_http_internet_connect(httpc);
2980 if (status != RPC_S_OK)
2981 return status;
2983 url = HeapAlloc(GetProcessHeap(), 0, sizeof(wszRpcProxyPrefix) + (strlen(Connection->NetworkAddr) + 1 + strlen(Connection->Endpoint))*sizeof(WCHAR));
2984 if (!url)
2985 return RPC_S_OUT_OF_MEMORY;
2986 memcpy(url, wszRpcProxyPrefix, sizeof(wszRpcProxyPrefix));
2987 MultiByteToWideChar(CP_ACP, 0, Connection->NetworkAddr, -1, url+sizeof(wszRpcProxyPrefix)/sizeof(wszRpcProxyPrefix[0])-1, strlen(Connection->NetworkAddr)+1);
2988 strcatW(url, wszColon);
2989 MultiByteToWideChar(CP_ACP, 0, Connection->Endpoint, -1, url+strlenW(url), strlen(Connection->Endpoint)+1);
2991 secure = is_secure(httpc);
2992 credentials = has_credentials(httpc);
2994 flags = INTERNET_FLAG_KEEP_CONNECTION | INTERNET_FLAG_PRAGMA_NOCACHE | INTERNET_FLAG_NO_CACHE_WRITE |
2995 INTERNET_FLAG_NO_AUTO_REDIRECT;
2996 if (secure) flags |= INTERNET_FLAG_SECURE;
2997 if (credentials) flags |= INTERNET_FLAG_NO_AUTH;
2999 status = set_auth_cookie(httpc, Connection->CookieAuth);
3000 if (status != RPC_S_OK)
3002 HeapFree(GetProcessHeap(), 0, url);
3003 return status;
3005 httpc->in_request = HttpOpenRequestW(httpc->session, wszVerbIn, url, NULL, NULL, wszAcceptTypes,
3006 flags, (DWORD_PTR)httpc->async_data);
3007 if (!httpc->in_request)
3009 ERR("HttpOpenRequestW failed with error %d\n", GetLastError());
3010 HeapFree(GetProcessHeap(), 0, url);
3011 return RPC_S_SERVER_UNAVAILABLE;
3014 if (credentials)
3016 status = authorize_request(httpc, httpc->in_request);
3017 if (status != RPC_S_OK)
3019 HeapFree(GetProcessHeap(), 0, url);
3020 return status;
3022 status = rpcrt4_http_check_response(httpc->in_request);
3023 if (status != RPC_S_OK)
3025 HeapFree(GetProcessHeap(), 0, url);
3026 return status;
3028 drain_content(httpc->in_request, httpc->async_data, httpc->cancel_event);
3031 httpc->out_request = HttpOpenRequestW(httpc->session, wszVerbOut, url, NULL, NULL, wszAcceptTypes,
3032 flags, (DWORD_PTR)httpc->async_data);
3033 HeapFree(GetProcessHeap(), 0, url);
3034 if (!httpc->out_request)
3036 ERR("HttpOpenRequestW failed with error %d\n", GetLastError());
3037 return RPC_S_SERVER_UNAVAILABLE;
3040 if (credentials)
3042 status = authorize_request(httpc, httpc->out_request);
3043 if (status != RPC_S_OK)
3044 return status;
3047 status = rpcrt4_http_prepare_in_pipe(httpc->in_request, httpc->async_data, httpc->cancel_event,
3048 &httpc->connection_uuid, &httpc->in_pipe_uuid,
3049 &Connection->assoc->http_uuid, credentials);
3050 if (status != RPC_S_OK)
3051 return status;
3053 status = rpcrt4_http_prepare_out_pipe(httpc->out_request, httpc->async_data, httpc->cancel_event,
3054 &httpc->connection_uuid, &httpc->out_pipe_uuid,
3055 &httpc->flow_control_increment, credentials);
3056 if (status != RPC_S_OK)
3057 return status;
3059 httpc->flow_control_mark = httpc->flow_control_increment / 2;
3060 httpc->last_sent_time = GetTickCount();
3061 httpc->timer_cancelled = CreateEventW(NULL, FALSE, FALSE, NULL);
3063 timer_data = HeapAlloc(GetProcessHeap(), 0, sizeof(*timer_data));
3064 if (!timer_data)
3065 return ERROR_OUTOFMEMORY;
3066 timer_data->timer_param = httpc->in_request;
3067 timer_data->last_sent_time = &httpc->last_sent_time;
3068 timer_data->timer_cancelled = httpc->timer_cancelled;
3069 /* FIXME: should use CreateTimerQueueTimer when implemented */
3070 thread = CreateThread(NULL, 0, rpcrt4_http_timer_thread, timer_data, 0, NULL);
3071 if (!thread)
3073 HeapFree(GetProcessHeap(), 0, timer_data);
3074 return GetLastError();
3076 CloseHandle(thread);
3078 return RPC_S_OK;
3081 static RPC_STATUS rpcrt4_ncacn_http_handoff(RpcConnection *old_conn, RpcConnection *new_conn)
3083 assert(0);
3084 return RPC_S_SERVER_UNAVAILABLE;
3087 static int rpcrt4_ncacn_http_read(RpcConnection *Connection,
3088 void *buffer, unsigned int count)
3090 RpcConnection_http *httpc = (RpcConnection_http *) Connection;
3091 return rpcrt4_http_async_read(httpc->out_request, httpc->async_data, httpc->cancel_event, buffer, count);
3094 static RPC_STATUS rpcrt4_ncacn_http_receive_fragment(RpcConnection *Connection, RpcPktHdr **Header, void **Payload)
3096 RpcConnection_http *httpc = (RpcConnection_http *) Connection;
3097 RPC_STATUS status;
3098 DWORD hdr_length;
3099 LONG dwRead;
3100 RpcPktCommonHdr common_hdr;
3102 *Header = NULL;
3104 TRACE("(%p, %p, %p)\n", Connection, Header, Payload);
3106 again:
3107 /* read packet common header */
3108 dwRead = rpcrt4_ncacn_http_read(Connection, &common_hdr, sizeof(common_hdr));
3109 if (dwRead != sizeof(common_hdr)) {
3110 WARN("Short read of header, %d bytes\n", dwRead);
3111 status = RPC_S_PROTOCOL_ERROR;
3112 goto fail;
3114 if (!memcmp(&common_hdr, "HTTP/1.1", sizeof("HTTP/1.1")) ||
3115 !memcmp(&common_hdr, "HTTP/1.0", sizeof("HTTP/1.0")))
3117 FIXME("server returned %s\n", debugstr_a((const char *)&common_hdr));
3118 status = RPC_S_PROTOCOL_ERROR;
3119 goto fail;
3122 status = RPCRT4_ValidateCommonHeader(&common_hdr);
3123 if (status != RPC_S_OK) goto fail;
3125 hdr_length = RPCRT4_GetHeaderSize((RpcPktHdr*)&common_hdr);
3126 if (hdr_length == 0) {
3127 WARN("header length == 0\n");
3128 status = RPC_S_PROTOCOL_ERROR;
3129 goto fail;
3132 *Header = HeapAlloc(GetProcessHeap(), 0, hdr_length);
3133 if (!*Header)
3135 status = RPC_S_OUT_OF_RESOURCES;
3136 goto fail;
3138 memcpy(*Header, &common_hdr, sizeof(common_hdr));
3140 /* read the rest of packet header */
3141 dwRead = rpcrt4_ncacn_http_read(Connection, &(*Header)->common + 1, hdr_length - sizeof(common_hdr));
3142 if (dwRead != hdr_length - sizeof(common_hdr)) {
3143 WARN("bad header length, %d bytes, hdr_length %d\n", dwRead, hdr_length);
3144 status = RPC_S_PROTOCOL_ERROR;
3145 goto fail;
3148 if (common_hdr.frag_len - hdr_length)
3150 *Payload = HeapAlloc(GetProcessHeap(), 0, common_hdr.frag_len - hdr_length);
3151 if (!*Payload)
3153 status = RPC_S_OUT_OF_RESOURCES;
3154 goto fail;
3157 dwRead = rpcrt4_ncacn_http_read(Connection, *Payload, common_hdr.frag_len - hdr_length);
3158 if (dwRead != common_hdr.frag_len - hdr_length)
3160 WARN("bad data length, %d/%d\n", dwRead, common_hdr.frag_len - hdr_length);
3161 status = RPC_S_PROTOCOL_ERROR;
3162 goto fail;
3165 else
3166 *Payload = NULL;
3168 if ((*Header)->common.ptype == PKT_HTTP)
3170 if (!RPCRT4_IsValidHttpPacket(*Header, *Payload, common_hdr.frag_len - hdr_length))
3172 ERR("invalid http packet of length %d bytes\n", (*Header)->common.frag_len);
3173 status = RPC_S_PROTOCOL_ERROR;
3174 goto fail;
3176 if ((*Header)->http.flags == 0x0001)
3178 TRACE("http idle packet, waiting for real packet\n");
3179 if ((*Header)->http.num_data_items != 0)
3181 ERR("HTTP idle packet should have no data items instead of %d\n", (*Header)->http.num_data_items);
3182 status = RPC_S_PROTOCOL_ERROR;
3183 goto fail;
3186 else if ((*Header)->http.flags == 0x0002)
3188 ULONG bytes_transmitted;
3189 ULONG flow_control_increment;
3190 UUID pipe_uuid;
3191 status = RPCRT4_ParseHttpFlowControlHeader(*Header, *Payload,
3192 Connection->server,
3193 &bytes_transmitted,
3194 &flow_control_increment,
3195 &pipe_uuid);
3196 if (status != RPC_S_OK)
3197 goto fail;
3198 TRACE("received http flow control header (0x%x, 0x%x, %s)\n",
3199 bytes_transmitted, flow_control_increment, debugstr_guid(&pipe_uuid));
3200 /* FIXME: do something with parsed data */
3202 else
3204 FIXME("unrecognised http packet with flags 0x%04x\n", (*Header)->http.flags);
3205 status = RPC_S_PROTOCOL_ERROR;
3206 goto fail;
3208 RPCRT4_FreeHeader(*Header);
3209 *Header = NULL;
3210 HeapFree(GetProcessHeap(), 0, *Payload);
3211 *Payload = NULL;
3212 goto again;
3215 /* success */
3216 status = RPC_S_OK;
3218 httpc->bytes_received += common_hdr.frag_len;
3220 TRACE("httpc->bytes_received = 0x%x\n", httpc->bytes_received);
3222 if (httpc->bytes_received > httpc->flow_control_mark)
3224 RpcPktHdr *hdr = RPCRT4_BuildHttpFlowControlHeader(httpc->common.server,
3225 httpc->bytes_received,
3226 httpc->flow_control_increment,
3227 &httpc->out_pipe_uuid);
3228 if (hdr)
3230 DWORD bytes_written;
3231 BOOL ret2;
3232 TRACE("sending flow control packet at 0x%x\n", httpc->bytes_received);
3233 ret2 = InternetWriteFile(httpc->in_request, hdr, hdr->common.frag_len, &bytes_written);
3234 RPCRT4_FreeHeader(hdr);
3235 if (ret2)
3236 httpc->flow_control_mark = httpc->bytes_received + httpc->flow_control_increment / 2;
3240 fail:
3241 if (status != RPC_S_OK) {
3242 RPCRT4_FreeHeader(*Header);
3243 *Header = NULL;
3244 HeapFree(GetProcessHeap(), 0, *Payload);
3245 *Payload = NULL;
3247 return status;
3250 static int rpcrt4_ncacn_http_write(RpcConnection *Connection,
3251 const void *buffer, unsigned int count)
3253 RpcConnection_http *httpc = (RpcConnection_http *) Connection;
3254 DWORD bytes_written;
3255 BOOL ret;
3257 httpc->last_sent_time = ~0U; /* disable idle packet sending */
3258 ret = InternetWriteFile(httpc->in_request, buffer, count, &bytes_written);
3259 httpc->last_sent_time = GetTickCount();
3260 TRACE("%p %p %u -> %s\n", httpc->in_request, buffer, count, ret ? "TRUE" : "FALSE");
3261 return ret ? bytes_written : -1;
3264 static int rpcrt4_ncacn_http_close(RpcConnection *Connection)
3266 RpcConnection_http *httpc = (RpcConnection_http *) Connection;
3268 TRACE("\n");
3270 SetEvent(httpc->timer_cancelled);
3271 if (httpc->in_request)
3272 InternetCloseHandle(httpc->in_request);
3273 httpc->in_request = NULL;
3274 if (httpc->out_request)
3275 InternetCloseHandle(httpc->out_request);
3276 httpc->out_request = NULL;
3277 if (httpc->app_info)
3278 InternetCloseHandle(httpc->app_info);
3279 httpc->app_info = NULL;
3280 if (httpc->session)
3281 InternetCloseHandle(httpc->session);
3282 httpc->session = NULL;
3283 RpcHttpAsyncData_Release(httpc->async_data);
3284 if (httpc->cancel_event)
3285 CloseHandle(httpc->cancel_event);
3286 HeapFree(GetProcessHeap(), 0, httpc->servername);
3287 httpc->servername = NULL;
3289 return 0;
3292 static void rpcrt4_ncacn_http_cancel_call(RpcConnection *Connection)
3294 RpcConnection_http *httpc = (RpcConnection_http *) Connection;
3296 SetEvent(httpc->cancel_event);
3299 static int rpcrt4_ncacn_http_wait_for_incoming_data(RpcConnection *Connection)
3301 RpcConnection_http *httpc = (RpcConnection_http *) Connection;
3302 BOOL ret;
3303 RPC_STATUS status;
3305 prepare_async_request(httpc->async_data);
3306 ret = InternetQueryDataAvailable(httpc->out_request,
3307 &httpc->async_data->inet_buffers.dwBufferLength, IRF_ASYNC, 0);
3308 status = wait_async_request(httpc->async_data, ret, httpc->cancel_event);
3309 return status == RPC_S_OK ? 0 : -1;
3312 static size_t rpcrt4_ncacn_http_get_top_of_tower(unsigned char *tower_data,
3313 const char *networkaddr,
3314 const char *endpoint)
3316 return rpcrt4_ip_tcp_get_top_of_tower(tower_data, networkaddr,
3317 EPM_PROTOCOL_HTTP, endpoint);
3320 static RPC_STATUS rpcrt4_ncacn_http_parse_top_of_tower(const unsigned char *tower_data,
3321 size_t tower_size,
3322 char **networkaddr,
3323 char **endpoint)
3325 return rpcrt4_ip_tcp_parse_top_of_tower(tower_data, tower_size,
3326 networkaddr, EPM_PROTOCOL_HTTP,
3327 endpoint);
3330 static const struct connection_ops conn_protseq_list[] = {
3331 { "ncacn_np",
3332 { EPM_PROTOCOL_NCACN, EPM_PROTOCOL_SMB },
3333 rpcrt4_conn_np_alloc,
3334 rpcrt4_ncacn_np_open,
3335 rpcrt4_ncacn_np_handoff,
3336 rpcrt4_conn_np_read,
3337 rpcrt4_conn_np_write,
3338 rpcrt4_conn_np_close,
3339 rpcrt4_conn_np_cancel_call,
3340 rpcrt4_conn_np_wait_for_incoming_data,
3341 rpcrt4_ncacn_np_get_top_of_tower,
3342 rpcrt4_ncacn_np_parse_top_of_tower,
3343 NULL,
3344 RPCRT4_default_is_authorized,
3345 RPCRT4_default_authorize,
3346 RPCRT4_default_secure_packet,
3347 rpcrt4_conn_np_impersonate_client,
3348 rpcrt4_conn_np_revert_to_self,
3349 RPCRT4_default_inquire_auth_client,
3351 { "ncalrpc",
3352 { EPM_PROTOCOL_NCALRPC, EPM_PROTOCOL_PIPE },
3353 rpcrt4_conn_np_alloc,
3354 rpcrt4_ncalrpc_open,
3355 rpcrt4_ncalrpc_handoff,
3356 rpcrt4_conn_np_read,
3357 rpcrt4_conn_np_write,
3358 rpcrt4_conn_np_close,
3359 rpcrt4_conn_np_cancel_call,
3360 rpcrt4_conn_np_wait_for_incoming_data,
3361 rpcrt4_ncalrpc_get_top_of_tower,
3362 rpcrt4_ncalrpc_parse_top_of_tower,
3363 NULL,
3364 rpcrt4_ncalrpc_is_authorized,
3365 rpcrt4_ncalrpc_authorize,
3366 rpcrt4_ncalrpc_secure_packet,
3367 rpcrt4_conn_np_impersonate_client,
3368 rpcrt4_conn_np_revert_to_self,
3369 rpcrt4_ncalrpc_inquire_auth_client,
3371 { "ncacn_ip_tcp",
3372 { EPM_PROTOCOL_NCACN, EPM_PROTOCOL_TCP },
3373 rpcrt4_conn_tcp_alloc,
3374 rpcrt4_ncacn_ip_tcp_open,
3375 rpcrt4_conn_tcp_handoff,
3376 rpcrt4_conn_tcp_read,
3377 rpcrt4_conn_tcp_write,
3378 rpcrt4_conn_tcp_close,
3379 rpcrt4_conn_tcp_cancel_call,
3380 rpcrt4_conn_tcp_wait_for_incoming_data,
3381 rpcrt4_ncacn_ip_tcp_get_top_of_tower,
3382 rpcrt4_ncacn_ip_tcp_parse_top_of_tower,
3383 NULL,
3384 RPCRT4_default_is_authorized,
3385 RPCRT4_default_authorize,
3386 RPCRT4_default_secure_packet,
3387 RPCRT4_default_impersonate_client,
3388 RPCRT4_default_revert_to_self,
3389 RPCRT4_default_inquire_auth_client,
3391 { "ncacn_http",
3392 { EPM_PROTOCOL_NCACN, EPM_PROTOCOL_HTTP },
3393 rpcrt4_ncacn_http_alloc,
3394 rpcrt4_ncacn_http_open,
3395 rpcrt4_ncacn_http_handoff,
3396 rpcrt4_ncacn_http_read,
3397 rpcrt4_ncacn_http_write,
3398 rpcrt4_ncacn_http_close,
3399 rpcrt4_ncacn_http_cancel_call,
3400 rpcrt4_ncacn_http_wait_for_incoming_data,
3401 rpcrt4_ncacn_http_get_top_of_tower,
3402 rpcrt4_ncacn_http_parse_top_of_tower,
3403 rpcrt4_ncacn_http_receive_fragment,
3404 RPCRT4_default_is_authorized,
3405 RPCRT4_default_authorize,
3406 RPCRT4_default_secure_packet,
3407 RPCRT4_default_impersonate_client,
3408 RPCRT4_default_revert_to_self,
3409 RPCRT4_default_inquire_auth_client,
3414 static const struct protseq_ops protseq_list[] =
3417 "ncacn_np",
3418 rpcrt4_protseq_np_alloc,
3419 rpcrt4_protseq_np_signal_state_changed,
3420 rpcrt4_protseq_np_get_wait_array,
3421 rpcrt4_protseq_np_free_wait_array,
3422 rpcrt4_protseq_np_wait_for_new_connection,
3423 rpcrt4_protseq_ncacn_np_open_endpoint,
3426 "ncalrpc",
3427 rpcrt4_protseq_np_alloc,
3428 rpcrt4_protseq_np_signal_state_changed,
3429 rpcrt4_protseq_np_get_wait_array,
3430 rpcrt4_protseq_np_free_wait_array,
3431 rpcrt4_protseq_np_wait_for_new_connection,
3432 rpcrt4_protseq_ncalrpc_open_endpoint,
3435 "ncacn_ip_tcp",
3436 rpcrt4_protseq_sock_alloc,
3437 rpcrt4_protseq_sock_signal_state_changed,
3438 rpcrt4_protseq_sock_get_wait_array,
3439 rpcrt4_protseq_sock_free_wait_array,
3440 rpcrt4_protseq_sock_wait_for_new_connection,
3441 rpcrt4_protseq_ncacn_ip_tcp_open_endpoint,
3445 const struct protseq_ops *rpcrt4_get_protseq_ops(const char *protseq)
3447 unsigned int i;
3448 for(i=0; i<ARRAYSIZE(protseq_list); i++)
3449 if (!strcmp(protseq_list[i].name, protseq))
3450 return &protseq_list[i];
3451 return NULL;
3454 static const struct connection_ops *rpcrt4_get_conn_protseq_ops(const char *protseq)
3456 unsigned int i;
3457 for(i=0; i<ARRAYSIZE(conn_protseq_list); i++)
3458 if (!strcmp(conn_protseq_list[i].name, protseq))
3459 return &conn_protseq_list[i];
3460 return NULL;
3463 /**** interface to rest of code ****/
3465 RPC_STATUS RPCRT4_OpenClientConnection(RpcConnection* Connection)
3467 TRACE("(Connection == ^%p)\n", Connection);
3469 assert(!Connection->server);
3470 return Connection->ops->open_connection_client(Connection);
3473 RPC_STATUS RPCRT4_CloseConnection(RpcConnection* Connection)
3475 TRACE("(Connection == ^%p)\n", Connection);
3476 if (SecIsValidHandle(&Connection->ctx))
3478 DeleteSecurityContext(&Connection->ctx);
3479 SecInvalidateHandle(&Connection->ctx);
3481 rpcrt4_conn_close(Connection);
3482 return RPC_S_OK;
3485 RPC_STATUS RPCRT4_CreateConnection(RpcConnection** Connection, BOOL server,
3486 LPCSTR Protseq, LPCSTR NetworkAddr, LPCSTR Endpoint,
3487 LPCWSTR NetworkOptions, RpcAuthInfo* AuthInfo, RpcQualityOfService *QOS, LPCWSTR CookieAuth)
3489 static LONG next_id;
3490 const struct connection_ops *ops;
3491 RpcConnection* NewConnection;
3493 ops = rpcrt4_get_conn_protseq_ops(Protseq);
3494 if (!ops)
3496 FIXME("not supported for protseq %s\n", Protseq);
3497 return RPC_S_PROTSEQ_NOT_SUPPORTED;
3500 NewConnection = ops->alloc();
3501 NewConnection->ref = 1;
3502 NewConnection->Next = NULL;
3503 NewConnection->server_binding = NULL;
3504 NewConnection->server = server;
3505 NewConnection->ops = ops;
3506 NewConnection->NetworkAddr = RPCRT4_strdupA(NetworkAddr);
3507 NewConnection->Endpoint = RPCRT4_strdupA(Endpoint);
3508 NewConnection->NetworkOptions = RPCRT4_strdupW(NetworkOptions);
3509 NewConnection->CookieAuth = RPCRT4_strdupW(CookieAuth);
3510 NewConnection->MaxTransmissionSize = RPC_MAX_PACKET_SIZE;
3511 memset(&NewConnection->ActiveInterface, 0, sizeof(NewConnection->ActiveInterface));
3512 NewConnection->NextCallId = 1;
3514 SecInvalidateHandle(&NewConnection->ctx);
3515 memset(&NewConnection->exp, 0, sizeof(NewConnection->exp));
3516 NewConnection->attr = 0;
3517 if (AuthInfo) RpcAuthInfo_AddRef(AuthInfo);
3518 NewConnection->AuthInfo = AuthInfo;
3519 NewConnection->auth_context_id = InterlockedIncrement( &next_id );
3520 NewConnection->encryption_auth_len = 0;
3521 NewConnection->signature_auth_len = 0;
3522 if (QOS) RpcQualityOfService_AddRef(QOS);
3523 NewConnection->QOS = QOS;
3525 list_init(&NewConnection->conn_pool_entry);
3526 NewConnection->async_state = NULL;
3528 TRACE("connection: %p\n", NewConnection);
3529 *Connection = NewConnection;
3531 return RPC_S_OK;
3534 static RPC_STATUS RPCRT4_SpawnConnection(RpcConnection** Connection, RpcConnection* OldConnection)
3536 RPC_STATUS err;
3538 err = RPCRT4_CreateConnection(Connection, OldConnection->server, rpcrt4_conn_get_name(OldConnection),
3539 OldConnection->NetworkAddr, OldConnection->Endpoint, NULL,
3540 OldConnection->AuthInfo, OldConnection->QOS, OldConnection->CookieAuth);
3541 if (err == RPC_S_OK)
3542 rpcrt4_conn_handoff(OldConnection, *Connection);
3543 return err;
3546 RpcConnection *RPCRT4_GrabConnection( RpcConnection *conn )
3548 InterlockedIncrement( &conn->ref );
3549 return conn;
3552 RPC_STATUS RPCRT4_ReleaseConnection(RpcConnection* Connection)
3554 if (InterlockedDecrement( &Connection->ref ) > 0) return RPC_S_OK;
3556 TRACE("destroying connection %p\n", Connection);
3558 RPCRT4_CloseConnection(Connection);
3559 RPCRT4_strfree(Connection->Endpoint);
3560 RPCRT4_strfree(Connection->NetworkAddr);
3561 HeapFree(GetProcessHeap(), 0, Connection->NetworkOptions);
3562 HeapFree(GetProcessHeap(), 0, Connection->CookieAuth);
3563 if (Connection->AuthInfo) RpcAuthInfo_Release(Connection->AuthInfo);
3564 if (Connection->QOS) RpcQualityOfService_Release(Connection->QOS);
3566 /* server-only */
3567 if (Connection->server_binding) RPCRT4_ReleaseBinding(Connection->server_binding);
3569 HeapFree(GetProcessHeap(), 0, Connection);
3570 return RPC_S_OK;
3573 RPC_STATUS RpcTransport_GetTopOfTower(unsigned char *tower_data,
3574 size_t *tower_size,
3575 const char *protseq,
3576 const char *networkaddr,
3577 const char *endpoint)
3579 twr_empty_floor_t *protocol_floor;
3580 const struct connection_ops *protseq_ops = rpcrt4_get_conn_protseq_ops(protseq);
3582 *tower_size = 0;
3584 if (!protseq_ops)
3585 return RPC_S_INVALID_RPC_PROTSEQ;
3587 if (!tower_data)
3589 *tower_size = sizeof(*protocol_floor);
3590 *tower_size += protseq_ops->get_top_of_tower(NULL, networkaddr, endpoint);
3591 return RPC_S_OK;
3594 protocol_floor = (twr_empty_floor_t *)tower_data;
3595 protocol_floor->count_lhs = sizeof(protocol_floor->protid);
3596 protocol_floor->protid = protseq_ops->epm_protocols[0];
3597 protocol_floor->count_rhs = 0;
3599 tower_data += sizeof(*protocol_floor);
3601 *tower_size = protseq_ops->get_top_of_tower(tower_data, networkaddr, endpoint);
3602 if (!*tower_size)
3603 return EPT_S_NOT_REGISTERED;
3605 *tower_size += sizeof(*protocol_floor);
3607 return RPC_S_OK;
3610 RPC_STATUS RpcTransport_ParseTopOfTower(const unsigned char *tower_data,
3611 size_t tower_size,
3612 char **protseq,
3613 char **networkaddr,
3614 char **endpoint)
3616 const twr_empty_floor_t *protocol_floor;
3617 const twr_empty_floor_t *floor4;
3618 const struct connection_ops *protseq_ops = NULL;
3619 RPC_STATUS status;
3620 unsigned int i;
3622 if (tower_size < sizeof(*protocol_floor))
3623 return EPT_S_NOT_REGISTERED;
3625 protocol_floor = (const twr_empty_floor_t *)tower_data;
3626 tower_data += sizeof(*protocol_floor);
3627 tower_size -= sizeof(*protocol_floor);
3628 if ((protocol_floor->count_lhs != sizeof(protocol_floor->protid)) ||
3629 (protocol_floor->count_rhs > tower_size))
3630 return EPT_S_NOT_REGISTERED;
3631 tower_data += protocol_floor->count_rhs;
3632 tower_size -= protocol_floor->count_rhs;
3634 floor4 = (const twr_empty_floor_t *)tower_data;
3635 if ((tower_size < sizeof(*floor4)) ||
3636 (floor4->count_lhs != sizeof(floor4->protid)))
3637 return EPT_S_NOT_REGISTERED;
3639 for(i = 0; i < ARRAYSIZE(conn_protseq_list); i++)
3640 if ((protocol_floor->protid == conn_protseq_list[i].epm_protocols[0]) &&
3641 (floor4->protid == conn_protseq_list[i].epm_protocols[1]))
3643 protseq_ops = &conn_protseq_list[i];
3644 break;
3647 if (!protseq_ops)
3648 return EPT_S_NOT_REGISTERED;
3650 status = protseq_ops->parse_top_of_tower(tower_data, tower_size, networkaddr, endpoint);
3652 if ((status == RPC_S_OK) && protseq)
3654 *protseq = I_RpcAllocate(strlen(protseq_ops->name) + 1);
3655 strcpy(*protseq, protseq_ops->name);
3658 return status;
3661 /***********************************************************************
3662 * RpcNetworkIsProtseqValidW (RPCRT4.@)
3664 * Checks if the given protocol sequence is known by the RPC system.
3665 * If it is, returns RPC_S_OK, otherwise RPC_S_PROTSEQ_NOT_SUPPORTED.
3668 RPC_STATUS WINAPI RpcNetworkIsProtseqValidW(RPC_WSTR protseq)
3670 char ps[0x10];
3672 WideCharToMultiByte(CP_ACP, 0, protseq, -1,
3673 ps, sizeof ps, NULL, NULL);
3674 if (rpcrt4_get_conn_protseq_ops(ps))
3675 return RPC_S_OK;
3677 FIXME("Unknown protseq %s\n", debugstr_w(protseq));
3679 return RPC_S_INVALID_RPC_PROTSEQ;
3682 /***********************************************************************
3683 * RpcNetworkIsProtseqValidA (RPCRT4.@)
3685 RPC_STATUS WINAPI RpcNetworkIsProtseqValidA(RPC_CSTR protseq)
3687 UNICODE_STRING protseqW;
3689 if (RtlCreateUnicodeStringFromAsciiz(&protseqW, (char*)protseq))
3691 RPC_STATUS ret = RpcNetworkIsProtseqValidW(protseqW.Buffer);
3692 RtlFreeUnicodeString(&protseqW);
3693 return ret;
3695 return RPC_S_OUT_OF_MEMORY;
3698 /***********************************************************************
3699 * RpcProtseqVectorFreeA (RPCRT4.@)
3701 RPC_STATUS WINAPI RpcProtseqVectorFreeA(RPC_PROTSEQ_VECTORA **protseqs)
3703 TRACE("(%p)\n", protseqs);
3705 if (*protseqs)
3707 unsigned int i;
3708 for (i = 0; i < (*protseqs)->Count; i++)
3709 HeapFree(GetProcessHeap(), 0, (*protseqs)->Protseq[i]);
3710 HeapFree(GetProcessHeap(), 0, *protseqs);
3711 *protseqs = NULL;
3713 return RPC_S_OK;
3716 /***********************************************************************
3717 * RpcProtseqVectorFreeW (RPCRT4.@)
3719 RPC_STATUS WINAPI RpcProtseqVectorFreeW(RPC_PROTSEQ_VECTORW **protseqs)
3721 TRACE("(%p)\n", protseqs);
3723 if (*protseqs)
3725 unsigned int i;
3726 for (i = 0; i < (*protseqs)->Count; i++)
3727 HeapFree(GetProcessHeap(), 0, (*protseqs)->Protseq[i]);
3728 HeapFree(GetProcessHeap(), 0, *protseqs);
3729 *protseqs = NULL;
3731 return RPC_S_OK;
3734 /***********************************************************************
3735 * RpcNetworkInqProtseqsW (RPCRT4.@)
3737 RPC_STATUS WINAPI RpcNetworkInqProtseqsW( RPC_PROTSEQ_VECTORW** protseqs )
3739 RPC_PROTSEQ_VECTORW *pvector;
3740 unsigned int i;
3741 RPC_STATUS status = RPC_S_OUT_OF_MEMORY;
3743 TRACE("(%p)\n", protseqs);
3745 *protseqs = HeapAlloc(GetProcessHeap(), 0, sizeof(RPC_PROTSEQ_VECTORW)+(sizeof(unsigned short*)*ARRAYSIZE(protseq_list)));
3746 if (!*protseqs)
3747 goto end;
3748 pvector = *protseqs;
3749 pvector->Count = 0;
3750 for (i = 0; i < ARRAYSIZE(protseq_list); i++)
3752 pvector->Protseq[i] = HeapAlloc(GetProcessHeap(), 0, (strlen(protseq_list[i].name)+1)*sizeof(unsigned short));
3753 if (pvector->Protseq[i] == NULL)
3754 goto end;
3755 MultiByteToWideChar(CP_ACP, 0, (CHAR*)protseq_list[i].name, -1,
3756 (WCHAR*)pvector->Protseq[i], strlen(protseq_list[i].name) + 1);
3757 pvector->Count++;
3759 status = RPC_S_OK;
3761 end:
3762 if (status != RPC_S_OK)
3763 RpcProtseqVectorFreeW(protseqs);
3764 return status;
3767 /***********************************************************************
3768 * RpcNetworkInqProtseqsA (RPCRT4.@)
3770 RPC_STATUS WINAPI RpcNetworkInqProtseqsA(RPC_PROTSEQ_VECTORA** protseqs)
3772 RPC_PROTSEQ_VECTORA *pvector;
3773 unsigned int i;
3774 RPC_STATUS status = RPC_S_OUT_OF_MEMORY;
3776 TRACE("(%p)\n", protseqs);
3778 *protseqs = HeapAlloc(GetProcessHeap(), 0, sizeof(RPC_PROTSEQ_VECTORW)+(sizeof(unsigned char*)*ARRAYSIZE(protseq_list)));
3779 if (!*protseqs)
3780 goto end;
3781 pvector = *protseqs;
3782 pvector->Count = 0;
3783 for (i = 0; i < ARRAYSIZE(protseq_list); i++)
3785 pvector->Protseq[i] = HeapAlloc(GetProcessHeap(), 0, strlen(protseq_list[i].name)+1);
3786 if (pvector->Protseq[i] == NULL)
3787 goto end;
3788 strcpy((char*)pvector->Protseq[i], protseq_list[i].name);
3789 pvector->Count++;
3791 status = RPC_S_OK;
3793 end:
3794 if (status != RPC_S_OK)
3795 RpcProtseqVectorFreeA(protseqs);
3796 return status;