d2d1/tests: Fix stroke style object leak (Valgrind).
[wine.git] / dlls / rpcrt4 / rpc_transport.c
blob48def497bbddcd356ec252bb98ab5e68e5a6d468
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 TRACE("connection failed, error=%x\n", err);
157 return RPC_S_SERVER_TOO_BUSY;
159 if (!wait || !WaitNamedPipeA(pname, NMPWAIT_WAIT_FOREVER)) {
160 err = GetLastError();
161 WARN("connection failed, error=%x\n", err);
162 return RPC_S_SERVER_UNAVAILABLE;
166 /* success */
167 /* pipe is connected; change to message-read mode. */
168 dwMode = PIPE_READMODE_MESSAGE;
169 SetNamedPipeHandleState(pipe, &dwMode, NULL, NULL);
170 npc->pipe = pipe;
172 return RPC_S_OK;
175 static char *ncalrpc_pipe_name(const char *endpoint)
177 static const char prefix[] = "\\\\.\\pipe\\lrpc\\";
178 char *pipe_name;
180 /* protseq=ncalrpc: supposed to use NT LPC ports,
181 * but we'll implement it with named pipes for now */
182 pipe_name = I_RpcAllocate(sizeof(prefix) + strlen(endpoint));
183 strcat(strcpy(pipe_name, prefix), endpoint);
184 return pipe_name;
187 static RPC_STATUS rpcrt4_ncalrpc_open(RpcConnection* Connection)
189 RpcConnection_np *npc = (RpcConnection_np *) Connection;
190 RPC_STATUS r;
191 LPSTR pname;
193 /* already connected? */
194 if (npc->pipe)
195 return RPC_S_OK;
197 pname = ncalrpc_pipe_name(Connection->Endpoint);
198 r = rpcrt4_conn_open_pipe(Connection, pname, TRUE);
199 I_RpcFree(pname);
201 return r;
204 static RPC_STATUS rpcrt4_protseq_ncalrpc_open_endpoint(RpcServerProtseq* protseq, const char *endpoint)
206 RPC_STATUS r;
207 RpcConnection *Connection;
208 char generated_endpoint[22];
210 if (!endpoint)
212 static LONG lrpc_nameless_id;
213 DWORD process_id = GetCurrentProcessId();
214 ULONG id = InterlockedIncrement(&lrpc_nameless_id);
215 snprintf(generated_endpoint, sizeof(generated_endpoint),
216 "LRPC%08x.%08x", process_id, id);
217 endpoint = generated_endpoint;
220 r = RPCRT4_CreateConnection(&Connection, TRUE, protseq->Protseq, NULL,
221 endpoint, NULL, NULL, NULL, NULL);
222 if (r != RPC_S_OK)
223 return r;
225 ((RpcConnection_np*)Connection)->listen_pipe = ncalrpc_pipe_name(Connection->Endpoint);
226 r = rpcrt4_conn_create_pipe(Connection);
228 EnterCriticalSection(&protseq->cs);
229 list_add_head(&protseq->listeners, &Connection->protseq_entry);
230 Connection->protseq = protseq;
231 LeaveCriticalSection(&protseq->cs);
233 return r;
236 static char *ncacn_pipe_name(const char *endpoint)
238 static const char prefix[] = "\\\\.";
239 char *pipe_name;
241 /* protseq=ncacn_np: named pipes */
242 pipe_name = I_RpcAllocate(sizeof(prefix) + strlen(endpoint));
243 strcat(strcpy(pipe_name, prefix), endpoint);
244 return pipe_name;
247 static RPC_STATUS rpcrt4_ncacn_np_open(RpcConnection* Connection)
249 RpcConnection_np *npc = (RpcConnection_np *) Connection;
250 RPC_STATUS r;
251 LPSTR pname;
253 /* already connected? */
254 if (npc->pipe)
255 return RPC_S_OK;
257 pname = ncacn_pipe_name(Connection->Endpoint);
258 r = rpcrt4_conn_open_pipe(Connection, pname, FALSE);
259 I_RpcFree(pname);
261 return r;
264 static RPC_STATUS rpcrt4_protseq_ncacn_np_open_endpoint(RpcServerProtseq *protseq, const char *endpoint)
266 RPC_STATUS r;
267 RpcConnection *Connection;
268 char generated_endpoint[26];
270 if (!endpoint)
272 static LONG np_nameless_id;
273 DWORD process_id = GetCurrentProcessId();
274 ULONG id = InterlockedExchangeAdd(&np_nameless_id, 1 );
275 snprintf(generated_endpoint, sizeof(generated_endpoint),
276 "\\\\pipe\\\\%08x.%03x", process_id, id);
277 endpoint = generated_endpoint;
280 r = RPCRT4_CreateConnection(&Connection, TRUE, protseq->Protseq, NULL,
281 endpoint, NULL, NULL, NULL, NULL);
282 if (r != RPC_S_OK)
283 return r;
285 ((RpcConnection_np*)Connection)->listen_pipe = ncacn_pipe_name(Connection->Endpoint);
286 r = rpcrt4_conn_create_pipe(Connection);
288 EnterCriticalSection(&protseq->cs);
289 list_add_head(&protseq->listeners, &Connection->protseq_entry);
290 Connection->protseq = protseq;
291 LeaveCriticalSection(&protseq->cs);
293 return r;
296 static void rpcrt4_conn_np_handoff(RpcConnection_np *old_npc, RpcConnection_np *new_npc)
298 /* because of the way named pipes work, we'll transfer the connected pipe
299 * to the child, then reopen the server binding to continue listening */
301 new_npc->pipe = old_npc->pipe;
302 old_npc->pipe = 0;
303 assert(!old_npc->listen_event);
306 static RPC_STATUS rpcrt4_ncacn_np_handoff(RpcConnection *old_conn, RpcConnection *new_conn)
308 DWORD len = MAX_COMPUTERNAME_LENGTH + 1;
309 RPC_STATUS status;
311 rpcrt4_conn_np_handoff((RpcConnection_np *)old_conn, (RpcConnection_np *)new_conn);
312 status = rpcrt4_conn_create_pipe(old_conn);
314 /* Store the local computer name as the NetworkAddr for ncacn_np as long as
315 * we don't support named pipes over the network. */
316 new_conn->NetworkAddr = HeapAlloc(GetProcessHeap(), 0, len);
317 if (!GetComputerNameA(new_conn->NetworkAddr, &len))
319 ERR("Failed to retrieve the computer name, error %u\n", GetLastError());
320 return RPC_S_OUT_OF_RESOURCES;
323 return status;
326 static RPC_STATUS is_pipe_listening(const char *pipe_name)
328 return WaitNamedPipeA(pipe_name, 1) ? RPC_S_OK : RPC_S_NOT_LISTENING;
331 static RPC_STATUS rpcrt4_ncacn_np_is_server_listening(const char *endpoint)
333 char *pipe_name;
334 RPC_STATUS status;
336 pipe_name = ncacn_pipe_name(endpoint);
337 status = is_pipe_listening(pipe_name);
338 I_RpcFree(pipe_name);
339 return status;
342 static RPC_STATUS rpcrt4_ncalrpc_np_is_server_listening(const char *endpoint)
344 char *pipe_name;
345 RPC_STATUS status;
347 pipe_name = ncalrpc_pipe_name(endpoint);
348 status = is_pipe_listening(pipe_name);
349 I_RpcFree(pipe_name);
350 return status;
353 static RPC_STATUS rpcrt4_ncalrpc_handoff(RpcConnection *old_conn, RpcConnection *new_conn)
355 DWORD len = MAX_COMPUTERNAME_LENGTH + 1;
356 RPC_STATUS status;
358 TRACE("%s\n", old_conn->Endpoint);
360 rpcrt4_conn_np_handoff((RpcConnection_np *)old_conn, (RpcConnection_np *)new_conn);
361 status = rpcrt4_conn_create_pipe(old_conn);
363 /* Store the local computer name as the NetworkAddr for ncalrpc. */
364 new_conn->NetworkAddr = HeapAlloc(GetProcessHeap(), 0, len);
365 if (!GetComputerNameA(new_conn->NetworkAddr, &len))
367 ERR("Failed to retrieve the computer name, error %u\n", GetLastError());
368 return RPC_S_OUT_OF_RESOURCES;
371 return status;
374 static int rpcrt4_conn_np_read(RpcConnection *conn, void *buffer, unsigned int count)
376 RpcConnection_np *connection = (RpcConnection_np *) conn;
377 HANDLE event;
378 NTSTATUS status;
380 event = get_np_event(connection);
381 if (!event)
382 return -1;
384 if (connection->read_closed)
385 status = STATUS_CANCELLED;
386 else
387 status = NtReadFile(connection->pipe, event, NULL, NULL, &connection->io_status, buffer, count, NULL, NULL);
388 if (status == STATUS_PENDING)
390 /* check read_closed again before waiting to avoid a race */
391 if (connection->read_closed)
393 IO_STATUS_BLOCK io_status;
394 NtCancelIoFileEx(connection->pipe, &connection->io_status, &io_status);
396 WaitForSingleObject(event, INFINITE);
397 status = connection->io_status.Status;
399 release_np_event(connection, event);
400 return status && status != STATUS_BUFFER_OVERFLOW ? -1 : connection->io_status.Information;
403 static int rpcrt4_conn_np_write(RpcConnection *conn, const void *buffer, unsigned int count)
405 RpcConnection_np *connection = (RpcConnection_np *) conn;
406 IO_STATUS_BLOCK io_status;
407 HANDLE event;
408 NTSTATUS status;
410 event = get_np_event(connection);
411 if (!event)
412 return -1;
414 status = NtWriteFile(connection->pipe, event, NULL, NULL, &io_status, buffer, count, NULL, NULL);
415 if (status == STATUS_PENDING)
417 WaitForSingleObject(event, INFINITE);
418 status = io_status.Status;
420 release_np_event(connection, event);
421 if (status)
422 return -1;
424 assert(io_status.Information == count);
425 return count;
428 static int rpcrt4_conn_np_close(RpcConnection *conn)
430 RpcConnection_np *connection = (RpcConnection_np *) conn;
431 if (connection->pipe)
433 FlushFileBuffers(connection->pipe);
434 CloseHandle(connection->pipe);
435 connection->pipe = 0;
437 if (connection->listen_event)
439 CloseHandle(connection->listen_event);
440 connection->listen_event = 0;
442 if (connection->event_cache)
444 CloseHandle(connection->event_cache);
445 connection->event_cache = 0;
447 return 0;
450 static void rpcrt4_conn_np_close_read(RpcConnection *conn)
452 RpcConnection_np *connection = (RpcConnection_np*)conn;
453 IO_STATUS_BLOCK io_status;
455 connection->read_closed = TRUE;
456 NtCancelIoFileEx(connection->pipe, &connection->io_status, &io_status);
459 static void rpcrt4_conn_np_cancel_call(RpcConnection *conn)
461 RpcConnection_np *connection = (RpcConnection_np *)conn;
462 CancelIoEx(connection->pipe, NULL);
465 static int rpcrt4_conn_np_wait_for_incoming_data(RpcConnection *Connection)
467 /* FIXME: implement when named pipe writes use overlapped I/O */
468 return -1;
471 static size_t rpcrt4_ncacn_np_get_top_of_tower(unsigned char *tower_data,
472 const char *networkaddr,
473 const char *endpoint)
475 twr_empty_floor_t *smb_floor;
476 twr_empty_floor_t *nb_floor;
477 size_t size;
478 size_t networkaddr_size;
479 size_t endpoint_size;
481 TRACE("(%p, %s, %s)\n", tower_data, networkaddr, endpoint);
483 networkaddr_size = networkaddr ? strlen(networkaddr) + 1 : 1;
484 endpoint_size = endpoint ? strlen(endpoint) + 1 : 1;
485 size = sizeof(*smb_floor) + endpoint_size + sizeof(*nb_floor) + networkaddr_size;
487 if (!tower_data)
488 return size;
490 smb_floor = (twr_empty_floor_t *)tower_data;
492 tower_data += sizeof(*smb_floor);
494 smb_floor->count_lhs = sizeof(smb_floor->protid);
495 smb_floor->protid = EPM_PROTOCOL_SMB;
496 smb_floor->count_rhs = endpoint_size;
498 if (endpoint)
499 memcpy(tower_data, endpoint, endpoint_size);
500 else
501 tower_data[0] = 0;
502 tower_data += endpoint_size;
504 nb_floor = (twr_empty_floor_t *)tower_data;
506 tower_data += sizeof(*nb_floor);
508 nb_floor->count_lhs = sizeof(nb_floor->protid);
509 nb_floor->protid = EPM_PROTOCOL_NETBIOS;
510 nb_floor->count_rhs = networkaddr_size;
512 if (networkaddr)
513 memcpy(tower_data, networkaddr, networkaddr_size);
514 else
515 tower_data[0] = 0;
517 return size;
520 static RPC_STATUS rpcrt4_ncacn_np_parse_top_of_tower(const unsigned char *tower_data,
521 size_t tower_size,
522 char **networkaddr,
523 char **endpoint)
525 const twr_empty_floor_t *smb_floor = (const twr_empty_floor_t *)tower_data;
526 const twr_empty_floor_t *nb_floor;
528 TRACE("(%p, %d, %p, %p)\n", tower_data, (int)tower_size, networkaddr, endpoint);
530 if (tower_size < sizeof(*smb_floor))
531 return EPT_S_NOT_REGISTERED;
533 tower_data += sizeof(*smb_floor);
534 tower_size -= sizeof(*smb_floor);
536 if ((smb_floor->count_lhs != sizeof(smb_floor->protid)) ||
537 (smb_floor->protid != EPM_PROTOCOL_SMB) ||
538 (smb_floor->count_rhs > tower_size) ||
539 (tower_data[smb_floor->count_rhs - 1] != '\0'))
540 return EPT_S_NOT_REGISTERED;
542 if (endpoint)
544 *endpoint = I_RpcAllocate(smb_floor->count_rhs);
545 if (!*endpoint)
546 return RPC_S_OUT_OF_RESOURCES;
547 memcpy(*endpoint, tower_data, smb_floor->count_rhs);
549 tower_data += smb_floor->count_rhs;
550 tower_size -= smb_floor->count_rhs;
552 if (tower_size < sizeof(*nb_floor))
553 return EPT_S_NOT_REGISTERED;
555 nb_floor = (const twr_empty_floor_t *)tower_data;
557 tower_data += sizeof(*nb_floor);
558 tower_size -= sizeof(*nb_floor);
560 if ((nb_floor->count_lhs != sizeof(nb_floor->protid)) ||
561 (nb_floor->protid != EPM_PROTOCOL_NETBIOS) ||
562 (nb_floor->count_rhs > tower_size) ||
563 (tower_data[nb_floor->count_rhs - 1] != '\0'))
564 return EPT_S_NOT_REGISTERED;
566 if (networkaddr)
568 *networkaddr = I_RpcAllocate(nb_floor->count_rhs);
569 if (!*networkaddr)
571 if (endpoint)
573 I_RpcFree(*endpoint);
574 *endpoint = NULL;
576 return RPC_S_OUT_OF_RESOURCES;
578 memcpy(*networkaddr, tower_data, nb_floor->count_rhs);
581 return RPC_S_OK;
584 static RPC_STATUS rpcrt4_conn_np_impersonate_client(RpcConnection *conn)
586 RpcConnection_np *npc = (RpcConnection_np *)conn;
587 BOOL ret;
589 TRACE("(%p)\n", conn);
591 if (conn->AuthInfo && SecIsValidHandle(&conn->ctx))
592 return RPCRT4_default_impersonate_client(conn);
594 ret = ImpersonateNamedPipeClient(npc->pipe);
595 if (!ret)
597 DWORD error = GetLastError();
598 WARN("ImpersonateNamedPipeClient failed with error %u\n", error);
599 switch (error)
601 case ERROR_CANNOT_IMPERSONATE:
602 return RPC_S_NO_CONTEXT_AVAILABLE;
605 return RPC_S_OK;
608 static RPC_STATUS rpcrt4_conn_np_revert_to_self(RpcConnection *conn)
610 BOOL ret;
612 TRACE("(%p)\n", conn);
614 if (conn->AuthInfo && SecIsValidHandle(&conn->ctx))
615 return RPCRT4_default_revert_to_self(conn);
617 ret = RevertToSelf();
618 if (!ret)
620 WARN("RevertToSelf failed with error %u\n", GetLastError());
621 return RPC_S_NO_CONTEXT_AVAILABLE;
623 return RPC_S_OK;
626 typedef struct _RpcServerProtseq_np
628 RpcServerProtseq common;
629 HANDLE mgr_event;
630 } RpcServerProtseq_np;
632 static RpcServerProtseq *rpcrt4_protseq_np_alloc(void)
634 RpcServerProtseq_np *ps = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*ps));
635 if (ps)
636 ps->mgr_event = CreateEventW(NULL, FALSE, FALSE, NULL);
637 return &ps->common;
640 static void rpcrt4_protseq_np_signal_state_changed(RpcServerProtseq *protseq)
642 RpcServerProtseq_np *npps = CONTAINING_RECORD(protseq, RpcServerProtseq_np, common);
643 SetEvent(npps->mgr_event);
646 static void *rpcrt4_protseq_np_get_wait_array(RpcServerProtseq *protseq, void *prev_array, unsigned int *count)
648 HANDLE *objs = prev_array;
649 RpcConnection_np *conn;
650 RpcServerProtseq_np *npps = CONTAINING_RECORD(protseq, RpcServerProtseq_np, common);
652 EnterCriticalSection(&protseq->cs);
654 /* open and count connections */
655 *count = 1;
656 LIST_FOR_EACH_ENTRY(conn, &protseq->listeners, RpcConnection_np, common.protseq_entry)
658 if (!conn->pipe && rpcrt4_conn_create_pipe(&conn->common) != RPC_S_OK)
659 continue;
660 if (!conn->listen_event)
662 NTSTATUS status;
663 HANDLE event;
665 event = get_np_event(conn);
666 if (!event)
667 continue;
669 status = NtFsControlFile(conn->pipe, event, NULL, NULL, &conn->io_status, FSCTL_PIPE_LISTEN, NULL, 0, NULL, 0);
670 switch (status)
672 case STATUS_SUCCESS:
673 case STATUS_PIPE_CONNECTED:
674 conn->io_status.Status = status;
675 SetEvent(event);
676 break;
677 case STATUS_PENDING:
678 break;
679 default:
680 ERR("pipe listen error %x\n", status);
681 continue;
684 conn->listen_event = event;
686 (*count)++;
689 /* make array of connections */
690 if (objs)
691 objs = HeapReAlloc(GetProcessHeap(), 0, objs, *count*sizeof(HANDLE));
692 else
693 objs = HeapAlloc(GetProcessHeap(), 0, *count*sizeof(HANDLE));
694 if (!objs)
696 ERR("couldn't allocate objs\n");
697 LeaveCriticalSection(&protseq->cs);
698 return NULL;
701 objs[0] = npps->mgr_event;
702 *count = 1;
703 LIST_FOR_EACH_ENTRY(conn, &protseq->listeners, RpcConnection_np, common.protseq_entry)
705 if (conn->listen_event)
706 objs[(*count)++] = conn->listen_event;
708 LeaveCriticalSection(&protseq->cs);
709 return objs;
712 static void rpcrt4_protseq_np_free_wait_array(RpcServerProtseq *protseq, void *array)
714 HeapFree(GetProcessHeap(), 0, array);
717 static int rpcrt4_protseq_np_wait_for_new_connection(RpcServerProtseq *protseq, unsigned int count, void *wait_array)
719 HANDLE b_handle;
720 HANDLE *objs = wait_array;
721 DWORD res;
722 RpcConnection *cconn = NULL;
723 RpcConnection_np *conn;
725 if (!objs)
726 return -1;
730 /* an alertable wait isn't strictly necessary, but due to our
731 * overlapped I/O implementation in Wine we need to free some memory
732 * by the file user APC being called, even if no completion routine was
733 * specified at the time of starting the async operation */
734 res = WaitForMultipleObjectsEx(count, objs, FALSE, INFINITE, TRUE);
735 } while (res == WAIT_IO_COMPLETION);
737 if (res == WAIT_OBJECT_0)
738 return 0;
739 else if (res == WAIT_FAILED)
741 ERR("wait failed with error %d\n", GetLastError());
742 return -1;
744 else
746 b_handle = objs[res - WAIT_OBJECT_0];
747 /* find which connection got a RPC */
748 EnterCriticalSection(&protseq->cs);
749 LIST_FOR_EACH_ENTRY(conn, &protseq->listeners, RpcConnection_np, common.protseq_entry)
751 if (b_handle == conn->listen_event)
753 release_np_event(conn, conn->listen_event);
754 conn->listen_event = NULL;
755 if (conn->io_status.Status == STATUS_SUCCESS || conn->io_status.Status == STATUS_PIPE_CONNECTED)
756 cconn = rpcrt4_spawn_connection(&conn->common);
757 else
758 ERR("listen failed %x\n", conn->io_status.Status);
759 break;
762 LeaveCriticalSection(&protseq->cs);
763 if (!cconn)
765 ERR("failed to locate connection for handle %p\n", b_handle);
766 return -1;
768 RPCRT4_new_client(cconn);
769 return 1;
773 static size_t rpcrt4_ncalrpc_get_top_of_tower(unsigned char *tower_data,
774 const char *networkaddr,
775 const char *endpoint)
777 twr_empty_floor_t *pipe_floor;
778 size_t size;
779 size_t endpoint_size;
781 TRACE("(%p, %s, %s)\n", tower_data, networkaddr, endpoint);
783 endpoint_size = strlen(endpoint) + 1;
784 size = sizeof(*pipe_floor) + endpoint_size;
786 if (!tower_data)
787 return size;
789 pipe_floor = (twr_empty_floor_t *)tower_data;
791 tower_data += sizeof(*pipe_floor);
793 pipe_floor->count_lhs = sizeof(pipe_floor->protid);
794 pipe_floor->protid = EPM_PROTOCOL_PIPE;
795 pipe_floor->count_rhs = endpoint_size;
797 memcpy(tower_data, endpoint, endpoint_size);
799 return size;
802 static RPC_STATUS rpcrt4_ncalrpc_parse_top_of_tower(const unsigned char *tower_data,
803 size_t tower_size,
804 char **networkaddr,
805 char **endpoint)
807 const twr_empty_floor_t *pipe_floor = (const twr_empty_floor_t *)tower_data;
809 TRACE("(%p, %d, %p, %p)\n", tower_data, (int)tower_size, networkaddr, endpoint);
811 if (tower_size < sizeof(*pipe_floor))
812 return EPT_S_NOT_REGISTERED;
814 tower_data += sizeof(*pipe_floor);
815 tower_size -= sizeof(*pipe_floor);
817 if ((pipe_floor->count_lhs != sizeof(pipe_floor->protid)) ||
818 (pipe_floor->protid != EPM_PROTOCOL_PIPE) ||
819 (pipe_floor->count_rhs > tower_size) ||
820 (tower_data[pipe_floor->count_rhs - 1] != '\0'))
821 return EPT_S_NOT_REGISTERED;
823 if (networkaddr)
824 *networkaddr = NULL;
826 if (endpoint)
828 *endpoint = I_RpcAllocate(pipe_floor->count_rhs);
829 if (!*endpoint)
830 return RPC_S_OUT_OF_RESOURCES;
831 memcpy(*endpoint, tower_data, pipe_floor->count_rhs);
834 return RPC_S_OK;
837 static BOOL rpcrt4_ncalrpc_is_authorized(RpcConnection *conn)
839 return FALSE;
842 static RPC_STATUS rpcrt4_ncalrpc_authorize(RpcConnection *conn, BOOL first_time,
843 unsigned char *in_buffer,
844 unsigned int in_size,
845 unsigned char *out_buffer,
846 unsigned int *out_size)
848 /* since this protocol is local to the machine there is no need to
849 * authenticate the caller */
850 *out_size = 0;
851 return RPC_S_OK;
854 static RPC_STATUS rpcrt4_ncalrpc_secure_packet(RpcConnection *conn,
855 enum secure_packet_direction dir,
856 RpcPktHdr *hdr, unsigned int hdr_size,
857 unsigned char *stub_data, unsigned int stub_data_size,
858 RpcAuthVerifier *auth_hdr,
859 unsigned char *auth_value, unsigned int auth_value_size)
861 /* since this protocol is local to the machine there is no need to secure
862 * the packet */
863 return RPC_S_OK;
866 static RPC_STATUS rpcrt4_ncalrpc_inquire_auth_client(
867 RpcConnection *conn, RPC_AUTHZ_HANDLE *privs, RPC_WSTR *server_princ_name,
868 ULONG *authn_level, ULONG *authn_svc, ULONG *authz_svc, ULONG flags)
870 TRACE("(%p, %p, %p, %p, %p, %p, 0x%x)\n", conn, privs,
871 server_princ_name, authn_level, authn_svc, authz_svc, flags);
873 if (privs)
875 FIXME("privs not implemented\n");
876 *privs = NULL;
878 if (server_princ_name)
880 FIXME("server_princ_name not implemented\n");
881 *server_princ_name = NULL;
883 if (authn_level) *authn_level = RPC_C_AUTHN_LEVEL_PKT_PRIVACY;
884 if (authn_svc) *authn_svc = RPC_C_AUTHN_WINNT;
885 if (authz_svc)
887 FIXME("authorization service not implemented\n");
888 *authz_svc = RPC_C_AUTHZ_NONE;
890 if (flags)
891 FIXME("flags 0x%x not implemented\n", flags);
893 return RPC_S_OK;
896 /**** ncacn_ip_tcp support ****/
898 static size_t rpcrt4_ip_tcp_get_top_of_tower(unsigned char *tower_data,
899 const char *networkaddr,
900 unsigned char tcp_protid,
901 const char *endpoint)
903 twr_tcp_floor_t *tcp_floor;
904 twr_ipv4_floor_t *ipv4_floor;
905 struct addrinfo *ai;
906 struct addrinfo hints;
907 int ret;
908 size_t size = sizeof(*tcp_floor) + sizeof(*ipv4_floor);
910 TRACE("(%p, %s, %s)\n", tower_data, networkaddr, endpoint);
912 if (!tower_data)
913 return size;
915 tcp_floor = (twr_tcp_floor_t *)tower_data;
916 tower_data += sizeof(*tcp_floor);
918 ipv4_floor = (twr_ipv4_floor_t *)tower_data;
920 tcp_floor->count_lhs = sizeof(tcp_floor->protid);
921 tcp_floor->protid = tcp_protid;
922 tcp_floor->count_rhs = sizeof(tcp_floor->port);
924 ipv4_floor->count_lhs = sizeof(ipv4_floor->protid);
925 ipv4_floor->protid = EPM_PROTOCOL_IP;
926 ipv4_floor->count_rhs = sizeof(ipv4_floor->ipv4addr);
928 hints.ai_flags = AI_NUMERICHOST;
929 /* FIXME: only support IPv4 at the moment. how is IPv6 represented by the EPM? */
930 hints.ai_family = PF_INET;
931 hints.ai_socktype = SOCK_STREAM;
932 hints.ai_protocol = IPPROTO_TCP;
933 hints.ai_addrlen = 0;
934 hints.ai_addr = NULL;
935 hints.ai_canonname = NULL;
936 hints.ai_next = NULL;
938 ret = getaddrinfo(networkaddr, endpoint, &hints, &ai);
939 if (ret)
941 ret = getaddrinfo("0.0.0.0", endpoint, &hints, &ai);
942 if (ret)
944 ERR("getaddrinfo failed: %s\n", gai_strerror(ret));
945 return 0;
949 if (ai->ai_family == PF_INET)
951 const struct sockaddr_in *sin = (const struct sockaddr_in *)ai->ai_addr;
952 tcp_floor->port = sin->sin_port;
953 ipv4_floor->ipv4addr = sin->sin_addr.s_addr;
955 else
957 ERR("unexpected protocol family %d\n", ai->ai_family);
958 freeaddrinfo(ai);
959 return 0;
962 freeaddrinfo(ai);
964 return size;
967 static RPC_STATUS rpcrt4_ip_tcp_parse_top_of_tower(const unsigned char *tower_data,
968 size_t tower_size,
969 char **networkaddr,
970 unsigned char tcp_protid,
971 char **endpoint)
973 const twr_tcp_floor_t *tcp_floor = (const twr_tcp_floor_t *)tower_data;
974 const twr_ipv4_floor_t *ipv4_floor;
975 struct in_addr in_addr;
977 TRACE("(%p, %d, %p, %p)\n", tower_data, (int)tower_size, networkaddr, endpoint);
979 if (tower_size < sizeof(*tcp_floor))
980 return EPT_S_NOT_REGISTERED;
982 tower_data += sizeof(*tcp_floor);
983 tower_size -= sizeof(*tcp_floor);
985 if (tower_size < sizeof(*ipv4_floor))
986 return EPT_S_NOT_REGISTERED;
988 ipv4_floor = (const twr_ipv4_floor_t *)tower_data;
990 if ((tcp_floor->count_lhs != sizeof(tcp_floor->protid)) ||
991 (tcp_floor->protid != tcp_protid) ||
992 (tcp_floor->count_rhs != sizeof(tcp_floor->port)) ||
993 (ipv4_floor->count_lhs != sizeof(ipv4_floor->protid)) ||
994 (ipv4_floor->protid != EPM_PROTOCOL_IP) ||
995 (ipv4_floor->count_rhs != sizeof(ipv4_floor->ipv4addr)))
996 return EPT_S_NOT_REGISTERED;
998 if (endpoint)
1000 *endpoint = I_RpcAllocate(6 /* sizeof("65535") + 1 */);
1001 if (!*endpoint)
1002 return RPC_S_OUT_OF_RESOURCES;
1003 sprintf(*endpoint, "%u", ntohs(tcp_floor->port));
1006 if (networkaddr)
1008 *networkaddr = I_RpcAllocate(INET_ADDRSTRLEN);
1009 if (!*networkaddr)
1011 if (endpoint)
1013 I_RpcFree(*endpoint);
1014 *endpoint = NULL;
1016 return RPC_S_OUT_OF_RESOURCES;
1018 in_addr.s_addr = ipv4_floor->ipv4addr;
1019 if (!inet_ntop(AF_INET, &in_addr, *networkaddr, INET_ADDRSTRLEN))
1021 ERR("inet_ntop: %u\n", WSAGetLastError());
1022 I_RpcFree(*networkaddr);
1023 *networkaddr = NULL;
1024 if (endpoint)
1026 I_RpcFree(*endpoint);
1027 *endpoint = NULL;
1029 return EPT_S_NOT_REGISTERED;
1033 return RPC_S_OK;
1036 typedef struct _RpcConnection_tcp
1038 RpcConnection common;
1039 int sock;
1040 HANDLE sock_event;
1041 HANDLE cancel_event;
1042 } RpcConnection_tcp;
1044 static BOOL rpcrt4_sock_wait_init(RpcConnection_tcp *tcpc)
1046 static BOOL wsa_inited;
1047 if (!wsa_inited)
1049 WSADATA wsadata;
1050 WSAStartup(MAKEWORD(2, 2), &wsadata);
1051 /* Note: WSAStartup can be called more than once so we don't bother with
1052 * making accesses to wsa_inited thread-safe */
1053 wsa_inited = TRUE;
1055 tcpc->sock_event = CreateEventW(NULL, FALSE, FALSE, NULL);
1056 tcpc->cancel_event = CreateEventW(NULL, FALSE, FALSE, NULL);
1057 if (!tcpc->sock_event || !tcpc->cancel_event)
1059 ERR("event creation failed\n");
1060 if (tcpc->sock_event) CloseHandle(tcpc->sock_event);
1061 return FALSE;
1063 return TRUE;
1066 static BOOL rpcrt4_sock_wait_for_recv(RpcConnection_tcp *tcpc)
1068 HANDLE wait_handles[2];
1069 DWORD res;
1070 if (WSAEventSelect(tcpc->sock, tcpc->sock_event, FD_READ | FD_CLOSE) == SOCKET_ERROR)
1072 ERR("WSAEventSelect() failed with error %d\n", WSAGetLastError());
1073 return FALSE;
1075 wait_handles[0] = tcpc->sock_event;
1076 wait_handles[1] = tcpc->cancel_event;
1077 res = WaitForMultipleObjects(2, wait_handles, FALSE, INFINITE);
1078 switch (res)
1080 case WAIT_OBJECT_0:
1081 return TRUE;
1082 case WAIT_OBJECT_0 + 1:
1083 return FALSE;
1084 default:
1085 ERR("WaitForMultipleObjects() failed with error %d\n", GetLastError());
1086 return FALSE;
1090 static BOOL rpcrt4_sock_wait_for_send(RpcConnection_tcp *tcpc)
1092 DWORD res;
1093 if (WSAEventSelect(tcpc->sock, tcpc->sock_event, FD_WRITE | FD_CLOSE) == SOCKET_ERROR)
1095 ERR("WSAEventSelect() failed with error %d\n", WSAGetLastError());
1096 return FALSE;
1098 res = WaitForSingleObject(tcpc->sock_event, INFINITE);
1099 switch (res)
1101 case WAIT_OBJECT_0:
1102 return TRUE;
1103 default:
1104 ERR("WaitForMultipleObjects() failed with error %d\n", GetLastError());
1105 return FALSE;
1109 static RpcConnection *rpcrt4_conn_tcp_alloc(void)
1111 RpcConnection_tcp *tcpc;
1112 tcpc = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(RpcConnection_tcp));
1113 if (tcpc == NULL)
1114 return NULL;
1115 tcpc->sock = -1;
1116 if (!rpcrt4_sock_wait_init(tcpc))
1118 HeapFree(GetProcessHeap(), 0, tcpc);
1119 return NULL;
1121 return &tcpc->common;
1124 static RPC_STATUS rpcrt4_ncacn_ip_tcp_open(RpcConnection* Connection)
1126 RpcConnection_tcp *tcpc = (RpcConnection_tcp *) Connection;
1127 int sock;
1128 int ret;
1129 struct addrinfo *ai;
1130 struct addrinfo *ai_cur;
1131 struct addrinfo hints;
1133 TRACE("(%s, %s)\n", Connection->NetworkAddr, Connection->Endpoint);
1135 if (tcpc->sock != -1)
1136 return RPC_S_OK;
1138 hints.ai_flags = 0;
1139 hints.ai_family = PF_UNSPEC;
1140 hints.ai_socktype = SOCK_STREAM;
1141 hints.ai_protocol = IPPROTO_TCP;
1142 hints.ai_addrlen = 0;
1143 hints.ai_addr = NULL;
1144 hints.ai_canonname = NULL;
1145 hints.ai_next = NULL;
1147 ret = getaddrinfo(Connection->NetworkAddr, Connection->Endpoint, &hints, &ai);
1148 if (ret)
1150 ERR("getaddrinfo for %s:%s failed: %s\n", Connection->NetworkAddr,
1151 Connection->Endpoint, gai_strerror(ret));
1152 return RPC_S_SERVER_UNAVAILABLE;
1155 for (ai_cur = ai; ai_cur; ai_cur = ai_cur->ai_next)
1157 int val;
1158 u_long nonblocking;
1160 if (ai_cur->ai_family != AF_INET && ai_cur->ai_family != AF_INET6)
1162 TRACE("skipping non-IP/IPv6 address family\n");
1163 continue;
1166 if (TRACE_ON(rpc))
1168 char host[256];
1169 char service[256];
1170 getnameinfo(ai_cur->ai_addr, ai_cur->ai_addrlen,
1171 host, sizeof(host), service, sizeof(service),
1172 NI_NUMERICHOST | NI_NUMERICSERV);
1173 TRACE("trying %s:%s\n", host, service);
1176 sock = socket(ai_cur->ai_family, ai_cur->ai_socktype, ai_cur->ai_protocol);
1177 if (sock == -1)
1179 WARN("socket() failed: %u\n", WSAGetLastError());
1180 continue;
1183 if (0>connect(sock, ai_cur->ai_addr, ai_cur->ai_addrlen))
1185 WARN("connect() failed: %u\n", WSAGetLastError());
1186 closesocket(sock);
1187 continue;
1190 /* RPC depends on having minimal latency so disable the Nagle algorithm */
1191 val = 1;
1192 setsockopt(sock, IPPROTO_TCP, TCP_NODELAY, (char *)&val, sizeof(val));
1193 nonblocking = 1;
1194 ioctlsocket(sock, FIONBIO, &nonblocking);
1196 tcpc->sock = sock;
1198 freeaddrinfo(ai);
1199 TRACE("connected\n");
1200 return RPC_S_OK;
1203 freeaddrinfo(ai);
1204 ERR("couldn't connect to %s:%s\n", Connection->NetworkAddr, Connection->Endpoint);
1205 return RPC_S_SERVER_UNAVAILABLE;
1208 static RPC_STATUS rpcrt4_protseq_ncacn_ip_tcp_open_endpoint(RpcServerProtseq *protseq, const char *endpoint)
1210 RPC_STATUS status = RPC_S_CANT_CREATE_ENDPOINT;
1211 int sock;
1212 int ret;
1213 struct addrinfo *ai;
1214 struct addrinfo *ai_cur;
1215 struct addrinfo hints;
1217 TRACE("(%p, %s)\n", protseq, endpoint);
1219 hints.ai_flags = AI_PASSIVE /* for non-localhost addresses */;
1220 hints.ai_family = PF_UNSPEC;
1221 hints.ai_socktype = SOCK_STREAM;
1222 hints.ai_protocol = IPPROTO_TCP;
1223 hints.ai_addrlen = 0;
1224 hints.ai_addr = NULL;
1225 hints.ai_canonname = NULL;
1226 hints.ai_next = NULL;
1228 ret = getaddrinfo(NULL, endpoint ? endpoint : "0", &hints, &ai);
1229 if (ret)
1231 ERR("getaddrinfo for port %s failed: %s\n", endpoint,
1232 gai_strerror(ret));
1233 if ((ret == EAI_SERVICE) || (ret == EAI_NONAME))
1234 return RPC_S_INVALID_ENDPOINT_FORMAT;
1235 return RPC_S_CANT_CREATE_ENDPOINT;
1238 for (ai_cur = ai; ai_cur; ai_cur = ai_cur->ai_next)
1240 RpcConnection_tcp *tcpc;
1241 RPC_STATUS create_status;
1242 struct sockaddr_storage sa;
1243 socklen_t sa_len;
1244 char service[NI_MAXSERV];
1245 u_long nonblocking;
1247 if (ai_cur->ai_family != AF_INET && ai_cur->ai_family != AF_INET6)
1249 TRACE("skipping non-IP/IPv6 address family\n");
1250 continue;
1253 if (TRACE_ON(rpc))
1255 char host[256];
1256 getnameinfo(ai_cur->ai_addr, ai_cur->ai_addrlen,
1257 host, sizeof(host), service, sizeof(service),
1258 NI_NUMERICHOST | NI_NUMERICSERV);
1259 TRACE("trying %s:%s\n", host, service);
1262 sock = socket(ai_cur->ai_family, ai_cur->ai_socktype, ai_cur->ai_protocol);
1263 if (sock == -1)
1265 WARN("socket() failed: %u\n", WSAGetLastError());
1266 status = RPC_S_CANT_CREATE_ENDPOINT;
1267 continue;
1270 ret = bind(sock, ai_cur->ai_addr, ai_cur->ai_addrlen);
1271 if (ret < 0)
1273 WARN("bind failed: %u\n", WSAGetLastError());
1274 closesocket(sock);
1275 if (WSAGetLastError() == WSAEADDRINUSE)
1276 status = RPC_S_DUPLICATE_ENDPOINT;
1277 else
1278 status = RPC_S_CANT_CREATE_ENDPOINT;
1279 continue;
1282 sa_len = sizeof(sa);
1283 if (getsockname(sock, (struct sockaddr *)&sa, &sa_len))
1285 WARN("getsockname() failed: %u\n", WSAGetLastError());
1286 closesocket(sock);
1287 status = RPC_S_CANT_CREATE_ENDPOINT;
1288 continue;
1291 ret = getnameinfo((struct sockaddr *)&sa, sa_len,
1292 NULL, 0, service, sizeof(service),
1293 NI_NUMERICSERV);
1294 if (ret)
1296 WARN("getnameinfo failed: %s\n", gai_strerror(ret));
1297 closesocket(sock);
1298 status = RPC_S_CANT_CREATE_ENDPOINT;
1299 continue;
1302 create_status = RPCRT4_CreateConnection((RpcConnection **)&tcpc, TRUE,
1303 protseq->Protseq, NULL,
1304 service, NULL, NULL, NULL, NULL);
1305 if (create_status != RPC_S_OK)
1307 closesocket(sock);
1308 status = create_status;
1309 continue;
1312 tcpc->sock = sock;
1313 ret = listen(sock, protseq->MaxCalls);
1314 if (ret < 0)
1316 WARN("listen failed: %u\n", WSAGetLastError());
1317 RPCRT4_ReleaseConnection(&tcpc->common);
1318 status = RPC_S_OUT_OF_RESOURCES;
1319 continue;
1321 /* need a non-blocking socket, otherwise accept() has a potential
1322 * race-condition (poll() says it is readable, connection drops,
1323 * and accept() blocks until the next connection comes...)
1325 nonblocking = 1;
1326 ret = ioctlsocket(sock, FIONBIO, &nonblocking);
1327 if (ret < 0)
1329 WARN("couldn't make socket non-blocking, error %d\n", ret);
1330 RPCRT4_ReleaseConnection(&tcpc->common);
1331 status = RPC_S_OUT_OF_RESOURCES;
1332 continue;
1335 EnterCriticalSection(&protseq->cs);
1336 list_add_tail(&protseq->listeners, &tcpc->common.protseq_entry);
1337 tcpc->common.protseq = protseq;
1338 LeaveCriticalSection(&protseq->cs);
1340 freeaddrinfo(ai);
1342 /* since IPv4 and IPv6 share the same port space, we only need one
1343 * successful bind to listen for both */
1344 TRACE("listening on %s\n", endpoint);
1345 return RPC_S_OK;
1348 freeaddrinfo(ai);
1349 ERR("couldn't listen on port %s\n", endpoint);
1350 return status;
1353 static RPC_STATUS rpcrt4_conn_tcp_handoff(RpcConnection *old_conn, RpcConnection *new_conn)
1355 int ret;
1356 struct sockaddr_in address;
1357 socklen_t addrsize;
1358 RpcConnection_tcp *server = (RpcConnection_tcp*) old_conn;
1359 RpcConnection_tcp *client = (RpcConnection_tcp*) new_conn;
1360 u_long nonblocking;
1362 addrsize = sizeof(address);
1363 ret = accept(server->sock, (struct sockaddr*) &address, &addrsize);
1364 if (ret < 0)
1366 ERR("Failed to accept a TCP connection: error %d\n", ret);
1367 return RPC_S_OUT_OF_RESOURCES;
1370 nonblocking = 1;
1371 ioctlsocket(ret, FIONBIO, &nonblocking);
1372 client->sock = ret;
1374 client->common.NetworkAddr = HeapAlloc(GetProcessHeap(), 0, INET6_ADDRSTRLEN);
1375 ret = getnameinfo((struct sockaddr*)&address, addrsize, client->common.NetworkAddr, INET6_ADDRSTRLEN, NULL, 0, NI_NUMERICHOST);
1376 if (ret != 0)
1378 ERR("Failed to retrieve the IP address, error %d\n", ret);
1379 return RPC_S_OUT_OF_RESOURCES;
1382 TRACE("Accepted a new TCP connection from %s\n", client->common.NetworkAddr);
1383 return RPC_S_OK;
1386 static int rpcrt4_conn_tcp_read(RpcConnection *Connection,
1387 void *buffer, unsigned int count)
1389 RpcConnection_tcp *tcpc = (RpcConnection_tcp *) Connection;
1390 int bytes_read = 0;
1391 while (bytes_read != count)
1393 int r = recv(tcpc->sock, (char *)buffer + bytes_read, count - bytes_read, 0);
1394 if (!r)
1395 return -1;
1396 else if (r > 0)
1397 bytes_read += r;
1398 else if (WSAGetLastError() == WSAEINTR)
1399 continue;
1400 else if (WSAGetLastError() != WSAEWOULDBLOCK)
1402 WARN("recv() failed: %u\n", WSAGetLastError());
1403 return -1;
1405 else
1407 if (!rpcrt4_sock_wait_for_recv(tcpc))
1408 return -1;
1411 TRACE("%d %p %u -> %d\n", tcpc->sock, buffer, count, bytes_read);
1412 return bytes_read;
1415 static int rpcrt4_conn_tcp_write(RpcConnection *Connection,
1416 const void *buffer, unsigned int count)
1418 RpcConnection_tcp *tcpc = (RpcConnection_tcp *) Connection;
1419 int bytes_written = 0;
1420 while (bytes_written != count)
1422 int r = send(tcpc->sock, (const char *)buffer + bytes_written, count - bytes_written, 0);
1423 if (r >= 0)
1424 bytes_written += r;
1425 else if (WSAGetLastError() == WSAEINTR)
1426 continue;
1427 else if (WSAGetLastError() != WSAEWOULDBLOCK)
1428 return -1;
1429 else
1431 if (!rpcrt4_sock_wait_for_send(tcpc))
1432 return -1;
1435 TRACE("%d %p %u -> %d\n", tcpc->sock, buffer, count, bytes_written);
1436 return bytes_written;
1439 static int rpcrt4_conn_tcp_close(RpcConnection *conn)
1441 RpcConnection_tcp *connection = (RpcConnection_tcp *) conn;
1443 TRACE("%d\n", connection->sock);
1445 if (connection->sock != -1)
1446 closesocket(connection->sock);
1447 connection->sock = -1;
1448 CloseHandle(connection->sock_event);
1449 CloseHandle(connection->cancel_event);
1450 return 0;
1453 static void rpcrt4_conn_tcp_close_read(RpcConnection *conn)
1455 RpcConnection_tcp *connection = (RpcConnection_tcp *) conn;
1456 shutdown(connection->sock, SD_RECEIVE);
1459 static void rpcrt4_conn_tcp_cancel_call(RpcConnection *conn)
1461 RpcConnection_tcp *connection = (RpcConnection_tcp *) conn;
1463 TRACE("%p\n", connection);
1465 SetEvent(connection->cancel_event);
1468 static RPC_STATUS rpcrt4_conn_tcp_is_server_listening(const char *endpoint)
1470 FIXME("\n");
1471 return RPC_S_ACCESS_DENIED;
1474 static int rpcrt4_conn_tcp_wait_for_incoming_data(RpcConnection *Connection)
1476 RpcConnection_tcp *tcpc = (RpcConnection_tcp *) Connection;
1478 TRACE("%p\n", Connection);
1480 if (!rpcrt4_sock_wait_for_recv(tcpc))
1481 return -1;
1482 return 0;
1485 static size_t rpcrt4_ncacn_ip_tcp_get_top_of_tower(unsigned char *tower_data,
1486 const char *networkaddr,
1487 const char *endpoint)
1489 return rpcrt4_ip_tcp_get_top_of_tower(tower_data, networkaddr,
1490 EPM_PROTOCOL_TCP, endpoint);
1493 typedef struct _RpcServerProtseq_sock
1495 RpcServerProtseq common;
1496 HANDLE mgr_event;
1497 } RpcServerProtseq_sock;
1499 static RpcServerProtseq *rpcrt4_protseq_sock_alloc(void)
1501 RpcServerProtseq_sock *ps = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*ps));
1502 if (ps)
1504 static BOOL wsa_inited;
1505 if (!wsa_inited)
1507 WSADATA wsadata;
1508 WSAStartup(MAKEWORD(2, 2), &wsadata);
1509 /* Note: WSAStartup can be called more than once so we don't bother with
1510 * making accesses to wsa_inited thread-safe */
1511 wsa_inited = TRUE;
1513 ps->mgr_event = CreateEventW(NULL, FALSE, FALSE, NULL);
1515 return &ps->common;
1518 static void rpcrt4_protseq_sock_signal_state_changed(RpcServerProtseq *protseq)
1520 RpcServerProtseq_sock *sockps = CONTAINING_RECORD(protseq, RpcServerProtseq_sock, common);
1521 SetEvent(sockps->mgr_event);
1524 static void *rpcrt4_protseq_sock_get_wait_array(RpcServerProtseq *protseq, void *prev_array, unsigned int *count)
1526 HANDLE *objs = prev_array;
1527 RpcConnection_tcp *conn;
1528 RpcServerProtseq_sock *sockps = CONTAINING_RECORD(protseq, RpcServerProtseq_sock, common);
1530 EnterCriticalSection(&protseq->cs);
1532 /* open and count connections */
1533 *count = 1;
1534 LIST_FOR_EACH_ENTRY(conn, &protseq->listeners, RpcConnection_tcp, common.protseq_entry)
1536 if (conn->sock != -1)
1537 (*count)++;
1540 /* make array of connections */
1541 if (objs)
1542 objs = HeapReAlloc(GetProcessHeap(), 0, objs, *count*sizeof(HANDLE));
1543 else
1544 objs = HeapAlloc(GetProcessHeap(), 0, *count*sizeof(HANDLE));
1545 if (!objs)
1547 ERR("couldn't allocate objs\n");
1548 LeaveCriticalSection(&protseq->cs);
1549 return NULL;
1552 objs[0] = sockps->mgr_event;
1553 *count = 1;
1554 LIST_FOR_EACH_ENTRY(conn, &protseq->listeners, RpcConnection_tcp, common.protseq_entry)
1556 if (conn->sock != -1)
1558 int res = WSAEventSelect(conn->sock, conn->sock_event, FD_ACCEPT);
1559 if (res == SOCKET_ERROR)
1560 ERR("WSAEventSelect() failed with error %d\n", WSAGetLastError());
1561 else
1563 objs[*count] = conn->sock_event;
1564 (*count)++;
1568 LeaveCriticalSection(&protseq->cs);
1569 return objs;
1572 static void rpcrt4_protseq_sock_free_wait_array(RpcServerProtseq *protseq, void *array)
1574 HeapFree(GetProcessHeap(), 0, array);
1577 static int rpcrt4_protseq_sock_wait_for_new_connection(RpcServerProtseq *protseq, unsigned int count, void *wait_array)
1579 HANDLE b_handle;
1580 HANDLE *objs = wait_array;
1581 DWORD res;
1582 RpcConnection *cconn = NULL;
1583 RpcConnection_tcp *conn;
1585 if (!objs)
1586 return -1;
1590 /* an alertable wait isn't strictly necessary, but due to our
1591 * overlapped I/O implementation in Wine we need to free some memory
1592 * by the file user APC being called, even if no completion routine was
1593 * specified at the time of starting the async operation */
1594 res = WaitForMultipleObjectsEx(count, objs, FALSE, INFINITE, TRUE);
1595 } while (res == WAIT_IO_COMPLETION);
1597 if (res == WAIT_OBJECT_0)
1598 return 0;
1599 if (res == WAIT_FAILED)
1601 ERR("wait failed with error %d\n", GetLastError());
1602 return -1;
1605 b_handle = objs[res - WAIT_OBJECT_0];
1607 /* find which connection got a RPC */
1608 EnterCriticalSection(&protseq->cs);
1609 LIST_FOR_EACH_ENTRY(conn, &protseq->listeners, RpcConnection_tcp, common.protseq_entry)
1611 if (b_handle == conn->sock_event)
1613 cconn = rpcrt4_spawn_connection(&conn->common);
1614 break;
1617 LeaveCriticalSection(&protseq->cs);
1618 if (!cconn)
1620 ERR("failed to locate connection for handle %p\n", b_handle);
1621 return -1;
1624 RPCRT4_new_client(cconn);
1625 return 1;
1628 static RPC_STATUS rpcrt4_ncacn_ip_tcp_parse_top_of_tower(const unsigned char *tower_data,
1629 size_t tower_size,
1630 char **networkaddr,
1631 char **endpoint)
1633 return rpcrt4_ip_tcp_parse_top_of_tower(tower_data, tower_size,
1634 networkaddr, EPM_PROTOCOL_TCP,
1635 endpoint);
1638 /**** ncacn_http support ****/
1640 /* 60 seconds is the period native uses */
1641 #define HTTP_IDLE_TIME 60000
1643 /* reference counted to avoid a race between a cancelled call's connection
1644 * being destroyed and the asynchronous InternetReadFileEx call being
1645 * completed */
1646 typedef struct _RpcHttpAsyncData
1648 LONG refs;
1649 HANDLE completion_event;
1650 WORD async_result;
1651 INTERNET_BUFFERSW inet_buffers;
1652 CRITICAL_SECTION cs;
1653 } RpcHttpAsyncData;
1655 static ULONG RpcHttpAsyncData_AddRef(RpcHttpAsyncData *data)
1657 return InterlockedIncrement(&data->refs);
1660 static ULONG RpcHttpAsyncData_Release(RpcHttpAsyncData *data)
1662 ULONG refs = InterlockedDecrement(&data->refs);
1663 if (!refs)
1665 TRACE("destroying async data %p\n", data);
1666 CloseHandle(data->completion_event);
1667 HeapFree(GetProcessHeap(), 0, data->inet_buffers.lpvBuffer);
1668 data->cs.DebugInfo->Spare[0] = 0;
1669 DeleteCriticalSection(&data->cs);
1670 HeapFree(GetProcessHeap(), 0, data);
1672 return refs;
1675 static void prepare_async_request(RpcHttpAsyncData *async_data)
1677 ResetEvent(async_data->completion_event);
1678 RpcHttpAsyncData_AddRef(async_data);
1681 static RPC_STATUS wait_async_request(RpcHttpAsyncData *async_data, BOOL call_ret, HANDLE cancel_event)
1683 HANDLE handles[2] = { async_data->completion_event, cancel_event };
1684 DWORD res;
1686 if(call_ret) {
1687 RpcHttpAsyncData_Release(async_data);
1688 return RPC_S_OK;
1691 if(GetLastError() != ERROR_IO_PENDING) {
1692 RpcHttpAsyncData_Release(async_data);
1693 ERR("Request failed with error %d\n", GetLastError());
1694 return RPC_S_SERVER_UNAVAILABLE;
1697 res = WaitForMultipleObjects(2, handles, FALSE, DEFAULT_NCACN_HTTP_TIMEOUT);
1698 if(res != WAIT_OBJECT_0) {
1699 TRACE("Cancelled\n");
1700 return RPC_S_CALL_CANCELLED;
1703 if(async_data->async_result) {
1704 ERR("Async request failed with error %d\n", async_data->async_result);
1705 return RPC_S_SERVER_UNAVAILABLE;
1708 return RPC_S_OK;
1711 struct authinfo
1713 DWORD scheme;
1714 CredHandle cred;
1715 CtxtHandle ctx;
1716 TimeStamp exp;
1717 ULONG attr;
1718 ULONG max_token;
1719 char *data;
1720 unsigned int data_len;
1721 BOOL finished; /* finished authenticating */
1724 typedef struct _RpcConnection_http
1726 RpcConnection common;
1727 HINTERNET app_info;
1728 HINTERNET session;
1729 HINTERNET in_request;
1730 HINTERNET out_request;
1731 WCHAR *servername;
1732 HANDLE timer_cancelled;
1733 HANDLE cancel_event;
1734 DWORD last_sent_time;
1735 ULONG bytes_received;
1736 ULONG flow_control_mark; /* send a control packet to the server when this many bytes received */
1737 ULONG flow_control_increment; /* number of bytes to increment flow_control_mark by */
1738 UUID connection_uuid;
1739 UUID in_pipe_uuid;
1740 UUID out_pipe_uuid;
1741 RpcHttpAsyncData *async_data;
1742 } RpcConnection_http;
1744 static RpcConnection *rpcrt4_ncacn_http_alloc(void)
1746 RpcConnection_http *httpc;
1747 httpc = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*httpc));
1748 if (!httpc) return NULL;
1749 httpc->async_data = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(RpcHttpAsyncData));
1750 if (!httpc->async_data)
1752 HeapFree(GetProcessHeap(), 0, httpc);
1753 return NULL;
1755 TRACE("async data = %p\n", httpc->async_data);
1756 httpc->cancel_event = CreateEventW(NULL, FALSE, FALSE, NULL);
1757 httpc->async_data->refs = 1;
1758 httpc->async_data->inet_buffers.dwStructSize = sizeof(INTERNET_BUFFERSW);
1759 InitializeCriticalSection(&httpc->async_data->cs);
1760 httpc->async_data->cs.DebugInfo->Spare[0] = (DWORD_PTR)(__FILE__ ": RpcHttpAsyncData.cs");
1761 return &httpc->common;
1764 typedef struct _HttpTimerThreadData
1766 PVOID timer_param;
1767 DWORD *last_sent_time;
1768 HANDLE timer_cancelled;
1769 } HttpTimerThreadData;
1771 static VOID rpcrt4_http_keep_connection_active_timer_proc(PVOID param, BOOLEAN dummy)
1773 HINTERNET in_request = param;
1774 RpcPktHdr *idle_pkt;
1776 idle_pkt = RPCRT4_BuildHttpHeader(NDR_LOCAL_DATA_REPRESENTATION, 0x0001,
1777 0, 0);
1778 if (idle_pkt)
1780 DWORD bytes_written;
1781 InternetWriteFile(in_request, idle_pkt, idle_pkt->common.frag_len, &bytes_written);
1782 RPCRT4_FreeHeader(idle_pkt);
1786 static inline DWORD rpcrt4_http_timer_calc_timeout(DWORD *last_sent_time)
1788 DWORD cur_time = GetTickCount();
1789 DWORD cached_last_sent_time = *last_sent_time;
1790 return HTTP_IDLE_TIME - (cur_time - cached_last_sent_time > HTTP_IDLE_TIME ? 0 : cur_time - cached_last_sent_time);
1793 static DWORD CALLBACK rpcrt4_http_timer_thread(PVOID param)
1795 HttpTimerThreadData *data_in = param;
1796 HttpTimerThreadData data;
1797 DWORD timeout;
1799 data = *data_in;
1800 HeapFree(GetProcessHeap(), 0, data_in);
1802 for (timeout = HTTP_IDLE_TIME;
1803 WaitForSingleObject(data.timer_cancelled, timeout) == WAIT_TIMEOUT;
1804 timeout = rpcrt4_http_timer_calc_timeout(data.last_sent_time))
1806 /* are we too soon after last send? */
1807 if (GetTickCount() - *data.last_sent_time < HTTP_IDLE_TIME)
1808 continue;
1809 rpcrt4_http_keep_connection_active_timer_proc(data.timer_param, TRUE);
1812 CloseHandle(data.timer_cancelled);
1813 return 0;
1816 static VOID WINAPI rpcrt4_http_internet_callback(
1817 HINTERNET hInternet,
1818 DWORD_PTR dwContext,
1819 DWORD dwInternetStatus,
1820 LPVOID lpvStatusInformation,
1821 DWORD dwStatusInformationLength)
1823 RpcHttpAsyncData *async_data = (RpcHttpAsyncData *)dwContext;
1825 switch (dwInternetStatus)
1827 case INTERNET_STATUS_REQUEST_COMPLETE:
1828 TRACE("INTERNET_STATUS_REQUEST_COMPLETED\n");
1829 if (async_data)
1831 INTERNET_ASYNC_RESULT *async_result = lpvStatusInformation;
1833 async_data->async_result = async_result->dwResult ? ERROR_SUCCESS : async_result->dwError;
1834 SetEvent(async_data->completion_event);
1835 RpcHttpAsyncData_Release(async_data);
1837 break;
1841 static RPC_STATUS rpcrt4_http_check_response(HINTERNET hor)
1843 BOOL ret;
1844 DWORD status_code;
1845 DWORD size;
1846 DWORD index;
1847 WCHAR buf[32];
1848 WCHAR *status_text = buf;
1849 TRACE("\n");
1851 index = 0;
1852 size = sizeof(status_code);
1853 ret = HttpQueryInfoW(hor, HTTP_QUERY_STATUS_CODE|HTTP_QUERY_FLAG_NUMBER, &status_code, &size, &index);
1854 if (!ret)
1855 return GetLastError();
1856 if (status_code == HTTP_STATUS_OK)
1857 return RPC_S_OK;
1858 index = 0;
1859 size = sizeof(buf);
1860 ret = HttpQueryInfoW(hor, HTTP_QUERY_STATUS_TEXT, status_text, &size, &index);
1861 if (!ret && GetLastError() == ERROR_INSUFFICIENT_BUFFER)
1863 status_text = HeapAlloc(GetProcessHeap(), 0, size);
1864 ret = HttpQueryInfoW(hor, HTTP_QUERY_STATUS_TEXT, status_text, &size, &index);
1867 ERR("server returned: %d %s\n", status_code, ret ? debugstr_w(status_text) : "<status text unavailable>");
1868 if(status_text != buf) HeapFree(GetProcessHeap(), 0, status_text);
1870 if (status_code == HTTP_STATUS_DENIED)
1871 return ERROR_ACCESS_DENIED;
1872 return RPC_S_SERVER_UNAVAILABLE;
1875 static RPC_STATUS rpcrt4_http_internet_connect(RpcConnection_http *httpc)
1877 static const WCHAR wszUserAgent[] = {'M','S','R','P','C',0};
1878 LPWSTR proxy = NULL;
1879 LPWSTR user = NULL;
1880 LPWSTR password = NULL;
1881 LPWSTR servername = NULL;
1882 const WCHAR *option;
1883 INTERNET_PORT port;
1885 if (httpc->common.QOS &&
1886 (httpc->common.QOS->qos->AdditionalSecurityInfoType == RPC_C_AUTHN_INFO_TYPE_HTTP))
1888 const RPC_HTTP_TRANSPORT_CREDENTIALS_W *http_cred = httpc->common.QOS->qos->u.HttpCredentials;
1889 if (http_cred->TransportCredentials)
1891 WCHAR *p;
1892 const SEC_WINNT_AUTH_IDENTITY_W *cred = http_cred->TransportCredentials;
1893 ULONG len = cred->DomainLength + 1 + cred->UserLength;
1894 user = HeapAlloc(GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR));
1895 if (!user)
1896 return RPC_S_OUT_OF_RESOURCES;
1897 p = user;
1898 if (cred->DomainLength)
1900 memcpy(p, cred->Domain, cred->DomainLength * sizeof(WCHAR));
1901 p += cred->DomainLength;
1902 *p = '\\';
1903 p++;
1905 memcpy(p, cred->User, cred->UserLength * sizeof(WCHAR));
1906 p[cred->UserLength] = 0;
1908 password = RPCRT4_strndupW(cred->Password, cred->PasswordLength);
1912 for (option = httpc->common.NetworkOptions; option;
1913 option = (strchrW(option, ',') ? strchrW(option, ',')+1 : NULL))
1915 static const WCHAR wszRpcProxy[] = {'R','p','c','P','r','o','x','y','=',0};
1916 static const WCHAR wszHttpProxy[] = {'H','t','t','p','P','r','o','x','y','=',0};
1918 if (!strncmpiW(option, wszRpcProxy, sizeof(wszRpcProxy)/sizeof(wszRpcProxy[0])-1))
1920 const WCHAR *value_start = option + sizeof(wszRpcProxy)/sizeof(wszRpcProxy[0])-1;
1921 const WCHAR *value_end;
1922 const WCHAR *p;
1924 value_end = strchrW(option, ',');
1925 if (!value_end)
1926 value_end = value_start + strlenW(value_start);
1927 for (p = value_start; p < value_end; p++)
1928 if (*p == ':')
1930 port = atoiW(p+1);
1931 value_end = p;
1932 break;
1934 TRACE("RpcProxy value is %s\n", debugstr_wn(value_start, value_end-value_start));
1935 servername = RPCRT4_strndupW(value_start, value_end-value_start);
1937 else if (!strncmpiW(option, wszHttpProxy, sizeof(wszHttpProxy)/sizeof(wszHttpProxy[0])-1))
1939 const WCHAR *value_start = option + sizeof(wszHttpProxy)/sizeof(wszHttpProxy[0])-1;
1940 const WCHAR *value_end;
1942 value_end = strchrW(option, ',');
1943 if (!value_end)
1944 value_end = value_start + strlenW(value_start);
1945 TRACE("HttpProxy value is %s\n", debugstr_wn(value_start, value_end-value_start));
1946 proxy = RPCRT4_strndupW(value_start, value_end-value_start);
1948 else
1949 FIXME("unhandled option %s\n", debugstr_w(option));
1952 httpc->app_info = InternetOpenW(wszUserAgent, proxy ? INTERNET_OPEN_TYPE_PROXY : INTERNET_OPEN_TYPE_PRECONFIG,
1953 NULL, NULL, INTERNET_FLAG_ASYNC);
1954 if (!httpc->app_info)
1956 HeapFree(GetProcessHeap(), 0, password);
1957 HeapFree(GetProcessHeap(), 0, user);
1958 HeapFree(GetProcessHeap(), 0, proxy);
1959 HeapFree(GetProcessHeap(), 0, servername);
1960 ERR("InternetOpenW failed with error %d\n", GetLastError());
1961 return RPC_S_SERVER_UNAVAILABLE;
1963 InternetSetStatusCallbackW(httpc->app_info, rpcrt4_http_internet_callback);
1965 /* if no RpcProxy option specified, set the HTTP server address to the
1966 * RPC server address */
1967 if (!servername)
1969 servername = HeapAlloc(GetProcessHeap(), 0, (strlen(httpc->common.NetworkAddr) + 1)*sizeof(WCHAR));
1970 if (!servername)
1972 HeapFree(GetProcessHeap(), 0, password);
1973 HeapFree(GetProcessHeap(), 0, user);
1974 HeapFree(GetProcessHeap(), 0, proxy);
1975 return RPC_S_OUT_OF_RESOURCES;
1977 MultiByteToWideChar(CP_ACP, 0, httpc->common.NetworkAddr, -1, servername, strlen(httpc->common.NetworkAddr) + 1);
1980 port = (httpc->common.QOS &&
1981 (httpc->common.QOS->qos->AdditionalSecurityInfoType == RPC_C_AUTHN_INFO_TYPE_HTTP) &&
1982 (httpc->common.QOS->qos->u.HttpCredentials->Flags & RPC_C_HTTP_FLAG_USE_SSL)) ?
1983 INTERNET_DEFAULT_HTTPS_PORT : INTERNET_DEFAULT_HTTP_PORT;
1985 httpc->session = InternetConnectW(httpc->app_info, servername, port, user, password,
1986 INTERNET_SERVICE_HTTP, 0, 0);
1988 HeapFree(GetProcessHeap(), 0, password);
1989 HeapFree(GetProcessHeap(), 0, user);
1990 HeapFree(GetProcessHeap(), 0, proxy);
1992 if (!httpc->session)
1994 ERR("InternetConnectW failed with error %d\n", GetLastError());
1995 HeapFree(GetProcessHeap(), 0, servername);
1996 return RPC_S_SERVER_UNAVAILABLE;
1998 httpc->servername = servername;
1999 return RPC_S_OK;
2002 static int rpcrt4_http_async_read(HINTERNET req, RpcHttpAsyncData *async_data, HANDLE cancel_event,
2003 void *buffer, unsigned int count)
2005 char *buf = buffer;
2006 BOOL ret;
2007 unsigned int bytes_left = count;
2008 RPC_STATUS status = RPC_S_OK;
2010 async_data->inet_buffers.lpvBuffer = HeapAlloc(GetProcessHeap(), 0, count);
2012 while (bytes_left)
2014 async_data->inet_buffers.dwBufferLength = bytes_left;
2015 prepare_async_request(async_data);
2016 ret = InternetReadFileExW(req, &async_data->inet_buffers, IRF_ASYNC, 0);
2017 status = wait_async_request(async_data, ret, cancel_event);
2018 if (status != RPC_S_OK)
2020 if (status == RPC_S_CALL_CANCELLED)
2021 TRACE("call cancelled\n");
2022 break;
2025 if (!async_data->inet_buffers.dwBufferLength)
2026 break;
2027 memcpy(buf, async_data->inet_buffers.lpvBuffer,
2028 async_data->inet_buffers.dwBufferLength);
2030 bytes_left -= async_data->inet_buffers.dwBufferLength;
2031 buf += async_data->inet_buffers.dwBufferLength;
2034 HeapFree(GetProcessHeap(), 0, async_data->inet_buffers.lpvBuffer);
2035 async_data->inet_buffers.lpvBuffer = NULL;
2037 TRACE("%p %p %u -> %u\n", req, buffer, count, status);
2038 return status == RPC_S_OK ? count : -1;
2041 static RPC_STATUS send_echo_request(HINTERNET req, RpcHttpAsyncData *async_data, HANDLE cancel_event)
2043 BYTE buf[20];
2044 BOOL ret;
2045 RPC_STATUS status;
2047 TRACE("sending echo request to server\n");
2049 prepare_async_request(async_data);
2050 ret = HttpSendRequestW(req, NULL, 0, NULL, 0);
2051 status = wait_async_request(async_data, ret, cancel_event);
2052 if (status != RPC_S_OK) return status;
2054 status = rpcrt4_http_check_response(req);
2055 if (status != RPC_S_OK) return status;
2057 rpcrt4_http_async_read(req, async_data, cancel_event, buf, sizeof(buf));
2058 /* FIXME: do something with retrieved data */
2060 return RPC_S_OK;
2063 static RPC_STATUS insert_content_length_header(HINTERNET request, DWORD len)
2065 static const WCHAR fmtW[] =
2066 {'C','o','n','t','e','n','t','-','L','e','n','g','t','h',':',' ','%','u','\r','\n',0};
2067 WCHAR header[sizeof(fmtW) / sizeof(fmtW[0]) + 10];
2069 sprintfW(header, fmtW, len);
2070 if ((HttpAddRequestHeadersW(request, header, -1, HTTP_ADDREQ_FLAG_REPLACE | HTTP_ADDREQ_FLAG_ADD))) return RPC_S_OK;
2071 return RPC_S_SERVER_UNAVAILABLE;
2074 /* prepare the in pipe for use by RPC packets */
2075 static RPC_STATUS rpcrt4_http_prepare_in_pipe(HINTERNET in_request, RpcHttpAsyncData *async_data, HANDLE cancel_event,
2076 const UUID *connection_uuid, const UUID *in_pipe_uuid,
2077 const UUID *association_uuid, BOOL authorized)
2079 BOOL ret;
2080 RPC_STATUS status;
2081 RpcPktHdr *hdr;
2082 INTERNET_BUFFERSW buffers_in;
2083 DWORD bytes_written;
2085 if (!authorized)
2087 /* ask wininet to authorize, if necessary */
2088 status = send_echo_request(in_request, async_data, cancel_event);
2089 if (status != RPC_S_OK) return status;
2091 memset(&buffers_in, 0, sizeof(buffers_in));
2092 buffers_in.dwStructSize = sizeof(buffers_in);
2093 /* FIXME: get this from the registry */
2094 buffers_in.dwBufferTotal = 1024 * 1024 * 1024; /* 1Gb */
2095 status = insert_content_length_header(in_request, buffers_in.dwBufferTotal);
2096 if (status != RPC_S_OK) return status;
2098 prepare_async_request(async_data);
2099 ret = HttpSendRequestExW(in_request, &buffers_in, NULL, 0, 0);
2100 status = wait_async_request(async_data, ret, cancel_event);
2101 if (status != RPC_S_OK) return status;
2103 TRACE("sending HTTP connect header to server\n");
2104 hdr = RPCRT4_BuildHttpConnectHeader(FALSE, connection_uuid, in_pipe_uuid, association_uuid);
2105 if (!hdr) return RPC_S_OUT_OF_RESOURCES;
2106 ret = InternetWriteFile(in_request, hdr, hdr->common.frag_len, &bytes_written);
2107 RPCRT4_FreeHeader(hdr);
2108 if (!ret)
2110 ERR("InternetWriteFile failed with error %d\n", GetLastError());
2111 return RPC_S_SERVER_UNAVAILABLE;
2114 return RPC_S_OK;
2117 static RPC_STATUS rpcrt4_http_read_http_packet(HINTERNET request, RpcHttpAsyncData *async_data,
2118 HANDLE cancel_event, RpcPktHdr *hdr, BYTE **data)
2120 unsigned short data_len;
2121 unsigned int size;
2123 if (rpcrt4_http_async_read(request, async_data, cancel_event, hdr, sizeof(hdr->common)) < 0)
2124 return RPC_S_SERVER_UNAVAILABLE;
2125 if (hdr->common.ptype != PKT_HTTP || hdr->common.frag_len < sizeof(hdr->http))
2127 ERR("wrong packet type received %d or wrong frag_len %d\n",
2128 hdr->common.ptype, hdr->common.frag_len);
2129 return RPC_S_PROTOCOL_ERROR;
2132 size = sizeof(hdr->http) - sizeof(hdr->common);
2133 if (rpcrt4_http_async_read(request, async_data, cancel_event, &hdr->common + 1, size) < 0)
2134 return RPC_S_SERVER_UNAVAILABLE;
2136 data_len = hdr->common.frag_len - sizeof(hdr->http);
2137 if (data_len)
2139 *data = HeapAlloc(GetProcessHeap(), 0, data_len);
2140 if (!*data)
2141 return RPC_S_OUT_OF_RESOURCES;
2142 if (rpcrt4_http_async_read(request, async_data, cancel_event, *data, data_len) < 0)
2144 HeapFree(GetProcessHeap(), 0, *data);
2145 return RPC_S_SERVER_UNAVAILABLE;
2148 else
2149 *data = NULL;
2151 if (!RPCRT4_IsValidHttpPacket(hdr, *data, data_len))
2153 ERR("invalid http packet\n");
2154 HeapFree(GetProcessHeap(), 0, *data);
2155 return RPC_S_PROTOCOL_ERROR;
2158 return RPC_S_OK;
2161 /* prepare the out pipe for use by RPC packets */
2162 static RPC_STATUS rpcrt4_http_prepare_out_pipe(HINTERNET out_request, RpcHttpAsyncData *async_data,
2163 HANDLE cancel_event, const UUID *connection_uuid,
2164 const UUID *out_pipe_uuid, ULONG *flow_control_increment,
2165 BOOL authorized)
2167 BOOL ret;
2168 RPC_STATUS status;
2169 RpcPktHdr *hdr;
2170 BYTE *data_from_server;
2171 RpcPktHdr pkt_from_server;
2172 ULONG field1, field3;
2173 BYTE buf[20];
2175 if (!authorized)
2177 /* ask wininet to authorize, if necessary */
2178 status = send_echo_request(out_request, async_data, cancel_event);
2179 if (status != RPC_S_OK) return status;
2181 else
2182 rpcrt4_http_async_read(out_request, async_data, cancel_event, buf, sizeof(buf));
2184 hdr = RPCRT4_BuildHttpConnectHeader(TRUE, connection_uuid, out_pipe_uuid, NULL);
2185 if (!hdr) return RPC_S_OUT_OF_RESOURCES;
2187 status = insert_content_length_header(out_request, hdr->common.frag_len);
2188 if (status != RPC_S_OK)
2190 RPCRT4_FreeHeader(hdr);
2191 return status;
2194 TRACE("sending HTTP connect header to server\n");
2195 prepare_async_request(async_data);
2196 ret = HttpSendRequestW(out_request, NULL, 0, hdr, hdr->common.frag_len);
2197 status = wait_async_request(async_data, ret, cancel_event);
2198 RPCRT4_FreeHeader(hdr);
2199 if (status != RPC_S_OK) return status;
2201 status = rpcrt4_http_check_response(out_request);
2202 if (status != RPC_S_OK) return status;
2204 status = rpcrt4_http_read_http_packet(out_request, async_data, cancel_event,
2205 &pkt_from_server, &data_from_server);
2206 if (status != RPC_S_OK) return status;
2207 status = RPCRT4_ParseHttpPrepareHeader1(&pkt_from_server, data_from_server,
2208 &field1);
2209 HeapFree(GetProcessHeap(), 0, data_from_server);
2210 if (status != RPC_S_OK) return status;
2211 TRACE("received (%d) from first prepare header\n", field1);
2213 for (;;)
2215 status = rpcrt4_http_read_http_packet(out_request, async_data, cancel_event,
2216 &pkt_from_server, &data_from_server);
2217 if (status != RPC_S_OK) return status;
2218 if (pkt_from_server.http.flags != 0x0001) break;
2220 TRACE("http idle packet, waiting for real packet\n");
2221 HeapFree(GetProcessHeap(), 0, data_from_server);
2222 if (pkt_from_server.http.num_data_items != 0)
2224 ERR("HTTP idle packet should have no data items instead of %d\n",
2225 pkt_from_server.http.num_data_items);
2226 return RPC_S_PROTOCOL_ERROR;
2229 status = RPCRT4_ParseHttpPrepareHeader2(&pkt_from_server, data_from_server,
2230 &field1, flow_control_increment,
2231 &field3);
2232 HeapFree(GetProcessHeap(), 0, data_from_server);
2233 if (status != RPC_S_OK) return status;
2234 TRACE("received (0x%08x 0x%08x %d) from second prepare header\n", field1, *flow_control_increment, field3);
2236 return RPC_S_OK;
2239 static UINT encode_base64(const char *bin, unsigned int len, WCHAR *base64)
2241 static const char enc[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
2242 UINT i = 0, x;
2244 while (len > 0)
2246 /* first 6 bits, all from bin[0] */
2247 base64[i++] = enc[(bin[0] & 0xfc) >> 2];
2248 x = (bin[0] & 3) << 4;
2250 /* next 6 bits, 2 from bin[0] and 4 from bin[1] */
2251 if (len == 1)
2253 base64[i++] = enc[x];
2254 base64[i++] = '=';
2255 base64[i++] = '=';
2256 break;
2258 base64[i++] = enc[x | ((bin[1] & 0xf0) >> 4)];
2259 x = (bin[1] & 0x0f) << 2;
2261 /* next 6 bits 4 from bin[1] and 2 from bin[2] */
2262 if (len == 2)
2264 base64[i++] = enc[x];
2265 base64[i++] = '=';
2266 break;
2268 base64[i++] = enc[x | ((bin[2] & 0xc0) >> 6)];
2270 /* last 6 bits, all from bin [2] */
2271 base64[i++] = enc[bin[2] & 0x3f];
2272 bin += 3;
2273 len -= 3;
2275 base64[i] = 0;
2276 return i;
2279 static inline char decode_char( WCHAR c )
2281 if (c >= 'A' && c <= 'Z') return c - 'A';
2282 if (c >= 'a' && c <= 'z') return c - 'a' + 26;
2283 if (c >= '0' && c <= '9') return c - '0' + 52;
2284 if (c == '+') return 62;
2285 if (c == '/') return 63;
2286 return 64;
2289 static unsigned int decode_base64( const WCHAR *base64, unsigned int len, char *buf )
2291 unsigned int i = 0;
2292 char c0, c1, c2, c3;
2293 const WCHAR *p = base64;
2295 while (len > 4)
2297 if ((c0 = decode_char( p[0] )) > 63) return 0;
2298 if ((c1 = decode_char( p[1] )) > 63) return 0;
2299 if ((c2 = decode_char( p[2] )) > 63) return 0;
2300 if ((c3 = decode_char( p[3] )) > 63) return 0;
2302 if (buf)
2304 buf[i + 0] = (c0 << 2) | (c1 >> 4);
2305 buf[i + 1] = (c1 << 4) | (c2 >> 2);
2306 buf[i + 2] = (c2 << 6) | c3;
2308 len -= 4;
2309 i += 3;
2310 p += 4;
2312 if (p[2] == '=')
2314 if ((c0 = decode_char( p[0] )) > 63) return 0;
2315 if ((c1 = decode_char( p[1] )) > 63) return 0;
2317 if (buf) buf[i] = (c0 << 2) | (c1 >> 4);
2318 i++;
2320 else if (p[3] == '=')
2322 if ((c0 = decode_char( p[0] )) > 63) return 0;
2323 if ((c1 = decode_char( p[1] )) > 63) return 0;
2324 if ((c2 = decode_char( p[2] )) > 63) return 0;
2326 if (buf)
2328 buf[i + 0] = (c0 << 2) | (c1 >> 4);
2329 buf[i + 1] = (c1 << 4) | (c2 >> 2);
2331 i += 2;
2333 else
2335 if ((c0 = decode_char( p[0] )) > 63) return 0;
2336 if ((c1 = decode_char( p[1] )) > 63) return 0;
2337 if ((c2 = decode_char( p[2] )) > 63) return 0;
2338 if ((c3 = decode_char( p[3] )) > 63) return 0;
2340 if (buf)
2342 buf[i + 0] = (c0 << 2) | (c1 >> 4);
2343 buf[i + 1] = (c1 << 4) | (c2 >> 2);
2344 buf[i + 2] = (c2 << 6) | c3;
2346 i += 3;
2348 return i;
2351 static struct authinfo *alloc_authinfo(void)
2353 struct authinfo *ret;
2355 if (!(ret = HeapAlloc(GetProcessHeap(), 0, sizeof(*ret) ))) return NULL;
2357 SecInvalidateHandle(&ret->cred);
2358 SecInvalidateHandle(&ret->ctx);
2359 memset(&ret->exp, 0, sizeof(ret->exp));
2360 ret->scheme = 0;
2361 ret->attr = 0;
2362 ret->max_token = 0;
2363 ret->data = NULL;
2364 ret->data_len = 0;
2365 ret->finished = FALSE;
2366 return ret;
2369 static void destroy_authinfo(struct authinfo *info)
2371 if (!info) return;
2373 if (SecIsValidHandle(&info->ctx))
2374 DeleteSecurityContext(&info->ctx);
2375 if (SecIsValidHandle(&info->cred))
2376 FreeCredentialsHandle(&info->cred);
2378 HeapFree(GetProcessHeap(), 0, info->data);
2379 HeapFree(GetProcessHeap(), 0, info);
2382 static const WCHAR basicW[] = {'B','a','s','i','c',0};
2383 static const WCHAR ntlmW[] = {'N','T','L','M',0};
2384 static const WCHAR passportW[] = {'P','a','s','s','p','o','r','t',0};
2385 static const WCHAR digestW[] = {'D','i','g','e','s','t',0};
2386 static const WCHAR negotiateW[] = {'N','e','g','o','t','i','a','t','e',0};
2388 static const struct
2390 const WCHAR *str;
2391 unsigned int len;
2392 DWORD scheme;
2394 auth_schemes[] =
2396 { basicW, ARRAYSIZE(basicW) - 1, RPC_C_HTTP_AUTHN_SCHEME_BASIC },
2397 { ntlmW, ARRAYSIZE(ntlmW) - 1, RPC_C_HTTP_AUTHN_SCHEME_NTLM },
2398 { passportW, ARRAYSIZE(passportW) - 1, RPC_C_HTTP_AUTHN_SCHEME_PASSPORT },
2399 { digestW, ARRAYSIZE(digestW) - 1, RPC_C_HTTP_AUTHN_SCHEME_DIGEST },
2400 { negotiateW, ARRAYSIZE(negotiateW) - 1, RPC_C_HTTP_AUTHN_SCHEME_NEGOTIATE }
2402 static const unsigned int num_auth_schemes = sizeof(auth_schemes)/sizeof(auth_schemes[0]);
2404 static DWORD auth_scheme_from_header( const WCHAR *header )
2406 unsigned int i;
2407 for (i = 0; i < num_auth_schemes; i++)
2409 if (!strncmpiW( header, auth_schemes[i].str, auth_schemes[i].len ) &&
2410 (header[auth_schemes[i].len] == ' ' || !header[auth_schemes[i].len])) return auth_schemes[i].scheme;
2412 return 0;
2415 static BOOL get_authvalue(HINTERNET request, DWORD scheme, WCHAR *buffer, DWORD buflen)
2417 DWORD len, index = 0;
2418 for (;;)
2420 len = buflen;
2421 if (!HttpQueryInfoW(request, HTTP_QUERY_WWW_AUTHENTICATE, buffer, &len, &index)) return FALSE;
2422 if (auth_scheme_from_header(buffer) == scheme) break;
2424 return TRUE;
2427 static RPC_STATUS do_authorization(HINTERNET request, SEC_WCHAR *servername,
2428 const RPC_HTTP_TRANSPORT_CREDENTIALS_W *creds, struct authinfo **auth_ptr)
2430 struct authinfo *info = *auth_ptr;
2431 SEC_WINNT_AUTH_IDENTITY_W *id = creds->TransportCredentials;
2432 RPC_STATUS status = RPC_S_SERVER_UNAVAILABLE;
2434 if ((!info && !(info = alloc_authinfo()))) return RPC_S_SERVER_UNAVAILABLE;
2436 switch (creds->AuthnSchemes[0])
2438 case RPC_C_HTTP_AUTHN_SCHEME_BASIC:
2440 int userlen = WideCharToMultiByte(CP_UTF8, 0, id->User, id->UserLength, NULL, 0, NULL, NULL);
2441 int passlen = WideCharToMultiByte(CP_UTF8, 0, id->Password, id->PasswordLength, NULL, 0, NULL, NULL);
2443 info->data_len = userlen + passlen + 1;
2444 if (!(info->data = HeapAlloc(GetProcessHeap(), 0, info->data_len)))
2446 status = RPC_S_OUT_OF_MEMORY;
2447 break;
2449 WideCharToMultiByte(CP_UTF8, 0, id->User, id->UserLength, info->data, userlen, NULL, NULL);
2450 info->data[userlen] = ':';
2451 WideCharToMultiByte(CP_UTF8, 0, id->Password, id->PasswordLength, info->data + userlen + 1, passlen, NULL, NULL);
2453 info->scheme = RPC_C_HTTP_AUTHN_SCHEME_BASIC;
2454 info->finished = TRUE;
2455 status = RPC_S_OK;
2456 break;
2458 case RPC_C_HTTP_AUTHN_SCHEME_NTLM:
2459 case RPC_C_HTTP_AUTHN_SCHEME_NEGOTIATE:
2462 static SEC_WCHAR ntlmW[] = {'N','T','L','M',0}, negotiateW[] = {'N','e','g','o','t','i','a','t','e',0};
2463 SECURITY_STATUS ret;
2464 SecBufferDesc out_desc, in_desc;
2465 SecBuffer out, in;
2466 ULONG flags = ISC_REQ_CONNECTION|ISC_REQ_USE_DCE_STYLE|ISC_REQ_MUTUAL_AUTH|ISC_REQ_DELEGATE;
2467 SEC_WCHAR *scheme;
2468 int scheme_len;
2469 const WCHAR *p;
2470 WCHAR auth_value[2048];
2471 DWORD size = sizeof(auth_value);
2472 BOOL first = FALSE;
2474 if (creds->AuthnSchemes[0] == RPC_C_HTTP_AUTHN_SCHEME_NTLM) scheme = ntlmW;
2475 else scheme = negotiateW;
2476 scheme_len = strlenW( scheme );
2478 if (!*auth_ptr)
2480 TimeStamp exp;
2481 SecPkgInfoW *pkg_info;
2483 ret = AcquireCredentialsHandleW(NULL, scheme, SECPKG_CRED_OUTBOUND, NULL, id, NULL, NULL, &info->cred, &exp);
2484 if (ret != SEC_E_OK) break;
2486 ret = QuerySecurityPackageInfoW(scheme, &pkg_info);
2487 if (ret != SEC_E_OK) break;
2489 info->max_token = pkg_info->cbMaxToken;
2490 FreeContextBuffer(pkg_info);
2491 first = TRUE;
2493 else
2495 if (info->finished || !get_authvalue(request, creds->AuthnSchemes[0], auth_value, size)) break;
2496 if (auth_scheme_from_header(auth_value) != info->scheme)
2498 ERR("authentication scheme changed\n");
2499 break;
2502 in.BufferType = SECBUFFER_TOKEN;
2503 in.cbBuffer = 0;
2504 in.pvBuffer = NULL;
2506 in_desc.ulVersion = 0;
2507 in_desc.cBuffers = 1;
2508 in_desc.pBuffers = &in;
2510 p = auth_value + scheme_len;
2511 if (!first && *p == ' ')
2513 int len = strlenW(++p);
2514 in.cbBuffer = decode_base64(p, len, NULL);
2515 if (!(in.pvBuffer = HeapAlloc(GetProcessHeap(), 0, in.cbBuffer))) break;
2516 decode_base64(p, len, in.pvBuffer);
2518 out.BufferType = SECBUFFER_TOKEN;
2519 out.cbBuffer = info->max_token;
2520 if (!(out.pvBuffer = HeapAlloc(GetProcessHeap(), 0, out.cbBuffer)))
2522 HeapFree(GetProcessHeap(), 0, in.pvBuffer);
2523 break;
2525 out_desc.ulVersion = 0;
2526 out_desc.cBuffers = 1;
2527 out_desc.pBuffers = &out;
2529 ret = InitializeSecurityContextW(first ? &info->cred : NULL, first ? NULL : &info->ctx,
2530 first ? servername : NULL, flags, 0, SECURITY_NETWORK_DREP,
2531 in.pvBuffer ? &in_desc : NULL, 0, &info->ctx, &out_desc,
2532 &info->attr, &info->exp);
2533 HeapFree(GetProcessHeap(), 0, in.pvBuffer);
2534 if (ret == SEC_E_OK)
2536 HeapFree(GetProcessHeap(), 0, info->data);
2537 info->data = out.pvBuffer;
2538 info->data_len = out.cbBuffer;
2539 info->finished = TRUE;
2540 TRACE("sending last auth packet\n");
2541 status = RPC_S_OK;
2543 else if (ret == SEC_I_CONTINUE_NEEDED)
2545 HeapFree(GetProcessHeap(), 0, info->data);
2546 info->data = out.pvBuffer;
2547 info->data_len = out.cbBuffer;
2548 TRACE("sending next auth packet\n");
2549 status = RPC_S_OK;
2551 else
2553 ERR("InitializeSecurityContextW failed with error 0x%08x\n", ret);
2554 HeapFree(GetProcessHeap(), 0, out.pvBuffer);
2555 break;
2557 info->scheme = creds->AuthnSchemes[0];
2558 break;
2560 default:
2561 FIXME("scheme %u not supported\n", creds->AuthnSchemes[0]);
2562 break;
2565 if (status != RPC_S_OK)
2567 destroy_authinfo(info);
2568 *auth_ptr = NULL;
2569 return status;
2571 *auth_ptr = info;
2572 return RPC_S_OK;
2575 static RPC_STATUS insert_authorization_header(HINTERNET request, ULONG scheme, char *data, int data_len)
2577 static const WCHAR authW[] = {'A','u','t','h','o','r','i','z','a','t','i','o','n',':',' '};
2578 static const WCHAR basicW[] = {'B','a','s','i','c',' '};
2579 static const WCHAR negotiateW[] = {'N','e','g','o','t','i','a','t','e',' '};
2580 static const WCHAR ntlmW[] = {'N','T','L','M',' '};
2581 int scheme_len, auth_len = sizeof(authW) / sizeof(authW[0]), len = ((data_len + 2) * 4) / 3;
2582 const WCHAR *scheme_str;
2583 WCHAR *header, *ptr;
2584 RPC_STATUS status = RPC_S_SERVER_UNAVAILABLE;
2586 switch (scheme)
2588 case RPC_C_HTTP_AUTHN_SCHEME_BASIC:
2589 scheme_str = basicW;
2590 scheme_len = sizeof(basicW) / sizeof(basicW[0]);
2591 break;
2592 case RPC_C_HTTP_AUTHN_SCHEME_NEGOTIATE:
2593 scheme_str = negotiateW;
2594 scheme_len = sizeof(negotiateW) / sizeof(negotiateW[0]);
2595 break;
2596 case RPC_C_HTTP_AUTHN_SCHEME_NTLM:
2597 scheme_str = ntlmW;
2598 scheme_len = sizeof(ntlmW) / sizeof(ntlmW[0]);
2599 break;
2600 default:
2601 ERR("unknown scheme %u\n", scheme);
2602 return RPC_S_SERVER_UNAVAILABLE;
2604 if ((header = HeapAlloc(GetProcessHeap(), 0, (auth_len + scheme_len + len + 2) * sizeof(WCHAR))))
2606 memcpy(header, authW, auth_len * sizeof(WCHAR));
2607 ptr = header + auth_len;
2608 memcpy(ptr, scheme_str, scheme_len * sizeof(WCHAR));
2609 ptr += scheme_len;
2610 len = encode_base64(data, data_len, ptr);
2611 ptr[len++] = '\r';
2612 ptr[len++] = '\n';
2613 ptr[len] = 0;
2614 if (HttpAddRequestHeadersW(request, header, -1, HTTP_ADDREQ_FLAG_ADD|HTTP_ADDREQ_FLAG_REPLACE))
2615 status = RPC_S_OK;
2616 HeapFree(GetProcessHeap(), 0, header);
2618 return status;
2621 static void drain_content(HINTERNET request, RpcHttpAsyncData *async_data, HANDLE cancel_event)
2623 DWORD count, len = 0, size = sizeof(len);
2624 char buf[2048];
2626 HttpQueryInfoW(request, HTTP_QUERY_FLAG_NUMBER|HTTP_QUERY_CONTENT_LENGTH, &len, &size, NULL);
2627 if (!len) return;
2628 for (;;)
2630 count = min(sizeof(buf), len);
2631 if (rpcrt4_http_async_read(request, async_data, cancel_event, buf, count) <= 0) return;
2632 len -= count;
2636 static RPC_STATUS authorize_request(RpcConnection_http *httpc, HINTERNET request)
2638 static const WCHAR authW[] = {'A','u','t','h','o','r','i','z','a','t','i','o','n',':','\r','\n',0};
2639 struct authinfo *info = NULL;
2640 RPC_STATUS status;
2641 BOOL ret;
2643 for (;;)
2645 status = do_authorization(request, httpc->servername, httpc->common.QOS->qos->u.HttpCredentials, &info);
2646 if (status != RPC_S_OK) break;
2648 status = insert_authorization_header(request, info->scheme, info->data, info->data_len);
2649 if (status != RPC_S_OK) break;
2651 prepare_async_request(httpc->async_data);
2652 ret = HttpSendRequestW(request, NULL, 0, NULL, 0);
2653 status = wait_async_request(httpc->async_data, ret, httpc->cancel_event);
2654 if (status != RPC_S_OK || info->finished) break;
2656 status = rpcrt4_http_check_response(request);
2657 if (status != RPC_S_OK && status != ERROR_ACCESS_DENIED) break;
2658 drain_content(request, httpc->async_data, httpc->cancel_event);
2661 if (info->scheme != RPC_C_HTTP_AUTHN_SCHEME_BASIC)
2662 HttpAddRequestHeadersW(request, authW, -1, HTTP_ADDREQ_FLAG_REPLACE | HTTP_ADDREQ_FLAG_ADD);
2664 destroy_authinfo(info);
2665 return status;
2668 static BOOL has_credentials(RpcConnection_http *httpc)
2670 RPC_HTTP_TRANSPORT_CREDENTIALS_W *creds;
2671 SEC_WINNT_AUTH_IDENTITY_W *id;
2673 if (!httpc->common.QOS || httpc->common.QOS->qos->AdditionalSecurityInfoType != RPC_C_AUTHN_INFO_TYPE_HTTP)
2674 return FALSE;
2676 creds = httpc->common.QOS->qos->u.HttpCredentials;
2677 if (creds->AuthenticationTarget != RPC_C_HTTP_AUTHN_TARGET_SERVER || !creds->NumberOfAuthnSchemes)
2678 return FALSE;
2680 id = creds->TransportCredentials;
2681 if (!id || !id->User || !id->Password) return FALSE;
2683 return TRUE;
2686 static BOOL is_secure(RpcConnection_http *httpc)
2688 return httpc->common.QOS &&
2689 (httpc->common.QOS->qos->AdditionalSecurityInfoType == RPC_C_AUTHN_INFO_TYPE_HTTP) &&
2690 (httpc->common.QOS->qos->u.HttpCredentials->Flags & RPC_C_HTTP_FLAG_USE_SSL);
2693 static RPC_STATUS set_auth_cookie(RpcConnection_http *httpc, const WCHAR *value)
2695 static WCHAR httpW[] = {'h','t','t','p',0};
2696 static WCHAR httpsW[] = {'h','t','t','p','s',0};
2697 URL_COMPONENTSW uc;
2698 DWORD len;
2699 WCHAR *url;
2700 BOOL ret;
2702 if (!value) return RPC_S_OK;
2704 uc.dwStructSize = sizeof(uc);
2705 uc.lpszScheme = is_secure(httpc) ? httpsW : httpW;
2706 uc.dwSchemeLength = 0;
2707 uc.lpszHostName = httpc->servername;
2708 uc.dwHostNameLength = 0;
2709 uc.nPort = 0;
2710 uc.lpszUserName = NULL;
2711 uc.dwUserNameLength = 0;
2712 uc.lpszPassword = NULL;
2713 uc.dwPasswordLength = 0;
2714 uc.lpszUrlPath = NULL;
2715 uc.dwUrlPathLength = 0;
2716 uc.lpszExtraInfo = NULL;
2717 uc.dwExtraInfoLength = 0;
2719 if (!InternetCreateUrlW(&uc, 0, NULL, &len) && (GetLastError() != ERROR_INSUFFICIENT_BUFFER))
2720 return RPC_S_SERVER_UNAVAILABLE;
2722 if (!(url = HeapAlloc(GetProcessHeap(), 0, len))) return RPC_S_OUT_OF_MEMORY;
2724 len = len / sizeof(WCHAR) - 1;
2725 if (!InternetCreateUrlW(&uc, 0, url, &len))
2727 HeapFree(GetProcessHeap(), 0, url);
2728 return RPC_S_SERVER_UNAVAILABLE;
2731 ret = InternetSetCookieW(url, NULL, value);
2732 HeapFree(GetProcessHeap(), 0, url);
2733 if (!ret) return RPC_S_SERVER_UNAVAILABLE;
2735 return RPC_S_OK;
2738 static RPC_STATUS rpcrt4_ncacn_http_open(RpcConnection* Connection)
2740 RpcConnection_http *httpc = (RpcConnection_http *)Connection;
2741 static const WCHAR wszVerbIn[] = {'R','P','C','_','I','N','_','D','A','T','A',0};
2742 static const WCHAR wszVerbOut[] = {'R','P','C','_','O','U','T','_','D','A','T','A',0};
2743 static const WCHAR wszRpcProxyPrefix[] = {'/','r','p','c','/','r','p','c','p','r','o','x','y','.','d','l','l','?',0};
2744 static const WCHAR wszColon[] = {':',0};
2745 static const WCHAR wszAcceptType[] = {'a','p','p','l','i','c','a','t','i','o','n','/','r','p','c',0};
2746 LPCWSTR wszAcceptTypes[] = { wszAcceptType, NULL };
2747 DWORD flags;
2748 WCHAR *url;
2749 RPC_STATUS status;
2750 BOOL secure, credentials;
2751 HttpTimerThreadData *timer_data;
2752 HANDLE thread;
2754 TRACE("(%s, %s)\n", Connection->NetworkAddr, Connection->Endpoint);
2756 if (Connection->server)
2758 ERR("ncacn_http servers not supported yet\n");
2759 return RPC_S_SERVER_UNAVAILABLE;
2762 if (httpc->in_request)
2763 return RPC_S_OK;
2765 httpc->async_data->completion_event = CreateEventW(NULL, FALSE, FALSE, NULL);
2767 UuidCreate(&httpc->connection_uuid);
2768 UuidCreate(&httpc->in_pipe_uuid);
2769 UuidCreate(&httpc->out_pipe_uuid);
2771 status = rpcrt4_http_internet_connect(httpc);
2772 if (status != RPC_S_OK)
2773 return status;
2775 url = HeapAlloc(GetProcessHeap(), 0, sizeof(wszRpcProxyPrefix) + (strlen(Connection->NetworkAddr) + 1 + strlen(Connection->Endpoint))*sizeof(WCHAR));
2776 if (!url)
2777 return RPC_S_OUT_OF_MEMORY;
2778 memcpy(url, wszRpcProxyPrefix, sizeof(wszRpcProxyPrefix));
2779 MultiByteToWideChar(CP_ACP, 0, Connection->NetworkAddr, -1, url+sizeof(wszRpcProxyPrefix)/sizeof(wszRpcProxyPrefix[0])-1, strlen(Connection->NetworkAddr)+1);
2780 strcatW(url, wszColon);
2781 MultiByteToWideChar(CP_ACP, 0, Connection->Endpoint, -1, url+strlenW(url), strlen(Connection->Endpoint)+1);
2783 secure = is_secure(httpc);
2784 credentials = has_credentials(httpc);
2786 flags = INTERNET_FLAG_KEEP_CONNECTION | INTERNET_FLAG_PRAGMA_NOCACHE | INTERNET_FLAG_NO_CACHE_WRITE |
2787 INTERNET_FLAG_NO_AUTO_REDIRECT;
2788 if (secure) flags |= INTERNET_FLAG_SECURE;
2789 if (credentials) flags |= INTERNET_FLAG_NO_AUTH;
2791 status = set_auth_cookie(httpc, Connection->CookieAuth);
2792 if (status != RPC_S_OK)
2794 HeapFree(GetProcessHeap(), 0, url);
2795 return status;
2797 httpc->in_request = HttpOpenRequestW(httpc->session, wszVerbIn, url, NULL, NULL, wszAcceptTypes,
2798 flags, (DWORD_PTR)httpc->async_data);
2799 if (!httpc->in_request)
2801 ERR("HttpOpenRequestW failed with error %d\n", GetLastError());
2802 HeapFree(GetProcessHeap(), 0, url);
2803 return RPC_S_SERVER_UNAVAILABLE;
2806 if (credentials)
2808 status = authorize_request(httpc, httpc->in_request);
2809 if (status != RPC_S_OK)
2811 HeapFree(GetProcessHeap(), 0, url);
2812 return status;
2814 status = rpcrt4_http_check_response(httpc->in_request);
2815 if (status != RPC_S_OK)
2817 HeapFree(GetProcessHeap(), 0, url);
2818 return status;
2820 drain_content(httpc->in_request, httpc->async_data, httpc->cancel_event);
2823 httpc->out_request = HttpOpenRequestW(httpc->session, wszVerbOut, url, NULL, NULL, wszAcceptTypes,
2824 flags, (DWORD_PTR)httpc->async_data);
2825 HeapFree(GetProcessHeap(), 0, url);
2826 if (!httpc->out_request)
2828 ERR("HttpOpenRequestW failed with error %d\n", GetLastError());
2829 return RPC_S_SERVER_UNAVAILABLE;
2832 if (credentials)
2834 status = authorize_request(httpc, httpc->out_request);
2835 if (status != RPC_S_OK)
2836 return status;
2839 status = rpcrt4_http_prepare_in_pipe(httpc->in_request, httpc->async_data, httpc->cancel_event,
2840 &httpc->connection_uuid, &httpc->in_pipe_uuid,
2841 &Connection->assoc->http_uuid, credentials);
2842 if (status != RPC_S_OK)
2843 return status;
2845 status = rpcrt4_http_prepare_out_pipe(httpc->out_request, httpc->async_data, httpc->cancel_event,
2846 &httpc->connection_uuid, &httpc->out_pipe_uuid,
2847 &httpc->flow_control_increment, credentials);
2848 if (status != RPC_S_OK)
2849 return status;
2851 httpc->flow_control_mark = httpc->flow_control_increment / 2;
2852 httpc->last_sent_time = GetTickCount();
2853 httpc->timer_cancelled = CreateEventW(NULL, FALSE, FALSE, NULL);
2855 timer_data = HeapAlloc(GetProcessHeap(), 0, sizeof(*timer_data));
2856 if (!timer_data)
2857 return ERROR_OUTOFMEMORY;
2858 timer_data->timer_param = httpc->in_request;
2859 timer_data->last_sent_time = &httpc->last_sent_time;
2860 timer_data->timer_cancelled = httpc->timer_cancelled;
2861 /* FIXME: should use CreateTimerQueueTimer when implemented */
2862 thread = CreateThread(NULL, 0, rpcrt4_http_timer_thread, timer_data, 0, NULL);
2863 if (!thread)
2865 HeapFree(GetProcessHeap(), 0, timer_data);
2866 return GetLastError();
2868 CloseHandle(thread);
2870 return RPC_S_OK;
2873 static RPC_STATUS rpcrt4_ncacn_http_handoff(RpcConnection *old_conn, RpcConnection *new_conn)
2875 assert(0);
2876 return RPC_S_SERVER_UNAVAILABLE;
2879 static int rpcrt4_ncacn_http_read(RpcConnection *Connection,
2880 void *buffer, unsigned int count)
2882 RpcConnection_http *httpc = (RpcConnection_http *) Connection;
2883 return rpcrt4_http_async_read(httpc->out_request, httpc->async_data, httpc->cancel_event, buffer, count);
2886 static RPC_STATUS rpcrt4_ncacn_http_receive_fragment(RpcConnection *Connection, RpcPktHdr **Header, void **Payload)
2888 RpcConnection_http *httpc = (RpcConnection_http *) Connection;
2889 RPC_STATUS status;
2890 DWORD hdr_length;
2891 LONG dwRead;
2892 RpcPktCommonHdr common_hdr;
2894 *Header = NULL;
2896 TRACE("(%p, %p, %p)\n", Connection, Header, Payload);
2898 again:
2899 /* read packet common header */
2900 dwRead = rpcrt4_ncacn_http_read(Connection, &common_hdr, sizeof(common_hdr));
2901 if (dwRead != sizeof(common_hdr)) {
2902 WARN("Short read of header, %d bytes\n", dwRead);
2903 status = RPC_S_PROTOCOL_ERROR;
2904 goto fail;
2906 if (!memcmp(&common_hdr, "HTTP/1.1", sizeof("HTTP/1.1")) ||
2907 !memcmp(&common_hdr, "HTTP/1.0", sizeof("HTTP/1.0")))
2909 FIXME("server returned %s\n", debugstr_a((const char *)&common_hdr));
2910 status = RPC_S_PROTOCOL_ERROR;
2911 goto fail;
2914 status = RPCRT4_ValidateCommonHeader(&common_hdr);
2915 if (status != RPC_S_OK) goto fail;
2917 hdr_length = RPCRT4_GetHeaderSize((RpcPktHdr*)&common_hdr);
2918 if (hdr_length == 0) {
2919 WARN("header length == 0\n");
2920 status = RPC_S_PROTOCOL_ERROR;
2921 goto fail;
2924 *Header = HeapAlloc(GetProcessHeap(), 0, hdr_length);
2925 if (!*Header)
2927 status = RPC_S_OUT_OF_RESOURCES;
2928 goto fail;
2930 memcpy(*Header, &common_hdr, sizeof(common_hdr));
2932 /* read the rest of packet header */
2933 dwRead = rpcrt4_ncacn_http_read(Connection, &(*Header)->common + 1, hdr_length - sizeof(common_hdr));
2934 if (dwRead != hdr_length - sizeof(common_hdr)) {
2935 WARN("bad header length, %d bytes, hdr_length %d\n", dwRead, hdr_length);
2936 status = RPC_S_PROTOCOL_ERROR;
2937 goto fail;
2940 if (common_hdr.frag_len - hdr_length)
2942 *Payload = HeapAlloc(GetProcessHeap(), 0, common_hdr.frag_len - hdr_length);
2943 if (!*Payload)
2945 status = RPC_S_OUT_OF_RESOURCES;
2946 goto fail;
2949 dwRead = rpcrt4_ncacn_http_read(Connection, *Payload, common_hdr.frag_len - hdr_length);
2950 if (dwRead != common_hdr.frag_len - hdr_length)
2952 WARN("bad data length, %d/%d\n", dwRead, common_hdr.frag_len - hdr_length);
2953 status = RPC_S_PROTOCOL_ERROR;
2954 goto fail;
2957 else
2958 *Payload = NULL;
2960 if ((*Header)->common.ptype == PKT_HTTP)
2962 if (!RPCRT4_IsValidHttpPacket(*Header, *Payload, common_hdr.frag_len - hdr_length))
2964 ERR("invalid http packet of length %d bytes\n", (*Header)->common.frag_len);
2965 status = RPC_S_PROTOCOL_ERROR;
2966 goto fail;
2968 if ((*Header)->http.flags == 0x0001)
2970 TRACE("http idle packet, waiting for real packet\n");
2971 if ((*Header)->http.num_data_items != 0)
2973 ERR("HTTP idle packet should have no data items instead of %d\n", (*Header)->http.num_data_items);
2974 status = RPC_S_PROTOCOL_ERROR;
2975 goto fail;
2978 else if ((*Header)->http.flags == 0x0002)
2980 ULONG bytes_transmitted;
2981 ULONG flow_control_increment;
2982 UUID pipe_uuid;
2983 status = RPCRT4_ParseHttpFlowControlHeader(*Header, *Payload,
2984 Connection->server,
2985 &bytes_transmitted,
2986 &flow_control_increment,
2987 &pipe_uuid);
2988 if (status != RPC_S_OK)
2989 goto fail;
2990 TRACE("received http flow control header (0x%x, 0x%x, %s)\n",
2991 bytes_transmitted, flow_control_increment, debugstr_guid(&pipe_uuid));
2992 /* FIXME: do something with parsed data */
2994 else
2996 FIXME("unrecognised http packet with flags 0x%04x\n", (*Header)->http.flags);
2997 status = RPC_S_PROTOCOL_ERROR;
2998 goto fail;
3000 RPCRT4_FreeHeader(*Header);
3001 *Header = NULL;
3002 HeapFree(GetProcessHeap(), 0, *Payload);
3003 *Payload = NULL;
3004 goto again;
3007 /* success */
3008 status = RPC_S_OK;
3010 httpc->bytes_received += common_hdr.frag_len;
3012 TRACE("httpc->bytes_received = 0x%x\n", httpc->bytes_received);
3014 if (httpc->bytes_received > httpc->flow_control_mark)
3016 RpcPktHdr *hdr = RPCRT4_BuildHttpFlowControlHeader(httpc->common.server,
3017 httpc->bytes_received,
3018 httpc->flow_control_increment,
3019 &httpc->out_pipe_uuid);
3020 if (hdr)
3022 DWORD bytes_written;
3023 BOOL ret2;
3024 TRACE("sending flow control packet at 0x%x\n", httpc->bytes_received);
3025 ret2 = InternetWriteFile(httpc->in_request, hdr, hdr->common.frag_len, &bytes_written);
3026 RPCRT4_FreeHeader(hdr);
3027 if (ret2)
3028 httpc->flow_control_mark = httpc->bytes_received + httpc->flow_control_increment / 2;
3032 fail:
3033 if (status != RPC_S_OK) {
3034 RPCRT4_FreeHeader(*Header);
3035 *Header = NULL;
3036 HeapFree(GetProcessHeap(), 0, *Payload);
3037 *Payload = NULL;
3039 return status;
3042 static int rpcrt4_ncacn_http_write(RpcConnection *Connection,
3043 const void *buffer, unsigned int count)
3045 RpcConnection_http *httpc = (RpcConnection_http *) Connection;
3046 DWORD bytes_written;
3047 BOOL ret;
3049 httpc->last_sent_time = ~0U; /* disable idle packet sending */
3050 ret = InternetWriteFile(httpc->in_request, buffer, count, &bytes_written);
3051 httpc->last_sent_time = GetTickCount();
3052 TRACE("%p %p %u -> %s\n", httpc->in_request, buffer, count, ret ? "TRUE" : "FALSE");
3053 return ret ? bytes_written : -1;
3056 static int rpcrt4_ncacn_http_close(RpcConnection *Connection)
3058 RpcConnection_http *httpc = (RpcConnection_http *) Connection;
3060 TRACE("\n");
3062 SetEvent(httpc->timer_cancelled);
3063 if (httpc->in_request)
3064 InternetCloseHandle(httpc->in_request);
3065 httpc->in_request = NULL;
3066 if (httpc->out_request)
3067 InternetCloseHandle(httpc->out_request);
3068 httpc->out_request = NULL;
3069 if (httpc->app_info)
3070 InternetCloseHandle(httpc->app_info);
3071 httpc->app_info = NULL;
3072 if (httpc->session)
3073 InternetCloseHandle(httpc->session);
3074 httpc->session = NULL;
3075 RpcHttpAsyncData_Release(httpc->async_data);
3076 if (httpc->cancel_event)
3077 CloseHandle(httpc->cancel_event);
3078 HeapFree(GetProcessHeap(), 0, httpc->servername);
3079 httpc->servername = NULL;
3081 return 0;
3084 static void rpcrt4_ncacn_http_close_read(RpcConnection *conn)
3086 rpcrt4_ncacn_http_close(conn); /* FIXME */
3089 static void rpcrt4_ncacn_http_cancel_call(RpcConnection *Connection)
3091 RpcConnection_http *httpc = (RpcConnection_http *) Connection;
3093 SetEvent(httpc->cancel_event);
3096 static RPC_STATUS rpcrt4_ncacn_http_is_server_listening(const char *endpoint)
3098 FIXME("\n");
3099 return RPC_S_ACCESS_DENIED;
3102 static int rpcrt4_ncacn_http_wait_for_incoming_data(RpcConnection *Connection)
3104 RpcConnection_http *httpc = (RpcConnection_http *) Connection;
3105 BOOL ret;
3106 RPC_STATUS status;
3108 prepare_async_request(httpc->async_data);
3109 ret = InternetQueryDataAvailable(httpc->out_request,
3110 &httpc->async_data->inet_buffers.dwBufferLength, IRF_ASYNC, 0);
3111 status = wait_async_request(httpc->async_data, ret, httpc->cancel_event);
3112 return status == RPC_S_OK ? 0 : -1;
3115 static size_t rpcrt4_ncacn_http_get_top_of_tower(unsigned char *tower_data,
3116 const char *networkaddr,
3117 const char *endpoint)
3119 return rpcrt4_ip_tcp_get_top_of_tower(tower_data, networkaddr,
3120 EPM_PROTOCOL_HTTP, endpoint);
3123 static RPC_STATUS rpcrt4_ncacn_http_parse_top_of_tower(const unsigned char *tower_data,
3124 size_t tower_size,
3125 char **networkaddr,
3126 char **endpoint)
3128 return rpcrt4_ip_tcp_parse_top_of_tower(tower_data, tower_size,
3129 networkaddr, EPM_PROTOCOL_HTTP,
3130 endpoint);
3133 static const struct connection_ops conn_protseq_list[] = {
3134 { "ncacn_np",
3135 { EPM_PROTOCOL_NCACN, EPM_PROTOCOL_SMB },
3136 rpcrt4_conn_np_alloc,
3137 rpcrt4_ncacn_np_open,
3138 rpcrt4_ncacn_np_handoff,
3139 rpcrt4_conn_np_read,
3140 rpcrt4_conn_np_write,
3141 rpcrt4_conn_np_close,
3142 rpcrt4_conn_np_close_read,
3143 rpcrt4_conn_np_cancel_call,
3144 rpcrt4_ncacn_np_is_server_listening,
3145 rpcrt4_conn_np_wait_for_incoming_data,
3146 rpcrt4_ncacn_np_get_top_of_tower,
3147 rpcrt4_ncacn_np_parse_top_of_tower,
3148 NULL,
3149 RPCRT4_default_is_authorized,
3150 RPCRT4_default_authorize,
3151 RPCRT4_default_secure_packet,
3152 rpcrt4_conn_np_impersonate_client,
3153 rpcrt4_conn_np_revert_to_self,
3154 RPCRT4_default_inquire_auth_client,
3156 { "ncalrpc",
3157 { EPM_PROTOCOL_NCALRPC, EPM_PROTOCOL_PIPE },
3158 rpcrt4_conn_np_alloc,
3159 rpcrt4_ncalrpc_open,
3160 rpcrt4_ncalrpc_handoff,
3161 rpcrt4_conn_np_read,
3162 rpcrt4_conn_np_write,
3163 rpcrt4_conn_np_close,
3164 rpcrt4_conn_np_close_read,
3165 rpcrt4_conn_np_cancel_call,
3166 rpcrt4_ncalrpc_np_is_server_listening,
3167 rpcrt4_conn_np_wait_for_incoming_data,
3168 rpcrt4_ncalrpc_get_top_of_tower,
3169 rpcrt4_ncalrpc_parse_top_of_tower,
3170 NULL,
3171 rpcrt4_ncalrpc_is_authorized,
3172 rpcrt4_ncalrpc_authorize,
3173 rpcrt4_ncalrpc_secure_packet,
3174 rpcrt4_conn_np_impersonate_client,
3175 rpcrt4_conn_np_revert_to_self,
3176 rpcrt4_ncalrpc_inquire_auth_client,
3178 { "ncacn_ip_tcp",
3179 { EPM_PROTOCOL_NCACN, EPM_PROTOCOL_TCP },
3180 rpcrt4_conn_tcp_alloc,
3181 rpcrt4_ncacn_ip_tcp_open,
3182 rpcrt4_conn_tcp_handoff,
3183 rpcrt4_conn_tcp_read,
3184 rpcrt4_conn_tcp_write,
3185 rpcrt4_conn_tcp_close,
3186 rpcrt4_conn_tcp_close_read,
3187 rpcrt4_conn_tcp_cancel_call,
3188 rpcrt4_conn_tcp_is_server_listening,
3189 rpcrt4_conn_tcp_wait_for_incoming_data,
3190 rpcrt4_ncacn_ip_tcp_get_top_of_tower,
3191 rpcrt4_ncacn_ip_tcp_parse_top_of_tower,
3192 NULL,
3193 RPCRT4_default_is_authorized,
3194 RPCRT4_default_authorize,
3195 RPCRT4_default_secure_packet,
3196 RPCRT4_default_impersonate_client,
3197 RPCRT4_default_revert_to_self,
3198 RPCRT4_default_inquire_auth_client,
3200 { "ncacn_http",
3201 { EPM_PROTOCOL_NCACN, EPM_PROTOCOL_HTTP },
3202 rpcrt4_ncacn_http_alloc,
3203 rpcrt4_ncacn_http_open,
3204 rpcrt4_ncacn_http_handoff,
3205 rpcrt4_ncacn_http_read,
3206 rpcrt4_ncacn_http_write,
3207 rpcrt4_ncacn_http_close,
3208 rpcrt4_ncacn_http_close_read,
3209 rpcrt4_ncacn_http_cancel_call,
3210 rpcrt4_ncacn_http_is_server_listening,
3211 rpcrt4_ncacn_http_wait_for_incoming_data,
3212 rpcrt4_ncacn_http_get_top_of_tower,
3213 rpcrt4_ncacn_http_parse_top_of_tower,
3214 rpcrt4_ncacn_http_receive_fragment,
3215 RPCRT4_default_is_authorized,
3216 RPCRT4_default_authorize,
3217 RPCRT4_default_secure_packet,
3218 RPCRT4_default_impersonate_client,
3219 RPCRT4_default_revert_to_self,
3220 RPCRT4_default_inquire_auth_client,
3225 static const struct protseq_ops protseq_list[] =
3228 "ncacn_np",
3229 rpcrt4_protseq_np_alloc,
3230 rpcrt4_protseq_np_signal_state_changed,
3231 rpcrt4_protseq_np_get_wait_array,
3232 rpcrt4_protseq_np_free_wait_array,
3233 rpcrt4_protseq_np_wait_for_new_connection,
3234 rpcrt4_protseq_ncacn_np_open_endpoint,
3237 "ncalrpc",
3238 rpcrt4_protseq_np_alloc,
3239 rpcrt4_protseq_np_signal_state_changed,
3240 rpcrt4_protseq_np_get_wait_array,
3241 rpcrt4_protseq_np_free_wait_array,
3242 rpcrt4_protseq_np_wait_for_new_connection,
3243 rpcrt4_protseq_ncalrpc_open_endpoint,
3246 "ncacn_ip_tcp",
3247 rpcrt4_protseq_sock_alloc,
3248 rpcrt4_protseq_sock_signal_state_changed,
3249 rpcrt4_protseq_sock_get_wait_array,
3250 rpcrt4_protseq_sock_free_wait_array,
3251 rpcrt4_protseq_sock_wait_for_new_connection,
3252 rpcrt4_protseq_ncacn_ip_tcp_open_endpoint,
3256 const struct protseq_ops *rpcrt4_get_protseq_ops(const char *protseq)
3258 unsigned int i;
3259 for(i=0; i<ARRAYSIZE(protseq_list); i++)
3260 if (!strcmp(protseq_list[i].name, protseq))
3261 return &protseq_list[i];
3262 return NULL;
3265 static const struct connection_ops *rpcrt4_get_conn_protseq_ops(const char *protseq)
3267 unsigned int i;
3268 for(i=0; i<ARRAYSIZE(conn_protseq_list); i++)
3269 if (!strcmp(conn_protseq_list[i].name, protseq))
3270 return &conn_protseq_list[i];
3271 return NULL;
3274 /**** interface to rest of code ****/
3276 RPC_STATUS RPCRT4_OpenClientConnection(RpcConnection* Connection)
3278 TRACE("(Connection == ^%p)\n", Connection);
3280 assert(!Connection->server);
3281 return Connection->ops->open_connection_client(Connection);
3284 RPC_STATUS RPCRT4_CloseConnection(RpcConnection* Connection)
3286 TRACE("(Connection == ^%p)\n", Connection);
3287 if (SecIsValidHandle(&Connection->ctx))
3289 DeleteSecurityContext(&Connection->ctx);
3290 SecInvalidateHandle(&Connection->ctx);
3292 rpcrt4_conn_close(Connection);
3293 return RPC_S_OK;
3296 RPC_STATUS RPCRT4_CreateConnection(RpcConnection** Connection, BOOL server,
3297 LPCSTR Protseq, LPCSTR NetworkAddr, LPCSTR Endpoint,
3298 LPCWSTR NetworkOptions, RpcAuthInfo* AuthInfo, RpcQualityOfService *QOS, LPCWSTR CookieAuth)
3300 static LONG next_id;
3301 const struct connection_ops *ops;
3302 RpcConnection* NewConnection;
3304 ops = rpcrt4_get_conn_protseq_ops(Protseq);
3305 if (!ops)
3307 FIXME("not supported for protseq %s\n", Protseq);
3308 return RPC_S_PROTSEQ_NOT_SUPPORTED;
3311 NewConnection = ops->alloc();
3312 NewConnection->ref = 1;
3313 NewConnection->server = server;
3314 NewConnection->ops = ops;
3315 NewConnection->NetworkAddr = RPCRT4_strdupA(NetworkAddr);
3316 NewConnection->Endpoint = RPCRT4_strdupA(Endpoint);
3317 NewConnection->NetworkOptions = RPCRT4_strdupW(NetworkOptions);
3318 NewConnection->CookieAuth = RPCRT4_strdupW(CookieAuth);
3319 NewConnection->MaxTransmissionSize = RPC_MAX_PACKET_SIZE;
3320 NewConnection->NextCallId = 1;
3322 SecInvalidateHandle(&NewConnection->ctx);
3323 if (AuthInfo) RpcAuthInfo_AddRef(AuthInfo);
3324 NewConnection->AuthInfo = AuthInfo;
3325 NewConnection->auth_context_id = InterlockedIncrement( &next_id );
3326 if (QOS) RpcQualityOfService_AddRef(QOS);
3327 NewConnection->QOS = QOS;
3329 list_init(&NewConnection->conn_pool_entry);
3330 list_init(&NewConnection->protseq_entry);
3332 TRACE("connection: %p\n", NewConnection);
3333 *Connection = NewConnection;
3335 return RPC_S_OK;
3338 static RpcConnection *rpcrt4_spawn_connection(RpcConnection *old_connection)
3340 RpcConnection *connection;
3341 RPC_STATUS err;
3343 err = RPCRT4_CreateConnection(&connection, old_connection->server, rpcrt4_conn_get_name(old_connection),
3344 old_connection->NetworkAddr, old_connection->Endpoint, NULL,
3345 old_connection->AuthInfo, old_connection->QOS, old_connection->CookieAuth);
3346 if (err != RPC_S_OK)
3347 return NULL;
3349 rpcrt4_conn_handoff(old_connection, connection);
3350 if (old_connection->protseq)
3352 EnterCriticalSection(&old_connection->protseq->cs);
3353 connection->protseq = old_connection->protseq;
3354 list_add_tail(&old_connection->protseq->connections, &connection->protseq_entry);
3355 LeaveCriticalSection(&old_connection->protseq->cs);
3357 return connection;
3360 void rpcrt4_conn_release_and_wait(RpcConnection *connection)
3362 HANDLE event = NULL;
3364 if (connection->ref > 1)
3365 event = connection->wait_release = CreateEventW(NULL, TRUE, FALSE, NULL);
3367 RPCRT4_ReleaseConnection(connection);
3369 if(event)
3371 WaitForSingleObject(event, INFINITE);
3372 CloseHandle(event);
3376 RpcConnection *RPCRT4_GrabConnection(RpcConnection *connection)
3378 LONG ref = InterlockedIncrement(&connection->ref);
3379 TRACE("%p ref=%u\n", connection, ref);
3380 return connection;
3383 void RPCRT4_ReleaseConnection(RpcConnection *connection)
3385 LONG ref = InterlockedDecrement(&connection->ref);
3387 if (!ref && connection->protseq)
3389 /* protseq stores a list of active connections, but does not own references to them.
3390 * It may need to grab a connection from the list, which could lead to a race if
3391 * connection is being released, but not yet removed from the list. We handle that
3392 * by synchronizing on CS here. */
3393 EnterCriticalSection(&connection->protseq->cs);
3394 ref = connection->ref;
3395 if (!ref)
3396 list_remove(&connection->protseq_entry);
3397 LeaveCriticalSection(&connection->protseq->cs);
3400 TRACE("%p ref=%u\n", connection, ref);
3402 if (!ref)
3404 RPCRT4_CloseConnection(connection);
3405 RPCRT4_strfree(connection->Endpoint);
3406 RPCRT4_strfree(connection->NetworkAddr);
3407 HeapFree(GetProcessHeap(), 0, connection->NetworkOptions);
3408 HeapFree(GetProcessHeap(), 0, connection->CookieAuth);
3409 if (connection->AuthInfo) RpcAuthInfo_Release(connection->AuthInfo);
3410 if (connection->QOS) RpcQualityOfService_Release(connection->QOS);
3412 /* server-only */
3413 if (connection->server_binding) RPCRT4_ReleaseBinding(connection->server_binding);
3415 if (connection->wait_release) SetEvent(connection->wait_release);
3417 HeapFree(GetProcessHeap(), 0, connection);
3421 RPC_STATUS RPCRT4_IsServerListening(const char *protseq, const char *endpoint)
3423 const struct connection_ops *ops;
3425 ops = rpcrt4_get_conn_protseq_ops(protseq);
3426 if (!ops)
3428 FIXME("not supported for protseq %s\n", protseq);
3429 return RPC_S_INVALID_BINDING;
3432 return ops->is_server_listening(endpoint);
3435 RPC_STATUS RpcTransport_GetTopOfTower(unsigned char *tower_data,
3436 size_t *tower_size,
3437 const char *protseq,
3438 const char *networkaddr,
3439 const char *endpoint)
3441 twr_empty_floor_t *protocol_floor;
3442 const struct connection_ops *protseq_ops = rpcrt4_get_conn_protseq_ops(protseq);
3444 *tower_size = 0;
3446 if (!protseq_ops)
3447 return RPC_S_INVALID_RPC_PROTSEQ;
3449 if (!tower_data)
3451 *tower_size = sizeof(*protocol_floor);
3452 *tower_size += protseq_ops->get_top_of_tower(NULL, networkaddr, endpoint);
3453 return RPC_S_OK;
3456 protocol_floor = (twr_empty_floor_t *)tower_data;
3457 protocol_floor->count_lhs = sizeof(protocol_floor->protid);
3458 protocol_floor->protid = protseq_ops->epm_protocols[0];
3459 protocol_floor->count_rhs = 0;
3461 tower_data += sizeof(*protocol_floor);
3463 *tower_size = protseq_ops->get_top_of_tower(tower_data, networkaddr, endpoint);
3464 if (!*tower_size)
3465 return EPT_S_NOT_REGISTERED;
3467 *tower_size += sizeof(*protocol_floor);
3469 return RPC_S_OK;
3472 RPC_STATUS RpcTransport_ParseTopOfTower(const unsigned char *tower_data,
3473 size_t tower_size,
3474 char **protseq,
3475 char **networkaddr,
3476 char **endpoint)
3478 const twr_empty_floor_t *protocol_floor;
3479 const twr_empty_floor_t *floor4;
3480 const struct connection_ops *protseq_ops = NULL;
3481 RPC_STATUS status;
3482 unsigned int i;
3484 if (tower_size < sizeof(*protocol_floor))
3485 return EPT_S_NOT_REGISTERED;
3487 protocol_floor = (const twr_empty_floor_t *)tower_data;
3488 tower_data += sizeof(*protocol_floor);
3489 tower_size -= sizeof(*protocol_floor);
3490 if ((protocol_floor->count_lhs != sizeof(protocol_floor->protid)) ||
3491 (protocol_floor->count_rhs > tower_size))
3492 return EPT_S_NOT_REGISTERED;
3493 tower_data += protocol_floor->count_rhs;
3494 tower_size -= protocol_floor->count_rhs;
3496 floor4 = (const twr_empty_floor_t *)tower_data;
3497 if ((tower_size < sizeof(*floor4)) ||
3498 (floor4->count_lhs != sizeof(floor4->protid)))
3499 return EPT_S_NOT_REGISTERED;
3501 for(i = 0; i < ARRAYSIZE(conn_protseq_list); i++)
3502 if ((protocol_floor->protid == conn_protseq_list[i].epm_protocols[0]) &&
3503 (floor4->protid == conn_protseq_list[i].epm_protocols[1]))
3505 protseq_ops = &conn_protseq_list[i];
3506 break;
3509 if (!protseq_ops)
3510 return EPT_S_NOT_REGISTERED;
3512 status = protseq_ops->parse_top_of_tower(tower_data, tower_size, networkaddr, endpoint);
3514 if ((status == RPC_S_OK) && protseq)
3516 *protseq = I_RpcAllocate(strlen(protseq_ops->name) + 1);
3517 strcpy(*protseq, protseq_ops->name);
3520 return status;
3523 /***********************************************************************
3524 * RpcNetworkIsProtseqValidW (RPCRT4.@)
3526 * Checks if the given protocol sequence is known by the RPC system.
3527 * If it is, returns RPC_S_OK, otherwise RPC_S_PROTSEQ_NOT_SUPPORTED.
3530 RPC_STATUS WINAPI RpcNetworkIsProtseqValidW(RPC_WSTR protseq)
3532 char ps[0x10];
3534 WideCharToMultiByte(CP_ACP, 0, protseq, -1,
3535 ps, sizeof ps, NULL, NULL);
3536 if (rpcrt4_get_conn_protseq_ops(ps))
3537 return RPC_S_OK;
3539 FIXME("Unknown protseq %s\n", debugstr_w(protseq));
3541 return RPC_S_INVALID_RPC_PROTSEQ;
3544 /***********************************************************************
3545 * RpcNetworkIsProtseqValidA (RPCRT4.@)
3547 RPC_STATUS WINAPI RpcNetworkIsProtseqValidA(RPC_CSTR protseq)
3549 UNICODE_STRING protseqW;
3551 if (RtlCreateUnicodeStringFromAsciiz(&protseqW, (char*)protseq))
3553 RPC_STATUS ret = RpcNetworkIsProtseqValidW(protseqW.Buffer);
3554 RtlFreeUnicodeString(&protseqW);
3555 return ret;
3557 return RPC_S_OUT_OF_MEMORY;
3560 /***********************************************************************
3561 * RpcProtseqVectorFreeA (RPCRT4.@)
3563 RPC_STATUS WINAPI RpcProtseqVectorFreeA(RPC_PROTSEQ_VECTORA **protseqs)
3565 TRACE("(%p)\n", protseqs);
3567 if (*protseqs)
3569 unsigned int i;
3570 for (i = 0; i < (*protseqs)->Count; i++)
3571 HeapFree(GetProcessHeap(), 0, (*protseqs)->Protseq[i]);
3572 HeapFree(GetProcessHeap(), 0, *protseqs);
3573 *protseqs = NULL;
3575 return RPC_S_OK;
3578 /***********************************************************************
3579 * RpcProtseqVectorFreeW (RPCRT4.@)
3581 RPC_STATUS WINAPI RpcProtseqVectorFreeW(RPC_PROTSEQ_VECTORW **protseqs)
3583 TRACE("(%p)\n", protseqs);
3585 if (*protseqs)
3587 unsigned int i;
3588 for (i = 0; i < (*protseqs)->Count; i++)
3589 HeapFree(GetProcessHeap(), 0, (*protseqs)->Protseq[i]);
3590 HeapFree(GetProcessHeap(), 0, *protseqs);
3591 *protseqs = NULL;
3593 return RPC_S_OK;
3596 /***********************************************************************
3597 * RpcNetworkInqProtseqsW (RPCRT4.@)
3599 RPC_STATUS WINAPI RpcNetworkInqProtseqsW( RPC_PROTSEQ_VECTORW** protseqs )
3601 RPC_PROTSEQ_VECTORW *pvector;
3602 unsigned int i;
3603 RPC_STATUS status = RPC_S_OUT_OF_MEMORY;
3605 TRACE("(%p)\n", protseqs);
3607 *protseqs = HeapAlloc(GetProcessHeap(), 0, sizeof(RPC_PROTSEQ_VECTORW)+(sizeof(unsigned short*)*ARRAYSIZE(protseq_list)));
3608 if (!*protseqs)
3609 goto end;
3610 pvector = *protseqs;
3611 pvector->Count = 0;
3612 for (i = 0; i < ARRAYSIZE(protseq_list); i++)
3614 pvector->Protseq[i] = HeapAlloc(GetProcessHeap(), 0, (strlen(protseq_list[i].name)+1)*sizeof(unsigned short));
3615 if (pvector->Protseq[i] == NULL)
3616 goto end;
3617 MultiByteToWideChar(CP_ACP, 0, (CHAR*)protseq_list[i].name, -1,
3618 (WCHAR*)pvector->Protseq[i], strlen(protseq_list[i].name) + 1);
3619 pvector->Count++;
3621 status = RPC_S_OK;
3623 end:
3624 if (status != RPC_S_OK)
3625 RpcProtseqVectorFreeW(protseqs);
3626 return status;
3629 /***********************************************************************
3630 * RpcNetworkInqProtseqsA (RPCRT4.@)
3632 RPC_STATUS WINAPI RpcNetworkInqProtseqsA(RPC_PROTSEQ_VECTORA** protseqs)
3634 RPC_PROTSEQ_VECTORA *pvector;
3635 unsigned int i;
3636 RPC_STATUS status = RPC_S_OUT_OF_MEMORY;
3638 TRACE("(%p)\n", protseqs);
3640 *protseqs = HeapAlloc(GetProcessHeap(), 0, sizeof(RPC_PROTSEQ_VECTORW)+(sizeof(unsigned char*)*ARRAYSIZE(protseq_list)));
3641 if (!*protseqs)
3642 goto end;
3643 pvector = *protseqs;
3644 pvector->Count = 0;
3645 for (i = 0; i < ARRAYSIZE(protseq_list); i++)
3647 pvector->Protseq[i] = HeapAlloc(GetProcessHeap(), 0, strlen(protseq_list[i].name)+1);
3648 if (pvector->Protseq[i] == NULL)
3649 goto end;
3650 strcpy((char*)pvector->Protseq[i], protseq_list[i].name);
3651 pvector->Count++;
3653 status = RPC_S_OK;
3655 end:
3656 if (status != RPC_S_OK)
3657 RpcProtseqVectorFreeA(protseqs);
3658 return status;