msvcrt: Use fpclass constants from public header.
[wine/zf.git] / dlls / rpcrt4 / rpc_transport.c
blob4f2c66427926086a8ec42d67020fb9fddb39ea22
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"
43 #include "rpc.h"
44 #include "rpcndr.h"
46 #include "wine/debug.h"
48 #include "rpc_binding.h"
49 #include "rpc_assoc.h"
50 #include "rpc_message.h"
51 #include "rpc_server.h"
52 #include "epm_towers.h"
54 #define DEFAULT_NCACN_HTTP_TIMEOUT (60 * 1000)
56 WINE_DEFAULT_DEBUG_CHANNEL(rpc);
58 static RpcConnection *rpcrt4_spawn_connection(RpcConnection *old_connection);
60 /**** ncacn_np support ****/
62 typedef struct _RpcConnection_np
64 RpcConnection common;
65 HANDLE pipe;
66 HANDLE listen_event;
67 char *listen_pipe;
68 IO_STATUS_BLOCK io_status;
69 HANDLE event_cache;
70 BOOL read_closed;
71 } RpcConnection_np;
73 static RpcConnection *rpcrt4_conn_np_alloc(void)
75 RpcConnection_np *npc = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(RpcConnection_np));
76 return &npc->common;
79 static HANDLE get_np_event(RpcConnection_np *connection)
81 HANDLE event = InterlockedExchangePointer(&connection->event_cache, NULL);
82 return event ? event : CreateEventW(NULL, TRUE, FALSE, NULL);
85 static void release_np_event(RpcConnection_np *connection, HANDLE event)
87 event = InterlockedExchangePointer(&connection->event_cache, event);
88 if (event)
89 CloseHandle(event);
92 static RPC_STATUS rpcrt4_conn_create_pipe(RpcConnection *conn)
94 RpcConnection_np *connection = (RpcConnection_np *) conn;
96 TRACE("listening on %s\n", connection->listen_pipe);
98 connection->pipe = CreateNamedPipeA(connection->listen_pipe, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
99 PIPE_TYPE_MESSAGE | PIPE_READMODE_MESSAGE,
100 PIPE_UNLIMITED_INSTANCES,
101 RPC_MAX_PACKET_SIZE, RPC_MAX_PACKET_SIZE, 5000, NULL);
102 if (connection->pipe == INVALID_HANDLE_VALUE)
104 WARN("CreateNamedPipe failed with error %d\n", GetLastError());
105 if (GetLastError() == ERROR_FILE_EXISTS)
106 return RPC_S_DUPLICATE_ENDPOINT;
107 else
108 return RPC_S_CANT_CREATE_ENDPOINT;
111 return RPC_S_OK;
114 static RPC_STATUS rpcrt4_conn_open_pipe(RpcConnection *Connection, LPCSTR pname, BOOL wait)
116 RpcConnection_np *npc = (RpcConnection_np *) Connection;
117 HANDLE pipe;
118 DWORD err, dwMode;
120 TRACE("connecting to %s\n", pname);
122 while (TRUE) {
123 DWORD dwFlags = 0;
124 if (Connection->QOS)
126 dwFlags = SECURITY_SQOS_PRESENT;
127 switch (Connection->QOS->qos->ImpersonationType)
129 case RPC_C_IMP_LEVEL_DEFAULT:
130 /* FIXME: what to do here? */
131 break;
132 case RPC_C_IMP_LEVEL_ANONYMOUS:
133 dwFlags |= SECURITY_ANONYMOUS;
134 break;
135 case RPC_C_IMP_LEVEL_IDENTIFY:
136 dwFlags |= SECURITY_IDENTIFICATION;
137 break;
138 case RPC_C_IMP_LEVEL_IMPERSONATE:
139 dwFlags |= SECURITY_IMPERSONATION;
140 break;
141 case RPC_C_IMP_LEVEL_DELEGATE:
142 dwFlags |= SECURITY_DELEGATION;
143 break;
145 if (Connection->QOS->qos->IdentityTracking == RPC_C_QOS_IDENTITY_DYNAMIC)
146 dwFlags |= SECURITY_CONTEXT_TRACKING;
148 pipe = CreateFileA(pname, GENERIC_READ|GENERIC_WRITE, 0, NULL,
149 OPEN_EXISTING, dwFlags | FILE_FLAG_OVERLAPPED, 0);
150 if (pipe != INVALID_HANDLE_VALUE) break;
151 err = GetLastError();
152 if (err == ERROR_PIPE_BUSY) {
153 if (WaitNamedPipeA(pname, NMPWAIT_USE_DEFAULT_WAIT)) {
154 TRACE("retrying busy server\n");
155 continue;
157 TRACE("connection failed, error=%x\n", err);
158 return RPC_S_SERVER_TOO_BUSY;
160 if (!wait || !WaitNamedPipeA(pname, NMPWAIT_WAIT_FOREVER)) {
161 err = GetLastError();
162 WARN("connection failed, error=%x\n", err);
163 return RPC_S_SERVER_UNAVAILABLE;
167 /* success */
168 /* pipe is connected; change to message-read mode. */
169 dwMode = PIPE_READMODE_MESSAGE;
170 SetNamedPipeHandleState(pipe, &dwMode, NULL, NULL);
171 npc->pipe = pipe;
173 return RPC_S_OK;
176 static char *ncalrpc_pipe_name(const char *endpoint)
178 static const char prefix[] = "\\\\.\\pipe\\lrpc\\";
179 char *pipe_name;
181 /* protseq=ncalrpc: supposed to use NT LPC ports,
182 * but we'll implement it with named pipes for now */
183 pipe_name = I_RpcAllocate(sizeof(prefix) + strlen(endpoint));
184 strcat(strcpy(pipe_name, prefix), endpoint);
185 return pipe_name;
188 static RPC_STATUS rpcrt4_ncalrpc_open(RpcConnection* Connection)
190 RpcConnection_np *npc = (RpcConnection_np *) Connection;
191 RPC_STATUS r;
192 LPSTR pname;
194 /* already connected? */
195 if (npc->pipe)
196 return RPC_S_OK;
198 pname = ncalrpc_pipe_name(Connection->Endpoint);
199 r = rpcrt4_conn_open_pipe(Connection, pname, TRUE);
200 I_RpcFree(pname);
202 return r;
205 static RPC_STATUS rpcrt4_protseq_ncalrpc_open_endpoint(RpcServerProtseq* protseq, const char *endpoint)
207 RPC_STATUS r;
208 RpcConnection *Connection;
209 char generated_endpoint[22];
211 if (!endpoint)
213 static LONG lrpc_nameless_id;
214 DWORD process_id = GetCurrentProcessId();
215 ULONG id = InterlockedIncrement(&lrpc_nameless_id);
216 snprintf(generated_endpoint, sizeof(generated_endpoint),
217 "LRPC%08x.%08x", process_id, id);
218 endpoint = generated_endpoint;
221 r = RPCRT4_CreateConnection(&Connection, TRUE, protseq->Protseq, NULL,
222 endpoint, NULL, NULL, NULL, NULL);
223 if (r != RPC_S_OK)
224 return r;
226 ((RpcConnection_np*)Connection)->listen_pipe = ncalrpc_pipe_name(Connection->Endpoint);
227 r = rpcrt4_conn_create_pipe(Connection);
229 EnterCriticalSection(&protseq->cs);
230 list_add_head(&protseq->listeners, &Connection->protseq_entry);
231 Connection->protseq = protseq;
232 LeaveCriticalSection(&protseq->cs);
234 return r;
237 static char *ncacn_pipe_name(const char *endpoint)
239 static const char prefix[] = "\\\\.";
240 char *pipe_name;
242 /* protseq=ncacn_np: named pipes */
243 pipe_name = I_RpcAllocate(sizeof(prefix) + strlen(endpoint));
244 strcat(strcpy(pipe_name, prefix), endpoint);
245 return pipe_name;
248 static RPC_STATUS rpcrt4_ncacn_np_open(RpcConnection* Connection)
250 RpcConnection_np *npc = (RpcConnection_np *) Connection;
251 RPC_STATUS r;
252 LPSTR pname;
254 /* already connected? */
255 if (npc->pipe)
256 return RPC_S_OK;
258 pname = ncacn_pipe_name(Connection->Endpoint);
259 r = rpcrt4_conn_open_pipe(Connection, pname, FALSE);
260 I_RpcFree(pname);
262 return r;
265 static RPC_STATUS rpcrt4_protseq_ncacn_np_open_endpoint(RpcServerProtseq *protseq, const char *endpoint)
267 RPC_STATUS r;
268 RpcConnection *Connection;
269 char generated_endpoint[26];
271 if (!endpoint)
273 static LONG np_nameless_id;
274 DWORD process_id = GetCurrentProcessId();
275 ULONG id = InterlockedExchangeAdd(&np_nameless_id, 1 );
276 snprintf(generated_endpoint, sizeof(generated_endpoint),
277 "\\\\pipe\\\\%08x.%03x", process_id, id);
278 endpoint = generated_endpoint;
281 r = RPCRT4_CreateConnection(&Connection, TRUE, protseq->Protseq, NULL,
282 endpoint, NULL, NULL, NULL, NULL);
283 if (r != RPC_S_OK)
284 return r;
286 ((RpcConnection_np*)Connection)->listen_pipe = ncacn_pipe_name(Connection->Endpoint);
287 r = rpcrt4_conn_create_pipe(Connection);
289 EnterCriticalSection(&protseq->cs);
290 list_add_head(&protseq->listeners, &Connection->protseq_entry);
291 Connection->protseq = protseq;
292 LeaveCriticalSection(&protseq->cs);
294 return r;
297 static void rpcrt4_conn_np_handoff(RpcConnection_np *old_npc, RpcConnection_np *new_npc)
299 /* because of the way named pipes work, we'll transfer the connected pipe
300 * to the child, then reopen the server binding to continue listening */
302 new_npc->pipe = old_npc->pipe;
303 old_npc->pipe = 0;
304 assert(!old_npc->listen_event);
307 static RPC_STATUS rpcrt4_ncacn_np_handoff(RpcConnection *old_conn, RpcConnection *new_conn)
309 DWORD len = MAX_COMPUTERNAME_LENGTH + 1;
310 RPC_STATUS status;
312 rpcrt4_conn_np_handoff((RpcConnection_np *)old_conn, (RpcConnection_np *)new_conn);
313 status = rpcrt4_conn_create_pipe(old_conn);
315 /* Store the local computer name as the NetworkAddr for ncacn_np as long as
316 * we don't support named pipes over the network. */
317 new_conn->NetworkAddr = HeapAlloc(GetProcessHeap(), 0, len);
318 if (!GetComputerNameA(new_conn->NetworkAddr, &len))
320 ERR("Failed to retrieve the computer name, error %u\n", GetLastError());
321 return RPC_S_OUT_OF_RESOURCES;
324 return status;
327 static RPC_STATUS is_pipe_listening(const char *pipe_name)
329 return WaitNamedPipeA(pipe_name, 1) ? RPC_S_OK : RPC_S_NOT_LISTENING;
332 static RPC_STATUS rpcrt4_ncacn_np_is_server_listening(const char *endpoint)
334 char *pipe_name;
335 RPC_STATUS status;
337 pipe_name = ncacn_pipe_name(endpoint);
338 status = is_pipe_listening(pipe_name);
339 I_RpcFree(pipe_name);
340 return status;
343 static RPC_STATUS rpcrt4_ncalrpc_np_is_server_listening(const char *endpoint)
345 char *pipe_name;
346 RPC_STATUS status;
348 pipe_name = ncalrpc_pipe_name(endpoint);
349 status = is_pipe_listening(pipe_name);
350 I_RpcFree(pipe_name);
351 return status;
354 static RPC_STATUS rpcrt4_ncalrpc_handoff(RpcConnection *old_conn, RpcConnection *new_conn)
356 DWORD len = MAX_COMPUTERNAME_LENGTH + 1;
357 RPC_STATUS status;
359 TRACE("%s\n", old_conn->Endpoint);
361 rpcrt4_conn_np_handoff((RpcConnection_np *)old_conn, (RpcConnection_np *)new_conn);
362 status = rpcrt4_conn_create_pipe(old_conn);
364 /* Store the local computer name as the NetworkAddr for ncalrpc. */
365 new_conn->NetworkAddr = HeapAlloc(GetProcessHeap(), 0, len);
366 if (!GetComputerNameA(new_conn->NetworkAddr, &len))
368 ERR("Failed to retrieve the computer name, error %u\n", GetLastError());
369 return RPC_S_OUT_OF_RESOURCES;
372 return status;
375 static int rpcrt4_conn_np_read(RpcConnection *conn, void *buffer, unsigned int count)
377 RpcConnection_np *connection = (RpcConnection_np *) conn;
378 HANDLE event;
379 NTSTATUS status;
381 event = get_np_event(connection);
382 if (!event)
383 return -1;
385 if (connection->read_closed)
386 status = STATUS_CANCELLED;
387 else
388 status = NtReadFile(connection->pipe, event, NULL, NULL, &connection->io_status, buffer, count, NULL, NULL);
389 if (status == STATUS_PENDING)
391 /* check read_closed again before waiting to avoid a race */
392 if (connection->read_closed)
394 IO_STATUS_BLOCK io_status;
395 NtCancelIoFileEx(connection->pipe, &connection->io_status, &io_status);
397 WaitForSingleObject(event, INFINITE);
398 status = connection->io_status.Status;
400 release_np_event(connection, event);
401 return status && status != STATUS_BUFFER_OVERFLOW ? -1 : connection->io_status.Information;
404 static int rpcrt4_conn_np_write(RpcConnection *conn, const void *buffer, unsigned int count)
406 RpcConnection_np *connection = (RpcConnection_np *) conn;
407 IO_STATUS_BLOCK io_status;
408 HANDLE event;
409 NTSTATUS status;
411 event = get_np_event(connection);
412 if (!event)
413 return -1;
415 status = NtWriteFile(connection->pipe, event, NULL, NULL, &io_status, buffer, count, NULL, NULL);
416 if (status == STATUS_PENDING)
418 WaitForSingleObject(event, INFINITE);
419 status = io_status.Status;
421 release_np_event(connection, event);
422 if (status)
423 return -1;
425 assert(io_status.Information == count);
426 return count;
429 static int rpcrt4_conn_np_close(RpcConnection *conn)
431 RpcConnection_np *connection = (RpcConnection_np *) conn;
432 if (connection->pipe)
434 FlushFileBuffers(connection->pipe);
435 CloseHandle(connection->pipe);
436 connection->pipe = 0;
438 if (connection->listen_event)
440 CloseHandle(connection->listen_event);
441 connection->listen_event = 0;
443 if (connection->event_cache)
445 CloseHandle(connection->event_cache);
446 connection->event_cache = 0;
448 return 0;
451 static void rpcrt4_conn_np_close_read(RpcConnection *conn)
453 RpcConnection_np *connection = (RpcConnection_np*)conn;
454 IO_STATUS_BLOCK io_status;
456 connection->read_closed = TRUE;
457 NtCancelIoFileEx(connection->pipe, &connection->io_status, &io_status);
460 static void rpcrt4_conn_np_cancel_call(RpcConnection *conn)
462 RpcConnection_np *connection = (RpcConnection_np *)conn;
463 CancelIoEx(connection->pipe, NULL);
466 static int rpcrt4_conn_np_wait_for_incoming_data(RpcConnection *conn)
468 return rpcrt4_conn_np_read(conn, NULL, 0);
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 LPWSTR proxy = NULL;
1878 LPWSTR user = NULL;
1879 LPWSTR password = NULL;
1880 LPWSTR servername = NULL;
1881 const WCHAR *option;
1882 INTERNET_PORT port;
1884 if (httpc->common.QOS &&
1885 (httpc->common.QOS->qos->AdditionalSecurityInfoType == RPC_C_AUTHN_INFO_TYPE_HTTP))
1887 const RPC_HTTP_TRANSPORT_CREDENTIALS_W *http_cred = httpc->common.QOS->qos->u.HttpCredentials;
1888 if (http_cred->TransportCredentials)
1890 WCHAR *p;
1891 const SEC_WINNT_AUTH_IDENTITY_W *cred = http_cred->TransportCredentials;
1892 ULONG len = cred->DomainLength + 1 + cred->UserLength;
1893 user = HeapAlloc(GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR));
1894 if (!user)
1895 return RPC_S_OUT_OF_RESOURCES;
1896 p = user;
1897 if (cred->DomainLength)
1899 memcpy(p, cred->Domain, cred->DomainLength * sizeof(WCHAR));
1900 p += cred->DomainLength;
1901 *p = '\\';
1902 p++;
1904 memcpy(p, cred->User, cred->UserLength * sizeof(WCHAR));
1905 p[cred->UserLength] = 0;
1907 password = RPCRT4_strndupW(cred->Password, cred->PasswordLength);
1911 for (option = httpc->common.NetworkOptions; option;
1912 option = (wcschr(option, ',') ? wcschr(option, ',')+1 : NULL))
1914 if (!wcsnicmp(option, L"RpcProxy=", ARRAY_SIZE(L"RpcProxy=")-1))
1916 const WCHAR *value_start = option + ARRAY_SIZE(L"RpcProxy=")-1;
1917 const WCHAR *value_end;
1918 const WCHAR *p;
1920 value_end = wcschr(option, ',');
1921 if (!value_end)
1922 value_end = value_start + lstrlenW(value_start);
1923 for (p = value_start; p < value_end; p++)
1924 if (*p == ':')
1926 port = wcstol(p+1, NULL, 10);
1927 value_end = p;
1928 break;
1930 TRACE("RpcProxy value is %s\n", debugstr_wn(value_start, value_end-value_start));
1931 servername = RPCRT4_strndupW(value_start, value_end-value_start);
1933 else if (!wcsnicmp(option, L"HttpProxy=", ARRAY_SIZE(L"HttpProxy=")-1))
1935 const WCHAR *value_start = option + ARRAY_SIZE(L"HttpProxy=")-1;
1936 const WCHAR *value_end;
1938 value_end = wcschr(option, ',');
1939 if (!value_end)
1940 value_end = value_start + lstrlenW(value_start);
1941 TRACE("HttpProxy value is %s\n", debugstr_wn(value_start, value_end-value_start));
1942 proxy = RPCRT4_strndupW(value_start, value_end-value_start);
1944 else
1945 FIXME("unhandled option %s\n", debugstr_w(option));
1948 httpc->app_info = InternetOpenW(L"MSRPC", proxy ? INTERNET_OPEN_TYPE_PROXY : INTERNET_OPEN_TYPE_PRECONFIG,
1949 NULL, NULL, INTERNET_FLAG_ASYNC);
1950 if (!httpc->app_info)
1952 HeapFree(GetProcessHeap(), 0, password);
1953 HeapFree(GetProcessHeap(), 0, user);
1954 HeapFree(GetProcessHeap(), 0, proxy);
1955 HeapFree(GetProcessHeap(), 0, servername);
1956 ERR("InternetOpenW failed with error %d\n", GetLastError());
1957 return RPC_S_SERVER_UNAVAILABLE;
1959 InternetSetStatusCallbackW(httpc->app_info, rpcrt4_http_internet_callback);
1961 /* if no RpcProxy option specified, set the HTTP server address to the
1962 * RPC server address */
1963 if (!servername)
1965 servername = HeapAlloc(GetProcessHeap(), 0, (strlen(httpc->common.NetworkAddr) + 1)*sizeof(WCHAR));
1966 if (!servername)
1968 HeapFree(GetProcessHeap(), 0, password);
1969 HeapFree(GetProcessHeap(), 0, user);
1970 HeapFree(GetProcessHeap(), 0, proxy);
1971 return RPC_S_OUT_OF_RESOURCES;
1973 MultiByteToWideChar(CP_ACP, 0, httpc->common.NetworkAddr, -1, servername, strlen(httpc->common.NetworkAddr) + 1);
1976 port = (httpc->common.QOS &&
1977 (httpc->common.QOS->qos->AdditionalSecurityInfoType == RPC_C_AUTHN_INFO_TYPE_HTTP) &&
1978 (httpc->common.QOS->qos->u.HttpCredentials->Flags & RPC_C_HTTP_FLAG_USE_SSL)) ?
1979 INTERNET_DEFAULT_HTTPS_PORT : INTERNET_DEFAULT_HTTP_PORT;
1981 httpc->session = InternetConnectW(httpc->app_info, servername, port, user, password,
1982 INTERNET_SERVICE_HTTP, 0, 0);
1984 HeapFree(GetProcessHeap(), 0, password);
1985 HeapFree(GetProcessHeap(), 0, user);
1986 HeapFree(GetProcessHeap(), 0, proxy);
1988 if (!httpc->session)
1990 ERR("InternetConnectW failed with error %d\n", GetLastError());
1991 HeapFree(GetProcessHeap(), 0, servername);
1992 return RPC_S_SERVER_UNAVAILABLE;
1994 httpc->servername = servername;
1995 return RPC_S_OK;
1998 static int rpcrt4_http_async_read(HINTERNET req, RpcHttpAsyncData *async_data, HANDLE cancel_event,
1999 void *buffer, unsigned int count)
2001 char *buf = buffer;
2002 BOOL ret;
2003 unsigned int bytes_left = count;
2004 RPC_STATUS status = RPC_S_OK;
2006 async_data->inet_buffers.lpvBuffer = HeapAlloc(GetProcessHeap(), 0, count);
2008 while (bytes_left)
2010 async_data->inet_buffers.dwBufferLength = bytes_left;
2011 prepare_async_request(async_data);
2012 ret = InternetReadFileExW(req, &async_data->inet_buffers, IRF_ASYNC, 0);
2013 status = wait_async_request(async_data, ret, cancel_event);
2014 if (status != RPC_S_OK)
2016 if (status == RPC_S_CALL_CANCELLED)
2017 TRACE("call cancelled\n");
2018 break;
2021 if (!async_data->inet_buffers.dwBufferLength)
2022 break;
2023 memcpy(buf, async_data->inet_buffers.lpvBuffer,
2024 async_data->inet_buffers.dwBufferLength);
2026 bytes_left -= async_data->inet_buffers.dwBufferLength;
2027 buf += async_data->inet_buffers.dwBufferLength;
2030 HeapFree(GetProcessHeap(), 0, async_data->inet_buffers.lpvBuffer);
2031 async_data->inet_buffers.lpvBuffer = NULL;
2033 TRACE("%p %p %u -> %u\n", req, buffer, count, status);
2034 return status == RPC_S_OK ? count : -1;
2037 static RPC_STATUS send_echo_request(HINTERNET req, RpcHttpAsyncData *async_data, HANDLE cancel_event)
2039 BYTE buf[20];
2040 BOOL ret;
2041 RPC_STATUS status;
2043 TRACE("sending echo request to server\n");
2045 prepare_async_request(async_data);
2046 ret = HttpSendRequestW(req, NULL, 0, NULL, 0);
2047 status = wait_async_request(async_data, ret, cancel_event);
2048 if (status != RPC_S_OK) return status;
2050 status = rpcrt4_http_check_response(req);
2051 if (status != RPC_S_OK) return status;
2053 rpcrt4_http_async_read(req, async_data, cancel_event, buf, sizeof(buf));
2054 /* FIXME: do something with retrieved data */
2056 return RPC_S_OK;
2059 static RPC_STATUS insert_content_length_header(HINTERNET request, DWORD len)
2061 WCHAR header[ARRAY_SIZE(L"Content-Length: %u\r\n") + 10];
2063 swprintf(header, ARRAY_SIZE(header), L"Content-Length: %u\r\n", len);
2064 if ((HttpAddRequestHeadersW(request, header, -1, HTTP_ADDREQ_FLAG_REPLACE | HTTP_ADDREQ_FLAG_ADD))) return RPC_S_OK;
2065 return RPC_S_SERVER_UNAVAILABLE;
2068 /* prepare the in pipe for use by RPC packets */
2069 static RPC_STATUS rpcrt4_http_prepare_in_pipe(HINTERNET in_request, RpcHttpAsyncData *async_data, HANDLE cancel_event,
2070 const UUID *connection_uuid, const UUID *in_pipe_uuid,
2071 const UUID *association_uuid, BOOL authorized)
2073 BOOL ret;
2074 RPC_STATUS status;
2075 RpcPktHdr *hdr;
2076 INTERNET_BUFFERSW buffers_in;
2077 DWORD bytes_written;
2079 if (!authorized)
2081 /* ask wininet to authorize, if necessary */
2082 status = send_echo_request(in_request, async_data, cancel_event);
2083 if (status != RPC_S_OK) return status;
2085 memset(&buffers_in, 0, sizeof(buffers_in));
2086 buffers_in.dwStructSize = sizeof(buffers_in);
2087 /* FIXME: get this from the registry */
2088 buffers_in.dwBufferTotal = 1024 * 1024 * 1024; /* 1Gb */
2089 status = insert_content_length_header(in_request, buffers_in.dwBufferTotal);
2090 if (status != RPC_S_OK) return status;
2092 prepare_async_request(async_data);
2093 ret = HttpSendRequestExW(in_request, &buffers_in, NULL, 0, 0);
2094 status = wait_async_request(async_data, ret, cancel_event);
2095 if (status != RPC_S_OK) return status;
2097 TRACE("sending HTTP connect header to server\n");
2098 hdr = RPCRT4_BuildHttpConnectHeader(FALSE, connection_uuid, in_pipe_uuid, association_uuid);
2099 if (!hdr) return RPC_S_OUT_OF_RESOURCES;
2100 ret = InternetWriteFile(in_request, hdr, hdr->common.frag_len, &bytes_written);
2101 RPCRT4_FreeHeader(hdr);
2102 if (!ret)
2104 ERR("InternetWriteFile failed with error %d\n", GetLastError());
2105 return RPC_S_SERVER_UNAVAILABLE;
2108 return RPC_S_OK;
2111 static RPC_STATUS rpcrt4_http_read_http_packet(HINTERNET request, RpcHttpAsyncData *async_data,
2112 HANDLE cancel_event, RpcPktHdr *hdr, BYTE **data)
2114 unsigned short data_len;
2115 unsigned int size;
2117 if (rpcrt4_http_async_read(request, async_data, cancel_event, hdr, sizeof(hdr->common)) < 0)
2118 return RPC_S_SERVER_UNAVAILABLE;
2119 if (hdr->common.ptype != PKT_HTTP || hdr->common.frag_len < sizeof(hdr->http))
2121 ERR("wrong packet type received %d or wrong frag_len %d\n",
2122 hdr->common.ptype, hdr->common.frag_len);
2123 return RPC_S_PROTOCOL_ERROR;
2126 size = sizeof(hdr->http) - sizeof(hdr->common);
2127 if (rpcrt4_http_async_read(request, async_data, cancel_event, &hdr->common + 1, size) < 0)
2128 return RPC_S_SERVER_UNAVAILABLE;
2130 data_len = hdr->common.frag_len - sizeof(hdr->http);
2131 if (data_len)
2133 *data = HeapAlloc(GetProcessHeap(), 0, data_len);
2134 if (!*data)
2135 return RPC_S_OUT_OF_RESOURCES;
2136 if (rpcrt4_http_async_read(request, async_data, cancel_event, *data, data_len) < 0)
2138 HeapFree(GetProcessHeap(), 0, *data);
2139 return RPC_S_SERVER_UNAVAILABLE;
2142 else
2143 *data = NULL;
2145 if (!RPCRT4_IsValidHttpPacket(hdr, *data, data_len))
2147 ERR("invalid http packet\n");
2148 HeapFree(GetProcessHeap(), 0, *data);
2149 return RPC_S_PROTOCOL_ERROR;
2152 return RPC_S_OK;
2155 /* prepare the out pipe for use by RPC packets */
2156 static RPC_STATUS rpcrt4_http_prepare_out_pipe(HINTERNET out_request, RpcHttpAsyncData *async_data,
2157 HANDLE cancel_event, const UUID *connection_uuid,
2158 const UUID *out_pipe_uuid, ULONG *flow_control_increment,
2159 BOOL authorized)
2161 BOOL ret;
2162 RPC_STATUS status;
2163 RpcPktHdr *hdr;
2164 BYTE *data_from_server;
2165 RpcPktHdr pkt_from_server;
2166 ULONG field1, field3;
2167 BYTE buf[20];
2169 if (!authorized)
2171 /* ask wininet to authorize, if necessary */
2172 status = send_echo_request(out_request, async_data, cancel_event);
2173 if (status != RPC_S_OK) return status;
2175 else
2176 rpcrt4_http_async_read(out_request, async_data, cancel_event, buf, sizeof(buf));
2178 hdr = RPCRT4_BuildHttpConnectHeader(TRUE, connection_uuid, out_pipe_uuid, NULL);
2179 if (!hdr) return RPC_S_OUT_OF_RESOURCES;
2181 status = insert_content_length_header(out_request, hdr->common.frag_len);
2182 if (status != RPC_S_OK)
2184 RPCRT4_FreeHeader(hdr);
2185 return status;
2188 TRACE("sending HTTP connect header to server\n");
2189 prepare_async_request(async_data);
2190 ret = HttpSendRequestW(out_request, NULL, 0, hdr, hdr->common.frag_len);
2191 status = wait_async_request(async_data, ret, cancel_event);
2192 RPCRT4_FreeHeader(hdr);
2193 if (status != RPC_S_OK) return status;
2195 status = rpcrt4_http_check_response(out_request);
2196 if (status != RPC_S_OK) return status;
2198 status = rpcrt4_http_read_http_packet(out_request, async_data, cancel_event,
2199 &pkt_from_server, &data_from_server);
2200 if (status != RPC_S_OK) return status;
2201 status = RPCRT4_ParseHttpPrepareHeader1(&pkt_from_server, data_from_server,
2202 &field1);
2203 HeapFree(GetProcessHeap(), 0, data_from_server);
2204 if (status != RPC_S_OK) return status;
2205 TRACE("received (%d) from first prepare header\n", field1);
2207 for (;;)
2209 status = rpcrt4_http_read_http_packet(out_request, async_data, cancel_event,
2210 &pkt_from_server, &data_from_server);
2211 if (status != RPC_S_OK) return status;
2212 if (pkt_from_server.http.flags != 0x0001) break;
2214 TRACE("http idle packet, waiting for real packet\n");
2215 HeapFree(GetProcessHeap(), 0, data_from_server);
2216 if (pkt_from_server.http.num_data_items != 0)
2218 ERR("HTTP idle packet should have no data items instead of %d\n",
2219 pkt_from_server.http.num_data_items);
2220 return RPC_S_PROTOCOL_ERROR;
2223 status = RPCRT4_ParseHttpPrepareHeader2(&pkt_from_server, data_from_server,
2224 &field1, flow_control_increment,
2225 &field3);
2226 HeapFree(GetProcessHeap(), 0, data_from_server);
2227 if (status != RPC_S_OK) return status;
2228 TRACE("received (0x%08x 0x%08x %d) from second prepare header\n", field1, *flow_control_increment, field3);
2230 return RPC_S_OK;
2233 static UINT encode_base64(const char *bin, unsigned int len, WCHAR *base64)
2235 static const char enc[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
2236 UINT i = 0, x;
2238 while (len > 0)
2240 /* first 6 bits, all from bin[0] */
2241 base64[i++] = enc[(bin[0] & 0xfc) >> 2];
2242 x = (bin[0] & 3) << 4;
2244 /* next 6 bits, 2 from bin[0] and 4 from bin[1] */
2245 if (len == 1)
2247 base64[i++] = enc[x];
2248 base64[i++] = '=';
2249 base64[i++] = '=';
2250 break;
2252 base64[i++] = enc[x | ((bin[1] & 0xf0) >> 4)];
2253 x = (bin[1] & 0x0f) << 2;
2255 /* next 6 bits 4 from bin[1] and 2 from bin[2] */
2256 if (len == 2)
2258 base64[i++] = enc[x];
2259 base64[i++] = '=';
2260 break;
2262 base64[i++] = enc[x | ((bin[2] & 0xc0) >> 6)];
2264 /* last 6 bits, all from bin [2] */
2265 base64[i++] = enc[bin[2] & 0x3f];
2266 bin += 3;
2267 len -= 3;
2269 base64[i] = 0;
2270 return i;
2273 static inline char decode_char( WCHAR c )
2275 if (c >= 'A' && c <= 'Z') return c - 'A';
2276 if (c >= 'a' && c <= 'z') return c - 'a' + 26;
2277 if (c >= '0' && c <= '9') return c - '0' + 52;
2278 if (c == '+') return 62;
2279 if (c == '/') return 63;
2280 return 64;
2283 static unsigned int decode_base64( const WCHAR *base64, unsigned int len, char *buf )
2285 unsigned int i = 0;
2286 char c0, c1, c2, c3;
2287 const WCHAR *p = base64;
2289 while (len > 4)
2291 if ((c0 = decode_char( p[0] )) > 63) return 0;
2292 if ((c1 = decode_char( p[1] )) > 63) return 0;
2293 if ((c2 = decode_char( p[2] )) > 63) return 0;
2294 if ((c3 = decode_char( p[3] )) > 63) return 0;
2296 if (buf)
2298 buf[i + 0] = (c0 << 2) | (c1 >> 4);
2299 buf[i + 1] = (c1 << 4) | (c2 >> 2);
2300 buf[i + 2] = (c2 << 6) | c3;
2302 len -= 4;
2303 i += 3;
2304 p += 4;
2306 if (p[2] == '=')
2308 if ((c0 = decode_char( p[0] )) > 63) return 0;
2309 if ((c1 = decode_char( p[1] )) > 63) return 0;
2311 if (buf) buf[i] = (c0 << 2) | (c1 >> 4);
2312 i++;
2314 else if (p[3] == '=')
2316 if ((c0 = decode_char( p[0] )) > 63) return 0;
2317 if ((c1 = decode_char( p[1] )) > 63) return 0;
2318 if ((c2 = decode_char( p[2] )) > 63) return 0;
2320 if (buf)
2322 buf[i + 0] = (c0 << 2) | (c1 >> 4);
2323 buf[i + 1] = (c1 << 4) | (c2 >> 2);
2325 i += 2;
2327 else
2329 if ((c0 = decode_char( p[0] )) > 63) return 0;
2330 if ((c1 = decode_char( p[1] )) > 63) return 0;
2331 if ((c2 = decode_char( p[2] )) > 63) return 0;
2332 if ((c3 = decode_char( p[3] )) > 63) return 0;
2334 if (buf)
2336 buf[i + 0] = (c0 << 2) | (c1 >> 4);
2337 buf[i + 1] = (c1 << 4) | (c2 >> 2);
2338 buf[i + 2] = (c2 << 6) | c3;
2340 i += 3;
2342 return i;
2345 static struct authinfo *alloc_authinfo(void)
2347 struct authinfo *ret;
2349 if (!(ret = HeapAlloc(GetProcessHeap(), 0, sizeof(*ret) ))) return NULL;
2351 SecInvalidateHandle(&ret->cred);
2352 SecInvalidateHandle(&ret->ctx);
2353 memset(&ret->exp, 0, sizeof(ret->exp));
2354 ret->scheme = 0;
2355 ret->attr = 0;
2356 ret->max_token = 0;
2357 ret->data = NULL;
2358 ret->data_len = 0;
2359 ret->finished = FALSE;
2360 return ret;
2363 static void destroy_authinfo(struct authinfo *info)
2365 if (!info) return;
2367 if (SecIsValidHandle(&info->ctx))
2368 DeleteSecurityContext(&info->ctx);
2369 if (SecIsValidHandle(&info->cred))
2370 FreeCredentialsHandle(&info->cred);
2372 HeapFree(GetProcessHeap(), 0, info->data);
2373 HeapFree(GetProcessHeap(), 0, info);
2376 static const struct
2378 const WCHAR *str;
2379 unsigned int len;
2380 DWORD scheme;
2382 auth_schemes[] =
2384 { L"Basic", ARRAY_SIZE(L"Basic") - 1, RPC_C_HTTP_AUTHN_SCHEME_BASIC },
2385 { L"NTLM", ARRAY_SIZE(L"NTLM") - 1, RPC_C_HTTP_AUTHN_SCHEME_NTLM },
2386 { L"Passport", ARRAY_SIZE(L"Passport") - 1, RPC_C_HTTP_AUTHN_SCHEME_PASSPORT },
2387 { L"Digest", ARRAY_SIZE(L"Digest") - 1, RPC_C_HTTP_AUTHN_SCHEME_DIGEST },
2388 { L"Negotiate", ARRAY_SIZE(L"Negotiate") - 1, RPC_C_HTTP_AUTHN_SCHEME_NEGOTIATE }
2391 static DWORD auth_scheme_from_header( const WCHAR *header )
2393 unsigned int i;
2394 for (i = 0; i < ARRAY_SIZE(auth_schemes); i++)
2396 if (!wcsnicmp( header, auth_schemes[i].str, auth_schemes[i].len ) &&
2397 (header[auth_schemes[i].len] == ' ' || !header[auth_schemes[i].len])) return auth_schemes[i].scheme;
2399 return 0;
2402 static BOOL get_authvalue(HINTERNET request, DWORD scheme, WCHAR *buffer, DWORD buflen)
2404 DWORD len, index = 0;
2405 for (;;)
2407 len = buflen;
2408 if (!HttpQueryInfoW(request, HTTP_QUERY_WWW_AUTHENTICATE, buffer, &len, &index)) return FALSE;
2409 if (auth_scheme_from_header(buffer) == scheme) break;
2411 return TRUE;
2414 static RPC_STATUS do_authorization(HINTERNET request, SEC_WCHAR *servername,
2415 const RPC_HTTP_TRANSPORT_CREDENTIALS_W *creds, struct authinfo **auth_ptr)
2417 struct authinfo *info = *auth_ptr;
2418 SEC_WINNT_AUTH_IDENTITY_W *id = creds->TransportCredentials;
2419 RPC_STATUS status = RPC_S_SERVER_UNAVAILABLE;
2421 if ((!info && !(info = alloc_authinfo()))) return RPC_S_SERVER_UNAVAILABLE;
2423 switch (creds->AuthnSchemes[0])
2425 case RPC_C_HTTP_AUTHN_SCHEME_BASIC:
2427 int userlen = WideCharToMultiByte(CP_UTF8, 0, id->User, id->UserLength, NULL, 0, NULL, NULL);
2428 int passlen = WideCharToMultiByte(CP_UTF8, 0, id->Password, id->PasswordLength, NULL, 0, NULL, NULL);
2430 info->data_len = userlen + passlen + 1;
2431 if (!(info->data = HeapAlloc(GetProcessHeap(), 0, info->data_len)))
2433 status = RPC_S_OUT_OF_MEMORY;
2434 break;
2436 WideCharToMultiByte(CP_UTF8, 0, id->User, id->UserLength, info->data, userlen, NULL, NULL);
2437 info->data[userlen] = ':';
2438 WideCharToMultiByte(CP_UTF8, 0, id->Password, id->PasswordLength, info->data + userlen + 1, passlen, NULL, NULL);
2440 info->scheme = RPC_C_HTTP_AUTHN_SCHEME_BASIC;
2441 info->finished = TRUE;
2442 status = RPC_S_OK;
2443 break;
2445 case RPC_C_HTTP_AUTHN_SCHEME_NTLM:
2446 case RPC_C_HTTP_AUTHN_SCHEME_NEGOTIATE:
2449 static SEC_WCHAR ntlmW[] = L"NTLM", negotiateW[] = L"Negotiate";
2450 SECURITY_STATUS ret;
2451 SecBufferDesc out_desc, in_desc;
2452 SecBuffer out, in;
2453 ULONG flags = ISC_REQ_CONNECTION|ISC_REQ_USE_DCE_STYLE|ISC_REQ_MUTUAL_AUTH|ISC_REQ_DELEGATE;
2454 SEC_WCHAR *scheme;
2455 int scheme_len;
2456 const WCHAR *p;
2457 WCHAR auth_value[2048];
2458 DWORD size = sizeof(auth_value);
2459 BOOL first = FALSE;
2461 if (creds->AuthnSchemes[0] == RPC_C_HTTP_AUTHN_SCHEME_NTLM) scheme = ntlmW;
2462 else scheme = negotiateW;
2463 scheme_len = lstrlenW( scheme );
2465 if (!*auth_ptr)
2467 TimeStamp exp;
2468 SecPkgInfoW *pkg_info;
2470 ret = AcquireCredentialsHandleW(NULL, scheme, SECPKG_CRED_OUTBOUND, NULL, id, NULL, NULL, &info->cred, &exp);
2471 if (ret != SEC_E_OK) break;
2473 ret = QuerySecurityPackageInfoW(scheme, &pkg_info);
2474 if (ret != SEC_E_OK) break;
2476 info->max_token = pkg_info->cbMaxToken;
2477 FreeContextBuffer(pkg_info);
2478 first = TRUE;
2480 else
2482 if (info->finished || !get_authvalue(request, creds->AuthnSchemes[0], auth_value, size)) break;
2483 if (auth_scheme_from_header(auth_value) != info->scheme)
2485 ERR("authentication scheme changed\n");
2486 break;
2489 in.BufferType = SECBUFFER_TOKEN;
2490 in.cbBuffer = 0;
2491 in.pvBuffer = NULL;
2493 in_desc.ulVersion = 0;
2494 in_desc.cBuffers = 1;
2495 in_desc.pBuffers = &in;
2497 p = auth_value + scheme_len;
2498 if (!first && *p == ' ')
2500 int len = lstrlenW(++p);
2501 in.cbBuffer = decode_base64(p, len, NULL);
2502 if (!(in.pvBuffer = HeapAlloc(GetProcessHeap(), 0, in.cbBuffer))) break;
2503 decode_base64(p, len, in.pvBuffer);
2505 out.BufferType = SECBUFFER_TOKEN;
2506 out.cbBuffer = info->max_token;
2507 if (!(out.pvBuffer = HeapAlloc(GetProcessHeap(), 0, out.cbBuffer)))
2509 HeapFree(GetProcessHeap(), 0, in.pvBuffer);
2510 break;
2512 out_desc.ulVersion = 0;
2513 out_desc.cBuffers = 1;
2514 out_desc.pBuffers = &out;
2516 ret = InitializeSecurityContextW(first ? &info->cred : NULL, first ? NULL : &info->ctx,
2517 first ? servername : NULL, flags, 0, SECURITY_NETWORK_DREP,
2518 in.pvBuffer ? &in_desc : NULL, 0, &info->ctx, &out_desc,
2519 &info->attr, &info->exp);
2520 HeapFree(GetProcessHeap(), 0, in.pvBuffer);
2521 if (ret == SEC_E_OK)
2523 HeapFree(GetProcessHeap(), 0, info->data);
2524 info->data = out.pvBuffer;
2525 info->data_len = out.cbBuffer;
2526 info->finished = TRUE;
2527 TRACE("sending last auth packet\n");
2528 status = RPC_S_OK;
2530 else if (ret == SEC_I_CONTINUE_NEEDED)
2532 HeapFree(GetProcessHeap(), 0, info->data);
2533 info->data = out.pvBuffer;
2534 info->data_len = out.cbBuffer;
2535 TRACE("sending next auth packet\n");
2536 status = RPC_S_OK;
2538 else
2540 ERR("InitializeSecurityContextW failed with error 0x%08x\n", ret);
2541 HeapFree(GetProcessHeap(), 0, out.pvBuffer);
2542 break;
2544 info->scheme = creds->AuthnSchemes[0];
2545 break;
2547 default:
2548 FIXME("scheme %u not supported\n", creds->AuthnSchemes[0]);
2549 break;
2552 if (status != RPC_S_OK)
2554 destroy_authinfo(info);
2555 *auth_ptr = NULL;
2556 return status;
2558 *auth_ptr = info;
2559 return RPC_S_OK;
2562 static RPC_STATUS insert_authorization_header(HINTERNET request, ULONG scheme, char *data, int data_len)
2564 static const WCHAR authW[] = {'A','u','t','h','o','r','i','z','a','t','i','o','n',':',' '};
2565 static const WCHAR basicW[] = {'B','a','s','i','c',' '};
2566 static const WCHAR negotiateW[] = {'N','e','g','o','t','i','a','t','e',' '};
2567 static const WCHAR ntlmW[] = {'N','T','L','M',' '};
2568 int scheme_len, auth_len = ARRAY_SIZE(authW), len = ((data_len + 2) * 4) / 3;
2569 const WCHAR *scheme_str;
2570 WCHAR *header, *ptr;
2571 RPC_STATUS status = RPC_S_SERVER_UNAVAILABLE;
2573 switch (scheme)
2575 case RPC_C_HTTP_AUTHN_SCHEME_BASIC:
2576 scheme_str = basicW;
2577 scheme_len = ARRAY_SIZE(basicW);
2578 break;
2579 case RPC_C_HTTP_AUTHN_SCHEME_NEGOTIATE:
2580 scheme_str = negotiateW;
2581 scheme_len = ARRAY_SIZE(negotiateW);
2582 break;
2583 case RPC_C_HTTP_AUTHN_SCHEME_NTLM:
2584 scheme_str = ntlmW;
2585 scheme_len = ARRAY_SIZE(ntlmW);
2586 break;
2587 default:
2588 ERR("unknown scheme %u\n", scheme);
2589 return RPC_S_SERVER_UNAVAILABLE;
2591 if ((header = HeapAlloc(GetProcessHeap(), 0, (auth_len + scheme_len + len + 2) * sizeof(WCHAR))))
2593 memcpy(header, authW, auth_len * sizeof(WCHAR));
2594 ptr = header + auth_len;
2595 memcpy(ptr, scheme_str, scheme_len * sizeof(WCHAR));
2596 ptr += scheme_len;
2597 len = encode_base64(data, data_len, ptr);
2598 ptr[len++] = '\r';
2599 ptr[len++] = '\n';
2600 ptr[len] = 0;
2601 if (HttpAddRequestHeadersW(request, header, -1, HTTP_ADDREQ_FLAG_ADD|HTTP_ADDREQ_FLAG_REPLACE))
2602 status = RPC_S_OK;
2603 HeapFree(GetProcessHeap(), 0, header);
2605 return status;
2608 static void drain_content(HINTERNET request, RpcHttpAsyncData *async_data, HANDLE cancel_event)
2610 DWORD count, len = 0, size = sizeof(len);
2611 char buf[2048];
2613 HttpQueryInfoW(request, HTTP_QUERY_FLAG_NUMBER|HTTP_QUERY_CONTENT_LENGTH, &len, &size, NULL);
2614 if (!len) return;
2615 for (;;)
2617 count = min(sizeof(buf), len);
2618 if (rpcrt4_http_async_read(request, async_data, cancel_event, buf, count) <= 0) return;
2619 len -= count;
2623 static RPC_STATUS authorize_request(RpcConnection_http *httpc, HINTERNET request)
2625 struct authinfo *info = NULL;
2626 RPC_STATUS status;
2627 BOOL ret;
2629 for (;;)
2631 status = do_authorization(request, httpc->servername, httpc->common.QOS->qos->u.HttpCredentials, &info);
2632 if (status != RPC_S_OK) break;
2634 status = insert_authorization_header(request, info->scheme, info->data, info->data_len);
2635 if (status != RPC_S_OK) break;
2637 prepare_async_request(httpc->async_data);
2638 ret = HttpSendRequestW(request, NULL, 0, NULL, 0);
2639 status = wait_async_request(httpc->async_data, ret, httpc->cancel_event);
2640 if (status != RPC_S_OK || info->finished) break;
2642 status = rpcrt4_http_check_response(request);
2643 if (status != RPC_S_OK && status != ERROR_ACCESS_DENIED) break;
2644 drain_content(request, httpc->async_data, httpc->cancel_event);
2647 if (info->scheme != RPC_C_HTTP_AUTHN_SCHEME_BASIC)
2648 HttpAddRequestHeadersW(request, L"Authorization:\r\n", -1, HTTP_ADDREQ_FLAG_REPLACE | HTTP_ADDREQ_FLAG_ADD);
2650 destroy_authinfo(info);
2651 return status;
2654 static BOOL has_credentials(RpcConnection_http *httpc)
2656 RPC_HTTP_TRANSPORT_CREDENTIALS_W *creds;
2657 SEC_WINNT_AUTH_IDENTITY_W *id;
2659 if (!httpc->common.QOS || httpc->common.QOS->qos->AdditionalSecurityInfoType != RPC_C_AUTHN_INFO_TYPE_HTTP)
2660 return FALSE;
2662 creds = httpc->common.QOS->qos->u.HttpCredentials;
2663 if (creds->AuthenticationTarget != RPC_C_HTTP_AUTHN_TARGET_SERVER || !creds->NumberOfAuthnSchemes)
2664 return FALSE;
2666 id = creds->TransportCredentials;
2667 if (!id || !id->User || !id->Password) return FALSE;
2669 return TRUE;
2672 static BOOL is_secure(RpcConnection_http *httpc)
2674 return httpc->common.QOS &&
2675 (httpc->common.QOS->qos->AdditionalSecurityInfoType == RPC_C_AUTHN_INFO_TYPE_HTTP) &&
2676 (httpc->common.QOS->qos->u.HttpCredentials->Flags & RPC_C_HTTP_FLAG_USE_SSL);
2679 static RPC_STATUS set_auth_cookie(RpcConnection_http *httpc, const WCHAR *value)
2681 static WCHAR httpW[] = L"http";
2682 static WCHAR httpsW[] = L"https";
2683 URL_COMPONENTSW uc;
2684 DWORD len;
2685 WCHAR *url;
2686 BOOL ret;
2688 if (!value) return RPC_S_OK;
2690 uc.dwStructSize = sizeof(uc);
2691 uc.lpszScheme = is_secure(httpc) ? httpsW : httpW;
2692 uc.dwSchemeLength = 0;
2693 uc.lpszHostName = httpc->servername;
2694 uc.dwHostNameLength = 0;
2695 uc.nPort = 0;
2696 uc.lpszUserName = NULL;
2697 uc.dwUserNameLength = 0;
2698 uc.lpszPassword = NULL;
2699 uc.dwPasswordLength = 0;
2700 uc.lpszUrlPath = NULL;
2701 uc.dwUrlPathLength = 0;
2702 uc.lpszExtraInfo = NULL;
2703 uc.dwExtraInfoLength = 0;
2705 if (!InternetCreateUrlW(&uc, 0, NULL, &len) && (GetLastError() != ERROR_INSUFFICIENT_BUFFER))
2706 return RPC_S_SERVER_UNAVAILABLE;
2708 if (!(url = HeapAlloc(GetProcessHeap(), 0, len))) return RPC_S_OUT_OF_MEMORY;
2710 len = len / sizeof(WCHAR) - 1;
2711 if (!InternetCreateUrlW(&uc, 0, url, &len))
2713 HeapFree(GetProcessHeap(), 0, url);
2714 return RPC_S_SERVER_UNAVAILABLE;
2717 ret = InternetSetCookieW(url, NULL, value);
2718 HeapFree(GetProcessHeap(), 0, url);
2719 if (!ret) return RPC_S_SERVER_UNAVAILABLE;
2721 return RPC_S_OK;
2724 static RPC_STATUS rpcrt4_ncacn_http_open(RpcConnection* Connection)
2726 RpcConnection_http *httpc = (RpcConnection_http *)Connection;
2727 static const WCHAR wszRpcProxyPrefix[] = L"/rpc/rpcproxy.dll?";
2728 LPCWSTR wszAcceptTypes[] = { L"application/rpc", NULL };
2729 DWORD flags;
2730 WCHAR *url;
2731 RPC_STATUS status;
2732 BOOL secure, credentials;
2733 HttpTimerThreadData *timer_data;
2734 HANDLE thread;
2736 TRACE("(%s, %s)\n", Connection->NetworkAddr, Connection->Endpoint);
2738 if (Connection->server)
2740 ERR("ncacn_http servers not supported yet\n");
2741 return RPC_S_SERVER_UNAVAILABLE;
2744 if (httpc->in_request)
2745 return RPC_S_OK;
2747 httpc->async_data->completion_event = CreateEventW(NULL, FALSE, FALSE, NULL);
2749 UuidCreate(&httpc->connection_uuid);
2750 UuidCreate(&httpc->in_pipe_uuid);
2751 UuidCreate(&httpc->out_pipe_uuid);
2753 status = rpcrt4_http_internet_connect(httpc);
2754 if (status != RPC_S_OK)
2755 return status;
2757 url = HeapAlloc(GetProcessHeap(), 0, sizeof(wszRpcProxyPrefix) + (strlen(Connection->NetworkAddr) + 1 + strlen(Connection->Endpoint))*sizeof(WCHAR));
2758 if (!url)
2759 return RPC_S_OUT_OF_MEMORY;
2760 memcpy(url, wszRpcProxyPrefix, sizeof(wszRpcProxyPrefix));
2761 MultiByteToWideChar(CP_ACP, 0, Connection->NetworkAddr, -1, url+ARRAY_SIZE(wszRpcProxyPrefix)-1,
2762 strlen(Connection->NetworkAddr)+1);
2763 lstrcatW(url, L":");
2764 MultiByteToWideChar(CP_ACP, 0, Connection->Endpoint, -1, url+lstrlenW(url), strlen(Connection->Endpoint)+1);
2766 secure = is_secure(httpc);
2767 credentials = has_credentials(httpc);
2769 flags = INTERNET_FLAG_KEEP_CONNECTION | INTERNET_FLAG_PRAGMA_NOCACHE | INTERNET_FLAG_NO_CACHE_WRITE |
2770 INTERNET_FLAG_NO_AUTO_REDIRECT;
2771 if (secure) flags |= INTERNET_FLAG_SECURE;
2772 if (credentials) flags |= INTERNET_FLAG_NO_AUTH;
2774 status = set_auth_cookie(httpc, Connection->CookieAuth);
2775 if (status != RPC_S_OK)
2777 HeapFree(GetProcessHeap(), 0, url);
2778 return status;
2780 httpc->in_request = HttpOpenRequestW(httpc->session, L"RPC_IN_DATA", url, NULL, NULL, wszAcceptTypes,
2781 flags, (DWORD_PTR)httpc->async_data);
2782 if (!httpc->in_request)
2784 ERR("HttpOpenRequestW failed with error %d\n", GetLastError());
2785 HeapFree(GetProcessHeap(), 0, url);
2786 return RPC_S_SERVER_UNAVAILABLE;
2789 if (credentials)
2791 status = authorize_request(httpc, httpc->in_request);
2792 if (status != RPC_S_OK)
2794 HeapFree(GetProcessHeap(), 0, url);
2795 return status;
2797 status = rpcrt4_http_check_response(httpc->in_request);
2798 if (status != RPC_S_OK)
2800 HeapFree(GetProcessHeap(), 0, url);
2801 return status;
2803 drain_content(httpc->in_request, httpc->async_data, httpc->cancel_event);
2806 httpc->out_request = HttpOpenRequestW(httpc->session, L"RPC_OUT_DATA", url, NULL, NULL, wszAcceptTypes,
2807 flags, (DWORD_PTR)httpc->async_data);
2808 HeapFree(GetProcessHeap(), 0, url);
2809 if (!httpc->out_request)
2811 ERR("HttpOpenRequestW failed with error %d\n", GetLastError());
2812 return RPC_S_SERVER_UNAVAILABLE;
2815 if (credentials)
2817 status = authorize_request(httpc, httpc->out_request);
2818 if (status != RPC_S_OK)
2819 return status;
2822 status = rpcrt4_http_prepare_in_pipe(httpc->in_request, httpc->async_data, httpc->cancel_event,
2823 &httpc->connection_uuid, &httpc->in_pipe_uuid,
2824 &Connection->assoc->http_uuid, credentials);
2825 if (status != RPC_S_OK)
2826 return status;
2828 status = rpcrt4_http_prepare_out_pipe(httpc->out_request, httpc->async_data, httpc->cancel_event,
2829 &httpc->connection_uuid, &httpc->out_pipe_uuid,
2830 &httpc->flow_control_increment, credentials);
2831 if (status != RPC_S_OK)
2832 return status;
2834 httpc->flow_control_mark = httpc->flow_control_increment / 2;
2835 httpc->last_sent_time = GetTickCount();
2836 httpc->timer_cancelled = CreateEventW(NULL, FALSE, FALSE, NULL);
2838 timer_data = HeapAlloc(GetProcessHeap(), 0, sizeof(*timer_data));
2839 if (!timer_data)
2840 return ERROR_OUTOFMEMORY;
2841 timer_data->timer_param = httpc->in_request;
2842 timer_data->last_sent_time = &httpc->last_sent_time;
2843 timer_data->timer_cancelled = httpc->timer_cancelled;
2844 /* FIXME: should use CreateTimerQueueTimer when implemented */
2845 thread = CreateThread(NULL, 0, rpcrt4_http_timer_thread, timer_data, 0, NULL);
2846 if (!thread)
2848 HeapFree(GetProcessHeap(), 0, timer_data);
2849 return GetLastError();
2851 CloseHandle(thread);
2853 return RPC_S_OK;
2856 static RPC_STATUS rpcrt4_ncacn_http_handoff(RpcConnection *old_conn, RpcConnection *new_conn)
2858 assert(0);
2859 return RPC_S_SERVER_UNAVAILABLE;
2862 static int rpcrt4_ncacn_http_read(RpcConnection *Connection,
2863 void *buffer, unsigned int count)
2865 RpcConnection_http *httpc = (RpcConnection_http *) Connection;
2866 return rpcrt4_http_async_read(httpc->out_request, httpc->async_data, httpc->cancel_event, buffer, count);
2869 static RPC_STATUS rpcrt4_ncacn_http_receive_fragment(RpcConnection *Connection, RpcPktHdr **Header, void **Payload)
2871 RpcConnection_http *httpc = (RpcConnection_http *) Connection;
2872 RPC_STATUS status;
2873 DWORD hdr_length;
2874 LONG dwRead;
2875 RpcPktCommonHdr common_hdr;
2877 *Header = NULL;
2879 TRACE("(%p, %p, %p)\n", Connection, Header, Payload);
2881 again:
2882 /* read packet common header */
2883 dwRead = rpcrt4_ncacn_http_read(Connection, &common_hdr, sizeof(common_hdr));
2884 if (dwRead != sizeof(common_hdr)) {
2885 WARN("Short read of header, %d bytes\n", dwRead);
2886 status = RPC_S_PROTOCOL_ERROR;
2887 goto fail;
2889 if (!memcmp(&common_hdr, "HTTP/1.1", sizeof("HTTP/1.1")) ||
2890 !memcmp(&common_hdr, "HTTP/1.0", sizeof("HTTP/1.0")))
2892 FIXME("server returned %s\n", debugstr_a((const char *)&common_hdr));
2893 status = RPC_S_PROTOCOL_ERROR;
2894 goto fail;
2897 status = RPCRT4_ValidateCommonHeader(&common_hdr);
2898 if (status != RPC_S_OK) goto fail;
2900 hdr_length = RPCRT4_GetHeaderSize((RpcPktHdr*)&common_hdr);
2901 if (hdr_length == 0) {
2902 WARN("header length == 0\n");
2903 status = RPC_S_PROTOCOL_ERROR;
2904 goto fail;
2907 *Header = HeapAlloc(GetProcessHeap(), 0, hdr_length);
2908 if (!*Header)
2910 status = RPC_S_OUT_OF_RESOURCES;
2911 goto fail;
2913 memcpy(*Header, &common_hdr, sizeof(common_hdr));
2915 /* read the rest of packet header */
2916 dwRead = rpcrt4_ncacn_http_read(Connection, &(*Header)->common + 1, hdr_length - sizeof(common_hdr));
2917 if (dwRead != hdr_length - sizeof(common_hdr)) {
2918 WARN("bad header length, %d bytes, hdr_length %d\n", dwRead, hdr_length);
2919 status = RPC_S_PROTOCOL_ERROR;
2920 goto fail;
2923 if (common_hdr.frag_len - hdr_length)
2925 *Payload = HeapAlloc(GetProcessHeap(), 0, common_hdr.frag_len - hdr_length);
2926 if (!*Payload)
2928 status = RPC_S_OUT_OF_RESOURCES;
2929 goto fail;
2932 dwRead = rpcrt4_ncacn_http_read(Connection, *Payload, common_hdr.frag_len - hdr_length);
2933 if (dwRead != common_hdr.frag_len - hdr_length)
2935 WARN("bad data length, %d/%d\n", dwRead, common_hdr.frag_len - hdr_length);
2936 status = RPC_S_PROTOCOL_ERROR;
2937 goto fail;
2940 else
2941 *Payload = NULL;
2943 if ((*Header)->common.ptype == PKT_HTTP)
2945 if (!RPCRT4_IsValidHttpPacket(*Header, *Payload, common_hdr.frag_len - hdr_length))
2947 ERR("invalid http packet of length %d bytes\n", (*Header)->common.frag_len);
2948 status = RPC_S_PROTOCOL_ERROR;
2949 goto fail;
2951 if ((*Header)->http.flags == 0x0001)
2953 TRACE("http idle packet, waiting for real packet\n");
2954 if ((*Header)->http.num_data_items != 0)
2956 ERR("HTTP idle packet should have no data items instead of %d\n", (*Header)->http.num_data_items);
2957 status = RPC_S_PROTOCOL_ERROR;
2958 goto fail;
2961 else if ((*Header)->http.flags == 0x0002)
2963 ULONG bytes_transmitted;
2964 ULONG flow_control_increment;
2965 UUID pipe_uuid;
2966 status = RPCRT4_ParseHttpFlowControlHeader(*Header, *Payload,
2967 Connection->server,
2968 &bytes_transmitted,
2969 &flow_control_increment,
2970 &pipe_uuid);
2971 if (status != RPC_S_OK)
2972 goto fail;
2973 TRACE("received http flow control header (0x%x, 0x%x, %s)\n",
2974 bytes_transmitted, flow_control_increment, debugstr_guid(&pipe_uuid));
2975 /* FIXME: do something with parsed data */
2977 else
2979 FIXME("unrecognised http packet with flags 0x%04x\n", (*Header)->http.flags);
2980 status = RPC_S_PROTOCOL_ERROR;
2981 goto fail;
2983 RPCRT4_FreeHeader(*Header);
2984 *Header = NULL;
2985 HeapFree(GetProcessHeap(), 0, *Payload);
2986 *Payload = NULL;
2987 goto again;
2990 /* success */
2991 status = RPC_S_OK;
2993 httpc->bytes_received += common_hdr.frag_len;
2995 TRACE("httpc->bytes_received = 0x%x\n", httpc->bytes_received);
2997 if (httpc->bytes_received > httpc->flow_control_mark)
2999 RpcPktHdr *hdr = RPCRT4_BuildHttpFlowControlHeader(httpc->common.server,
3000 httpc->bytes_received,
3001 httpc->flow_control_increment,
3002 &httpc->out_pipe_uuid);
3003 if (hdr)
3005 DWORD bytes_written;
3006 BOOL ret2;
3007 TRACE("sending flow control packet at 0x%x\n", httpc->bytes_received);
3008 ret2 = InternetWriteFile(httpc->in_request, hdr, hdr->common.frag_len, &bytes_written);
3009 RPCRT4_FreeHeader(hdr);
3010 if (ret2)
3011 httpc->flow_control_mark = httpc->bytes_received + httpc->flow_control_increment / 2;
3015 fail:
3016 if (status != RPC_S_OK) {
3017 RPCRT4_FreeHeader(*Header);
3018 *Header = NULL;
3019 HeapFree(GetProcessHeap(), 0, *Payload);
3020 *Payload = NULL;
3022 return status;
3025 static int rpcrt4_ncacn_http_write(RpcConnection *Connection,
3026 const void *buffer, unsigned int count)
3028 RpcConnection_http *httpc = (RpcConnection_http *) Connection;
3029 DWORD bytes_written;
3030 BOOL ret;
3032 httpc->last_sent_time = ~0U; /* disable idle packet sending */
3033 ret = InternetWriteFile(httpc->in_request, buffer, count, &bytes_written);
3034 httpc->last_sent_time = GetTickCount();
3035 TRACE("%p %p %u -> %s\n", httpc->in_request, buffer, count, ret ? "TRUE" : "FALSE");
3036 return ret ? bytes_written : -1;
3039 static int rpcrt4_ncacn_http_close(RpcConnection *Connection)
3041 RpcConnection_http *httpc = (RpcConnection_http *) Connection;
3043 TRACE("\n");
3045 SetEvent(httpc->timer_cancelled);
3046 if (httpc->in_request)
3047 InternetCloseHandle(httpc->in_request);
3048 httpc->in_request = NULL;
3049 if (httpc->out_request)
3050 InternetCloseHandle(httpc->out_request);
3051 httpc->out_request = NULL;
3052 if (httpc->app_info)
3053 InternetCloseHandle(httpc->app_info);
3054 httpc->app_info = NULL;
3055 if (httpc->session)
3056 InternetCloseHandle(httpc->session);
3057 httpc->session = NULL;
3058 RpcHttpAsyncData_Release(httpc->async_data);
3059 if (httpc->cancel_event)
3060 CloseHandle(httpc->cancel_event);
3061 HeapFree(GetProcessHeap(), 0, httpc->servername);
3062 httpc->servername = NULL;
3064 return 0;
3067 static void rpcrt4_ncacn_http_close_read(RpcConnection *conn)
3069 rpcrt4_ncacn_http_close(conn); /* FIXME */
3072 static void rpcrt4_ncacn_http_cancel_call(RpcConnection *Connection)
3074 RpcConnection_http *httpc = (RpcConnection_http *) Connection;
3076 SetEvent(httpc->cancel_event);
3079 static RPC_STATUS rpcrt4_ncacn_http_is_server_listening(const char *endpoint)
3081 FIXME("\n");
3082 return RPC_S_ACCESS_DENIED;
3085 static int rpcrt4_ncacn_http_wait_for_incoming_data(RpcConnection *Connection)
3087 RpcConnection_http *httpc = (RpcConnection_http *) Connection;
3088 BOOL ret;
3089 RPC_STATUS status;
3091 prepare_async_request(httpc->async_data);
3092 ret = InternetQueryDataAvailable(httpc->out_request,
3093 &httpc->async_data->inet_buffers.dwBufferLength, IRF_ASYNC, 0);
3094 status = wait_async_request(httpc->async_data, ret, httpc->cancel_event);
3095 return status == RPC_S_OK ? 0 : -1;
3098 static size_t rpcrt4_ncacn_http_get_top_of_tower(unsigned char *tower_data,
3099 const char *networkaddr,
3100 const char *endpoint)
3102 return rpcrt4_ip_tcp_get_top_of_tower(tower_data, networkaddr,
3103 EPM_PROTOCOL_HTTP, endpoint);
3106 static RPC_STATUS rpcrt4_ncacn_http_parse_top_of_tower(const unsigned char *tower_data,
3107 size_t tower_size,
3108 char **networkaddr,
3109 char **endpoint)
3111 return rpcrt4_ip_tcp_parse_top_of_tower(tower_data, tower_size,
3112 networkaddr, EPM_PROTOCOL_HTTP,
3113 endpoint);
3116 static const struct connection_ops conn_protseq_list[] = {
3117 { "ncacn_np",
3118 { EPM_PROTOCOL_NCACN, EPM_PROTOCOL_SMB },
3119 rpcrt4_conn_np_alloc,
3120 rpcrt4_ncacn_np_open,
3121 rpcrt4_ncacn_np_handoff,
3122 rpcrt4_conn_np_read,
3123 rpcrt4_conn_np_write,
3124 rpcrt4_conn_np_close,
3125 rpcrt4_conn_np_close_read,
3126 rpcrt4_conn_np_cancel_call,
3127 rpcrt4_ncacn_np_is_server_listening,
3128 rpcrt4_conn_np_wait_for_incoming_data,
3129 rpcrt4_ncacn_np_get_top_of_tower,
3130 rpcrt4_ncacn_np_parse_top_of_tower,
3131 NULL,
3132 RPCRT4_default_is_authorized,
3133 RPCRT4_default_authorize,
3134 RPCRT4_default_secure_packet,
3135 rpcrt4_conn_np_impersonate_client,
3136 rpcrt4_conn_np_revert_to_self,
3137 RPCRT4_default_inquire_auth_client,
3139 { "ncalrpc",
3140 { EPM_PROTOCOL_NCALRPC, EPM_PROTOCOL_PIPE },
3141 rpcrt4_conn_np_alloc,
3142 rpcrt4_ncalrpc_open,
3143 rpcrt4_ncalrpc_handoff,
3144 rpcrt4_conn_np_read,
3145 rpcrt4_conn_np_write,
3146 rpcrt4_conn_np_close,
3147 rpcrt4_conn_np_close_read,
3148 rpcrt4_conn_np_cancel_call,
3149 rpcrt4_ncalrpc_np_is_server_listening,
3150 rpcrt4_conn_np_wait_for_incoming_data,
3151 rpcrt4_ncalrpc_get_top_of_tower,
3152 rpcrt4_ncalrpc_parse_top_of_tower,
3153 NULL,
3154 rpcrt4_ncalrpc_is_authorized,
3155 rpcrt4_ncalrpc_authorize,
3156 rpcrt4_ncalrpc_secure_packet,
3157 rpcrt4_conn_np_impersonate_client,
3158 rpcrt4_conn_np_revert_to_self,
3159 rpcrt4_ncalrpc_inquire_auth_client,
3161 { "ncacn_ip_tcp",
3162 { EPM_PROTOCOL_NCACN, EPM_PROTOCOL_TCP },
3163 rpcrt4_conn_tcp_alloc,
3164 rpcrt4_ncacn_ip_tcp_open,
3165 rpcrt4_conn_tcp_handoff,
3166 rpcrt4_conn_tcp_read,
3167 rpcrt4_conn_tcp_write,
3168 rpcrt4_conn_tcp_close,
3169 rpcrt4_conn_tcp_close_read,
3170 rpcrt4_conn_tcp_cancel_call,
3171 rpcrt4_conn_tcp_is_server_listening,
3172 rpcrt4_conn_tcp_wait_for_incoming_data,
3173 rpcrt4_ncacn_ip_tcp_get_top_of_tower,
3174 rpcrt4_ncacn_ip_tcp_parse_top_of_tower,
3175 NULL,
3176 RPCRT4_default_is_authorized,
3177 RPCRT4_default_authorize,
3178 RPCRT4_default_secure_packet,
3179 RPCRT4_default_impersonate_client,
3180 RPCRT4_default_revert_to_self,
3181 RPCRT4_default_inquire_auth_client,
3183 { "ncacn_http",
3184 { EPM_PROTOCOL_NCACN, EPM_PROTOCOL_HTTP },
3185 rpcrt4_ncacn_http_alloc,
3186 rpcrt4_ncacn_http_open,
3187 rpcrt4_ncacn_http_handoff,
3188 rpcrt4_ncacn_http_read,
3189 rpcrt4_ncacn_http_write,
3190 rpcrt4_ncacn_http_close,
3191 rpcrt4_ncacn_http_close_read,
3192 rpcrt4_ncacn_http_cancel_call,
3193 rpcrt4_ncacn_http_is_server_listening,
3194 rpcrt4_ncacn_http_wait_for_incoming_data,
3195 rpcrt4_ncacn_http_get_top_of_tower,
3196 rpcrt4_ncacn_http_parse_top_of_tower,
3197 rpcrt4_ncacn_http_receive_fragment,
3198 RPCRT4_default_is_authorized,
3199 RPCRT4_default_authorize,
3200 RPCRT4_default_secure_packet,
3201 RPCRT4_default_impersonate_client,
3202 RPCRT4_default_revert_to_self,
3203 RPCRT4_default_inquire_auth_client,
3208 static const struct protseq_ops protseq_list[] =
3211 "ncacn_np",
3212 rpcrt4_protseq_np_alloc,
3213 rpcrt4_protseq_np_signal_state_changed,
3214 rpcrt4_protseq_np_get_wait_array,
3215 rpcrt4_protseq_np_free_wait_array,
3216 rpcrt4_protseq_np_wait_for_new_connection,
3217 rpcrt4_protseq_ncacn_np_open_endpoint,
3220 "ncalrpc",
3221 rpcrt4_protseq_np_alloc,
3222 rpcrt4_protseq_np_signal_state_changed,
3223 rpcrt4_protseq_np_get_wait_array,
3224 rpcrt4_protseq_np_free_wait_array,
3225 rpcrt4_protseq_np_wait_for_new_connection,
3226 rpcrt4_protseq_ncalrpc_open_endpoint,
3229 "ncacn_ip_tcp",
3230 rpcrt4_protseq_sock_alloc,
3231 rpcrt4_protseq_sock_signal_state_changed,
3232 rpcrt4_protseq_sock_get_wait_array,
3233 rpcrt4_protseq_sock_free_wait_array,
3234 rpcrt4_protseq_sock_wait_for_new_connection,
3235 rpcrt4_protseq_ncacn_ip_tcp_open_endpoint,
3239 const struct protseq_ops *rpcrt4_get_protseq_ops(const char *protseq)
3241 unsigned int i;
3242 for(i = 0; i < ARRAY_SIZE(protseq_list); i++)
3243 if (!strcmp(protseq_list[i].name, protseq))
3244 return &protseq_list[i];
3245 return NULL;
3248 static const struct connection_ops *rpcrt4_get_conn_protseq_ops(const char *protseq)
3250 unsigned int i;
3251 for(i = 0; i < ARRAY_SIZE(conn_protseq_list); i++)
3252 if (!strcmp(conn_protseq_list[i].name, protseq))
3253 return &conn_protseq_list[i];
3254 return NULL;
3257 /**** interface to rest of code ****/
3259 RPC_STATUS RPCRT4_OpenClientConnection(RpcConnection* Connection)
3261 TRACE("(Connection == ^%p)\n", Connection);
3263 assert(!Connection->server);
3264 return Connection->ops->open_connection_client(Connection);
3267 RPC_STATUS RPCRT4_CloseConnection(RpcConnection* Connection)
3269 TRACE("(Connection == ^%p)\n", Connection);
3270 if (SecIsValidHandle(&Connection->ctx))
3272 DeleteSecurityContext(&Connection->ctx);
3273 SecInvalidateHandle(&Connection->ctx);
3275 rpcrt4_conn_close(Connection);
3276 return RPC_S_OK;
3279 RPC_STATUS RPCRT4_CreateConnection(RpcConnection** Connection, BOOL server,
3280 LPCSTR Protseq, LPCSTR NetworkAddr, LPCSTR Endpoint,
3281 LPCWSTR NetworkOptions, RpcAuthInfo* AuthInfo, RpcQualityOfService *QOS, LPCWSTR CookieAuth)
3283 static LONG next_id;
3284 const struct connection_ops *ops;
3285 RpcConnection* NewConnection;
3287 ops = rpcrt4_get_conn_protseq_ops(Protseq);
3288 if (!ops)
3290 FIXME("not supported for protseq %s\n", Protseq);
3291 return RPC_S_PROTSEQ_NOT_SUPPORTED;
3294 NewConnection = ops->alloc();
3295 NewConnection->ref = 1;
3296 NewConnection->server = server;
3297 NewConnection->ops = ops;
3298 NewConnection->NetworkAddr = RPCRT4_strdupA(NetworkAddr);
3299 NewConnection->Endpoint = RPCRT4_strdupA(Endpoint);
3300 NewConnection->NetworkOptions = RPCRT4_strdupW(NetworkOptions);
3301 NewConnection->CookieAuth = RPCRT4_strdupW(CookieAuth);
3302 NewConnection->MaxTransmissionSize = RPC_MAX_PACKET_SIZE;
3303 NewConnection->NextCallId = 1;
3305 SecInvalidateHandle(&NewConnection->ctx);
3306 if (AuthInfo) RpcAuthInfo_AddRef(AuthInfo);
3307 NewConnection->AuthInfo = AuthInfo;
3308 NewConnection->auth_context_id = InterlockedIncrement( &next_id );
3309 if (QOS) RpcQualityOfService_AddRef(QOS);
3310 NewConnection->QOS = QOS;
3312 list_init(&NewConnection->conn_pool_entry);
3313 list_init(&NewConnection->protseq_entry);
3315 TRACE("connection: %p\n", NewConnection);
3316 *Connection = NewConnection;
3318 return RPC_S_OK;
3321 static RpcConnection *rpcrt4_spawn_connection(RpcConnection *old_connection)
3323 RpcConnection *connection;
3324 RPC_STATUS err;
3326 err = RPCRT4_CreateConnection(&connection, old_connection->server, rpcrt4_conn_get_name(old_connection),
3327 old_connection->NetworkAddr, old_connection->Endpoint, NULL,
3328 old_connection->AuthInfo, old_connection->QOS, old_connection->CookieAuth);
3329 if (err != RPC_S_OK)
3330 return NULL;
3332 rpcrt4_conn_handoff(old_connection, connection);
3333 if (old_connection->protseq)
3335 EnterCriticalSection(&old_connection->protseq->cs);
3336 connection->protseq = old_connection->protseq;
3337 list_add_tail(&old_connection->protseq->connections, &connection->protseq_entry);
3338 LeaveCriticalSection(&old_connection->protseq->cs);
3340 return connection;
3343 void rpcrt4_conn_release_and_wait(RpcConnection *connection)
3345 HANDLE event = NULL;
3347 if (connection->ref > 1)
3348 event = connection->wait_release = CreateEventW(NULL, TRUE, FALSE, NULL);
3350 RPCRT4_ReleaseConnection(connection);
3352 if(event)
3354 WaitForSingleObject(event, INFINITE);
3355 CloseHandle(event);
3359 RpcConnection *RPCRT4_GrabConnection(RpcConnection *connection)
3361 LONG ref = InterlockedIncrement(&connection->ref);
3362 TRACE("%p ref=%u\n", connection, ref);
3363 return connection;
3366 void RPCRT4_ReleaseConnection(RpcConnection *connection)
3368 LONG ref;
3370 /* protseq stores a list of active connections, but does not own references to them.
3371 * It may need to grab a connection from the list, which could lead to a race if
3372 * connection is being released, but not yet removed from the list. We handle that
3373 * by synchronizing on CS here. */
3374 if (connection->protseq)
3376 EnterCriticalSection(&connection->protseq->cs);
3377 ref = InterlockedDecrement(&connection->ref);
3378 if (!ref)
3379 list_remove(&connection->protseq_entry);
3380 LeaveCriticalSection(&connection->protseq->cs);
3382 else
3384 ref = InterlockedDecrement(&connection->ref);
3387 TRACE("%p ref=%u\n", connection, ref);
3389 if (!ref)
3391 RPCRT4_CloseConnection(connection);
3392 RPCRT4_strfree(connection->Endpoint);
3393 RPCRT4_strfree(connection->NetworkAddr);
3394 HeapFree(GetProcessHeap(), 0, connection->NetworkOptions);
3395 HeapFree(GetProcessHeap(), 0, connection->CookieAuth);
3396 if (connection->AuthInfo) RpcAuthInfo_Release(connection->AuthInfo);
3397 if (connection->QOS) RpcQualityOfService_Release(connection->QOS);
3399 /* server-only */
3400 if (connection->server_binding) RPCRT4_ReleaseBinding(connection->server_binding);
3401 else if (connection->assoc) RpcAssoc_ConnectionReleased(connection->assoc);
3403 if (connection->wait_release) SetEvent(connection->wait_release);
3405 HeapFree(GetProcessHeap(), 0, connection);
3409 RPC_STATUS RPCRT4_IsServerListening(const char *protseq, const char *endpoint)
3411 const struct connection_ops *ops;
3413 ops = rpcrt4_get_conn_protseq_ops(protseq);
3414 if (!ops)
3416 FIXME("not supported for protseq %s\n", protseq);
3417 return RPC_S_INVALID_BINDING;
3420 return ops->is_server_listening(endpoint);
3423 RPC_STATUS RpcTransport_GetTopOfTower(unsigned char *tower_data,
3424 size_t *tower_size,
3425 const char *protseq,
3426 const char *networkaddr,
3427 const char *endpoint)
3429 twr_empty_floor_t *protocol_floor;
3430 const struct connection_ops *protseq_ops = rpcrt4_get_conn_protseq_ops(protseq);
3432 *tower_size = 0;
3434 if (!protseq_ops)
3435 return RPC_S_INVALID_RPC_PROTSEQ;
3437 if (!tower_data)
3439 *tower_size = sizeof(*protocol_floor);
3440 *tower_size += protseq_ops->get_top_of_tower(NULL, networkaddr, endpoint);
3441 return RPC_S_OK;
3444 protocol_floor = (twr_empty_floor_t *)tower_data;
3445 protocol_floor->count_lhs = sizeof(protocol_floor->protid);
3446 protocol_floor->protid = protseq_ops->epm_protocols[0];
3447 protocol_floor->count_rhs = 0;
3449 tower_data += sizeof(*protocol_floor);
3451 *tower_size = protseq_ops->get_top_of_tower(tower_data, networkaddr, endpoint);
3452 if (!*tower_size)
3453 return EPT_S_NOT_REGISTERED;
3455 *tower_size += sizeof(*protocol_floor);
3457 return RPC_S_OK;
3460 RPC_STATUS RpcTransport_ParseTopOfTower(const unsigned char *tower_data,
3461 size_t tower_size,
3462 char **protseq,
3463 char **networkaddr,
3464 char **endpoint)
3466 const twr_empty_floor_t *protocol_floor;
3467 const twr_empty_floor_t *floor4;
3468 const struct connection_ops *protseq_ops = NULL;
3469 RPC_STATUS status;
3470 unsigned int i;
3472 if (tower_size < sizeof(*protocol_floor))
3473 return EPT_S_NOT_REGISTERED;
3475 protocol_floor = (const twr_empty_floor_t *)tower_data;
3476 tower_data += sizeof(*protocol_floor);
3477 tower_size -= sizeof(*protocol_floor);
3478 if ((protocol_floor->count_lhs != sizeof(protocol_floor->protid)) ||
3479 (protocol_floor->count_rhs > tower_size))
3480 return EPT_S_NOT_REGISTERED;
3481 tower_data += protocol_floor->count_rhs;
3482 tower_size -= protocol_floor->count_rhs;
3484 floor4 = (const twr_empty_floor_t *)tower_data;
3485 if ((tower_size < sizeof(*floor4)) ||
3486 (floor4->count_lhs != sizeof(floor4->protid)))
3487 return EPT_S_NOT_REGISTERED;
3489 for(i = 0; i < ARRAY_SIZE(conn_protseq_list); i++)
3490 if ((protocol_floor->protid == conn_protseq_list[i].epm_protocols[0]) &&
3491 (floor4->protid == conn_protseq_list[i].epm_protocols[1]))
3493 protseq_ops = &conn_protseq_list[i];
3494 break;
3497 if (!protseq_ops)
3498 return EPT_S_NOT_REGISTERED;
3500 status = protseq_ops->parse_top_of_tower(tower_data, tower_size, networkaddr, endpoint);
3502 if ((status == RPC_S_OK) && protseq)
3504 *protseq = I_RpcAllocate(strlen(protseq_ops->name) + 1);
3505 strcpy(*protseq, protseq_ops->name);
3508 return status;
3511 /***********************************************************************
3512 * RpcNetworkIsProtseqValidW (RPCRT4.@)
3514 * Checks if the given protocol sequence is known by the RPC system.
3515 * If it is, returns RPC_S_OK, otherwise RPC_S_PROTSEQ_NOT_SUPPORTED.
3518 RPC_STATUS WINAPI RpcNetworkIsProtseqValidW(RPC_WSTR protseq)
3520 char ps[0x10];
3522 WideCharToMultiByte(CP_ACP, 0, protseq, -1,
3523 ps, sizeof ps, NULL, NULL);
3524 if (rpcrt4_get_conn_protseq_ops(ps))
3525 return RPC_S_OK;
3527 FIXME("Unknown protseq %s\n", debugstr_w(protseq));
3529 return RPC_S_INVALID_RPC_PROTSEQ;
3532 /***********************************************************************
3533 * RpcNetworkIsProtseqValidA (RPCRT4.@)
3535 RPC_STATUS WINAPI RpcNetworkIsProtseqValidA(RPC_CSTR protseq)
3537 UNICODE_STRING protseqW;
3539 if (RtlCreateUnicodeStringFromAsciiz(&protseqW, (char*)protseq))
3541 RPC_STATUS ret = RpcNetworkIsProtseqValidW(protseqW.Buffer);
3542 RtlFreeUnicodeString(&protseqW);
3543 return ret;
3545 return RPC_S_OUT_OF_MEMORY;
3548 /***********************************************************************
3549 * RpcProtseqVectorFreeA (RPCRT4.@)
3551 RPC_STATUS WINAPI RpcProtseqVectorFreeA(RPC_PROTSEQ_VECTORA **protseqs)
3553 TRACE("(%p)\n", protseqs);
3555 if (*protseqs)
3557 unsigned int i;
3558 for (i = 0; i < (*protseqs)->Count; i++)
3559 HeapFree(GetProcessHeap(), 0, (*protseqs)->Protseq[i]);
3560 HeapFree(GetProcessHeap(), 0, *protseqs);
3561 *protseqs = NULL;
3563 return RPC_S_OK;
3566 /***********************************************************************
3567 * RpcProtseqVectorFreeW (RPCRT4.@)
3569 RPC_STATUS WINAPI RpcProtseqVectorFreeW(RPC_PROTSEQ_VECTORW **protseqs)
3571 TRACE("(%p)\n", protseqs);
3573 if (*protseqs)
3575 unsigned int i;
3576 for (i = 0; i < (*protseqs)->Count; i++)
3577 HeapFree(GetProcessHeap(), 0, (*protseqs)->Protseq[i]);
3578 HeapFree(GetProcessHeap(), 0, *protseqs);
3579 *protseqs = NULL;
3581 return RPC_S_OK;
3584 /***********************************************************************
3585 * RpcNetworkInqProtseqsW (RPCRT4.@)
3587 RPC_STATUS WINAPI RpcNetworkInqProtseqsW( RPC_PROTSEQ_VECTORW** protseqs )
3589 RPC_PROTSEQ_VECTORW *pvector;
3590 unsigned int i;
3591 RPC_STATUS status = RPC_S_OUT_OF_MEMORY;
3593 TRACE("(%p)\n", protseqs);
3595 *protseqs = HeapAlloc(GetProcessHeap(), 0, sizeof(RPC_PROTSEQ_VECTORW)+(sizeof(unsigned short*)*ARRAY_SIZE(protseq_list)));
3596 if (!*protseqs)
3597 goto end;
3598 pvector = *protseqs;
3599 pvector->Count = 0;
3600 for (i = 0; i < ARRAY_SIZE(protseq_list); i++)
3602 pvector->Protseq[i] = HeapAlloc(GetProcessHeap(), 0, (strlen(protseq_list[i].name)+1)*sizeof(unsigned short));
3603 if (pvector->Protseq[i] == NULL)
3604 goto end;
3605 MultiByteToWideChar(CP_ACP, 0, (CHAR*)protseq_list[i].name, -1,
3606 (WCHAR*)pvector->Protseq[i], strlen(protseq_list[i].name) + 1);
3607 pvector->Count++;
3609 status = RPC_S_OK;
3611 end:
3612 if (status != RPC_S_OK)
3613 RpcProtseqVectorFreeW(protseqs);
3614 return status;
3617 /***********************************************************************
3618 * RpcNetworkInqProtseqsA (RPCRT4.@)
3620 RPC_STATUS WINAPI RpcNetworkInqProtseqsA(RPC_PROTSEQ_VECTORA** protseqs)
3622 RPC_PROTSEQ_VECTORA *pvector;
3623 unsigned int i;
3624 RPC_STATUS status = RPC_S_OUT_OF_MEMORY;
3626 TRACE("(%p)\n", protseqs);
3628 *protseqs = HeapAlloc(GetProcessHeap(), 0, sizeof(RPC_PROTSEQ_VECTORW)+(sizeof(unsigned char*)*ARRAY_SIZE(protseq_list)));
3629 if (!*protseqs)
3630 goto end;
3631 pvector = *protseqs;
3632 pvector->Count = 0;
3633 for (i = 0; i < ARRAY_SIZE(protseq_list); i++)
3635 pvector->Protseq[i] = HeapAlloc(GetProcessHeap(), 0, strlen(protseq_list[i].name)+1);
3636 if (pvector->Protseq[i] == NULL)
3637 goto end;
3638 strcpy((char*)pvector->Protseq[i], protseq_list[i].name);
3639 pvector->Count++;
3641 status = RPC_S_OK;
3643 end:
3644 if (status != RPC_S_OK)
3645 RpcProtseqVectorFreeA(protseqs);
3646 return status;