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