secur32: Set output buffer size to zero during handshake when no data needs to be...
[wine.git] / dlls / rpcrt4 / rpc_transport.c
blobc374ba1ccb1ec07c02fa16326cb6d96e09787872
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 "ntstatus.h"
27 #define WIN32_NO_STATUS
28 #include "ws2tcpip.h"
30 #include <stdarg.h>
31 #include <stdio.h>
32 #include <string.h>
33 #include <assert.h>
35 #include "windef.h"
36 #include "winbase.h"
37 #include "winnls.h"
38 #include "winerror.h"
39 #include "wininet.h"
40 #include "winternl.h"
41 #include "winioctl.h"
42 #include "wine/unicode.h"
44 #include "rpc.h"
45 #include "rpcndr.h"
47 #include "wine/debug.h"
49 #include "rpc_binding.h"
50 #include "rpc_assoc.h"
51 #include "rpc_message.h"
52 #include "rpc_server.h"
53 #include "epm_towers.h"
55 #define DEFAULT_NCACN_HTTP_TIMEOUT (60 * 1000)
57 #define ARRAYSIZE(a) (sizeof((a)) / sizeof((a)[0]))
59 WINE_DEFAULT_DEBUG_CHANNEL(rpc);
61 static RpcConnection *rpcrt4_spawn_connection(RpcConnection *old_connection);
63 /**** ncacn_np support ****/
65 typedef struct _RpcConnection_np
67 RpcConnection common;
68 HANDLE pipe;
69 HANDLE listen_event;
70 char *listen_pipe;
71 IO_STATUS_BLOCK io_status;
72 HANDLE event_cache;
73 BOOL read_closed;
74 } RpcConnection_np;
76 static RpcConnection *rpcrt4_conn_np_alloc(void)
78 RpcConnection_np *npc = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(RpcConnection_np));
79 return &npc->common;
82 static HANDLE get_np_event(RpcConnection_np *connection)
84 HANDLE event = InterlockedExchangePointer(&connection->event_cache, NULL);
85 return event ? event : CreateEventW(NULL, TRUE, FALSE, NULL);
88 static void release_np_event(RpcConnection_np *connection, HANDLE event)
90 event = InterlockedExchangePointer(&connection->event_cache, event);
91 if (event)
92 CloseHandle(event);
95 static RPC_STATUS rpcrt4_conn_create_pipe(RpcConnection *conn)
97 RpcConnection_np *connection = (RpcConnection_np *) conn;
99 TRACE("listening on %s\n", connection->listen_pipe);
101 connection->pipe = CreateNamedPipeA(connection->listen_pipe, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
102 PIPE_TYPE_MESSAGE | PIPE_READMODE_MESSAGE,
103 PIPE_UNLIMITED_INSTANCES,
104 RPC_MAX_PACKET_SIZE, RPC_MAX_PACKET_SIZE, 5000, NULL);
105 if (connection->pipe == INVALID_HANDLE_VALUE)
107 WARN("CreateNamedPipe failed with error %d\n", GetLastError());
108 if (GetLastError() == ERROR_FILE_EXISTS)
109 return RPC_S_DUPLICATE_ENDPOINT;
110 else
111 return RPC_S_CANT_CREATE_ENDPOINT;
114 return RPC_S_OK;
117 static RPC_STATUS rpcrt4_conn_open_pipe(RpcConnection *Connection, LPCSTR pname, BOOL wait)
119 RpcConnection_np *npc = (RpcConnection_np *) Connection;
120 HANDLE pipe;
121 DWORD err, dwMode;
123 TRACE("connecting to %s\n", pname);
125 while (TRUE) {
126 DWORD dwFlags = 0;
127 if (Connection->QOS)
129 dwFlags = SECURITY_SQOS_PRESENT;
130 switch (Connection->QOS->qos->ImpersonationType)
132 case RPC_C_IMP_LEVEL_DEFAULT:
133 /* FIXME: what to do here? */
134 break;
135 case RPC_C_IMP_LEVEL_ANONYMOUS:
136 dwFlags |= SECURITY_ANONYMOUS;
137 break;
138 case RPC_C_IMP_LEVEL_IDENTIFY:
139 dwFlags |= SECURITY_IDENTIFICATION;
140 break;
141 case RPC_C_IMP_LEVEL_IMPERSONATE:
142 dwFlags |= SECURITY_IMPERSONATION;
143 break;
144 case RPC_C_IMP_LEVEL_DELEGATE:
145 dwFlags |= SECURITY_DELEGATION;
146 break;
148 if (Connection->QOS->qos->IdentityTracking == RPC_C_QOS_IDENTITY_DYNAMIC)
149 dwFlags |= SECURITY_CONTEXT_TRACKING;
151 pipe = CreateFileA(pname, GENERIC_READ|GENERIC_WRITE, 0, NULL,
152 OPEN_EXISTING, dwFlags | FILE_FLAG_OVERLAPPED, 0);
153 if (pipe != INVALID_HANDLE_VALUE) break;
154 err = GetLastError();
155 if (err == ERROR_PIPE_BUSY) {
156 if (WaitNamedPipeA(pname, NMPWAIT_USE_DEFAULT_WAIT)) {
157 TRACE("retrying busy server\n");
158 continue;
160 TRACE("connection failed, error=%x\n", err);
161 return RPC_S_SERVER_TOO_BUSY;
163 if (!wait || !WaitNamedPipeA(pname, NMPWAIT_WAIT_FOREVER)) {
164 err = GetLastError();
165 WARN("connection failed, error=%x\n", err);
166 return RPC_S_SERVER_UNAVAILABLE;
170 /* success */
171 /* pipe is connected; change to message-read mode. */
172 dwMode = PIPE_READMODE_MESSAGE;
173 SetNamedPipeHandleState(pipe, &dwMode, NULL, NULL);
174 npc->pipe = pipe;
176 return RPC_S_OK;
179 static char *ncalrpc_pipe_name(const char *endpoint)
181 static const char prefix[] = "\\\\.\\pipe\\lrpc\\";
182 char *pipe_name;
184 /* protseq=ncalrpc: supposed to use NT LPC ports,
185 * but we'll implement it with named pipes for now */
186 pipe_name = I_RpcAllocate(sizeof(prefix) + strlen(endpoint));
187 strcat(strcpy(pipe_name, prefix), endpoint);
188 return pipe_name;
191 static RPC_STATUS rpcrt4_ncalrpc_open(RpcConnection* Connection)
193 RpcConnection_np *npc = (RpcConnection_np *) Connection;
194 RPC_STATUS r;
195 LPSTR pname;
197 /* already connected? */
198 if (npc->pipe)
199 return RPC_S_OK;
201 pname = ncalrpc_pipe_name(Connection->Endpoint);
202 r = rpcrt4_conn_open_pipe(Connection, pname, TRUE);
203 I_RpcFree(pname);
205 return r;
208 static RPC_STATUS rpcrt4_protseq_ncalrpc_open_endpoint(RpcServerProtseq* protseq, const char *endpoint)
210 RPC_STATUS r;
211 RpcConnection *Connection;
212 char generated_endpoint[22];
214 if (!endpoint)
216 static LONG lrpc_nameless_id;
217 DWORD process_id = GetCurrentProcessId();
218 ULONG id = InterlockedIncrement(&lrpc_nameless_id);
219 snprintf(generated_endpoint, sizeof(generated_endpoint),
220 "LRPC%08x.%08x", process_id, id);
221 endpoint = generated_endpoint;
224 r = RPCRT4_CreateConnection(&Connection, TRUE, protseq->Protseq, NULL,
225 endpoint, NULL, NULL, NULL, NULL);
226 if (r != RPC_S_OK)
227 return r;
229 ((RpcConnection_np*)Connection)->listen_pipe = ncalrpc_pipe_name(Connection->Endpoint);
230 r = rpcrt4_conn_create_pipe(Connection);
232 EnterCriticalSection(&protseq->cs);
233 list_add_head(&protseq->listeners, &Connection->protseq_entry);
234 Connection->protseq = protseq;
235 LeaveCriticalSection(&protseq->cs);
237 return r;
240 static char *ncacn_pipe_name(const char *endpoint)
242 static const char prefix[] = "\\\\.";
243 char *pipe_name;
245 /* protseq=ncacn_np: named pipes */
246 pipe_name = I_RpcAllocate(sizeof(prefix) + strlen(endpoint));
247 strcat(strcpy(pipe_name, prefix), endpoint);
248 return pipe_name;
251 static RPC_STATUS rpcrt4_ncacn_np_open(RpcConnection* Connection)
253 RpcConnection_np *npc = (RpcConnection_np *) Connection;
254 RPC_STATUS r;
255 LPSTR pname;
257 /* already connected? */
258 if (npc->pipe)
259 return RPC_S_OK;
261 pname = ncacn_pipe_name(Connection->Endpoint);
262 r = rpcrt4_conn_open_pipe(Connection, pname, FALSE);
263 I_RpcFree(pname);
265 return r;
268 static RPC_STATUS rpcrt4_protseq_ncacn_np_open_endpoint(RpcServerProtseq *protseq, const char *endpoint)
270 RPC_STATUS r;
271 RpcConnection *Connection;
272 char generated_endpoint[26];
274 if (!endpoint)
276 static LONG np_nameless_id;
277 DWORD process_id = GetCurrentProcessId();
278 ULONG id = InterlockedExchangeAdd(&np_nameless_id, 1 );
279 snprintf(generated_endpoint, sizeof(generated_endpoint),
280 "\\\\pipe\\\\%08x.%03x", process_id, id);
281 endpoint = generated_endpoint;
284 r = RPCRT4_CreateConnection(&Connection, TRUE, protseq->Protseq, NULL,
285 endpoint, NULL, NULL, NULL, NULL);
286 if (r != RPC_S_OK)
287 return r;
289 ((RpcConnection_np*)Connection)->listen_pipe = ncacn_pipe_name(Connection->Endpoint);
290 r = rpcrt4_conn_create_pipe(Connection);
292 EnterCriticalSection(&protseq->cs);
293 list_add_head(&protseq->listeners, &Connection->protseq_entry);
294 Connection->protseq = protseq;
295 LeaveCriticalSection(&protseq->cs);
297 return r;
300 static void rpcrt4_conn_np_handoff(RpcConnection_np *old_npc, RpcConnection_np *new_npc)
302 /* because of the way named pipes work, we'll transfer the connected pipe
303 * to the child, then reopen the server binding to continue listening */
305 new_npc->pipe = old_npc->pipe;
306 old_npc->pipe = 0;
307 assert(!old_npc->listen_event);
310 static RPC_STATUS rpcrt4_ncacn_np_handoff(RpcConnection *old_conn, RpcConnection *new_conn)
312 DWORD len = MAX_COMPUTERNAME_LENGTH + 1;
313 RPC_STATUS status;
315 rpcrt4_conn_np_handoff((RpcConnection_np *)old_conn, (RpcConnection_np *)new_conn);
316 status = rpcrt4_conn_create_pipe(old_conn);
318 /* Store the local computer name as the NetworkAddr for ncacn_np as long as
319 * we don't support named pipes over the network. */
320 new_conn->NetworkAddr = HeapAlloc(GetProcessHeap(), 0, len);
321 if (!GetComputerNameA(new_conn->NetworkAddr, &len))
323 ERR("Failed to retrieve the computer name, error %u\n", GetLastError());
324 return RPC_S_OUT_OF_RESOURCES;
327 return status;
330 static RPC_STATUS is_pipe_listening(const char *pipe_name)
332 return WaitNamedPipeA(pipe_name, 1) ? RPC_S_OK : RPC_S_NOT_LISTENING;
335 static RPC_STATUS rpcrt4_ncacn_np_is_server_listening(const char *endpoint)
337 char *pipe_name;
338 RPC_STATUS status;
340 pipe_name = ncacn_pipe_name(endpoint);
341 status = is_pipe_listening(pipe_name);
342 I_RpcFree(pipe_name);
343 return status;
346 static RPC_STATUS rpcrt4_ncalrpc_np_is_server_listening(const char *endpoint)
348 char *pipe_name;
349 RPC_STATUS status;
351 pipe_name = ncalrpc_pipe_name(endpoint);
352 status = is_pipe_listening(pipe_name);
353 I_RpcFree(pipe_name);
354 return status;
357 static RPC_STATUS rpcrt4_ncalrpc_handoff(RpcConnection *old_conn, RpcConnection *new_conn)
359 DWORD len = MAX_COMPUTERNAME_LENGTH + 1;
360 RPC_STATUS status;
362 TRACE("%s\n", old_conn->Endpoint);
364 rpcrt4_conn_np_handoff((RpcConnection_np *)old_conn, (RpcConnection_np *)new_conn);
365 status = rpcrt4_conn_create_pipe(old_conn);
367 /* Store the local computer name as the NetworkAddr for ncalrpc. */
368 new_conn->NetworkAddr = HeapAlloc(GetProcessHeap(), 0, len);
369 if (!GetComputerNameA(new_conn->NetworkAddr, &len))
371 ERR("Failed to retrieve the computer name, error %u\n", GetLastError());
372 return RPC_S_OUT_OF_RESOURCES;
375 return status;
378 static int rpcrt4_conn_np_read(RpcConnection *conn, void *buffer, unsigned int count)
380 RpcConnection_np *connection = (RpcConnection_np *) conn;
381 HANDLE event;
382 NTSTATUS status;
384 event = get_np_event(connection);
385 if (!event)
386 return -1;
388 if (connection->read_closed)
389 status = STATUS_CANCELLED;
390 else
391 status = NtReadFile(connection->pipe, event, NULL, NULL, &connection->io_status, buffer, count, NULL, NULL);
392 if (status == STATUS_PENDING)
394 /* check read_closed again before waiting to avoid a race */
395 if (connection->read_closed)
397 IO_STATUS_BLOCK io_status;
398 NtCancelIoFileEx(connection->pipe, &connection->io_status, &io_status);
400 WaitForSingleObject(event, INFINITE);
401 status = connection->io_status.Status;
403 release_np_event(connection, event);
404 return status && status != STATUS_BUFFER_OVERFLOW ? -1 : connection->io_status.Information;
407 static int rpcrt4_conn_np_write(RpcConnection *conn, const void *buffer, unsigned int count)
409 RpcConnection_np *connection = (RpcConnection_np *) conn;
410 IO_STATUS_BLOCK io_status;
411 HANDLE event;
412 NTSTATUS status;
414 event = get_np_event(connection);
415 if (!event)
416 return -1;
418 status = NtWriteFile(connection->pipe, event, NULL, NULL, &io_status, buffer, count, NULL, NULL);
419 if (status == STATUS_PENDING)
421 WaitForSingleObject(event, INFINITE);
422 status = io_status.Status;
424 release_np_event(connection, event);
425 if (status)
426 return -1;
428 assert(io_status.Information == count);
429 return count;
432 static int rpcrt4_conn_np_close(RpcConnection *conn)
434 RpcConnection_np *connection = (RpcConnection_np *) conn;
435 if (connection->pipe)
437 FlushFileBuffers(connection->pipe);
438 CloseHandle(connection->pipe);
439 connection->pipe = 0;
441 if (connection->listen_event)
443 CloseHandle(connection->listen_event);
444 connection->listen_event = 0;
446 if (connection->event_cache)
448 CloseHandle(connection->event_cache);
449 connection->event_cache = 0;
451 return 0;
454 static void rpcrt4_conn_np_close_read(RpcConnection *conn)
456 RpcConnection_np *connection = (RpcConnection_np*)conn;
457 IO_STATUS_BLOCK io_status;
459 connection->read_closed = TRUE;
460 NtCancelIoFileEx(connection->pipe, &connection->io_status, &io_status);
463 static void rpcrt4_conn_np_cancel_call(RpcConnection *conn)
465 RpcConnection_np *connection = (RpcConnection_np *)conn;
466 CancelIoEx(connection->pipe, NULL);
469 static int rpcrt4_conn_np_wait_for_incoming_data(RpcConnection *Connection)
471 /* FIXME: implement when named pipe writes use overlapped I/O */
472 return -1;
475 static size_t rpcrt4_ncacn_np_get_top_of_tower(unsigned char *tower_data,
476 const char *networkaddr,
477 const char *endpoint)
479 twr_empty_floor_t *smb_floor;
480 twr_empty_floor_t *nb_floor;
481 size_t size;
482 size_t networkaddr_size;
483 size_t endpoint_size;
485 TRACE("(%p, %s, %s)\n", tower_data, networkaddr, endpoint);
487 networkaddr_size = networkaddr ? strlen(networkaddr) + 1 : 1;
488 endpoint_size = endpoint ? strlen(endpoint) + 1 : 1;
489 size = sizeof(*smb_floor) + endpoint_size + sizeof(*nb_floor) + networkaddr_size;
491 if (!tower_data)
492 return size;
494 smb_floor = (twr_empty_floor_t *)tower_data;
496 tower_data += sizeof(*smb_floor);
498 smb_floor->count_lhs = sizeof(smb_floor->protid);
499 smb_floor->protid = EPM_PROTOCOL_SMB;
500 smb_floor->count_rhs = endpoint_size;
502 if (endpoint)
503 memcpy(tower_data, endpoint, endpoint_size);
504 else
505 tower_data[0] = 0;
506 tower_data += endpoint_size;
508 nb_floor = (twr_empty_floor_t *)tower_data;
510 tower_data += sizeof(*nb_floor);
512 nb_floor->count_lhs = sizeof(nb_floor->protid);
513 nb_floor->protid = EPM_PROTOCOL_NETBIOS;
514 nb_floor->count_rhs = networkaddr_size;
516 if (networkaddr)
517 memcpy(tower_data, networkaddr, networkaddr_size);
518 else
519 tower_data[0] = 0;
521 return size;
524 static RPC_STATUS rpcrt4_ncacn_np_parse_top_of_tower(const unsigned char *tower_data,
525 size_t tower_size,
526 char **networkaddr,
527 char **endpoint)
529 const twr_empty_floor_t *smb_floor = (const twr_empty_floor_t *)tower_data;
530 const twr_empty_floor_t *nb_floor;
532 TRACE("(%p, %d, %p, %p)\n", tower_data, (int)tower_size, networkaddr, endpoint);
534 if (tower_size < sizeof(*smb_floor))
535 return EPT_S_NOT_REGISTERED;
537 tower_data += sizeof(*smb_floor);
538 tower_size -= sizeof(*smb_floor);
540 if ((smb_floor->count_lhs != sizeof(smb_floor->protid)) ||
541 (smb_floor->protid != EPM_PROTOCOL_SMB) ||
542 (smb_floor->count_rhs > tower_size) ||
543 (tower_data[smb_floor->count_rhs - 1] != '\0'))
544 return EPT_S_NOT_REGISTERED;
546 if (endpoint)
548 *endpoint = I_RpcAllocate(smb_floor->count_rhs);
549 if (!*endpoint)
550 return RPC_S_OUT_OF_RESOURCES;
551 memcpy(*endpoint, tower_data, smb_floor->count_rhs);
553 tower_data += smb_floor->count_rhs;
554 tower_size -= smb_floor->count_rhs;
556 if (tower_size < sizeof(*nb_floor))
557 return EPT_S_NOT_REGISTERED;
559 nb_floor = (const twr_empty_floor_t *)tower_data;
561 tower_data += sizeof(*nb_floor);
562 tower_size -= sizeof(*nb_floor);
564 if ((nb_floor->count_lhs != sizeof(nb_floor->protid)) ||
565 (nb_floor->protid != EPM_PROTOCOL_NETBIOS) ||
566 (nb_floor->count_rhs > tower_size) ||
567 (tower_data[nb_floor->count_rhs - 1] != '\0'))
568 return EPT_S_NOT_REGISTERED;
570 if (networkaddr)
572 *networkaddr = I_RpcAllocate(nb_floor->count_rhs);
573 if (!*networkaddr)
575 if (endpoint)
577 I_RpcFree(*endpoint);
578 *endpoint = NULL;
580 return RPC_S_OUT_OF_RESOURCES;
582 memcpy(*networkaddr, tower_data, nb_floor->count_rhs);
585 return RPC_S_OK;
588 static RPC_STATUS rpcrt4_conn_np_impersonate_client(RpcConnection *conn)
590 RpcConnection_np *npc = (RpcConnection_np *)conn;
591 BOOL ret;
593 TRACE("(%p)\n", conn);
595 if (conn->AuthInfo && SecIsValidHandle(&conn->ctx))
596 return RPCRT4_default_impersonate_client(conn);
598 ret = ImpersonateNamedPipeClient(npc->pipe);
599 if (!ret)
601 DWORD error = GetLastError();
602 WARN("ImpersonateNamedPipeClient failed with error %u\n", error);
603 switch (error)
605 case ERROR_CANNOT_IMPERSONATE:
606 return RPC_S_NO_CONTEXT_AVAILABLE;
609 return RPC_S_OK;
612 static RPC_STATUS rpcrt4_conn_np_revert_to_self(RpcConnection *conn)
614 BOOL ret;
616 TRACE("(%p)\n", conn);
618 if (conn->AuthInfo && SecIsValidHandle(&conn->ctx))
619 return RPCRT4_default_revert_to_self(conn);
621 ret = RevertToSelf();
622 if (!ret)
624 WARN("RevertToSelf failed with error %u\n", GetLastError());
625 return RPC_S_NO_CONTEXT_AVAILABLE;
627 return RPC_S_OK;
630 typedef struct _RpcServerProtseq_np
632 RpcServerProtseq common;
633 HANDLE mgr_event;
634 } RpcServerProtseq_np;
636 static RpcServerProtseq *rpcrt4_protseq_np_alloc(void)
638 RpcServerProtseq_np *ps = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*ps));
639 if (ps)
640 ps->mgr_event = CreateEventW(NULL, FALSE, FALSE, NULL);
641 return &ps->common;
644 static void rpcrt4_protseq_np_signal_state_changed(RpcServerProtseq *protseq)
646 RpcServerProtseq_np *npps = CONTAINING_RECORD(protseq, RpcServerProtseq_np, common);
647 SetEvent(npps->mgr_event);
650 static void *rpcrt4_protseq_np_get_wait_array(RpcServerProtseq *protseq, void *prev_array, unsigned int *count)
652 HANDLE *objs = prev_array;
653 RpcConnection_np *conn;
654 RpcServerProtseq_np *npps = CONTAINING_RECORD(protseq, RpcServerProtseq_np, common);
656 EnterCriticalSection(&protseq->cs);
658 /* open and count connections */
659 *count = 1;
660 LIST_FOR_EACH_ENTRY(conn, &protseq->listeners, RpcConnection_np, common.protseq_entry)
662 if (!conn->pipe && rpcrt4_conn_create_pipe(&conn->common) != RPC_S_OK)
663 continue;
664 if (!conn->listen_event)
666 NTSTATUS status;
667 HANDLE event;
669 event = get_np_event(conn);
670 if (!event)
671 continue;
673 status = NtFsControlFile(conn->pipe, event, NULL, NULL, &conn->io_status, FSCTL_PIPE_LISTEN, NULL, 0, NULL, 0);
674 switch (status)
676 case STATUS_SUCCESS:
677 case STATUS_PIPE_CONNECTED:
678 conn->io_status.Status = status;
679 SetEvent(event);
680 break;
681 case STATUS_PENDING:
682 break;
683 default:
684 ERR("pipe listen error %x\n", status);
685 continue;
688 conn->listen_event = event;
690 (*count)++;
693 /* make array of connections */
694 if (objs)
695 objs = HeapReAlloc(GetProcessHeap(), 0, objs, *count*sizeof(HANDLE));
696 else
697 objs = HeapAlloc(GetProcessHeap(), 0, *count*sizeof(HANDLE));
698 if (!objs)
700 ERR("couldn't allocate objs\n");
701 LeaveCriticalSection(&protseq->cs);
702 return NULL;
705 objs[0] = npps->mgr_event;
706 *count = 1;
707 LIST_FOR_EACH_ENTRY(conn, &protseq->listeners, RpcConnection_np, common.protseq_entry)
709 if (conn->listen_event)
710 objs[(*count)++] = conn->listen_event;
712 LeaveCriticalSection(&protseq->cs);
713 return objs;
716 static void rpcrt4_protseq_np_free_wait_array(RpcServerProtseq *protseq, void *array)
718 HeapFree(GetProcessHeap(), 0, array);
721 static int rpcrt4_protseq_np_wait_for_new_connection(RpcServerProtseq *protseq, unsigned int count, void *wait_array)
723 HANDLE b_handle;
724 HANDLE *objs = wait_array;
725 DWORD res;
726 RpcConnection *cconn = NULL;
727 RpcConnection_np *conn;
729 if (!objs)
730 return -1;
734 /* an alertable wait isn't strictly necessary, but due to our
735 * overlapped I/O implementation in Wine we need to free some memory
736 * by the file user APC being called, even if no completion routine was
737 * specified at the time of starting the async operation */
738 res = WaitForMultipleObjectsEx(count, objs, FALSE, INFINITE, TRUE);
739 } while (res == WAIT_IO_COMPLETION);
741 if (res == WAIT_OBJECT_0)
742 return 0;
743 else if (res == WAIT_FAILED)
745 ERR("wait failed with error %d\n", GetLastError());
746 return -1;
748 else
750 b_handle = objs[res - WAIT_OBJECT_0];
751 /* find which connection got a RPC */
752 EnterCriticalSection(&protseq->cs);
753 LIST_FOR_EACH_ENTRY(conn, &protseq->listeners, RpcConnection_np, common.protseq_entry)
755 if (b_handle == conn->listen_event)
757 release_np_event(conn, conn->listen_event);
758 conn->listen_event = NULL;
759 if (conn->io_status.Status == STATUS_SUCCESS || conn->io_status.Status == STATUS_PIPE_CONNECTED)
760 cconn = rpcrt4_spawn_connection(&conn->common);
761 else
762 ERR("listen failed %x\n", conn->io_status.Status);
763 break;
766 LeaveCriticalSection(&protseq->cs);
767 if (!cconn)
769 ERR("failed to locate connection for handle %p\n", b_handle);
770 return -1;
772 RPCRT4_new_client(cconn);
773 return 1;
777 static size_t rpcrt4_ncalrpc_get_top_of_tower(unsigned char *tower_data,
778 const char *networkaddr,
779 const char *endpoint)
781 twr_empty_floor_t *pipe_floor;
782 size_t size;
783 size_t endpoint_size;
785 TRACE("(%p, %s, %s)\n", tower_data, networkaddr, endpoint);
787 endpoint_size = strlen(endpoint) + 1;
788 size = sizeof(*pipe_floor) + endpoint_size;
790 if (!tower_data)
791 return size;
793 pipe_floor = (twr_empty_floor_t *)tower_data;
795 tower_data += sizeof(*pipe_floor);
797 pipe_floor->count_lhs = sizeof(pipe_floor->protid);
798 pipe_floor->protid = EPM_PROTOCOL_PIPE;
799 pipe_floor->count_rhs = endpoint_size;
801 memcpy(tower_data, endpoint, endpoint_size);
803 return size;
806 static RPC_STATUS rpcrt4_ncalrpc_parse_top_of_tower(const unsigned char *tower_data,
807 size_t tower_size,
808 char **networkaddr,
809 char **endpoint)
811 const twr_empty_floor_t *pipe_floor = (const twr_empty_floor_t *)tower_data;
813 TRACE("(%p, %d, %p, %p)\n", tower_data, (int)tower_size, networkaddr, endpoint);
815 if (tower_size < sizeof(*pipe_floor))
816 return EPT_S_NOT_REGISTERED;
818 tower_data += sizeof(*pipe_floor);
819 tower_size -= sizeof(*pipe_floor);
821 if ((pipe_floor->count_lhs != sizeof(pipe_floor->protid)) ||
822 (pipe_floor->protid != EPM_PROTOCOL_PIPE) ||
823 (pipe_floor->count_rhs > tower_size) ||
824 (tower_data[pipe_floor->count_rhs - 1] != '\0'))
825 return EPT_S_NOT_REGISTERED;
827 if (networkaddr)
828 *networkaddr = NULL;
830 if (endpoint)
832 *endpoint = I_RpcAllocate(pipe_floor->count_rhs);
833 if (!*endpoint)
834 return RPC_S_OUT_OF_RESOURCES;
835 memcpy(*endpoint, tower_data, pipe_floor->count_rhs);
838 return RPC_S_OK;
841 static BOOL rpcrt4_ncalrpc_is_authorized(RpcConnection *conn)
843 return FALSE;
846 static RPC_STATUS rpcrt4_ncalrpc_authorize(RpcConnection *conn, BOOL first_time,
847 unsigned char *in_buffer,
848 unsigned int in_size,
849 unsigned char *out_buffer,
850 unsigned int *out_size)
852 /* since this protocol is local to the machine there is no need to
853 * authenticate the caller */
854 *out_size = 0;
855 return RPC_S_OK;
858 static RPC_STATUS rpcrt4_ncalrpc_secure_packet(RpcConnection *conn,
859 enum secure_packet_direction dir,
860 RpcPktHdr *hdr, unsigned int hdr_size,
861 unsigned char *stub_data, unsigned int stub_data_size,
862 RpcAuthVerifier *auth_hdr,
863 unsigned char *auth_value, unsigned int auth_value_size)
865 /* since this protocol is local to the machine there is no need to secure
866 * the packet */
867 return RPC_S_OK;
870 static RPC_STATUS rpcrt4_ncalrpc_inquire_auth_client(
871 RpcConnection *conn, RPC_AUTHZ_HANDLE *privs, RPC_WSTR *server_princ_name,
872 ULONG *authn_level, ULONG *authn_svc, ULONG *authz_svc, ULONG flags)
874 TRACE("(%p, %p, %p, %p, %p, %p, 0x%x)\n", conn, privs,
875 server_princ_name, authn_level, authn_svc, authz_svc, flags);
877 if (privs)
879 FIXME("privs not implemented\n");
880 *privs = NULL;
882 if (server_princ_name)
884 FIXME("server_princ_name not implemented\n");
885 *server_princ_name = NULL;
887 if (authn_level) *authn_level = RPC_C_AUTHN_LEVEL_PKT_PRIVACY;
888 if (authn_svc) *authn_svc = RPC_C_AUTHN_WINNT;
889 if (authz_svc)
891 FIXME("authorization service not implemented\n");
892 *authz_svc = RPC_C_AUTHZ_NONE;
894 if (flags)
895 FIXME("flags 0x%x not implemented\n", flags);
897 return RPC_S_OK;
900 /**** ncacn_ip_tcp support ****/
902 static size_t rpcrt4_ip_tcp_get_top_of_tower(unsigned char *tower_data,
903 const char *networkaddr,
904 unsigned char tcp_protid,
905 const char *endpoint)
907 twr_tcp_floor_t *tcp_floor;
908 twr_ipv4_floor_t *ipv4_floor;
909 struct addrinfo *ai;
910 struct addrinfo hints;
911 int ret;
912 size_t size = sizeof(*tcp_floor) + sizeof(*ipv4_floor);
914 TRACE("(%p, %s, %s)\n", tower_data, networkaddr, endpoint);
916 if (!tower_data)
917 return size;
919 tcp_floor = (twr_tcp_floor_t *)tower_data;
920 tower_data += sizeof(*tcp_floor);
922 ipv4_floor = (twr_ipv4_floor_t *)tower_data;
924 tcp_floor->count_lhs = sizeof(tcp_floor->protid);
925 tcp_floor->protid = tcp_protid;
926 tcp_floor->count_rhs = sizeof(tcp_floor->port);
928 ipv4_floor->count_lhs = sizeof(ipv4_floor->protid);
929 ipv4_floor->protid = EPM_PROTOCOL_IP;
930 ipv4_floor->count_rhs = sizeof(ipv4_floor->ipv4addr);
932 hints.ai_flags = AI_NUMERICHOST;
933 /* FIXME: only support IPv4 at the moment. how is IPv6 represented by the EPM? */
934 hints.ai_family = PF_INET;
935 hints.ai_socktype = SOCK_STREAM;
936 hints.ai_protocol = IPPROTO_TCP;
937 hints.ai_addrlen = 0;
938 hints.ai_addr = NULL;
939 hints.ai_canonname = NULL;
940 hints.ai_next = NULL;
942 ret = getaddrinfo(networkaddr, endpoint, &hints, &ai);
943 if (ret)
945 ret = getaddrinfo("0.0.0.0", endpoint, &hints, &ai);
946 if (ret)
948 ERR("getaddrinfo failed: %s\n", gai_strerror(ret));
949 return 0;
953 if (ai->ai_family == PF_INET)
955 const struct sockaddr_in *sin = (const struct sockaddr_in *)ai->ai_addr;
956 tcp_floor->port = sin->sin_port;
957 ipv4_floor->ipv4addr = sin->sin_addr.s_addr;
959 else
961 ERR("unexpected protocol family %d\n", ai->ai_family);
962 freeaddrinfo(ai);
963 return 0;
966 freeaddrinfo(ai);
968 return size;
971 static RPC_STATUS rpcrt4_ip_tcp_parse_top_of_tower(const unsigned char *tower_data,
972 size_t tower_size,
973 char **networkaddr,
974 unsigned char tcp_protid,
975 char **endpoint)
977 const twr_tcp_floor_t *tcp_floor = (const twr_tcp_floor_t *)tower_data;
978 const twr_ipv4_floor_t *ipv4_floor;
979 struct in_addr in_addr;
981 TRACE("(%p, %d, %p, %p)\n", tower_data, (int)tower_size, networkaddr, endpoint);
983 if (tower_size < sizeof(*tcp_floor))
984 return EPT_S_NOT_REGISTERED;
986 tower_data += sizeof(*tcp_floor);
987 tower_size -= sizeof(*tcp_floor);
989 if (tower_size < sizeof(*ipv4_floor))
990 return EPT_S_NOT_REGISTERED;
992 ipv4_floor = (const twr_ipv4_floor_t *)tower_data;
994 if ((tcp_floor->count_lhs != sizeof(tcp_floor->protid)) ||
995 (tcp_floor->protid != tcp_protid) ||
996 (tcp_floor->count_rhs != sizeof(tcp_floor->port)) ||
997 (ipv4_floor->count_lhs != sizeof(ipv4_floor->protid)) ||
998 (ipv4_floor->protid != EPM_PROTOCOL_IP) ||
999 (ipv4_floor->count_rhs != sizeof(ipv4_floor->ipv4addr)))
1000 return EPT_S_NOT_REGISTERED;
1002 if (endpoint)
1004 *endpoint = I_RpcAllocate(6 /* sizeof("65535") + 1 */);
1005 if (!*endpoint)
1006 return RPC_S_OUT_OF_RESOURCES;
1007 sprintf(*endpoint, "%u", ntohs(tcp_floor->port));
1010 if (networkaddr)
1012 *networkaddr = I_RpcAllocate(INET_ADDRSTRLEN);
1013 if (!*networkaddr)
1015 if (endpoint)
1017 I_RpcFree(*endpoint);
1018 *endpoint = NULL;
1020 return RPC_S_OUT_OF_RESOURCES;
1022 in_addr.s_addr = ipv4_floor->ipv4addr;
1023 if (!inet_ntop(AF_INET, &in_addr, *networkaddr, INET_ADDRSTRLEN))
1025 ERR("inet_ntop: %u\n", WSAGetLastError());
1026 I_RpcFree(*networkaddr);
1027 *networkaddr = NULL;
1028 if (endpoint)
1030 I_RpcFree(*endpoint);
1031 *endpoint = NULL;
1033 return EPT_S_NOT_REGISTERED;
1037 return RPC_S_OK;
1040 typedef struct _RpcConnection_tcp
1042 RpcConnection common;
1043 int sock;
1044 HANDLE sock_event;
1045 HANDLE cancel_event;
1046 } RpcConnection_tcp;
1048 static BOOL rpcrt4_sock_wait_init(RpcConnection_tcp *tcpc)
1050 static BOOL wsa_inited;
1051 if (!wsa_inited)
1053 WSADATA wsadata;
1054 WSAStartup(MAKEWORD(2, 2), &wsadata);
1055 /* Note: WSAStartup can be called more than once so we don't bother with
1056 * making accesses to wsa_inited thread-safe */
1057 wsa_inited = TRUE;
1059 tcpc->sock_event = CreateEventW(NULL, FALSE, FALSE, NULL);
1060 tcpc->cancel_event = CreateEventW(NULL, FALSE, FALSE, NULL);
1061 if (!tcpc->sock_event || !tcpc->cancel_event)
1063 ERR("event creation failed\n");
1064 if (tcpc->sock_event) CloseHandle(tcpc->sock_event);
1065 return FALSE;
1067 return TRUE;
1070 static BOOL rpcrt4_sock_wait_for_recv(RpcConnection_tcp *tcpc)
1072 HANDLE wait_handles[2];
1073 DWORD res;
1074 if (WSAEventSelect(tcpc->sock, tcpc->sock_event, FD_READ | FD_CLOSE) == SOCKET_ERROR)
1076 ERR("WSAEventSelect() failed with error %d\n", WSAGetLastError());
1077 return FALSE;
1079 wait_handles[0] = tcpc->sock_event;
1080 wait_handles[1] = tcpc->cancel_event;
1081 res = WaitForMultipleObjects(2, wait_handles, FALSE, INFINITE);
1082 switch (res)
1084 case WAIT_OBJECT_0:
1085 return TRUE;
1086 case WAIT_OBJECT_0 + 1:
1087 return FALSE;
1088 default:
1089 ERR("WaitForMultipleObjects() failed with error %d\n", GetLastError());
1090 return FALSE;
1094 static BOOL rpcrt4_sock_wait_for_send(RpcConnection_tcp *tcpc)
1096 DWORD res;
1097 if (WSAEventSelect(tcpc->sock, tcpc->sock_event, FD_WRITE | FD_CLOSE) == SOCKET_ERROR)
1099 ERR("WSAEventSelect() failed with error %d\n", WSAGetLastError());
1100 return FALSE;
1102 res = WaitForSingleObject(tcpc->sock_event, INFINITE);
1103 switch (res)
1105 case WAIT_OBJECT_0:
1106 return TRUE;
1107 default:
1108 ERR("WaitForMultipleObjects() failed with error %d\n", GetLastError());
1109 return FALSE;
1113 static RpcConnection *rpcrt4_conn_tcp_alloc(void)
1115 RpcConnection_tcp *tcpc;
1116 tcpc = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(RpcConnection_tcp));
1117 if (tcpc == NULL)
1118 return NULL;
1119 tcpc->sock = -1;
1120 if (!rpcrt4_sock_wait_init(tcpc))
1122 HeapFree(GetProcessHeap(), 0, tcpc);
1123 return NULL;
1125 return &tcpc->common;
1128 static RPC_STATUS rpcrt4_ncacn_ip_tcp_open(RpcConnection* Connection)
1130 RpcConnection_tcp *tcpc = (RpcConnection_tcp *) Connection;
1131 int sock;
1132 int ret;
1133 struct addrinfo *ai;
1134 struct addrinfo *ai_cur;
1135 struct addrinfo hints;
1137 TRACE("(%s, %s)\n", Connection->NetworkAddr, Connection->Endpoint);
1139 if (tcpc->sock != -1)
1140 return RPC_S_OK;
1142 hints.ai_flags = 0;
1143 hints.ai_family = PF_UNSPEC;
1144 hints.ai_socktype = SOCK_STREAM;
1145 hints.ai_protocol = IPPROTO_TCP;
1146 hints.ai_addrlen = 0;
1147 hints.ai_addr = NULL;
1148 hints.ai_canonname = NULL;
1149 hints.ai_next = NULL;
1151 ret = getaddrinfo(Connection->NetworkAddr, Connection->Endpoint, &hints, &ai);
1152 if (ret)
1154 ERR("getaddrinfo for %s:%s failed: %s\n", Connection->NetworkAddr,
1155 Connection->Endpoint, gai_strerror(ret));
1156 return RPC_S_SERVER_UNAVAILABLE;
1159 for (ai_cur = ai; ai_cur; ai_cur = ai_cur->ai_next)
1161 int val;
1162 u_long nonblocking;
1164 if (ai_cur->ai_family != AF_INET && ai_cur->ai_family != AF_INET6)
1166 TRACE("skipping non-IP/IPv6 address family\n");
1167 continue;
1170 if (TRACE_ON(rpc))
1172 char host[256];
1173 char service[256];
1174 getnameinfo(ai_cur->ai_addr, ai_cur->ai_addrlen,
1175 host, sizeof(host), service, sizeof(service),
1176 NI_NUMERICHOST | NI_NUMERICSERV);
1177 TRACE("trying %s:%s\n", host, service);
1180 sock = socket(ai_cur->ai_family, ai_cur->ai_socktype, ai_cur->ai_protocol);
1181 if (sock == -1)
1183 WARN("socket() failed: %u\n", WSAGetLastError());
1184 continue;
1187 if (0>connect(sock, ai_cur->ai_addr, ai_cur->ai_addrlen))
1189 WARN("connect() failed: %u\n", WSAGetLastError());
1190 closesocket(sock);
1191 continue;
1194 /* RPC depends on having minimal latency so disable the Nagle algorithm */
1195 val = 1;
1196 setsockopt(sock, IPPROTO_TCP, TCP_NODELAY, (char *)&val, sizeof(val));
1197 nonblocking = 1;
1198 ioctlsocket(sock, FIONBIO, &nonblocking);
1200 tcpc->sock = sock;
1202 freeaddrinfo(ai);
1203 TRACE("connected\n");
1204 return RPC_S_OK;
1207 freeaddrinfo(ai);
1208 ERR("couldn't connect to %s:%s\n", Connection->NetworkAddr, Connection->Endpoint);
1209 return RPC_S_SERVER_UNAVAILABLE;
1212 static RPC_STATUS rpcrt4_protseq_ncacn_ip_tcp_open_endpoint(RpcServerProtseq *protseq, const char *endpoint)
1214 RPC_STATUS status = RPC_S_CANT_CREATE_ENDPOINT;
1215 int sock;
1216 int ret;
1217 struct addrinfo *ai;
1218 struct addrinfo *ai_cur;
1219 struct addrinfo hints;
1221 TRACE("(%p, %s)\n", protseq, endpoint);
1223 hints.ai_flags = AI_PASSIVE /* for non-localhost addresses */;
1224 hints.ai_family = PF_UNSPEC;
1225 hints.ai_socktype = SOCK_STREAM;
1226 hints.ai_protocol = IPPROTO_TCP;
1227 hints.ai_addrlen = 0;
1228 hints.ai_addr = NULL;
1229 hints.ai_canonname = NULL;
1230 hints.ai_next = NULL;
1232 ret = getaddrinfo(NULL, endpoint ? endpoint : "0", &hints, &ai);
1233 if (ret)
1235 ERR("getaddrinfo for port %s failed: %s\n", endpoint,
1236 gai_strerror(ret));
1237 if ((ret == EAI_SERVICE) || (ret == EAI_NONAME))
1238 return RPC_S_INVALID_ENDPOINT_FORMAT;
1239 return RPC_S_CANT_CREATE_ENDPOINT;
1242 for (ai_cur = ai; ai_cur; ai_cur = ai_cur->ai_next)
1244 RpcConnection_tcp *tcpc;
1245 RPC_STATUS create_status;
1246 struct sockaddr_storage sa;
1247 socklen_t sa_len;
1248 char service[NI_MAXSERV];
1249 u_long nonblocking;
1251 if (ai_cur->ai_family != AF_INET && ai_cur->ai_family != AF_INET6)
1253 TRACE("skipping non-IP/IPv6 address family\n");
1254 continue;
1257 if (TRACE_ON(rpc))
1259 char host[256];
1260 getnameinfo(ai_cur->ai_addr, ai_cur->ai_addrlen,
1261 host, sizeof(host), service, sizeof(service),
1262 NI_NUMERICHOST | NI_NUMERICSERV);
1263 TRACE("trying %s:%s\n", host, service);
1266 sock = socket(ai_cur->ai_family, ai_cur->ai_socktype, ai_cur->ai_protocol);
1267 if (sock == -1)
1269 WARN("socket() failed: %u\n", WSAGetLastError());
1270 status = RPC_S_CANT_CREATE_ENDPOINT;
1271 continue;
1274 ret = bind(sock, ai_cur->ai_addr, ai_cur->ai_addrlen);
1275 if (ret < 0)
1277 WARN("bind failed: %u\n", WSAGetLastError());
1278 closesocket(sock);
1279 if (WSAGetLastError() == WSAEADDRINUSE)
1280 status = RPC_S_DUPLICATE_ENDPOINT;
1281 else
1282 status = RPC_S_CANT_CREATE_ENDPOINT;
1283 continue;
1286 sa_len = sizeof(sa);
1287 if (getsockname(sock, (struct sockaddr *)&sa, &sa_len))
1289 WARN("getsockname() failed: %u\n", WSAGetLastError());
1290 closesocket(sock);
1291 status = RPC_S_CANT_CREATE_ENDPOINT;
1292 continue;
1295 ret = getnameinfo((struct sockaddr *)&sa, sa_len,
1296 NULL, 0, service, sizeof(service),
1297 NI_NUMERICSERV);
1298 if (ret)
1300 WARN("getnameinfo failed: %s\n", gai_strerror(ret));
1301 closesocket(sock);
1302 status = RPC_S_CANT_CREATE_ENDPOINT;
1303 continue;
1306 create_status = RPCRT4_CreateConnection((RpcConnection **)&tcpc, TRUE,
1307 protseq->Protseq, NULL,
1308 service, NULL, NULL, NULL, NULL);
1309 if (create_status != RPC_S_OK)
1311 closesocket(sock);
1312 status = create_status;
1313 continue;
1316 tcpc->sock = sock;
1317 ret = listen(sock, protseq->MaxCalls);
1318 if (ret < 0)
1320 WARN("listen failed: %u\n", WSAGetLastError());
1321 RPCRT4_ReleaseConnection(&tcpc->common);
1322 status = RPC_S_OUT_OF_RESOURCES;
1323 continue;
1325 /* need a non-blocking socket, otherwise accept() has a potential
1326 * race-condition (poll() says it is readable, connection drops,
1327 * and accept() blocks until the next connection comes...)
1329 nonblocking = 1;
1330 ret = ioctlsocket(sock, FIONBIO, &nonblocking);
1331 if (ret < 0)
1333 WARN("couldn't make socket non-blocking, error %d\n", ret);
1334 RPCRT4_ReleaseConnection(&tcpc->common);
1335 status = RPC_S_OUT_OF_RESOURCES;
1336 continue;
1339 EnterCriticalSection(&protseq->cs);
1340 list_add_tail(&protseq->listeners, &tcpc->common.protseq_entry);
1341 tcpc->common.protseq = protseq;
1342 LeaveCriticalSection(&protseq->cs);
1344 freeaddrinfo(ai);
1346 /* since IPv4 and IPv6 share the same port space, we only need one
1347 * successful bind to listen for both */
1348 TRACE("listening on %s\n", endpoint);
1349 return RPC_S_OK;
1352 freeaddrinfo(ai);
1353 ERR("couldn't listen on port %s\n", endpoint);
1354 return status;
1357 static RPC_STATUS rpcrt4_conn_tcp_handoff(RpcConnection *old_conn, RpcConnection *new_conn)
1359 int ret;
1360 struct sockaddr_in address;
1361 socklen_t addrsize;
1362 RpcConnection_tcp *server = (RpcConnection_tcp*) old_conn;
1363 RpcConnection_tcp *client = (RpcConnection_tcp*) new_conn;
1364 u_long nonblocking;
1366 addrsize = sizeof(address);
1367 ret = accept(server->sock, (struct sockaddr*) &address, &addrsize);
1368 if (ret < 0)
1370 ERR("Failed to accept a TCP connection: error %d\n", ret);
1371 return RPC_S_OUT_OF_RESOURCES;
1374 nonblocking = 1;
1375 ioctlsocket(ret, FIONBIO, &nonblocking);
1376 client->sock = ret;
1378 client->common.NetworkAddr = HeapAlloc(GetProcessHeap(), 0, INET6_ADDRSTRLEN);
1379 ret = getnameinfo((struct sockaddr*)&address, addrsize, client->common.NetworkAddr, INET6_ADDRSTRLEN, NULL, 0, NI_NUMERICHOST);
1380 if (ret != 0)
1382 ERR("Failed to retrieve the IP address, error %d\n", ret);
1383 return RPC_S_OUT_OF_RESOURCES;
1386 TRACE("Accepted a new TCP connection from %s\n", client->common.NetworkAddr);
1387 return RPC_S_OK;
1390 static int rpcrt4_conn_tcp_read(RpcConnection *Connection,
1391 void *buffer, unsigned int count)
1393 RpcConnection_tcp *tcpc = (RpcConnection_tcp *) Connection;
1394 int bytes_read = 0;
1395 while (bytes_read != count)
1397 int r = recv(tcpc->sock, (char *)buffer + bytes_read, count - bytes_read, 0);
1398 if (!r)
1399 return -1;
1400 else if (r > 0)
1401 bytes_read += r;
1402 else if (WSAGetLastError() == WSAEINTR)
1403 continue;
1404 else if (WSAGetLastError() != WSAEWOULDBLOCK)
1406 WARN("recv() failed: %u\n", WSAGetLastError());
1407 return -1;
1409 else
1411 if (!rpcrt4_sock_wait_for_recv(tcpc))
1412 return -1;
1415 TRACE("%d %p %u -> %d\n", tcpc->sock, buffer, count, bytes_read);
1416 return bytes_read;
1419 static int rpcrt4_conn_tcp_write(RpcConnection *Connection,
1420 const void *buffer, unsigned int count)
1422 RpcConnection_tcp *tcpc = (RpcConnection_tcp *) Connection;
1423 int bytes_written = 0;
1424 while (bytes_written != count)
1426 int r = send(tcpc->sock, (const char *)buffer + bytes_written, count - bytes_written, 0);
1427 if (r >= 0)
1428 bytes_written += r;
1429 else if (WSAGetLastError() == WSAEINTR)
1430 continue;
1431 else if (WSAGetLastError() != WSAEWOULDBLOCK)
1432 return -1;
1433 else
1435 if (!rpcrt4_sock_wait_for_send(tcpc))
1436 return -1;
1439 TRACE("%d %p %u -> %d\n", tcpc->sock, buffer, count, bytes_written);
1440 return bytes_written;
1443 static int rpcrt4_conn_tcp_close(RpcConnection *conn)
1445 RpcConnection_tcp *connection = (RpcConnection_tcp *) conn;
1447 TRACE("%d\n", connection->sock);
1449 if (connection->sock != -1)
1450 closesocket(connection->sock);
1451 connection->sock = -1;
1452 CloseHandle(connection->sock_event);
1453 CloseHandle(connection->cancel_event);
1454 return 0;
1457 static void rpcrt4_conn_tcp_close_read(RpcConnection *conn)
1459 RpcConnection_tcp *connection = (RpcConnection_tcp *) conn;
1460 shutdown(connection->sock, SD_RECEIVE);
1463 static void rpcrt4_conn_tcp_cancel_call(RpcConnection *conn)
1465 RpcConnection_tcp *connection = (RpcConnection_tcp *) conn;
1467 TRACE("%p\n", connection);
1469 SetEvent(connection->cancel_event);
1472 static RPC_STATUS rpcrt4_conn_tcp_is_server_listening(const char *endpoint)
1474 FIXME("\n");
1475 return RPC_S_ACCESS_DENIED;
1478 static int rpcrt4_conn_tcp_wait_for_incoming_data(RpcConnection *Connection)
1480 RpcConnection_tcp *tcpc = (RpcConnection_tcp *) Connection;
1482 TRACE("%p\n", Connection);
1484 if (!rpcrt4_sock_wait_for_recv(tcpc))
1485 return -1;
1486 return 0;
1489 static size_t rpcrt4_ncacn_ip_tcp_get_top_of_tower(unsigned char *tower_data,
1490 const char *networkaddr,
1491 const char *endpoint)
1493 return rpcrt4_ip_tcp_get_top_of_tower(tower_data, networkaddr,
1494 EPM_PROTOCOL_TCP, endpoint);
1497 typedef struct _RpcServerProtseq_sock
1499 RpcServerProtseq common;
1500 HANDLE mgr_event;
1501 } RpcServerProtseq_sock;
1503 static RpcServerProtseq *rpcrt4_protseq_sock_alloc(void)
1505 RpcServerProtseq_sock *ps = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*ps));
1506 if (ps)
1508 static BOOL wsa_inited;
1509 if (!wsa_inited)
1511 WSADATA wsadata;
1512 WSAStartup(MAKEWORD(2, 2), &wsadata);
1513 /* Note: WSAStartup can be called more than once so we don't bother with
1514 * making accesses to wsa_inited thread-safe */
1515 wsa_inited = TRUE;
1517 ps->mgr_event = CreateEventW(NULL, FALSE, FALSE, NULL);
1519 return &ps->common;
1522 static void rpcrt4_protseq_sock_signal_state_changed(RpcServerProtseq *protseq)
1524 RpcServerProtseq_sock *sockps = CONTAINING_RECORD(protseq, RpcServerProtseq_sock, common);
1525 SetEvent(sockps->mgr_event);
1528 static void *rpcrt4_protseq_sock_get_wait_array(RpcServerProtseq *protseq, void *prev_array, unsigned int *count)
1530 HANDLE *objs = prev_array;
1531 RpcConnection_tcp *conn;
1532 RpcServerProtseq_sock *sockps = CONTAINING_RECORD(protseq, RpcServerProtseq_sock, common);
1534 EnterCriticalSection(&protseq->cs);
1536 /* open and count connections */
1537 *count = 1;
1538 LIST_FOR_EACH_ENTRY(conn, &protseq->listeners, RpcConnection_tcp, common.protseq_entry)
1540 if (conn->sock != -1)
1541 (*count)++;
1544 /* make array of connections */
1545 if (objs)
1546 objs = HeapReAlloc(GetProcessHeap(), 0, objs, *count*sizeof(HANDLE));
1547 else
1548 objs = HeapAlloc(GetProcessHeap(), 0, *count*sizeof(HANDLE));
1549 if (!objs)
1551 ERR("couldn't allocate objs\n");
1552 LeaveCriticalSection(&protseq->cs);
1553 return NULL;
1556 objs[0] = sockps->mgr_event;
1557 *count = 1;
1558 LIST_FOR_EACH_ENTRY(conn, &protseq->listeners, RpcConnection_tcp, common.protseq_entry)
1560 if (conn->sock != -1)
1562 int res = WSAEventSelect(conn->sock, conn->sock_event, FD_ACCEPT);
1563 if (res == SOCKET_ERROR)
1564 ERR("WSAEventSelect() failed with error %d\n", WSAGetLastError());
1565 else
1567 objs[*count] = conn->sock_event;
1568 (*count)++;
1572 LeaveCriticalSection(&protseq->cs);
1573 return objs;
1576 static void rpcrt4_protseq_sock_free_wait_array(RpcServerProtseq *protseq, void *array)
1578 HeapFree(GetProcessHeap(), 0, array);
1581 static int rpcrt4_protseq_sock_wait_for_new_connection(RpcServerProtseq *protseq, unsigned int count, void *wait_array)
1583 HANDLE b_handle;
1584 HANDLE *objs = wait_array;
1585 DWORD res;
1586 RpcConnection *cconn = NULL;
1587 RpcConnection_tcp *conn;
1589 if (!objs)
1590 return -1;
1594 /* an alertable wait isn't strictly necessary, but due to our
1595 * overlapped I/O implementation in Wine we need to free some memory
1596 * by the file user APC being called, even if no completion routine was
1597 * specified at the time of starting the async operation */
1598 res = WaitForMultipleObjectsEx(count, objs, FALSE, INFINITE, TRUE);
1599 } while (res == WAIT_IO_COMPLETION);
1601 if (res == WAIT_OBJECT_0)
1602 return 0;
1603 if (res == WAIT_FAILED)
1605 ERR("wait failed with error %d\n", GetLastError());
1606 return -1;
1609 b_handle = objs[res - WAIT_OBJECT_0];
1611 /* find which connection got a RPC */
1612 EnterCriticalSection(&protseq->cs);
1613 LIST_FOR_EACH_ENTRY(conn, &protseq->listeners, RpcConnection_tcp, common.protseq_entry)
1615 if (b_handle == conn->sock_event)
1617 cconn = rpcrt4_spawn_connection(&conn->common);
1618 break;
1621 LeaveCriticalSection(&protseq->cs);
1622 if (!cconn)
1624 ERR("failed to locate connection for handle %p\n", b_handle);
1625 return -1;
1628 RPCRT4_new_client(cconn);
1629 return 1;
1632 static RPC_STATUS rpcrt4_ncacn_ip_tcp_parse_top_of_tower(const unsigned char *tower_data,
1633 size_t tower_size,
1634 char **networkaddr,
1635 char **endpoint)
1637 return rpcrt4_ip_tcp_parse_top_of_tower(tower_data, tower_size,
1638 networkaddr, EPM_PROTOCOL_TCP,
1639 endpoint);
1642 /**** ncacn_http support ****/
1644 /* 60 seconds is the period native uses */
1645 #define HTTP_IDLE_TIME 60000
1647 /* reference counted to avoid a race between a cancelled call's connection
1648 * being destroyed and the asynchronous InternetReadFileEx call being
1649 * completed */
1650 typedef struct _RpcHttpAsyncData
1652 LONG refs;
1653 HANDLE completion_event;
1654 WORD async_result;
1655 INTERNET_BUFFERSW inet_buffers;
1656 CRITICAL_SECTION cs;
1657 } RpcHttpAsyncData;
1659 static ULONG RpcHttpAsyncData_AddRef(RpcHttpAsyncData *data)
1661 return InterlockedIncrement(&data->refs);
1664 static ULONG RpcHttpAsyncData_Release(RpcHttpAsyncData *data)
1666 ULONG refs = InterlockedDecrement(&data->refs);
1667 if (!refs)
1669 TRACE("destroying async data %p\n", data);
1670 CloseHandle(data->completion_event);
1671 HeapFree(GetProcessHeap(), 0, data->inet_buffers.lpvBuffer);
1672 data->cs.DebugInfo->Spare[0] = 0;
1673 DeleteCriticalSection(&data->cs);
1674 HeapFree(GetProcessHeap(), 0, data);
1676 return refs;
1679 static void prepare_async_request(RpcHttpAsyncData *async_data)
1681 ResetEvent(async_data->completion_event);
1682 RpcHttpAsyncData_AddRef(async_data);
1685 static RPC_STATUS wait_async_request(RpcHttpAsyncData *async_data, BOOL call_ret, HANDLE cancel_event)
1687 HANDLE handles[2] = { async_data->completion_event, cancel_event };
1688 DWORD res;
1690 if(call_ret) {
1691 RpcHttpAsyncData_Release(async_data);
1692 return RPC_S_OK;
1695 if(GetLastError() != ERROR_IO_PENDING) {
1696 RpcHttpAsyncData_Release(async_data);
1697 ERR("Request failed with error %d\n", GetLastError());
1698 return RPC_S_SERVER_UNAVAILABLE;
1701 res = WaitForMultipleObjects(2, handles, FALSE, DEFAULT_NCACN_HTTP_TIMEOUT);
1702 if(res != WAIT_OBJECT_0) {
1703 TRACE("Cancelled\n");
1704 return RPC_S_CALL_CANCELLED;
1707 if(async_data->async_result) {
1708 ERR("Async request failed with error %d\n", async_data->async_result);
1709 return RPC_S_SERVER_UNAVAILABLE;
1712 return RPC_S_OK;
1715 struct authinfo
1717 DWORD scheme;
1718 CredHandle cred;
1719 CtxtHandle ctx;
1720 TimeStamp exp;
1721 ULONG attr;
1722 ULONG max_token;
1723 char *data;
1724 unsigned int data_len;
1725 BOOL finished; /* finished authenticating */
1728 typedef struct _RpcConnection_http
1730 RpcConnection common;
1731 HINTERNET app_info;
1732 HINTERNET session;
1733 HINTERNET in_request;
1734 HINTERNET out_request;
1735 WCHAR *servername;
1736 HANDLE timer_cancelled;
1737 HANDLE cancel_event;
1738 DWORD last_sent_time;
1739 ULONG bytes_received;
1740 ULONG flow_control_mark; /* send a control packet to the server when this many bytes received */
1741 ULONG flow_control_increment; /* number of bytes to increment flow_control_mark by */
1742 UUID connection_uuid;
1743 UUID in_pipe_uuid;
1744 UUID out_pipe_uuid;
1745 RpcHttpAsyncData *async_data;
1746 } RpcConnection_http;
1748 static RpcConnection *rpcrt4_ncacn_http_alloc(void)
1750 RpcConnection_http *httpc;
1751 httpc = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*httpc));
1752 if (!httpc) return NULL;
1753 httpc->async_data = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(RpcHttpAsyncData));
1754 if (!httpc->async_data)
1756 HeapFree(GetProcessHeap(), 0, httpc);
1757 return NULL;
1759 TRACE("async data = %p\n", httpc->async_data);
1760 httpc->cancel_event = CreateEventW(NULL, FALSE, FALSE, NULL);
1761 httpc->async_data->refs = 1;
1762 httpc->async_data->inet_buffers.dwStructSize = sizeof(INTERNET_BUFFERSW);
1763 InitializeCriticalSection(&httpc->async_data->cs);
1764 httpc->async_data->cs.DebugInfo->Spare[0] = (DWORD_PTR)(__FILE__ ": RpcHttpAsyncData.cs");
1765 return &httpc->common;
1768 typedef struct _HttpTimerThreadData
1770 PVOID timer_param;
1771 DWORD *last_sent_time;
1772 HANDLE timer_cancelled;
1773 } HttpTimerThreadData;
1775 static VOID rpcrt4_http_keep_connection_active_timer_proc(PVOID param, BOOLEAN dummy)
1777 HINTERNET in_request = param;
1778 RpcPktHdr *idle_pkt;
1780 idle_pkt = RPCRT4_BuildHttpHeader(NDR_LOCAL_DATA_REPRESENTATION, 0x0001,
1781 0, 0);
1782 if (idle_pkt)
1784 DWORD bytes_written;
1785 InternetWriteFile(in_request, idle_pkt, idle_pkt->common.frag_len, &bytes_written);
1786 RPCRT4_FreeHeader(idle_pkt);
1790 static inline DWORD rpcrt4_http_timer_calc_timeout(DWORD *last_sent_time)
1792 DWORD cur_time = GetTickCount();
1793 DWORD cached_last_sent_time = *last_sent_time;
1794 return HTTP_IDLE_TIME - (cur_time - cached_last_sent_time > HTTP_IDLE_TIME ? 0 : cur_time - cached_last_sent_time);
1797 static DWORD CALLBACK rpcrt4_http_timer_thread(PVOID param)
1799 HttpTimerThreadData *data_in = param;
1800 HttpTimerThreadData data;
1801 DWORD timeout;
1803 data = *data_in;
1804 HeapFree(GetProcessHeap(), 0, data_in);
1806 for (timeout = HTTP_IDLE_TIME;
1807 WaitForSingleObject(data.timer_cancelled, timeout) == WAIT_TIMEOUT;
1808 timeout = rpcrt4_http_timer_calc_timeout(data.last_sent_time))
1810 /* are we too soon after last send? */
1811 if (GetTickCount() - *data.last_sent_time < HTTP_IDLE_TIME)
1812 continue;
1813 rpcrt4_http_keep_connection_active_timer_proc(data.timer_param, TRUE);
1816 CloseHandle(data.timer_cancelled);
1817 return 0;
1820 static VOID WINAPI rpcrt4_http_internet_callback(
1821 HINTERNET hInternet,
1822 DWORD_PTR dwContext,
1823 DWORD dwInternetStatus,
1824 LPVOID lpvStatusInformation,
1825 DWORD dwStatusInformationLength)
1827 RpcHttpAsyncData *async_data = (RpcHttpAsyncData *)dwContext;
1829 switch (dwInternetStatus)
1831 case INTERNET_STATUS_REQUEST_COMPLETE:
1832 TRACE("INTERNET_STATUS_REQUEST_COMPLETED\n");
1833 if (async_data)
1835 INTERNET_ASYNC_RESULT *async_result = lpvStatusInformation;
1837 async_data->async_result = async_result->dwResult ? ERROR_SUCCESS : async_result->dwError;
1838 SetEvent(async_data->completion_event);
1839 RpcHttpAsyncData_Release(async_data);
1841 break;
1845 static RPC_STATUS rpcrt4_http_check_response(HINTERNET hor)
1847 BOOL ret;
1848 DWORD status_code;
1849 DWORD size;
1850 DWORD index;
1851 WCHAR buf[32];
1852 WCHAR *status_text = buf;
1853 TRACE("\n");
1855 index = 0;
1856 size = sizeof(status_code);
1857 ret = HttpQueryInfoW(hor, HTTP_QUERY_STATUS_CODE|HTTP_QUERY_FLAG_NUMBER, &status_code, &size, &index);
1858 if (!ret)
1859 return GetLastError();
1860 if (status_code == HTTP_STATUS_OK)
1861 return RPC_S_OK;
1862 index = 0;
1863 size = sizeof(buf);
1864 ret = HttpQueryInfoW(hor, HTTP_QUERY_STATUS_TEXT, status_text, &size, &index);
1865 if (!ret && GetLastError() == ERROR_INSUFFICIENT_BUFFER)
1867 status_text = HeapAlloc(GetProcessHeap(), 0, size);
1868 ret = HttpQueryInfoW(hor, HTTP_QUERY_STATUS_TEXT, status_text, &size, &index);
1871 ERR("server returned: %d %s\n", status_code, ret ? debugstr_w(status_text) : "<status text unavailable>");
1872 if(status_text != buf) HeapFree(GetProcessHeap(), 0, status_text);
1874 if (status_code == HTTP_STATUS_DENIED)
1875 return ERROR_ACCESS_DENIED;
1876 return RPC_S_SERVER_UNAVAILABLE;
1879 static RPC_STATUS rpcrt4_http_internet_connect(RpcConnection_http *httpc)
1881 static const WCHAR wszUserAgent[] = {'M','S','R','P','C',0};
1882 LPWSTR proxy = NULL;
1883 LPWSTR user = NULL;
1884 LPWSTR password = NULL;
1885 LPWSTR servername = NULL;
1886 const WCHAR *option;
1887 INTERNET_PORT port;
1889 if (httpc->common.QOS &&
1890 (httpc->common.QOS->qos->AdditionalSecurityInfoType == RPC_C_AUTHN_INFO_TYPE_HTTP))
1892 const RPC_HTTP_TRANSPORT_CREDENTIALS_W *http_cred = httpc->common.QOS->qos->u.HttpCredentials;
1893 if (http_cred->TransportCredentials)
1895 WCHAR *p;
1896 const SEC_WINNT_AUTH_IDENTITY_W *cred = http_cred->TransportCredentials;
1897 ULONG len = cred->DomainLength + 1 + cred->UserLength;
1898 user = HeapAlloc(GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR));
1899 if (!user)
1900 return RPC_S_OUT_OF_RESOURCES;
1901 p = user;
1902 if (cred->DomainLength)
1904 memcpy(p, cred->Domain, cred->DomainLength * sizeof(WCHAR));
1905 p += cred->DomainLength;
1906 *p = '\\';
1907 p++;
1909 memcpy(p, cred->User, cred->UserLength * sizeof(WCHAR));
1910 p[cred->UserLength] = 0;
1912 password = RPCRT4_strndupW(cred->Password, cred->PasswordLength);
1916 for (option = httpc->common.NetworkOptions; option;
1917 option = (strchrW(option, ',') ? strchrW(option, ',')+1 : NULL))
1919 static const WCHAR wszRpcProxy[] = {'R','p','c','P','r','o','x','y','=',0};
1920 static const WCHAR wszHttpProxy[] = {'H','t','t','p','P','r','o','x','y','=',0};
1922 if (!strncmpiW(option, wszRpcProxy, sizeof(wszRpcProxy)/sizeof(wszRpcProxy[0])-1))
1924 const WCHAR *value_start = option + sizeof(wszRpcProxy)/sizeof(wszRpcProxy[0])-1;
1925 const WCHAR *value_end;
1926 const WCHAR *p;
1928 value_end = strchrW(option, ',');
1929 if (!value_end)
1930 value_end = value_start + strlenW(value_start);
1931 for (p = value_start; p < value_end; p++)
1932 if (*p == ':')
1934 port = atoiW(p+1);
1935 value_end = p;
1936 break;
1938 TRACE("RpcProxy value is %s\n", debugstr_wn(value_start, value_end-value_start));
1939 servername = RPCRT4_strndupW(value_start, value_end-value_start);
1941 else if (!strncmpiW(option, wszHttpProxy, sizeof(wszHttpProxy)/sizeof(wszHttpProxy[0])-1))
1943 const WCHAR *value_start = option + sizeof(wszHttpProxy)/sizeof(wszHttpProxy[0])-1;
1944 const WCHAR *value_end;
1946 value_end = strchrW(option, ',');
1947 if (!value_end)
1948 value_end = value_start + strlenW(value_start);
1949 TRACE("HttpProxy value is %s\n", debugstr_wn(value_start, value_end-value_start));
1950 proxy = RPCRT4_strndupW(value_start, value_end-value_start);
1952 else
1953 FIXME("unhandled option %s\n", debugstr_w(option));
1956 httpc->app_info = InternetOpenW(wszUserAgent, proxy ? INTERNET_OPEN_TYPE_PROXY : INTERNET_OPEN_TYPE_PRECONFIG,
1957 NULL, NULL, INTERNET_FLAG_ASYNC);
1958 if (!httpc->app_info)
1960 HeapFree(GetProcessHeap(), 0, password);
1961 HeapFree(GetProcessHeap(), 0, user);
1962 HeapFree(GetProcessHeap(), 0, proxy);
1963 HeapFree(GetProcessHeap(), 0, servername);
1964 ERR("InternetOpenW failed with error %d\n", GetLastError());
1965 return RPC_S_SERVER_UNAVAILABLE;
1967 InternetSetStatusCallbackW(httpc->app_info, rpcrt4_http_internet_callback);
1969 /* if no RpcProxy option specified, set the HTTP server address to the
1970 * RPC server address */
1971 if (!servername)
1973 servername = HeapAlloc(GetProcessHeap(), 0, (strlen(httpc->common.NetworkAddr) + 1)*sizeof(WCHAR));
1974 if (!servername)
1976 HeapFree(GetProcessHeap(), 0, password);
1977 HeapFree(GetProcessHeap(), 0, user);
1978 HeapFree(GetProcessHeap(), 0, proxy);
1979 return RPC_S_OUT_OF_RESOURCES;
1981 MultiByteToWideChar(CP_ACP, 0, httpc->common.NetworkAddr, -1, servername, strlen(httpc->common.NetworkAddr) + 1);
1984 port = (httpc->common.QOS &&
1985 (httpc->common.QOS->qos->AdditionalSecurityInfoType == RPC_C_AUTHN_INFO_TYPE_HTTP) &&
1986 (httpc->common.QOS->qos->u.HttpCredentials->Flags & RPC_C_HTTP_FLAG_USE_SSL)) ?
1987 INTERNET_DEFAULT_HTTPS_PORT : INTERNET_DEFAULT_HTTP_PORT;
1989 httpc->session = InternetConnectW(httpc->app_info, servername, port, user, password,
1990 INTERNET_SERVICE_HTTP, 0, 0);
1992 HeapFree(GetProcessHeap(), 0, password);
1993 HeapFree(GetProcessHeap(), 0, user);
1994 HeapFree(GetProcessHeap(), 0, proxy);
1996 if (!httpc->session)
1998 ERR("InternetConnectW failed with error %d\n", GetLastError());
1999 HeapFree(GetProcessHeap(), 0, servername);
2000 return RPC_S_SERVER_UNAVAILABLE;
2002 httpc->servername = servername;
2003 return RPC_S_OK;
2006 static int rpcrt4_http_async_read(HINTERNET req, RpcHttpAsyncData *async_data, HANDLE cancel_event,
2007 void *buffer, unsigned int count)
2009 char *buf = buffer;
2010 BOOL ret;
2011 unsigned int bytes_left = count;
2012 RPC_STATUS status = RPC_S_OK;
2014 async_data->inet_buffers.lpvBuffer = HeapAlloc(GetProcessHeap(), 0, count);
2016 while (bytes_left)
2018 async_data->inet_buffers.dwBufferLength = bytes_left;
2019 prepare_async_request(async_data);
2020 ret = InternetReadFileExW(req, &async_data->inet_buffers, IRF_ASYNC, 0);
2021 status = wait_async_request(async_data, ret, cancel_event);
2022 if (status != RPC_S_OK)
2024 if (status == RPC_S_CALL_CANCELLED)
2025 TRACE("call cancelled\n");
2026 break;
2029 if (!async_data->inet_buffers.dwBufferLength)
2030 break;
2031 memcpy(buf, async_data->inet_buffers.lpvBuffer,
2032 async_data->inet_buffers.dwBufferLength);
2034 bytes_left -= async_data->inet_buffers.dwBufferLength;
2035 buf += async_data->inet_buffers.dwBufferLength;
2038 HeapFree(GetProcessHeap(), 0, async_data->inet_buffers.lpvBuffer);
2039 async_data->inet_buffers.lpvBuffer = NULL;
2041 TRACE("%p %p %u -> %u\n", req, buffer, count, status);
2042 return status == RPC_S_OK ? count : -1;
2045 static RPC_STATUS send_echo_request(HINTERNET req, RpcHttpAsyncData *async_data, HANDLE cancel_event)
2047 BYTE buf[20];
2048 BOOL ret;
2049 RPC_STATUS status;
2051 TRACE("sending echo request to server\n");
2053 prepare_async_request(async_data);
2054 ret = HttpSendRequestW(req, NULL, 0, NULL, 0);
2055 status = wait_async_request(async_data, ret, cancel_event);
2056 if (status != RPC_S_OK) return status;
2058 status = rpcrt4_http_check_response(req);
2059 if (status != RPC_S_OK) return status;
2061 rpcrt4_http_async_read(req, async_data, cancel_event, buf, sizeof(buf));
2062 /* FIXME: do something with retrieved data */
2064 return RPC_S_OK;
2067 static RPC_STATUS insert_content_length_header(HINTERNET request, DWORD len)
2069 static const WCHAR fmtW[] =
2070 {'C','o','n','t','e','n','t','-','L','e','n','g','t','h',':',' ','%','u','\r','\n',0};
2071 WCHAR header[sizeof(fmtW) / sizeof(fmtW[0]) + 10];
2073 sprintfW(header, fmtW, len);
2074 if ((HttpAddRequestHeadersW(request, header, -1, HTTP_ADDREQ_FLAG_REPLACE | HTTP_ADDREQ_FLAG_ADD))) return RPC_S_OK;
2075 return RPC_S_SERVER_UNAVAILABLE;
2078 /* prepare the in pipe for use by RPC packets */
2079 static RPC_STATUS rpcrt4_http_prepare_in_pipe(HINTERNET in_request, RpcHttpAsyncData *async_data, HANDLE cancel_event,
2080 const UUID *connection_uuid, const UUID *in_pipe_uuid,
2081 const UUID *association_uuid, BOOL authorized)
2083 BOOL ret;
2084 RPC_STATUS status;
2085 RpcPktHdr *hdr;
2086 INTERNET_BUFFERSW buffers_in;
2087 DWORD bytes_written;
2089 if (!authorized)
2091 /* ask wininet to authorize, if necessary */
2092 status = send_echo_request(in_request, async_data, cancel_event);
2093 if (status != RPC_S_OK) return status;
2095 memset(&buffers_in, 0, sizeof(buffers_in));
2096 buffers_in.dwStructSize = sizeof(buffers_in);
2097 /* FIXME: get this from the registry */
2098 buffers_in.dwBufferTotal = 1024 * 1024 * 1024; /* 1Gb */
2099 status = insert_content_length_header(in_request, buffers_in.dwBufferTotal);
2100 if (status != RPC_S_OK) return status;
2102 prepare_async_request(async_data);
2103 ret = HttpSendRequestExW(in_request, &buffers_in, NULL, 0, 0);
2104 status = wait_async_request(async_data, ret, cancel_event);
2105 if (status != RPC_S_OK) return status;
2107 TRACE("sending HTTP connect header to server\n");
2108 hdr = RPCRT4_BuildHttpConnectHeader(FALSE, connection_uuid, in_pipe_uuid, association_uuid);
2109 if (!hdr) return RPC_S_OUT_OF_RESOURCES;
2110 ret = InternetWriteFile(in_request, hdr, hdr->common.frag_len, &bytes_written);
2111 RPCRT4_FreeHeader(hdr);
2112 if (!ret)
2114 ERR("InternetWriteFile failed with error %d\n", GetLastError());
2115 return RPC_S_SERVER_UNAVAILABLE;
2118 return RPC_S_OK;
2121 static RPC_STATUS rpcrt4_http_read_http_packet(HINTERNET request, RpcHttpAsyncData *async_data,
2122 HANDLE cancel_event, RpcPktHdr *hdr, BYTE **data)
2124 unsigned short data_len;
2125 unsigned int size;
2127 if (rpcrt4_http_async_read(request, async_data, cancel_event, hdr, sizeof(hdr->common)) < 0)
2128 return RPC_S_SERVER_UNAVAILABLE;
2129 if (hdr->common.ptype != PKT_HTTP || hdr->common.frag_len < sizeof(hdr->http))
2131 ERR("wrong packet type received %d or wrong frag_len %d\n",
2132 hdr->common.ptype, hdr->common.frag_len);
2133 return RPC_S_PROTOCOL_ERROR;
2136 size = sizeof(hdr->http) - sizeof(hdr->common);
2137 if (rpcrt4_http_async_read(request, async_data, cancel_event, &hdr->common + 1, size) < 0)
2138 return RPC_S_SERVER_UNAVAILABLE;
2140 data_len = hdr->common.frag_len - sizeof(hdr->http);
2141 if (data_len)
2143 *data = HeapAlloc(GetProcessHeap(), 0, data_len);
2144 if (!*data)
2145 return RPC_S_OUT_OF_RESOURCES;
2146 if (rpcrt4_http_async_read(request, async_data, cancel_event, *data, data_len) < 0)
2148 HeapFree(GetProcessHeap(), 0, *data);
2149 return RPC_S_SERVER_UNAVAILABLE;
2152 else
2153 *data = NULL;
2155 if (!RPCRT4_IsValidHttpPacket(hdr, *data, data_len))
2157 ERR("invalid http packet\n");
2158 HeapFree(GetProcessHeap(), 0, *data);
2159 return RPC_S_PROTOCOL_ERROR;
2162 return RPC_S_OK;
2165 /* prepare the out pipe for use by RPC packets */
2166 static RPC_STATUS rpcrt4_http_prepare_out_pipe(HINTERNET out_request, RpcHttpAsyncData *async_data,
2167 HANDLE cancel_event, const UUID *connection_uuid,
2168 const UUID *out_pipe_uuid, ULONG *flow_control_increment,
2169 BOOL authorized)
2171 BOOL ret;
2172 RPC_STATUS status;
2173 RpcPktHdr *hdr;
2174 BYTE *data_from_server;
2175 RpcPktHdr pkt_from_server;
2176 ULONG field1, field3;
2177 BYTE buf[20];
2179 if (!authorized)
2181 /* ask wininet to authorize, if necessary */
2182 status = send_echo_request(out_request, async_data, cancel_event);
2183 if (status != RPC_S_OK) return status;
2185 else
2186 rpcrt4_http_async_read(out_request, async_data, cancel_event, buf, sizeof(buf));
2188 hdr = RPCRT4_BuildHttpConnectHeader(TRUE, connection_uuid, out_pipe_uuid, NULL);
2189 if (!hdr) return RPC_S_OUT_OF_RESOURCES;
2191 status = insert_content_length_header(out_request, hdr->common.frag_len);
2192 if (status != RPC_S_OK)
2194 RPCRT4_FreeHeader(hdr);
2195 return status;
2198 TRACE("sending HTTP connect header to server\n");
2199 prepare_async_request(async_data);
2200 ret = HttpSendRequestW(out_request, NULL, 0, hdr, hdr->common.frag_len);
2201 status = wait_async_request(async_data, ret, cancel_event);
2202 RPCRT4_FreeHeader(hdr);
2203 if (status != RPC_S_OK) return status;
2205 status = rpcrt4_http_check_response(out_request);
2206 if (status != RPC_S_OK) return status;
2208 status = rpcrt4_http_read_http_packet(out_request, async_data, cancel_event,
2209 &pkt_from_server, &data_from_server);
2210 if (status != RPC_S_OK) return status;
2211 status = RPCRT4_ParseHttpPrepareHeader1(&pkt_from_server, data_from_server,
2212 &field1);
2213 HeapFree(GetProcessHeap(), 0, data_from_server);
2214 if (status != RPC_S_OK) return status;
2215 TRACE("received (%d) from first prepare header\n", field1);
2217 for (;;)
2219 status = rpcrt4_http_read_http_packet(out_request, async_data, cancel_event,
2220 &pkt_from_server, &data_from_server);
2221 if (status != RPC_S_OK) return status;
2222 if (pkt_from_server.http.flags != 0x0001) break;
2224 TRACE("http idle packet, waiting for real packet\n");
2225 HeapFree(GetProcessHeap(), 0, data_from_server);
2226 if (pkt_from_server.http.num_data_items != 0)
2228 ERR("HTTP idle packet should have no data items instead of %d\n",
2229 pkt_from_server.http.num_data_items);
2230 return RPC_S_PROTOCOL_ERROR;
2233 status = RPCRT4_ParseHttpPrepareHeader2(&pkt_from_server, data_from_server,
2234 &field1, flow_control_increment,
2235 &field3);
2236 HeapFree(GetProcessHeap(), 0, data_from_server);
2237 if (status != RPC_S_OK) return status;
2238 TRACE("received (0x%08x 0x%08x %d) from second prepare header\n", field1, *flow_control_increment, field3);
2240 return RPC_S_OK;
2243 static UINT encode_base64(const char *bin, unsigned int len, WCHAR *base64)
2245 static const char enc[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
2246 UINT i = 0, x;
2248 while (len > 0)
2250 /* first 6 bits, all from bin[0] */
2251 base64[i++] = enc[(bin[0] & 0xfc) >> 2];
2252 x = (bin[0] & 3) << 4;
2254 /* next 6 bits, 2 from bin[0] and 4 from bin[1] */
2255 if (len == 1)
2257 base64[i++] = enc[x];
2258 base64[i++] = '=';
2259 base64[i++] = '=';
2260 break;
2262 base64[i++] = enc[x | ((bin[1] & 0xf0) >> 4)];
2263 x = (bin[1] & 0x0f) << 2;
2265 /* next 6 bits 4 from bin[1] and 2 from bin[2] */
2266 if (len == 2)
2268 base64[i++] = enc[x];
2269 base64[i++] = '=';
2270 break;
2272 base64[i++] = enc[x | ((bin[2] & 0xc0) >> 6)];
2274 /* last 6 bits, all from bin [2] */
2275 base64[i++] = enc[bin[2] & 0x3f];
2276 bin += 3;
2277 len -= 3;
2279 base64[i] = 0;
2280 return i;
2283 static inline char decode_char( WCHAR c )
2285 if (c >= 'A' && c <= 'Z') return c - 'A';
2286 if (c >= 'a' && c <= 'z') return c - 'a' + 26;
2287 if (c >= '0' && c <= '9') return c - '0' + 52;
2288 if (c == '+') return 62;
2289 if (c == '/') return 63;
2290 return 64;
2293 static unsigned int decode_base64( const WCHAR *base64, unsigned int len, char *buf )
2295 unsigned int i = 0;
2296 char c0, c1, c2, c3;
2297 const WCHAR *p = base64;
2299 while (len > 4)
2301 if ((c0 = decode_char( p[0] )) > 63) return 0;
2302 if ((c1 = decode_char( p[1] )) > 63) return 0;
2303 if ((c2 = decode_char( p[2] )) > 63) return 0;
2304 if ((c3 = decode_char( p[3] )) > 63) return 0;
2306 if (buf)
2308 buf[i + 0] = (c0 << 2) | (c1 >> 4);
2309 buf[i + 1] = (c1 << 4) | (c2 >> 2);
2310 buf[i + 2] = (c2 << 6) | c3;
2312 len -= 4;
2313 i += 3;
2314 p += 4;
2316 if (p[2] == '=')
2318 if ((c0 = decode_char( p[0] )) > 63) return 0;
2319 if ((c1 = decode_char( p[1] )) > 63) return 0;
2321 if (buf) buf[i] = (c0 << 2) | (c1 >> 4);
2322 i++;
2324 else if (p[3] == '=')
2326 if ((c0 = decode_char( p[0] )) > 63) return 0;
2327 if ((c1 = decode_char( p[1] )) > 63) return 0;
2328 if ((c2 = decode_char( p[2] )) > 63) return 0;
2330 if (buf)
2332 buf[i + 0] = (c0 << 2) | (c1 >> 4);
2333 buf[i + 1] = (c1 << 4) | (c2 >> 2);
2335 i += 2;
2337 else
2339 if ((c0 = decode_char( p[0] )) > 63) return 0;
2340 if ((c1 = decode_char( p[1] )) > 63) return 0;
2341 if ((c2 = decode_char( p[2] )) > 63) return 0;
2342 if ((c3 = decode_char( p[3] )) > 63) return 0;
2344 if (buf)
2346 buf[i + 0] = (c0 << 2) | (c1 >> 4);
2347 buf[i + 1] = (c1 << 4) | (c2 >> 2);
2348 buf[i + 2] = (c2 << 6) | c3;
2350 i += 3;
2352 return i;
2355 static struct authinfo *alloc_authinfo(void)
2357 struct authinfo *ret;
2359 if (!(ret = HeapAlloc(GetProcessHeap(), 0, sizeof(*ret) ))) return NULL;
2361 SecInvalidateHandle(&ret->cred);
2362 SecInvalidateHandle(&ret->ctx);
2363 memset(&ret->exp, 0, sizeof(ret->exp));
2364 ret->scheme = 0;
2365 ret->attr = 0;
2366 ret->max_token = 0;
2367 ret->data = NULL;
2368 ret->data_len = 0;
2369 ret->finished = FALSE;
2370 return ret;
2373 static void destroy_authinfo(struct authinfo *info)
2375 if (!info) return;
2377 if (SecIsValidHandle(&info->ctx))
2378 DeleteSecurityContext(&info->ctx);
2379 if (SecIsValidHandle(&info->cred))
2380 FreeCredentialsHandle(&info->cred);
2382 HeapFree(GetProcessHeap(), 0, info->data);
2383 HeapFree(GetProcessHeap(), 0, info);
2386 static const WCHAR basicW[] = {'B','a','s','i','c',0};
2387 static const WCHAR ntlmW[] = {'N','T','L','M',0};
2388 static const WCHAR passportW[] = {'P','a','s','s','p','o','r','t',0};
2389 static const WCHAR digestW[] = {'D','i','g','e','s','t',0};
2390 static const WCHAR negotiateW[] = {'N','e','g','o','t','i','a','t','e',0};
2392 static const struct
2394 const WCHAR *str;
2395 unsigned int len;
2396 DWORD scheme;
2398 auth_schemes[] =
2400 { basicW, ARRAYSIZE(basicW) - 1, RPC_C_HTTP_AUTHN_SCHEME_BASIC },
2401 { ntlmW, ARRAYSIZE(ntlmW) - 1, RPC_C_HTTP_AUTHN_SCHEME_NTLM },
2402 { passportW, ARRAYSIZE(passportW) - 1, RPC_C_HTTP_AUTHN_SCHEME_PASSPORT },
2403 { digestW, ARRAYSIZE(digestW) - 1, RPC_C_HTTP_AUTHN_SCHEME_DIGEST },
2404 { negotiateW, ARRAYSIZE(negotiateW) - 1, RPC_C_HTTP_AUTHN_SCHEME_NEGOTIATE }
2406 static const unsigned int num_auth_schemes = sizeof(auth_schemes)/sizeof(auth_schemes[0]);
2408 static DWORD auth_scheme_from_header( const WCHAR *header )
2410 unsigned int i;
2411 for (i = 0; i < num_auth_schemes; i++)
2413 if (!strncmpiW( header, auth_schemes[i].str, auth_schemes[i].len ) &&
2414 (header[auth_schemes[i].len] == ' ' || !header[auth_schemes[i].len])) return auth_schemes[i].scheme;
2416 return 0;
2419 static BOOL get_authvalue(HINTERNET request, DWORD scheme, WCHAR *buffer, DWORD buflen)
2421 DWORD len, index = 0;
2422 for (;;)
2424 len = buflen;
2425 if (!HttpQueryInfoW(request, HTTP_QUERY_WWW_AUTHENTICATE, buffer, &len, &index)) return FALSE;
2426 if (auth_scheme_from_header(buffer) == scheme) break;
2428 return TRUE;
2431 static RPC_STATUS do_authorization(HINTERNET request, SEC_WCHAR *servername,
2432 const RPC_HTTP_TRANSPORT_CREDENTIALS_W *creds, struct authinfo **auth_ptr)
2434 struct authinfo *info = *auth_ptr;
2435 SEC_WINNT_AUTH_IDENTITY_W *id = creds->TransportCredentials;
2436 RPC_STATUS status = RPC_S_SERVER_UNAVAILABLE;
2438 if ((!info && !(info = alloc_authinfo()))) return RPC_S_SERVER_UNAVAILABLE;
2440 switch (creds->AuthnSchemes[0])
2442 case RPC_C_HTTP_AUTHN_SCHEME_BASIC:
2444 int userlen = WideCharToMultiByte(CP_UTF8, 0, id->User, id->UserLength, NULL, 0, NULL, NULL);
2445 int passlen = WideCharToMultiByte(CP_UTF8, 0, id->Password, id->PasswordLength, NULL, 0, NULL, NULL);
2447 info->data_len = userlen + passlen + 1;
2448 if (!(info->data = HeapAlloc(GetProcessHeap(), 0, info->data_len)))
2450 status = RPC_S_OUT_OF_MEMORY;
2451 break;
2453 WideCharToMultiByte(CP_UTF8, 0, id->User, id->UserLength, info->data, userlen, NULL, NULL);
2454 info->data[userlen] = ':';
2455 WideCharToMultiByte(CP_UTF8, 0, id->Password, id->PasswordLength, info->data + userlen + 1, passlen, NULL, NULL);
2457 info->scheme = RPC_C_HTTP_AUTHN_SCHEME_BASIC;
2458 info->finished = TRUE;
2459 status = RPC_S_OK;
2460 break;
2462 case RPC_C_HTTP_AUTHN_SCHEME_NTLM:
2463 case RPC_C_HTTP_AUTHN_SCHEME_NEGOTIATE:
2466 static SEC_WCHAR ntlmW[] = {'N','T','L','M',0}, negotiateW[] = {'N','e','g','o','t','i','a','t','e',0};
2467 SECURITY_STATUS ret;
2468 SecBufferDesc out_desc, in_desc;
2469 SecBuffer out, in;
2470 ULONG flags = ISC_REQ_CONNECTION|ISC_REQ_USE_DCE_STYLE|ISC_REQ_MUTUAL_AUTH|ISC_REQ_DELEGATE;
2471 SEC_WCHAR *scheme;
2472 int scheme_len;
2473 const WCHAR *p;
2474 WCHAR auth_value[2048];
2475 DWORD size = sizeof(auth_value);
2476 BOOL first = FALSE;
2478 if (creds->AuthnSchemes[0] == RPC_C_HTTP_AUTHN_SCHEME_NTLM) scheme = ntlmW;
2479 else scheme = negotiateW;
2480 scheme_len = strlenW( scheme );
2482 if (!*auth_ptr)
2484 TimeStamp exp;
2485 SecPkgInfoW *pkg_info;
2487 ret = AcquireCredentialsHandleW(NULL, scheme, SECPKG_CRED_OUTBOUND, NULL, id, NULL, NULL, &info->cred, &exp);
2488 if (ret != SEC_E_OK) break;
2490 ret = QuerySecurityPackageInfoW(scheme, &pkg_info);
2491 if (ret != SEC_E_OK) break;
2493 info->max_token = pkg_info->cbMaxToken;
2494 FreeContextBuffer(pkg_info);
2495 first = TRUE;
2497 else
2499 if (info->finished || !get_authvalue(request, creds->AuthnSchemes[0], auth_value, size)) break;
2500 if (auth_scheme_from_header(auth_value) != info->scheme)
2502 ERR("authentication scheme changed\n");
2503 break;
2506 in.BufferType = SECBUFFER_TOKEN;
2507 in.cbBuffer = 0;
2508 in.pvBuffer = NULL;
2510 in_desc.ulVersion = 0;
2511 in_desc.cBuffers = 1;
2512 in_desc.pBuffers = &in;
2514 p = auth_value + scheme_len;
2515 if (!first && *p == ' ')
2517 int len = strlenW(++p);
2518 in.cbBuffer = decode_base64(p, len, NULL);
2519 if (!(in.pvBuffer = HeapAlloc(GetProcessHeap(), 0, in.cbBuffer))) break;
2520 decode_base64(p, len, in.pvBuffer);
2522 out.BufferType = SECBUFFER_TOKEN;
2523 out.cbBuffer = info->max_token;
2524 if (!(out.pvBuffer = HeapAlloc(GetProcessHeap(), 0, out.cbBuffer)))
2526 HeapFree(GetProcessHeap(), 0, in.pvBuffer);
2527 break;
2529 out_desc.ulVersion = 0;
2530 out_desc.cBuffers = 1;
2531 out_desc.pBuffers = &out;
2533 ret = InitializeSecurityContextW(first ? &info->cred : NULL, first ? NULL : &info->ctx,
2534 first ? servername : NULL, flags, 0, SECURITY_NETWORK_DREP,
2535 in.pvBuffer ? &in_desc : NULL, 0, &info->ctx, &out_desc,
2536 &info->attr, &info->exp);
2537 HeapFree(GetProcessHeap(), 0, in.pvBuffer);
2538 if (ret == SEC_E_OK)
2540 HeapFree(GetProcessHeap(), 0, info->data);
2541 info->data = out.pvBuffer;
2542 info->data_len = out.cbBuffer;
2543 info->finished = TRUE;
2544 TRACE("sending last auth packet\n");
2545 status = RPC_S_OK;
2547 else if (ret == SEC_I_CONTINUE_NEEDED)
2549 HeapFree(GetProcessHeap(), 0, info->data);
2550 info->data = out.pvBuffer;
2551 info->data_len = out.cbBuffer;
2552 TRACE("sending next auth packet\n");
2553 status = RPC_S_OK;
2555 else
2557 ERR("InitializeSecurityContextW failed with error 0x%08x\n", ret);
2558 HeapFree(GetProcessHeap(), 0, out.pvBuffer);
2559 break;
2561 info->scheme = creds->AuthnSchemes[0];
2562 break;
2564 default:
2565 FIXME("scheme %u not supported\n", creds->AuthnSchemes[0]);
2566 break;
2569 if (status != RPC_S_OK)
2571 destroy_authinfo(info);
2572 *auth_ptr = NULL;
2573 return status;
2575 *auth_ptr = info;
2576 return RPC_S_OK;
2579 static RPC_STATUS insert_authorization_header(HINTERNET request, ULONG scheme, char *data, int data_len)
2581 static const WCHAR authW[] = {'A','u','t','h','o','r','i','z','a','t','i','o','n',':',' '};
2582 static const WCHAR basicW[] = {'B','a','s','i','c',' '};
2583 static const WCHAR negotiateW[] = {'N','e','g','o','t','i','a','t','e',' '};
2584 static const WCHAR ntlmW[] = {'N','T','L','M',' '};
2585 int scheme_len, auth_len = sizeof(authW) / sizeof(authW[0]), len = ((data_len + 2) * 4) / 3;
2586 const WCHAR *scheme_str;
2587 WCHAR *header, *ptr;
2588 RPC_STATUS status = RPC_S_SERVER_UNAVAILABLE;
2590 switch (scheme)
2592 case RPC_C_HTTP_AUTHN_SCHEME_BASIC:
2593 scheme_str = basicW;
2594 scheme_len = sizeof(basicW) / sizeof(basicW[0]);
2595 break;
2596 case RPC_C_HTTP_AUTHN_SCHEME_NEGOTIATE:
2597 scheme_str = negotiateW;
2598 scheme_len = sizeof(negotiateW) / sizeof(negotiateW[0]);
2599 break;
2600 case RPC_C_HTTP_AUTHN_SCHEME_NTLM:
2601 scheme_str = ntlmW;
2602 scheme_len = sizeof(ntlmW) / sizeof(ntlmW[0]);
2603 break;
2604 default:
2605 ERR("unknown scheme %u\n", scheme);
2606 return RPC_S_SERVER_UNAVAILABLE;
2608 if ((header = HeapAlloc(GetProcessHeap(), 0, (auth_len + scheme_len + len + 2) * sizeof(WCHAR))))
2610 memcpy(header, authW, auth_len * sizeof(WCHAR));
2611 ptr = header + auth_len;
2612 memcpy(ptr, scheme_str, scheme_len * sizeof(WCHAR));
2613 ptr += scheme_len;
2614 len = encode_base64(data, data_len, ptr);
2615 ptr[len++] = '\r';
2616 ptr[len++] = '\n';
2617 ptr[len] = 0;
2618 if (HttpAddRequestHeadersW(request, header, -1, HTTP_ADDREQ_FLAG_ADD|HTTP_ADDREQ_FLAG_REPLACE))
2619 status = RPC_S_OK;
2620 HeapFree(GetProcessHeap(), 0, header);
2622 return status;
2625 static void drain_content(HINTERNET request, RpcHttpAsyncData *async_data, HANDLE cancel_event)
2627 DWORD count, len = 0, size = sizeof(len);
2628 char buf[2048];
2630 HttpQueryInfoW(request, HTTP_QUERY_FLAG_NUMBER|HTTP_QUERY_CONTENT_LENGTH, &len, &size, NULL);
2631 if (!len) return;
2632 for (;;)
2634 count = min(sizeof(buf), len);
2635 if (rpcrt4_http_async_read(request, async_data, cancel_event, buf, count) <= 0) return;
2636 len -= count;
2640 static RPC_STATUS authorize_request(RpcConnection_http *httpc, HINTERNET request)
2642 static const WCHAR authW[] = {'A','u','t','h','o','r','i','z','a','t','i','o','n',':','\r','\n',0};
2643 struct authinfo *info = NULL;
2644 RPC_STATUS status;
2645 BOOL ret;
2647 for (;;)
2649 status = do_authorization(request, httpc->servername, httpc->common.QOS->qos->u.HttpCredentials, &info);
2650 if (status != RPC_S_OK) break;
2652 status = insert_authorization_header(request, info->scheme, info->data, info->data_len);
2653 if (status != RPC_S_OK) break;
2655 prepare_async_request(httpc->async_data);
2656 ret = HttpSendRequestW(request, NULL, 0, NULL, 0);
2657 status = wait_async_request(httpc->async_data, ret, httpc->cancel_event);
2658 if (status != RPC_S_OK || info->finished) break;
2660 status = rpcrt4_http_check_response(request);
2661 if (status != RPC_S_OK && status != ERROR_ACCESS_DENIED) break;
2662 drain_content(request, httpc->async_data, httpc->cancel_event);
2665 if (info->scheme != RPC_C_HTTP_AUTHN_SCHEME_BASIC)
2666 HttpAddRequestHeadersW(request, authW, -1, HTTP_ADDREQ_FLAG_REPLACE | HTTP_ADDREQ_FLAG_ADD);
2668 destroy_authinfo(info);
2669 return status;
2672 static BOOL has_credentials(RpcConnection_http *httpc)
2674 RPC_HTTP_TRANSPORT_CREDENTIALS_W *creds;
2675 SEC_WINNT_AUTH_IDENTITY_W *id;
2677 if (!httpc->common.QOS || httpc->common.QOS->qos->AdditionalSecurityInfoType != RPC_C_AUTHN_INFO_TYPE_HTTP)
2678 return FALSE;
2680 creds = httpc->common.QOS->qos->u.HttpCredentials;
2681 if (creds->AuthenticationTarget != RPC_C_HTTP_AUTHN_TARGET_SERVER || !creds->NumberOfAuthnSchemes)
2682 return FALSE;
2684 id = creds->TransportCredentials;
2685 if (!id || !id->User || !id->Password) return FALSE;
2687 return TRUE;
2690 static BOOL is_secure(RpcConnection_http *httpc)
2692 return httpc->common.QOS &&
2693 (httpc->common.QOS->qos->AdditionalSecurityInfoType == RPC_C_AUTHN_INFO_TYPE_HTTP) &&
2694 (httpc->common.QOS->qos->u.HttpCredentials->Flags & RPC_C_HTTP_FLAG_USE_SSL);
2697 static RPC_STATUS set_auth_cookie(RpcConnection_http *httpc, const WCHAR *value)
2699 static WCHAR httpW[] = {'h','t','t','p',0};
2700 static WCHAR httpsW[] = {'h','t','t','p','s',0};
2701 URL_COMPONENTSW uc;
2702 DWORD len;
2703 WCHAR *url;
2704 BOOL ret;
2706 if (!value) return RPC_S_OK;
2708 uc.dwStructSize = sizeof(uc);
2709 uc.lpszScheme = is_secure(httpc) ? httpsW : httpW;
2710 uc.dwSchemeLength = 0;
2711 uc.lpszHostName = httpc->servername;
2712 uc.dwHostNameLength = 0;
2713 uc.nPort = 0;
2714 uc.lpszUserName = NULL;
2715 uc.dwUserNameLength = 0;
2716 uc.lpszPassword = NULL;
2717 uc.dwPasswordLength = 0;
2718 uc.lpszUrlPath = NULL;
2719 uc.dwUrlPathLength = 0;
2720 uc.lpszExtraInfo = NULL;
2721 uc.dwExtraInfoLength = 0;
2723 if (!InternetCreateUrlW(&uc, 0, NULL, &len) && (GetLastError() != ERROR_INSUFFICIENT_BUFFER))
2724 return RPC_S_SERVER_UNAVAILABLE;
2726 if (!(url = HeapAlloc(GetProcessHeap(), 0, len))) return RPC_S_OUT_OF_MEMORY;
2728 len = len / sizeof(WCHAR) - 1;
2729 if (!InternetCreateUrlW(&uc, 0, url, &len))
2731 HeapFree(GetProcessHeap(), 0, url);
2732 return RPC_S_SERVER_UNAVAILABLE;
2735 ret = InternetSetCookieW(url, NULL, value);
2736 HeapFree(GetProcessHeap(), 0, url);
2737 if (!ret) return RPC_S_SERVER_UNAVAILABLE;
2739 return RPC_S_OK;
2742 static RPC_STATUS rpcrt4_ncacn_http_open(RpcConnection* Connection)
2744 RpcConnection_http *httpc = (RpcConnection_http *)Connection;
2745 static const WCHAR wszVerbIn[] = {'R','P','C','_','I','N','_','D','A','T','A',0};
2746 static const WCHAR wszVerbOut[] = {'R','P','C','_','O','U','T','_','D','A','T','A',0};
2747 static const WCHAR wszRpcProxyPrefix[] = {'/','r','p','c','/','r','p','c','p','r','o','x','y','.','d','l','l','?',0};
2748 static const WCHAR wszColon[] = {':',0};
2749 static const WCHAR wszAcceptType[] = {'a','p','p','l','i','c','a','t','i','o','n','/','r','p','c',0};
2750 LPCWSTR wszAcceptTypes[] = { wszAcceptType, NULL };
2751 DWORD flags;
2752 WCHAR *url;
2753 RPC_STATUS status;
2754 BOOL secure, credentials;
2755 HttpTimerThreadData *timer_data;
2756 HANDLE thread;
2758 TRACE("(%s, %s)\n", Connection->NetworkAddr, Connection->Endpoint);
2760 if (Connection->server)
2762 ERR("ncacn_http servers not supported yet\n");
2763 return RPC_S_SERVER_UNAVAILABLE;
2766 if (httpc->in_request)
2767 return RPC_S_OK;
2769 httpc->async_data->completion_event = CreateEventW(NULL, FALSE, FALSE, NULL);
2771 UuidCreate(&httpc->connection_uuid);
2772 UuidCreate(&httpc->in_pipe_uuid);
2773 UuidCreate(&httpc->out_pipe_uuid);
2775 status = rpcrt4_http_internet_connect(httpc);
2776 if (status != RPC_S_OK)
2777 return status;
2779 url = HeapAlloc(GetProcessHeap(), 0, sizeof(wszRpcProxyPrefix) + (strlen(Connection->NetworkAddr) + 1 + strlen(Connection->Endpoint))*sizeof(WCHAR));
2780 if (!url)
2781 return RPC_S_OUT_OF_MEMORY;
2782 memcpy(url, wszRpcProxyPrefix, sizeof(wszRpcProxyPrefix));
2783 MultiByteToWideChar(CP_ACP, 0, Connection->NetworkAddr, -1, url+sizeof(wszRpcProxyPrefix)/sizeof(wszRpcProxyPrefix[0])-1, strlen(Connection->NetworkAddr)+1);
2784 strcatW(url, wszColon);
2785 MultiByteToWideChar(CP_ACP, 0, Connection->Endpoint, -1, url+strlenW(url), strlen(Connection->Endpoint)+1);
2787 secure = is_secure(httpc);
2788 credentials = has_credentials(httpc);
2790 flags = INTERNET_FLAG_KEEP_CONNECTION | INTERNET_FLAG_PRAGMA_NOCACHE | INTERNET_FLAG_NO_CACHE_WRITE |
2791 INTERNET_FLAG_NO_AUTO_REDIRECT;
2792 if (secure) flags |= INTERNET_FLAG_SECURE;
2793 if (credentials) flags |= INTERNET_FLAG_NO_AUTH;
2795 status = set_auth_cookie(httpc, Connection->CookieAuth);
2796 if (status != RPC_S_OK)
2798 HeapFree(GetProcessHeap(), 0, url);
2799 return status;
2801 httpc->in_request = HttpOpenRequestW(httpc->session, wszVerbIn, url, NULL, NULL, wszAcceptTypes,
2802 flags, (DWORD_PTR)httpc->async_data);
2803 if (!httpc->in_request)
2805 ERR("HttpOpenRequestW failed with error %d\n", GetLastError());
2806 HeapFree(GetProcessHeap(), 0, url);
2807 return RPC_S_SERVER_UNAVAILABLE;
2810 if (credentials)
2812 status = authorize_request(httpc, httpc->in_request);
2813 if (status != RPC_S_OK)
2815 HeapFree(GetProcessHeap(), 0, url);
2816 return status;
2818 status = rpcrt4_http_check_response(httpc->in_request);
2819 if (status != RPC_S_OK)
2821 HeapFree(GetProcessHeap(), 0, url);
2822 return status;
2824 drain_content(httpc->in_request, httpc->async_data, httpc->cancel_event);
2827 httpc->out_request = HttpOpenRequestW(httpc->session, wszVerbOut, url, NULL, NULL, wszAcceptTypes,
2828 flags, (DWORD_PTR)httpc->async_data);
2829 HeapFree(GetProcessHeap(), 0, url);
2830 if (!httpc->out_request)
2832 ERR("HttpOpenRequestW failed with error %d\n", GetLastError());
2833 return RPC_S_SERVER_UNAVAILABLE;
2836 if (credentials)
2838 status = authorize_request(httpc, httpc->out_request);
2839 if (status != RPC_S_OK)
2840 return status;
2843 status = rpcrt4_http_prepare_in_pipe(httpc->in_request, httpc->async_data, httpc->cancel_event,
2844 &httpc->connection_uuid, &httpc->in_pipe_uuid,
2845 &Connection->assoc->http_uuid, credentials);
2846 if (status != RPC_S_OK)
2847 return status;
2849 status = rpcrt4_http_prepare_out_pipe(httpc->out_request, httpc->async_data, httpc->cancel_event,
2850 &httpc->connection_uuid, &httpc->out_pipe_uuid,
2851 &httpc->flow_control_increment, credentials);
2852 if (status != RPC_S_OK)
2853 return status;
2855 httpc->flow_control_mark = httpc->flow_control_increment / 2;
2856 httpc->last_sent_time = GetTickCount();
2857 httpc->timer_cancelled = CreateEventW(NULL, FALSE, FALSE, NULL);
2859 timer_data = HeapAlloc(GetProcessHeap(), 0, sizeof(*timer_data));
2860 if (!timer_data)
2861 return ERROR_OUTOFMEMORY;
2862 timer_data->timer_param = httpc->in_request;
2863 timer_data->last_sent_time = &httpc->last_sent_time;
2864 timer_data->timer_cancelled = httpc->timer_cancelled;
2865 /* FIXME: should use CreateTimerQueueTimer when implemented */
2866 thread = CreateThread(NULL, 0, rpcrt4_http_timer_thread, timer_data, 0, NULL);
2867 if (!thread)
2869 HeapFree(GetProcessHeap(), 0, timer_data);
2870 return GetLastError();
2872 CloseHandle(thread);
2874 return RPC_S_OK;
2877 static RPC_STATUS rpcrt4_ncacn_http_handoff(RpcConnection *old_conn, RpcConnection *new_conn)
2879 assert(0);
2880 return RPC_S_SERVER_UNAVAILABLE;
2883 static int rpcrt4_ncacn_http_read(RpcConnection *Connection,
2884 void *buffer, unsigned int count)
2886 RpcConnection_http *httpc = (RpcConnection_http *) Connection;
2887 return rpcrt4_http_async_read(httpc->out_request, httpc->async_data, httpc->cancel_event, buffer, count);
2890 static RPC_STATUS rpcrt4_ncacn_http_receive_fragment(RpcConnection *Connection, RpcPktHdr **Header, void **Payload)
2892 RpcConnection_http *httpc = (RpcConnection_http *) Connection;
2893 RPC_STATUS status;
2894 DWORD hdr_length;
2895 LONG dwRead;
2896 RpcPktCommonHdr common_hdr;
2898 *Header = NULL;
2900 TRACE("(%p, %p, %p)\n", Connection, Header, Payload);
2902 again:
2903 /* read packet common header */
2904 dwRead = rpcrt4_ncacn_http_read(Connection, &common_hdr, sizeof(common_hdr));
2905 if (dwRead != sizeof(common_hdr)) {
2906 WARN("Short read of header, %d bytes\n", dwRead);
2907 status = RPC_S_PROTOCOL_ERROR;
2908 goto fail;
2910 if (!memcmp(&common_hdr, "HTTP/1.1", sizeof("HTTP/1.1")) ||
2911 !memcmp(&common_hdr, "HTTP/1.0", sizeof("HTTP/1.0")))
2913 FIXME("server returned %s\n", debugstr_a((const char *)&common_hdr));
2914 status = RPC_S_PROTOCOL_ERROR;
2915 goto fail;
2918 status = RPCRT4_ValidateCommonHeader(&common_hdr);
2919 if (status != RPC_S_OK) goto fail;
2921 hdr_length = RPCRT4_GetHeaderSize((RpcPktHdr*)&common_hdr);
2922 if (hdr_length == 0) {
2923 WARN("header length == 0\n");
2924 status = RPC_S_PROTOCOL_ERROR;
2925 goto fail;
2928 *Header = HeapAlloc(GetProcessHeap(), 0, hdr_length);
2929 if (!*Header)
2931 status = RPC_S_OUT_OF_RESOURCES;
2932 goto fail;
2934 memcpy(*Header, &common_hdr, sizeof(common_hdr));
2936 /* read the rest of packet header */
2937 dwRead = rpcrt4_ncacn_http_read(Connection, &(*Header)->common + 1, hdr_length - sizeof(common_hdr));
2938 if (dwRead != hdr_length - sizeof(common_hdr)) {
2939 WARN("bad header length, %d bytes, hdr_length %d\n", dwRead, hdr_length);
2940 status = RPC_S_PROTOCOL_ERROR;
2941 goto fail;
2944 if (common_hdr.frag_len - hdr_length)
2946 *Payload = HeapAlloc(GetProcessHeap(), 0, common_hdr.frag_len - hdr_length);
2947 if (!*Payload)
2949 status = RPC_S_OUT_OF_RESOURCES;
2950 goto fail;
2953 dwRead = rpcrt4_ncacn_http_read(Connection, *Payload, common_hdr.frag_len - hdr_length);
2954 if (dwRead != common_hdr.frag_len - hdr_length)
2956 WARN("bad data length, %d/%d\n", dwRead, common_hdr.frag_len - hdr_length);
2957 status = RPC_S_PROTOCOL_ERROR;
2958 goto fail;
2961 else
2962 *Payload = NULL;
2964 if ((*Header)->common.ptype == PKT_HTTP)
2966 if (!RPCRT4_IsValidHttpPacket(*Header, *Payload, common_hdr.frag_len - hdr_length))
2968 ERR("invalid http packet of length %d bytes\n", (*Header)->common.frag_len);
2969 status = RPC_S_PROTOCOL_ERROR;
2970 goto fail;
2972 if ((*Header)->http.flags == 0x0001)
2974 TRACE("http idle packet, waiting for real packet\n");
2975 if ((*Header)->http.num_data_items != 0)
2977 ERR("HTTP idle packet should have no data items instead of %d\n", (*Header)->http.num_data_items);
2978 status = RPC_S_PROTOCOL_ERROR;
2979 goto fail;
2982 else if ((*Header)->http.flags == 0x0002)
2984 ULONG bytes_transmitted;
2985 ULONG flow_control_increment;
2986 UUID pipe_uuid;
2987 status = RPCRT4_ParseHttpFlowControlHeader(*Header, *Payload,
2988 Connection->server,
2989 &bytes_transmitted,
2990 &flow_control_increment,
2991 &pipe_uuid);
2992 if (status != RPC_S_OK)
2993 goto fail;
2994 TRACE("received http flow control header (0x%x, 0x%x, %s)\n",
2995 bytes_transmitted, flow_control_increment, debugstr_guid(&pipe_uuid));
2996 /* FIXME: do something with parsed data */
2998 else
3000 FIXME("unrecognised http packet with flags 0x%04x\n", (*Header)->http.flags);
3001 status = RPC_S_PROTOCOL_ERROR;
3002 goto fail;
3004 RPCRT4_FreeHeader(*Header);
3005 *Header = NULL;
3006 HeapFree(GetProcessHeap(), 0, *Payload);
3007 *Payload = NULL;
3008 goto again;
3011 /* success */
3012 status = RPC_S_OK;
3014 httpc->bytes_received += common_hdr.frag_len;
3016 TRACE("httpc->bytes_received = 0x%x\n", httpc->bytes_received);
3018 if (httpc->bytes_received > httpc->flow_control_mark)
3020 RpcPktHdr *hdr = RPCRT4_BuildHttpFlowControlHeader(httpc->common.server,
3021 httpc->bytes_received,
3022 httpc->flow_control_increment,
3023 &httpc->out_pipe_uuid);
3024 if (hdr)
3026 DWORD bytes_written;
3027 BOOL ret2;
3028 TRACE("sending flow control packet at 0x%x\n", httpc->bytes_received);
3029 ret2 = InternetWriteFile(httpc->in_request, hdr, hdr->common.frag_len, &bytes_written);
3030 RPCRT4_FreeHeader(hdr);
3031 if (ret2)
3032 httpc->flow_control_mark = httpc->bytes_received + httpc->flow_control_increment / 2;
3036 fail:
3037 if (status != RPC_S_OK) {
3038 RPCRT4_FreeHeader(*Header);
3039 *Header = NULL;
3040 HeapFree(GetProcessHeap(), 0, *Payload);
3041 *Payload = NULL;
3043 return status;
3046 static int rpcrt4_ncacn_http_write(RpcConnection *Connection,
3047 const void *buffer, unsigned int count)
3049 RpcConnection_http *httpc = (RpcConnection_http *) Connection;
3050 DWORD bytes_written;
3051 BOOL ret;
3053 httpc->last_sent_time = ~0U; /* disable idle packet sending */
3054 ret = InternetWriteFile(httpc->in_request, buffer, count, &bytes_written);
3055 httpc->last_sent_time = GetTickCount();
3056 TRACE("%p %p %u -> %s\n", httpc->in_request, buffer, count, ret ? "TRUE" : "FALSE");
3057 return ret ? bytes_written : -1;
3060 static int rpcrt4_ncacn_http_close(RpcConnection *Connection)
3062 RpcConnection_http *httpc = (RpcConnection_http *) Connection;
3064 TRACE("\n");
3066 SetEvent(httpc->timer_cancelled);
3067 if (httpc->in_request)
3068 InternetCloseHandle(httpc->in_request);
3069 httpc->in_request = NULL;
3070 if (httpc->out_request)
3071 InternetCloseHandle(httpc->out_request);
3072 httpc->out_request = NULL;
3073 if (httpc->app_info)
3074 InternetCloseHandle(httpc->app_info);
3075 httpc->app_info = NULL;
3076 if (httpc->session)
3077 InternetCloseHandle(httpc->session);
3078 httpc->session = NULL;
3079 RpcHttpAsyncData_Release(httpc->async_data);
3080 if (httpc->cancel_event)
3081 CloseHandle(httpc->cancel_event);
3082 HeapFree(GetProcessHeap(), 0, httpc->servername);
3083 httpc->servername = NULL;
3085 return 0;
3088 static void rpcrt4_ncacn_http_close_read(RpcConnection *conn)
3090 rpcrt4_ncacn_http_close(conn); /* FIXME */
3093 static void rpcrt4_ncacn_http_cancel_call(RpcConnection *Connection)
3095 RpcConnection_http *httpc = (RpcConnection_http *) Connection;
3097 SetEvent(httpc->cancel_event);
3100 static RPC_STATUS rpcrt4_ncacn_http_is_server_listening(const char *endpoint)
3102 FIXME("\n");
3103 return RPC_S_ACCESS_DENIED;
3106 static int rpcrt4_ncacn_http_wait_for_incoming_data(RpcConnection *Connection)
3108 RpcConnection_http *httpc = (RpcConnection_http *) Connection;
3109 BOOL ret;
3110 RPC_STATUS status;
3112 prepare_async_request(httpc->async_data);
3113 ret = InternetQueryDataAvailable(httpc->out_request,
3114 &httpc->async_data->inet_buffers.dwBufferLength, IRF_ASYNC, 0);
3115 status = wait_async_request(httpc->async_data, ret, httpc->cancel_event);
3116 return status == RPC_S_OK ? 0 : -1;
3119 static size_t rpcrt4_ncacn_http_get_top_of_tower(unsigned char *tower_data,
3120 const char *networkaddr,
3121 const char *endpoint)
3123 return rpcrt4_ip_tcp_get_top_of_tower(tower_data, networkaddr,
3124 EPM_PROTOCOL_HTTP, endpoint);
3127 static RPC_STATUS rpcrt4_ncacn_http_parse_top_of_tower(const unsigned char *tower_data,
3128 size_t tower_size,
3129 char **networkaddr,
3130 char **endpoint)
3132 return rpcrt4_ip_tcp_parse_top_of_tower(tower_data, tower_size,
3133 networkaddr, EPM_PROTOCOL_HTTP,
3134 endpoint);
3137 static const struct connection_ops conn_protseq_list[] = {
3138 { "ncacn_np",
3139 { EPM_PROTOCOL_NCACN, EPM_PROTOCOL_SMB },
3140 rpcrt4_conn_np_alloc,
3141 rpcrt4_ncacn_np_open,
3142 rpcrt4_ncacn_np_handoff,
3143 rpcrt4_conn_np_read,
3144 rpcrt4_conn_np_write,
3145 rpcrt4_conn_np_close,
3146 rpcrt4_conn_np_close_read,
3147 rpcrt4_conn_np_cancel_call,
3148 rpcrt4_ncacn_np_is_server_listening,
3149 rpcrt4_conn_np_wait_for_incoming_data,
3150 rpcrt4_ncacn_np_get_top_of_tower,
3151 rpcrt4_ncacn_np_parse_top_of_tower,
3152 NULL,
3153 RPCRT4_default_is_authorized,
3154 RPCRT4_default_authorize,
3155 RPCRT4_default_secure_packet,
3156 rpcrt4_conn_np_impersonate_client,
3157 rpcrt4_conn_np_revert_to_self,
3158 RPCRT4_default_inquire_auth_client,
3160 { "ncalrpc",
3161 { EPM_PROTOCOL_NCALRPC, EPM_PROTOCOL_PIPE },
3162 rpcrt4_conn_np_alloc,
3163 rpcrt4_ncalrpc_open,
3164 rpcrt4_ncalrpc_handoff,
3165 rpcrt4_conn_np_read,
3166 rpcrt4_conn_np_write,
3167 rpcrt4_conn_np_close,
3168 rpcrt4_conn_np_close_read,
3169 rpcrt4_conn_np_cancel_call,
3170 rpcrt4_ncalrpc_np_is_server_listening,
3171 rpcrt4_conn_np_wait_for_incoming_data,
3172 rpcrt4_ncalrpc_get_top_of_tower,
3173 rpcrt4_ncalrpc_parse_top_of_tower,
3174 NULL,
3175 rpcrt4_ncalrpc_is_authorized,
3176 rpcrt4_ncalrpc_authorize,
3177 rpcrt4_ncalrpc_secure_packet,
3178 rpcrt4_conn_np_impersonate_client,
3179 rpcrt4_conn_np_revert_to_self,
3180 rpcrt4_ncalrpc_inquire_auth_client,
3182 { "ncacn_ip_tcp",
3183 { EPM_PROTOCOL_NCACN, EPM_PROTOCOL_TCP },
3184 rpcrt4_conn_tcp_alloc,
3185 rpcrt4_ncacn_ip_tcp_open,
3186 rpcrt4_conn_tcp_handoff,
3187 rpcrt4_conn_tcp_read,
3188 rpcrt4_conn_tcp_write,
3189 rpcrt4_conn_tcp_close,
3190 rpcrt4_conn_tcp_close_read,
3191 rpcrt4_conn_tcp_cancel_call,
3192 rpcrt4_conn_tcp_is_server_listening,
3193 rpcrt4_conn_tcp_wait_for_incoming_data,
3194 rpcrt4_ncacn_ip_tcp_get_top_of_tower,
3195 rpcrt4_ncacn_ip_tcp_parse_top_of_tower,
3196 NULL,
3197 RPCRT4_default_is_authorized,
3198 RPCRT4_default_authorize,
3199 RPCRT4_default_secure_packet,
3200 RPCRT4_default_impersonate_client,
3201 RPCRT4_default_revert_to_self,
3202 RPCRT4_default_inquire_auth_client,
3204 { "ncacn_http",
3205 { EPM_PROTOCOL_NCACN, EPM_PROTOCOL_HTTP },
3206 rpcrt4_ncacn_http_alloc,
3207 rpcrt4_ncacn_http_open,
3208 rpcrt4_ncacn_http_handoff,
3209 rpcrt4_ncacn_http_read,
3210 rpcrt4_ncacn_http_write,
3211 rpcrt4_ncacn_http_close,
3212 rpcrt4_ncacn_http_close_read,
3213 rpcrt4_ncacn_http_cancel_call,
3214 rpcrt4_ncacn_http_is_server_listening,
3215 rpcrt4_ncacn_http_wait_for_incoming_data,
3216 rpcrt4_ncacn_http_get_top_of_tower,
3217 rpcrt4_ncacn_http_parse_top_of_tower,
3218 rpcrt4_ncacn_http_receive_fragment,
3219 RPCRT4_default_is_authorized,
3220 RPCRT4_default_authorize,
3221 RPCRT4_default_secure_packet,
3222 RPCRT4_default_impersonate_client,
3223 RPCRT4_default_revert_to_self,
3224 RPCRT4_default_inquire_auth_client,
3229 static const struct protseq_ops protseq_list[] =
3232 "ncacn_np",
3233 rpcrt4_protseq_np_alloc,
3234 rpcrt4_protseq_np_signal_state_changed,
3235 rpcrt4_protseq_np_get_wait_array,
3236 rpcrt4_protseq_np_free_wait_array,
3237 rpcrt4_protseq_np_wait_for_new_connection,
3238 rpcrt4_protseq_ncacn_np_open_endpoint,
3241 "ncalrpc",
3242 rpcrt4_protseq_np_alloc,
3243 rpcrt4_protseq_np_signal_state_changed,
3244 rpcrt4_protseq_np_get_wait_array,
3245 rpcrt4_protseq_np_free_wait_array,
3246 rpcrt4_protseq_np_wait_for_new_connection,
3247 rpcrt4_protseq_ncalrpc_open_endpoint,
3250 "ncacn_ip_tcp",
3251 rpcrt4_protseq_sock_alloc,
3252 rpcrt4_protseq_sock_signal_state_changed,
3253 rpcrt4_protseq_sock_get_wait_array,
3254 rpcrt4_protseq_sock_free_wait_array,
3255 rpcrt4_protseq_sock_wait_for_new_connection,
3256 rpcrt4_protseq_ncacn_ip_tcp_open_endpoint,
3260 const struct protseq_ops *rpcrt4_get_protseq_ops(const char *protseq)
3262 unsigned int i;
3263 for(i=0; i<ARRAYSIZE(protseq_list); i++)
3264 if (!strcmp(protseq_list[i].name, protseq))
3265 return &protseq_list[i];
3266 return NULL;
3269 static const struct connection_ops *rpcrt4_get_conn_protseq_ops(const char *protseq)
3271 unsigned int i;
3272 for(i=0; i<ARRAYSIZE(conn_protseq_list); i++)
3273 if (!strcmp(conn_protseq_list[i].name, protseq))
3274 return &conn_protseq_list[i];
3275 return NULL;
3278 /**** interface to rest of code ****/
3280 RPC_STATUS RPCRT4_OpenClientConnection(RpcConnection* Connection)
3282 TRACE("(Connection == ^%p)\n", Connection);
3284 assert(!Connection->server);
3285 return Connection->ops->open_connection_client(Connection);
3288 RPC_STATUS RPCRT4_CloseConnection(RpcConnection* Connection)
3290 TRACE("(Connection == ^%p)\n", Connection);
3291 if (SecIsValidHandle(&Connection->ctx))
3293 DeleteSecurityContext(&Connection->ctx);
3294 SecInvalidateHandle(&Connection->ctx);
3296 rpcrt4_conn_close(Connection);
3297 return RPC_S_OK;
3300 RPC_STATUS RPCRT4_CreateConnection(RpcConnection** Connection, BOOL server,
3301 LPCSTR Protseq, LPCSTR NetworkAddr, LPCSTR Endpoint,
3302 LPCWSTR NetworkOptions, RpcAuthInfo* AuthInfo, RpcQualityOfService *QOS, LPCWSTR CookieAuth)
3304 static LONG next_id;
3305 const struct connection_ops *ops;
3306 RpcConnection* NewConnection;
3308 ops = rpcrt4_get_conn_protseq_ops(Protseq);
3309 if (!ops)
3311 FIXME("not supported for protseq %s\n", Protseq);
3312 return RPC_S_PROTSEQ_NOT_SUPPORTED;
3315 NewConnection = ops->alloc();
3316 NewConnection->ref = 1;
3317 NewConnection->server = server;
3318 NewConnection->ops = ops;
3319 NewConnection->NetworkAddr = RPCRT4_strdupA(NetworkAddr);
3320 NewConnection->Endpoint = RPCRT4_strdupA(Endpoint);
3321 NewConnection->NetworkOptions = RPCRT4_strdupW(NetworkOptions);
3322 NewConnection->CookieAuth = RPCRT4_strdupW(CookieAuth);
3323 NewConnection->MaxTransmissionSize = RPC_MAX_PACKET_SIZE;
3324 NewConnection->NextCallId = 1;
3326 SecInvalidateHandle(&NewConnection->ctx);
3327 if (AuthInfo) RpcAuthInfo_AddRef(AuthInfo);
3328 NewConnection->AuthInfo = AuthInfo;
3329 NewConnection->auth_context_id = InterlockedIncrement( &next_id );
3330 if (QOS) RpcQualityOfService_AddRef(QOS);
3331 NewConnection->QOS = QOS;
3333 list_init(&NewConnection->conn_pool_entry);
3334 list_init(&NewConnection->protseq_entry);
3336 TRACE("connection: %p\n", NewConnection);
3337 *Connection = NewConnection;
3339 return RPC_S_OK;
3342 static RpcConnection *rpcrt4_spawn_connection(RpcConnection *old_connection)
3344 RpcConnection *connection;
3345 RPC_STATUS err;
3347 err = RPCRT4_CreateConnection(&connection, old_connection->server, rpcrt4_conn_get_name(old_connection),
3348 old_connection->NetworkAddr, old_connection->Endpoint, NULL,
3349 old_connection->AuthInfo, old_connection->QOS, old_connection->CookieAuth);
3350 if (err != RPC_S_OK)
3351 return NULL;
3353 rpcrt4_conn_handoff(old_connection, connection);
3354 if (old_connection->protseq)
3356 EnterCriticalSection(&old_connection->protseq->cs);
3357 connection->protseq = old_connection->protseq;
3358 list_add_tail(&old_connection->protseq->connections, &connection->protseq_entry);
3359 LeaveCriticalSection(&old_connection->protseq->cs);
3361 return connection;
3364 void rpcrt4_conn_release_and_wait(RpcConnection *connection)
3366 HANDLE event = NULL;
3368 if (connection->ref > 1)
3369 event = connection->wait_release = CreateEventW(NULL, TRUE, FALSE, NULL);
3371 RPCRT4_ReleaseConnection(connection);
3373 if(event)
3375 WaitForSingleObject(event, INFINITE);
3376 CloseHandle(event);
3380 RpcConnection *RPCRT4_GrabConnection(RpcConnection *connection)
3382 LONG ref = InterlockedIncrement(&connection->ref);
3383 TRACE("%p ref=%u\n", connection, ref);
3384 return connection;
3387 void RPCRT4_ReleaseConnection(RpcConnection *connection)
3389 LONG ref;
3391 /* protseq stores a list of active connections, but does not own references to them.
3392 * It may need to grab a connection from the list, which could lead to a race if
3393 * connection is being released, but not yet removed from the list. We handle that
3394 * by synchronizing on CS here. */
3395 if (connection->protseq)
3397 EnterCriticalSection(&connection->protseq->cs);
3398 ref = InterlockedDecrement(&connection->ref);
3399 if (!ref)
3400 list_remove(&connection->protseq_entry);
3401 LeaveCriticalSection(&connection->protseq->cs);
3403 else
3405 ref = InterlockedDecrement(&connection->ref);
3408 TRACE("%p ref=%u\n", connection, ref);
3410 if (!ref)
3412 RPCRT4_CloseConnection(connection);
3413 RPCRT4_strfree(connection->Endpoint);
3414 RPCRT4_strfree(connection->NetworkAddr);
3415 HeapFree(GetProcessHeap(), 0, connection->NetworkOptions);
3416 HeapFree(GetProcessHeap(), 0, connection->CookieAuth);
3417 if (connection->AuthInfo) RpcAuthInfo_Release(connection->AuthInfo);
3418 if (connection->QOS) RpcQualityOfService_Release(connection->QOS);
3420 /* server-only */
3421 if (connection->server_binding) RPCRT4_ReleaseBinding(connection->server_binding);
3423 if (connection->wait_release) SetEvent(connection->wait_release);
3425 HeapFree(GetProcessHeap(), 0, connection);
3429 RPC_STATUS RPCRT4_IsServerListening(const char *protseq, const char *endpoint)
3431 const struct connection_ops *ops;
3433 ops = rpcrt4_get_conn_protseq_ops(protseq);
3434 if (!ops)
3436 FIXME("not supported for protseq %s\n", protseq);
3437 return RPC_S_INVALID_BINDING;
3440 return ops->is_server_listening(endpoint);
3443 RPC_STATUS RpcTransport_GetTopOfTower(unsigned char *tower_data,
3444 size_t *tower_size,
3445 const char *protseq,
3446 const char *networkaddr,
3447 const char *endpoint)
3449 twr_empty_floor_t *protocol_floor;
3450 const struct connection_ops *protseq_ops = rpcrt4_get_conn_protseq_ops(protseq);
3452 *tower_size = 0;
3454 if (!protseq_ops)
3455 return RPC_S_INVALID_RPC_PROTSEQ;
3457 if (!tower_data)
3459 *tower_size = sizeof(*protocol_floor);
3460 *tower_size += protseq_ops->get_top_of_tower(NULL, networkaddr, endpoint);
3461 return RPC_S_OK;
3464 protocol_floor = (twr_empty_floor_t *)tower_data;
3465 protocol_floor->count_lhs = sizeof(protocol_floor->protid);
3466 protocol_floor->protid = protseq_ops->epm_protocols[0];
3467 protocol_floor->count_rhs = 0;
3469 tower_data += sizeof(*protocol_floor);
3471 *tower_size = protseq_ops->get_top_of_tower(tower_data, networkaddr, endpoint);
3472 if (!*tower_size)
3473 return EPT_S_NOT_REGISTERED;
3475 *tower_size += sizeof(*protocol_floor);
3477 return RPC_S_OK;
3480 RPC_STATUS RpcTransport_ParseTopOfTower(const unsigned char *tower_data,
3481 size_t tower_size,
3482 char **protseq,
3483 char **networkaddr,
3484 char **endpoint)
3486 const twr_empty_floor_t *protocol_floor;
3487 const twr_empty_floor_t *floor4;
3488 const struct connection_ops *protseq_ops = NULL;
3489 RPC_STATUS status;
3490 unsigned int i;
3492 if (tower_size < sizeof(*protocol_floor))
3493 return EPT_S_NOT_REGISTERED;
3495 protocol_floor = (const twr_empty_floor_t *)tower_data;
3496 tower_data += sizeof(*protocol_floor);
3497 tower_size -= sizeof(*protocol_floor);
3498 if ((protocol_floor->count_lhs != sizeof(protocol_floor->protid)) ||
3499 (protocol_floor->count_rhs > tower_size))
3500 return EPT_S_NOT_REGISTERED;
3501 tower_data += protocol_floor->count_rhs;
3502 tower_size -= protocol_floor->count_rhs;
3504 floor4 = (const twr_empty_floor_t *)tower_data;
3505 if ((tower_size < sizeof(*floor4)) ||
3506 (floor4->count_lhs != sizeof(floor4->protid)))
3507 return EPT_S_NOT_REGISTERED;
3509 for(i = 0; i < ARRAYSIZE(conn_protseq_list); i++)
3510 if ((protocol_floor->protid == conn_protseq_list[i].epm_protocols[0]) &&
3511 (floor4->protid == conn_protseq_list[i].epm_protocols[1]))
3513 protseq_ops = &conn_protseq_list[i];
3514 break;
3517 if (!protseq_ops)
3518 return EPT_S_NOT_REGISTERED;
3520 status = protseq_ops->parse_top_of_tower(tower_data, tower_size, networkaddr, endpoint);
3522 if ((status == RPC_S_OK) && protseq)
3524 *protseq = I_RpcAllocate(strlen(protseq_ops->name) + 1);
3525 strcpy(*protseq, protseq_ops->name);
3528 return status;
3531 /***********************************************************************
3532 * RpcNetworkIsProtseqValidW (RPCRT4.@)
3534 * Checks if the given protocol sequence is known by the RPC system.
3535 * If it is, returns RPC_S_OK, otherwise RPC_S_PROTSEQ_NOT_SUPPORTED.
3538 RPC_STATUS WINAPI RpcNetworkIsProtseqValidW(RPC_WSTR protseq)
3540 char ps[0x10];
3542 WideCharToMultiByte(CP_ACP, 0, protseq, -1,
3543 ps, sizeof ps, NULL, NULL);
3544 if (rpcrt4_get_conn_protseq_ops(ps))
3545 return RPC_S_OK;
3547 FIXME("Unknown protseq %s\n", debugstr_w(protseq));
3549 return RPC_S_INVALID_RPC_PROTSEQ;
3552 /***********************************************************************
3553 * RpcNetworkIsProtseqValidA (RPCRT4.@)
3555 RPC_STATUS WINAPI RpcNetworkIsProtseqValidA(RPC_CSTR protseq)
3557 UNICODE_STRING protseqW;
3559 if (RtlCreateUnicodeStringFromAsciiz(&protseqW, (char*)protseq))
3561 RPC_STATUS ret = RpcNetworkIsProtseqValidW(protseqW.Buffer);
3562 RtlFreeUnicodeString(&protseqW);
3563 return ret;
3565 return RPC_S_OUT_OF_MEMORY;
3568 /***********************************************************************
3569 * RpcProtseqVectorFreeA (RPCRT4.@)
3571 RPC_STATUS WINAPI RpcProtseqVectorFreeA(RPC_PROTSEQ_VECTORA **protseqs)
3573 TRACE("(%p)\n", protseqs);
3575 if (*protseqs)
3577 unsigned int i;
3578 for (i = 0; i < (*protseqs)->Count; i++)
3579 HeapFree(GetProcessHeap(), 0, (*protseqs)->Protseq[i]);
3580 HeapFree(GetProcessHeap(), 0, *protseqs);
3581 *protseqs = NULL;
3583 return RPC_S_OK;
3586 /***********************************************************************
3587 * RpcProtseqVectorFreeW (RPCRT4.@)
3589 RPC_STATUS WINAPI RpcProtseqVectorFreeW(RPC_PROTSEQ_VECTORW **protseqs)
3591 TRACE("(%p)\n", protseqs);
3593 if (*protseqs)
3595 unsigned int i;
3596 for (i = 0; i < (*protseqs)->Count; i++)
3597 HeapFree(GetProcessHeap(), 0, (*protseqs)->Protseq[i]);
3598 HeapFree(GetProcessHeap(), 0, *protseqs);
3599 *protseqs = NULL;
3601 return RPC_S_OK;
3604 /***********************************************************************
3605 * RpcNetworkInqProtseqsW (RPCRT4.@)
3607 RPC_STATUS WINAPI RpcNetworkInqProtseqsW( RPC_PROTSEQ_VECTORW** protseqs )
3609 RPC_PROTSEQ_VECTORW *pvector;
3610 unsigned int i;
3611 RPC_STATUS status = RPC_S_OUT_OF_MEMORY;
3613 TRACE("(%p)\n", protseqs);
3615 *protseqs = HeapAlloc(GetProcessHeap(), 0, sizeof(RPC_PROTSEQ_VECTORW)+(sizeof(unsigned short*)*ARRAYSIZE(protseq_list)));
3616 if (!*protseqs)
3617 goto end;
3618 pvector = *protseqs;
3619 pvector->Count = 0;
3620 for (i = 0; i < ARRAYSIZE(protseq_list); i++)
3622 pvector->Protseq[i] = HeapAlloc(GetProcessHeap(), 0, (strlen(protseq_list[i].name)+1)*sizeof(unsigned short));
3623 if (pvector->Protseq[i] == NULL)
3624 goto end;
3625 MultiByteToWideChar(CP_ACP, 0, (CHAR*)protseq_list[i].name, -1,
3626 (WCHAR*)pvector->Protseq[i], strlen(protseq_list[i].name) + 1);
3627 pvector->Count++;
3629 status = RPC_S_OK;
3631 end:
3632 if (status != RPC_S_OK)
3633 RpcProtseqVectorFreeW(protseqs);
3634 return status;
3637 /***********************************************************************
3638 * RpcNetworkInqProtseqsA (RPCRT4.@)
3640 RPC_STATUS WINAPI RpcNetworkInqProtseqsA(RPC_PROTSEQ_VECTORA** protseqs)
3642 RPC_PROTSEQ_VECTORA *pvector;
3643 unsigned int i;
3644 RPC_STATUS status = RPC_S_OUT_OF_MEMORY;
3646 TRACE("(%p)\n", protseqs);
3648 *protseqs = HeapAlloc(GetProcessHeap(), 0, sizeof(RPC_PROTSEQ_VECTORW)+(sizeof(unsigned char*)*ARRAYSIZE(protseq_list)));
3649 if (!*protseqs)
3650 goto end;
3651 pvector = *protseqs;
3652 pvector->Count = 0;
3653 for (i = 0; i < ARRAYSIZE(protseq_list); i++)
3655 pvector->Protseq[i] = HeapAlloc(GetProcessHeap(), 0, strlen(protseq_list[i].name)+1);
3656 if (pvector->Protseq[i] == NULL)
3657 goto end;
3658 strcpy((char*)pvector->Protseq[i], protseq_list[i].name);
3659 pvector->Count++;
3661 status = RPC_S_OK;
3663 end:
3664 if (status != RPC_S_OK)
3665 RpcProtseqVectorFreeA(protseqs);
3666 return status;