rpcrt4: Free url in error paths (Coverity).
[wine.git] / dlls / rpcrt4 / rpc_transport.c
blobc004f66a26939fc696d6497fd84ae5711adbc2c9
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 <stdlib.h>
33 #include <sys/types.h>
35 #if defined(__MINGW32__) || defined (_MSC_VER)
36 # include <ws2tcpip.h>
37 # ifndef EADDRINUSE
38 # define EADDRINUSE WSAEADDRINUSE
39 # endif
40 # ifndef EAGAIN
41 # define EAGAIN WSAEWOULDBLOCK
42 # endif
43 # undef errno
44 # define errno WSAGetLastError()
45 #else
46 # include <errno.h>
47 # ifdef HAVE_UNISTD_H
48 # include <unistd.h>
49 # endif
50 # include <fcntl.h>
51 # ifdef HAVE_SYS_SOCKET_H
52 # include <sys/socket.h>
53 # endif
54 # ifdef HAVE_NETINET_IN_H
55 # include <netinet/in.h>
56 # endif
57 # ifdef HAVE_NETINET_TCP_H
58 # include <netinet/tcp.h>
59 # endif
60 # ifdef HAVE_ARPA_INET_H
61 # include <arpa/inet.h>
62 # endif
63 # ifdef HAVE_NETDB_H
64 # include <netdb.h>
65 # endif
66 # ifdef HAVE_SYS_POLL_H
67 # include <sys/poll.h>
68 # endif
69 # ifdef HAVE_SYS_FILIO_H
70 # include <sys/filio.h>
71 # endif
72 # ifdef HAVE_SYS_IOCTL_H
73 # include <sys/ioctl.h>
74 # endif
75 # define closesocket close
76 # define ioctlsocket ioctl
77 #endif /* defined(__MINGW32__) || defined (_MSC_VER) */
79 #include "windef.h"
80 #include "winbase.h"
81 #include "winnls.h"
82 #include "winerror.h"
83 #include "wininet.h"
84 #include "winternl.h"
85 #include "wine/unicode.h"
87 #include "rpc.h"
88 #include "rpcndr.h"
90 #include "wine/debug.h"
92 #include "rpc_binding.h"
93 #include "rpc_assoc.h"
94 #include "rpc_message.h"
95 #include "rpc_server.h"
96 #include "epm_towers.h"
98 #ifndef SOL_TCP
99 # define SOL_TCP IPPROTO_TCP
100 #endif
102 #define DEFAULT_NCACN_HTTP_TIMEOUT (60 * 1000)
104 WINE_DEFAULT_DEBUG_CHANNEL(rpc);
106 static RPC_STATUS RPCRT4_SpawnConnection(RpcConnection** Connection, RpcConnection* OldConnection);
108 /**** ncacn_np support ****/
110 typedef struct _RpcConnection_np
112 RpcConnection common;
113 HANDLE pipe;
114 HANDLE listen_thread;
115 BOOL listening;
116 } RpcConnection_np;
118 static RpcConnection *rpcrt4_conn_np_alloc(void)
120 RpcConnection_np *npc = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(RpcConnection_np));
121 return &npc->common;
124 static DWORD CALLBACK listen_thread(void *arg)
126 RpcConnection_np *npc = arg;
127 for (;;)
129 if (ConnectNamedPipe(npc->pipe, NULL))
130 return RPC_S_OK;
132 switch(GetLastError())
134 case ERROR_PIPE_CONNECTED:
135 return RPC_S_OK;
136 case ERROR_HANDLES_CLOSED:
137 /* connection closed during listen */
138 return RPC_S_NO_CONTEXT_AVAILABLE;
139 case ERROR_NO_DATA_DETECTED:
140 /* client has disconnected, retry */
141 DisconnectNamedPipe( npc->pipe );
142 break;
143 default:
144 npc->listening = FALSE;
145 WARN("Couldn't ConnectNamedPipe (error was %d)\n", GetLastError());
146 return RPC_S_OUT_OF_RESOURCES;
151 static RPC_STATUS rpcrt4_conn_listen_pipe(RpcConnection_np *npc)
153 if (npc->listening)
154 return RPC_S_OK;
156 npc->listening = TRUE;
157 npc->listen_thread = CreateThread(NULL, 0, listen_thread, npc, 0, NULL);
158 if (!npc->listen_thread)
160 npc->listening = FALSE;
161 ERR("Couldn't create listen thread (error was %d)\n", GetLastError());
162 return RPC_S_OUT_OF_RESOURCES;
164 return RPC_S_OK;
167 static RPC_STATUS rpcrt4_conn_create_pipe(RpcConnection *Connection, LPCSTR pname)
169 RpcConnection_np *npc = (RpcConnection_np *) Connection;
170 TRACE("listening on %s\n", pname);
172 npc->pipe = CreateNamedPipeA(pname, PIPE_ACCESS_DUPLEX,
173 PIPE_TYPE_MESSAGE | PIPE_READMODE_MESSAGE,
174 PIPE_UNLIMITED_INSTANCES,
175 RPC_MAX_PACKET_SIZE, RPC_MAX_PACKET_SIZE, 5000, NULL);
176 if (npc->pipe == INVALID_HANDLE_VALUE) {
177 WARN("CreateNamedPipe failed with error %d\n", GetLastError());
178 if (GetLastError() == ERROR_FILE_EXISTS)
179 return RPC_S_DUPLICATE_ENDPOINT;
180 else
181 return RPC_S_CANT_CREATE_ENDPOINT;
184 /* Note: we don't call ConnectNamedPipe here because it must be done in the
185 * server thread as the thread must be alertable */
186 return RPC_S_OK;
189 static RPC_STATUS rpcrt4_conn_open_pipe(RpcConnection *Connection, LPCSTR pname, BOOL wait)
191 RpcConnection_np *npc = (RpcConnection_np *) Connection;
192 HANDLE pipe;
193 DWORD err, dwMode;
195 TRACE("connecting to %s\n", pname);
197 while (TRUE) {
198 DWORD dwFlags = 0;
199 if (Connection->QOS)
201 dwFlags = SECURITY_SQOS_PRESENT;
202 switch (Connection->QOS->qos->ImpersonationType)
204 case RPC_C_IMP_LEVEL_DEFAULT:
205 /* FIXME: what to do here? */
206 break;
207 case RPC_C_IMP_LEVEL_ANONYMOUS:
208 dwFlags |= SECURITY_ANONYMOUS;
209 break;
210 case RPC_C_IMP_LEVEL_IDENTIFY:
211 dwFlags |= SECURITY_IDENTIFICATION;
212 break;
213 case RPC_C_IMP_LEVEL_IMPERSONATE:
214 dwFlags |= SECURITY_IMPERSONATION;
215 break;
216 case RPC_C_IMP_LEVEL_DELEGATE:
217 dwFlags |= SECURITY_DELEGATION;
218 break;
220 if (Connection->QOS->qos->IdentityTracking == RPC_C_QOS_IDENTITY_DYNAMIC)
221 dwFlags |= SECURITY_CONTEXT_TRACKING;
223 pipe = CreateFileA(pname, GENERIC_READ|GENERIC_WRITE, 0, NULL,
224 OPEN_EXISTING, dwFlags, 0);
225 if (pipe != INVALID_HANDLE_VALUE) break;
226 err = GetLastError();
227 if (err == ERROR_PIPE_BUSY) {
228 TRACE("connection failed, error=%x\n", err);
229 return RPC_S_SERVER_TOO_BUSY;
231 if (!wait || !WaitNamedPipeA(pname, NMPWAIT_WAIT_FOREVER)) {
232 err = GetLastError();
233 WARN("connection failed, error=%x\n", err);
234 return RPC_S_SERVER_UNAVAILABLE;
238 /* success */
239 /* pipe is connected; change to message-read mode. */
240 dwMode = PIPE_READMODE_MESSAGE;
241 SetNamedPipeHandleState(pipe, &dwMode, NULL, NULL);
242 npc->pipe = pipe;
244 return RPC_S_OK;
247 static RPC_STATUS rpcrt4_ncalrpc_open(RpcConnection* Connection)
249 RpcConnection_np *npc = (RpcConnection_np *) Connection;
250 static const char prefix[] = "\\\\.\\pipe\\lrpc\\";
251 RPC_STATUS r;
252 LPSTR pname;
254 /* already connected? */
255 if (npc->pipe)
256 return RPC_S_OK;
258 /* protseq=ncalrpc: supposed to use NT LPC ports,
259 * but we'll implement it with named pipes for now */
260 pname = I_RpcAllocate(strlen(prefix) + strlen(Connection->Endpoint) + 1);
261 strcat(strcpy(pname, prefix), Connection->Endpoint);
262 r = rpcrt4_conn_open_pipe(Connection, pname, TRUE);
263 I_RpcFree(pname);
265 return r;
268 static RPC_STATUS rpcrt4_protseq_ncalrpc_open_endpoint(RpcServerProtseq* protseq, const char *endpoint)
270 static const char prefix[] = "\\\\.\\pipe\\lrpc\\";
271 RPC_STATUS r;
272 LPSTR pname;
273 RpcConnection *Connection;
274 char generated_endpoint[22];
276 if (!endpoint)
278 static LONG lrpc_nameless_id;
279 DWORD process_id = GetCurrentProcessId();
280 ULONG id = InterlockedIncrement(&lrpc_nameless_id);
281 snprintf(generated_endpoint, sizeof(generated_endpoint),
282 "LRPC%08x.%08x", process_id, id);
283 endpoint = generated_endpoint;
286 r = RPCRT4_CreateConnection(&Connection, TRUE, protseq->Protseq, NULL,
287 endpoint, NULL, NULL, NULL, NULL);
288 if (r != RPC_S_OK)
289 return r;
291 /* protseq=ncalrpc: supposed to use NT LPC ports,
292 * but we'll implement it with named pipes for now */
293 pname = I_RpcAllocate(strlen(prefix) + strlen(Connection->Endpoint) + 1);
294 strcat(strcpy(pname, prefix), Connection->Endpoint);
295 r = rpcrt4_conn_create_pipe(Connection, pname);
296 I_RpcFree(pname);
298 EnterCriticalSection(&protseq->cs);
299 Connection->Next = protseq->conn;
300 protseq->conn = Connection;
301 LeaveCriticalSection(&protseq->cs);
303 return r;
306 static RPC_STATUS rpcrt4_ncacn_np_open(RpcConnection* Connection)
308 RpcConnection_np *npc = (RpcConnection_np *) Connection;
309 static const char prefix[] = "\\\\.";
310 RPC_STATUS r;
311 LPSTR pname;
313 /* already connected? */
314 if (npc->pipe)
315 return RPC_S_OK;
317 /* protseq=ncacn_np: named pipes */
318 pname = I_RpcAllocate(strlen(prefix) + strlen(Connection->Endpoint) + 1);
319 strcat(strcpy(pname, prefix), Connection->Endpoint);
320 r = rpcrt4_conn_open_pipe(Connection, pname, FALSE);
321 I_RpcFree(pname);
323 return r;
326 static RPC_STATUS rpcrt4_protseq_ncacn_np_open_endpoint(RpcServerProtseq *protseq, const char *endpoint)
328 static const char prefix[] = "\\\\.";
329 RPC_STATUS r;
330 LPSTR pname;
331 RpcConnection *Connection;
332 char generated_endpoint[21];
334 if (!endpoint)
336 static LONG np_nameless_id;
337 DWORD process_id = GetCurrentProcessId();
338 ULONG id = InterlockedExchangeAdd(&np_nameless_id, 1 );
339 snprintf(generated_endpoint, sizeof(generated_endpoint),
340 "\\\\pipe\\\\%08x.%03x", process_id, id);
341 endpoint = generated_endpoint;
344 r = RPCRT4_CreateConnection(&Connection, TRUE, protseq->Protseq, NULL,
345 endpoint, NULL, NULL, NULL, NULL);
346 if (r != RPC_S_OK)
347 return r;
349 /* protseq=ncacn_np: named pipes */
350 pname = I_RpcAllocate(strlen(prefix) + strlen(Connection->Endpoint) + 1);
351 strcat(strcpy(pname, prefix), Connection->Endpoint);
352 r = rpcrt4_conn_create_pipe(Connection, pname);
353 I_RpcFree(pname);
355 EnterCriticalSection(&protseq->cs);
356 Connection->Next = protseq->conn;
357 protseq->conn = Connection;
358 LeaveCriticalSection(&protseq->cs);
360 return r;
363 static void rpcrt4_conn_np_handoff(RpcConnection_np *old_npc, RpcConnection_np *new_npc)
365 /* because of the way named pipes work, we'll transfer the connected pipe
366 * to the child, then reopen the server binding to continue listening */
368 new_npc->pipe = old_npc->pipe;
369 new_npc->listen_thread = old_npc->listen_thread;
370 old_npc->pipe = 0;
371 old_npc->listen_thread = 0;
372 old_npc->listening = FALSE;
375 static RPC_STATUS rpcrt4_ncacn_np_handoff(RpcConnection *old_conn, RpcConnection *new_conn)
377 RPC_STATUS status;
378 LPSTR pname;
379 static const char prefix[] = "\\\\.";
381 rpcrt4_conn_np_handoff((RpcConnection_np *)old_conn, (RpcConnection_np *)new_conn);
383 pname = I_RpcAllocate(strlen(prefix) + strlen(old_conn->Endpoint) + 1);
384 strcat(strcpy(pname, prefix), old_conn->Endpoint);
385 status = rpcrt4_conn_create_pipe(old_conn, pname);
386 I_RpcFree(pname);
388 return status;
391 static RPC_STATUS rpcrt4_ncalrpc_handoff(RpcConnection *old_conn, RpcConnection *new_conn)
393 RPC_STATUS status;
394 LPSTR pname;
395 static const char prefix[] = "\\\\.\\pipe\\lrpc\\";
397 TRACE("%s\n", old_conn->Endpoint);
399 rpcrt4_conn_np_handoff((RpcConnection_np *)old_conn, (RpcConnection_np *)new_conn);
401 pname = I_RpcAllocate(strlen(prefix) + strlen(old_conn->Endpoint) + 1);
402 strcat(strcpy(pname, prefix), old_conn->Endpoint);
403 status = rpcrt4_conn_create_pipe(old_conn, pname);
404 I_RpcFree(pname);
406 return status;
409 static int rpcrt4_conn_np_read(RpcConnection *Connection,
410 void *buffer, unsigned int count)
412 RpcConnection_np *npc = (RpcConnection_np *) Connection;
413 char *buf = buffer;
414 BOOL ret = TRUE;
415 unsigned int bytes_left = count;
417 while (bytes_left)
419 DWORD bytes_read;
420 ret = ReadFile(npc->pipe, buf, bytes_left, &bytes_read, NULL);
421 if (!ret && GetLastError() == ERROR_MORE_DATA)
422 ret = TRUE;
423 if (!ret || !bytes_read)
424 break;
425 bytes_left -= bytes_read;
426 buf += bytes_read;
428 return ret ? count : -1;
431 static int rpcrt4_conn_np_write(RpcConnection *Connection,
432 const void *buffer, unsigned int count)
434 RpcConnection_np *npc = (RpcConnection_np *) Connection;
435 const char *buf = buffer;
436 BOOL ret = TRUE;
437 unsigned int bytes_left = count;
439 while (bytes_left)
441 DWORD bytes_written;
442 ret = WriteFile(npc->pipe, buf, bytes_left, &bytes_written, NULL);
443 if (!ret || !bytes_written)
444 break;
445 bytes_left -= bytes_written;
446 buf += bytes_written;
448 return ret ? count : -1;
451 static int rpcrt4_conn_np_close(RpcConnection *Connection)
453 RpcConnection_np *npc = (RpcConnection_np *) Connection;
454 if (npc->pipe) {
455 FlushFileBuffers(npc->pipe);
456 CloseHandle(npc->pipe);
457 npc->pipe = 0;
459 if (npc->listen_thread) {
460 CloseHandle(npc->listen_thread);
461 npc->listen_thread = 0;
463 return 0;
466 static void rpcrt4_conn_np_cancel_call(RpcConnection *Connection)
468 /* FIXME: implement when named pipe writes use overlapped I/O */
471 static int rpcrt4_conn_np_wait_for_incoming_data(RpcConnection *Connection)
473 /* FIXME: implement when named pipe writes use overlapped I/O */
474 return -1;
477 static size_t rpcrt4_ncacn_np_get_top_of_tower(unsigned char *tower_data,
478 const char *networkaddr,
479 const char *endpoint)
481 twr_empty_floor_t *smb_floor;
482 twr_empty_floor_t *nb_floor;
483 size_t size;
484 size_t networkaddr_size;
485 size_t endpoint_size;
487 TRACE("(%p, %s, %s)\n", tower_data, networkaddr, endpoint);
489 networkaddr_size = networkaddr ? strlen(networkaddr) + 1 : 1;
490 endpoint_size = endpoint ? strlen(endpoint) + 1 : 1;
491 size = sizeof(*smb_floor) + endpoint_size + sizeof(*nb_floor) + networkaddr_size;
493 if (!tower_data)
494 return size;
496 smb_floor = (twr_empty_floor_t *)tower_data;
498 tower_data += sizeof(*smb_floor);
500 smb_floor->count_lhs = sizeof(smb_floor->protid);
501 smb_floor->protid = EPM_PROTOCOL_SMB;
502 smb_floor->count_rhs = endpoint_size;
504 if (endpoint)
505 memcpy(tower_data, endpoint, endpoint_size);
506 else
507 tower_data[0] = 0;
508 tower_data += endpoint_size;
510 nb_floor = (twr_empty_floor_t *)tower_data;
512 tower_data += sizeof(*nb_floor);
514 nb_floor->count_lhs = sizeof(nb_floor->protid);
515 nb_floor->protid = EPM_PROTOCOL_NETBIOS;
516 nb_floor->count_rhs = networkaddr_size;
518 if (networkaddr)
519 memcpy(tower_data, networkaddr, networkaddr_size);
520 else
521 tower_data[0] = 0;
523 return size;
526 static RPC_STATUS rpcrt4_ncacn_np_parse_top_of_tower(const unsigned char *tower_data,
527 size_t tower_size,
528 char **networkaddr,
529 char **endpoint)
531 const twr_empty_floor_t *smb_floor = (const twr_empty_floor_t *)tower_data;
532 const twr_empty_floor_t *nb_floor;
534 TRACE("(%p, %d, %p, %p)\n", tower_data, (int)tower_size, networkaddr, endpoint);
536 if (tower_size < sizeof(*smb_floor))
537 return EPT_S_NOT_REGISTERED;
539 tower_data += sizeof(*smb_floor);
540 tower_size -= sizeof(*smb_floor);
542 if ((smb_floor->count_lhs != sizeof(smb_floor->protid)) ||
543 (smb_floor->protid != EPM_PROTOCOL_SMB) ||
544 (smb_floor->count_rhs > tower_size) ||
545 (tower_data[smb_floor->count_rhs - 1] != '\0'))
546 return EPT_S_NOT_REGISTERED;
548 if (endpoint)
550 *endpoint = I_RpcAllocate(smb_floor->count_rhs);
551 if (!*endpoint)
552 return RPC_S_OUT_OF_RESOURCES;
553 memcpy(*endpoint, tower_data, smb_floor->count_rhs);
555 tower_data += smb_floor->count_rhs;
556 tower_size -= smb_floor->count_rhs;
558 if (tower_size < sizeof(*nb_floor))
559 return EPT_S_NOT_REGISTERED;
561 nb_floor = (const twr_empty_floor_t *)tower_data;
563 tower_data += sizeof(*nb_floor);
564 tower_size -= sizeof(*nb_floor);
566 if ((nb_floor->count_lhs != sizeof(nb_floor->protid)) ||
567 (nb_floor->protid != EPM_PROTOCOL_NETBIOS) ||
568 (nb_floor->count_rhs > tower_size) ||
569 (tower_data[nb_floor->count_rhs - 1] != '\0'))
570 return EPT_S_NOT_REGISTERED;
572 if (networkaddr)
574 *networkaddr = I_RpcAllocate(nb_floor->count_rhs);
575 if (!*networkaddr)
577 if (endpoint)
579 I_RpcFree(*endpoint);
580 *endpoint = NULL;
582 return RPC_S_OUT_OF_RESOURCES;
584 memcpy(*networkaddr, tower_data, nb_floor->count_rhs);
587 return RPC_S_OK;
590 static RPC_STATUS rpcrt4_conn_np_impersonate_client(RpcConnection *conn)
592 RpcConnection_np *npc = (RpcConnection_np *)conn;
593 BOOL ret;
595 TRACE("(%p)\n", conn);
597 if (conn->AuthInfo && SecIsValidHandle(&conn->ctx))
598 return RPCRT4_default_impersonate_client(conn);
600 ret = ImpersonateNamedPipeClient(npc->pipe);
601 if (!ret)
603 DWORD error = GetLastError();
604 WARN("ImpersonateNamedPipeClient failed with error %u\n", error);
605 switch (error)
607 case ERROR_CANNOT_IMPERSONATE:
608 return RPC_S_NO_CONTEXT_AVAILABLE;
611 return RPC_S_OK;
614 static RPC_STATUS rpcrt4_conn_np_revert_to_self(RpcConnection *conn)
616 BOOL ret;
618 TRACE("(%p)\n", conn);
620 if (conn->AuthInfo && SecIsValidHandle(&conn->ctx))
621 return RPCRT4_default_revert_to_self(conn);
623 ret = RevertToSelf();
624 if (!ret)
626 WARN("RevertToSelf failed with error %u\n", GetLastError());
627 return RPC_S_NO_CONTEXT_AVAILABLE;
629 return RPC_S_OK;
632 typedef struct _RpcServerProtseq_np
634 RpcServerProtseq common;
635 HANDLE mgr_event;
636 } RpcServerProtseq_np;
638 static RpcServerProtseq *rpcrt4_protseq_np_alloc(void)
640 RpcServerProtseq_np *ps = HeapAlloc(GetProcessHeap(), 0, sizeof(*ps));
641 if (ps)
642 ps->mgr_event = CreateEventW(NULL, FALSE, FALSE, NULL);
643 return &ps->common;
646 static void rpcrt4_protseq_np_signal_state_changed(RpcServerProtseq *protseq)
648 RpcServerProtseq_np *npps = CONTAINING_RECORD(protseq, RpcServerProtseq_np, common);
649 SetEvent(npps->mgr_event);
652 static void *rpcrt4_protseq_np_get_wait_array(RpcServerProtseq *protseq, void *prev_array, unsigned int *count)
654 HANDLE *objs = prev_array;
655 RpcConnection_np *conn;
656 RpcServerProtseq_np *npps = CONTAINING_RECORD(protseq, RpcServerProtseq_np, common);
658 EnterCriticalSection(&protseq->cs);
660 /* open and count connections */
661 *count = 1;
662 conn = CONTAINING_RECORD(protseq->conn, RpcConnection_np, common);
663 while (conn) {
664 rpcrt4_conn_listen_pipe(conn);
665 if (conn->listen_thread)
666 (*count)++;
667 conn = CONTAINING_RECORD(conn->common.Next, RpcConnection_np, common);
670 /* make array of connections */
671 if (objs)
672 objs = HeapReAlloc(GetProcessHeap(), 0, objs, *count*sizeof(HANDLE));
673 else
674 objs = HeapAlloc(GetProcessHeap(), 0, *count*sizeof(HANDLE));
675 if (!objs)
677 ERR("couldn't allocate objs\n");
678 LeaveCriticalSection(&protseq->cs);
679 return NULL;
682 objs[0] = npps->mgr_event;
683 *count = 1;
684 conn = CONTAINING_RECORD(protseq->conn, RpcConnection_np, common);
685 while (conn) {
686 if ((objs[*count] = conn->listen_thread))
687 (*count)++;
688 conn = CONTAINING_RECORD(conn->common.Next, RpcConnection_np, common);
690 LeaveCriticalSection(&protseq->cs);
691 return objs;
694 static void rpcrt4_protseq_np_free_wait_array(RpcServerProtseq *protseq, void *array)
696 HeapFree(GetProcessHeap(), 0, array);
699 static int rpcrt4_protseq_np_wait_for_new_connection(RpcServerProtseq *protseq, unsigned int count, void *wait_array)
701 HANDLE b_handle;
702 HANDLE *objs = wait_array;
703 DWORD res;
704 RpcConnection *cconn;
705 RpcConnection_np *conn;
707 if (!objs)
708 return -1;
712 /* an alertable wait isn't strictly necessary, but due to our
713 * overlapped I/O implementation in Wine we need to free some memory
714 * by the file user APC being called, even if no completion routine was
715 * specified at the time of starting the async operation */
716 res = WaitForMultipleObjectsEx(count, objs, FALSE, INFINITE, TRUE);
717 } while (res == WAIT_IO_COMPLETION);
719 if (res == WAIT_OBJECT_0)
720 return 0;
721 else if (res == WAIT_FAILED)
723 ERR("wait failed with error %d\n", GetLastError());
724 return -1;
726 else
728 b_handle = objs[res - WAIT_OBJECT_0];
729 /* find which connection got a RPC */
730 EnterCriticalSection(&protseq->cs);
731 conn = CONTAINING_RECORD(protseq->conn, RpcConnection_np, common);
732 while (conn) {
733 if (b_handle == conn->listen_thread) break;
734 conn = CONTAINING_RECORD(conn->common.Next, RpcConnection_np, common);
736 cconn = NULL;
737 if (conn)
739 DWORD exit_code;
740 if (GetExitCodeThread(conn->listen_thread, &exit_code) && exit_code == RPC_S_OK)
741 RPCRT4_SpawnConnection(&cconn, &conn->common);
742 CloseHandle(conn->listen_thread);
743 conn->listen_thread = 0;
745 else
746 ERR("failed to locate connection for handle %p\n", b_handle);
747 LeaveCriticalSection(&protseq->cs);
748 if (cconn)
750 RPCRT4_new_client(cconn);
751 return 1;
753 else return -1;
757 static size_t rpcrt4_ncalrpc_get_top_of_tower(unsigned char *tower_data,
758 const char *networkaddr,
759 const char *endpoint)
761 twr_empty_floor_t *pipe_floor;
762 size_t size;
763 size_t endpoint_size;
765 TRACE("(%p, %s, %s)\n", tower_data, networkaddr, endpoint);
767 endpoint_size = strlen(endpoint) + 1;
768 size = sizeof(*pipe_floor) + endpoint_size;
770 if (!tower_data)
771 return size;
773 pipe_floor = (twr_empty_floor_t *)tower_data;
775 tower_data += sizeof(*pipe_floor);
777 pipe_floor->count_lhs = sizeof(pipe_floor->protid);
778 pipe_floor->protid = EPM_PROTOCOL_PIPE;
779 pipe_floor->count_rhs = endpoint_size;
781 memcpy(tower_data, endpoint, endpoint_size);
783 return size;
786 static RPC_STATUS rpcrt4_ncalrpc_parse_top_of_tower(const unsigned char *tower_data,
787 size_t tower_size,
788 char **networkaddr,
789 char **endpoint)
791 const twr_empty_floor_t *pipe_floor = (const twr_empty_floor_t *)tower_data;
793 TRACE("(%p, %d, %p, %p)\n", tower_data, (int)tower_size, networkaddr, endpoint);
795 if (tower_size < sizeof(*pipe_floor))
796 return EPT_S_NOT_REGISTERED;
798 tower_data += sizeof(*pipe_floor);
799 tower_size -= sizeof(*pipe_floor);
801 if ((pipe_floor->count_lhs != sizeof(pipe_floor->protid)) ||
802 (pipe_floor->protid != EPM_PROTOCOL_PIPE) ||
803 (pipe_floor->count_rhs > tower_size) ||
804 (tower_data[pipe_floor->count_rhs - 1] != '\0'))
805 return EPT_S_NOT_REGISTERED;
807 if (networkaddr)
808 *networkaddr = NULL;
810 if (endpoint)
812 *endpoint = I_RpcAllocate(pipe_floor->count_rhs);
813 if (!*endpoint)
814 return RPC_S_OUT_OF_RESOURCES;
815 memcpy(*endpoint, tower_data, pipe_floor->count_rhs);
818 return RPC_S_OK;
821 static BOOL rpcrt4_ncalrpc_is_authorized(RpcConnection *conn)
823 return FALSE;
826 static RPC_STATUS rpcrt4_ncalrpc_authorize(RpcConnection *conn, BOOL first_time,
827 unsigned char *in_buffer,
828 unsigned int in_size,
829 unsigned char *out_buffer,
830 unsigned int *out_size)
832 /* since this protocol is local to the machine there is no need to
833 * authenticate the caller */
834 *out_size = 0;
835 return RPC_S_OK;
838 static RPC_STATUS rpcrt4_ncalrpc_secure_packet(RpcConnection *conn,
839 enum secure_packet_direction dir,
840 RpcPktHdr *hdr, unsigned int hdr_size,
841 unsigned char *stub_data, unsigned int stub_data_size,
842 RpcAuthVerifier *auth_hdr,
843 unsigned char *auth_value, unsigned int auth_value_size)
845 /* since this protocol is local to the machine there is no need to secure
846 * the packet */
847 return RPC_S_OK;
850 static RPC_STATUS rpcrt4_ncalrpc_inquire_auth_client(
851 RpcConnection *conn, RPC_AUTHZ_HANDLE *privs, RPC_WSTR *server_princ_name,
852 ULONG *authn_level, ULONG *authn_svc, ULONG *authz_svc, ULONG flags)
854 TRACE("(%p, %p, %p, %p, %p, %p, 0x%x)\n", conn, privs,
855 server_princ_name, authn_level, authn_svc, authz_svc, flags);
857 if (privs)
859 FIXME("privs not implemented\n");
860 *privs = NULL;
862 if (server_princ_name)
864 FIXME("server_princ_name not implemented\n");
865 *server_princ_name = NULL;
867 if (authn_level) *authn_level = RPC_C_AUTHN_LEVEL_PKT_PRIVACY;
868 if (authn_svc) *authn_svc = RPC_C_AUTHN_WINNT;
869 if (authz_svc)
871 FIXME("authorization service not implemented\n");
872 *authz_svc = RPC_C_AUTHZ_NONE;
874 if (flags)
875 FIXME("flags 0x%x not implemented\n", flags);
877 return RPC_S_OK;
880 /**** ncacn_ip_tcp support ****/
882 static size_t rpcrt4_ip_tcp_get_top_of_tower(unsigned char *tower_data,
883 const char *networkaddr,
884 unsigned char tcp_protid,
885 const char *endpoint)
887 twr_tcp_floor_t *tcp_floor;
888 twr_ipv4_floor_t *ipv4_floor;
889 struct addrinfo *ai;
890 struct addrinfo hints;
891 int ret;
892 size_t size = sizeof(*tcp_floor) + sizeof(*ipv4_floor);
894 TRACE("(%p, %s, %s)\n", tower_data, networkaddr, endpoint);
896 if (!tower_data)
897 return size;
899 tcp_floor = (twr_tcp_floor_t *)tower_data;
900 tower_data += sizeof(*tcp_floor);
902 ipv4_floor = (twr_ipv4_floor_t *)tower_data;
904 tcp_floor->count_lhs = sizeof(tcp_floor->protid);
905 tcp_floor->protid = tcp_protid;
906 tcp_floor->count_rhs = sizeof(tcp_floor->port);
908 ipv4_floor->count_lhs = sizeof(ipv4_floor->protid);
909 ipv4_floor->protid = EPM_PROTOCOL_IP;
910 ipv4_floor->count_rhs = sizeof(ipv4_floor->ipv4addr);
912 hints.ai_flags = AI_NUMERICHOST;
913 /* FIXME: only support IPv4 at the moment. how is IPv6 represented by the EPM? */
914 hints.ai_family = PF_INET;
915 hints.ai_socktype = SOCK_STREAM;
916 hints.ai_protocol = IPPROTO_TCP;
917 hints.ai_addrlen = 0;
918 hints.ai_addr = NULL;
919 hints.ai_canonname = NULL;
920 hints.ai_next = NULL;
922 ret = getaddrinfo(networkaddr, endpoint, &hints, &ai);
923 if (ret)
925 ret = getaddrinfo("0.0.0.0", endpoint, &hints, &ai);
926 if (ret)
928 ERR("getaddrinfo failed: %s\n", gai_strerror(ret));
929 return 0;
933 if (ai->ai_family == PF_INET)
935 const struct sockaddr_in *sin = (const struct sockaddr_in *)ai->ai_addr;
936 tcp_floor->port = sin->sin_port;
937 ipv4_floor->ipv4addr = sin->sin_addr.s_addr;
939 else
941 ERR("unexpected protocol family %d\n", ai->ai_family);
942 return 0;
945 freeaddrinfo(ai);
947 return size;
950 static RPC_STATUS rpcrt4_ip_tcp_parse_top_of_tower(const unsigned char *tower_data,
951 size_t tower_size,
952 char **networkaddr,
953 unsigned char tcp_protid,
954 char **endpoint)
956 const twr_tcp_floor_t *tcp_floor = (const twr_tcp_floor_t *)tower_data;
957 const twr_ipv4_floor_t *ipv4_floor;
958 struct in_addr in_addr;
960 TRACE("(%p, %d, %p, %p)\n", tower_data, (int)tower_size, networkaddr, endpoint);
962 if (tower_size < sizeof(*tcp_floor))
963 return EPT_S_NOT_REGISTERED;
965 tower_data += sizeof(*tcp_floor);
966 tower_size -= sizeof(*tcp_floor);
968 if (tower_size < sizeof(*ipv4_floor))
969 return EPT_S_NOT_REGISTERED;
971 ipv4_floor = (const twr_ipv4_floor_t *)tower_data;
973 if ((tcp_floor->count_lhs != sizeof(tcp_floor->protid)) ||
974 (tcp_floor->protid != tcp_protid) ||
975 (tcp_floor->count_rhs != sizeof(tcp_floor->port)) ||
976 (ipv4_floor->count_lhs != sizeof(ipv4_floor->protid)) ||
977 (ipv4_floor->protid != EPM_PROTOCOL_IP) ||
978 (ipv4_floor->count_rhs != sizeof(ipv4_floor->ipv4addr)))
979 return EPT_S_NOT_REGISTERED;
981 if (endpoint)
983 *endpoint = I_RpcAllocate(6 /* sizeof("65535") + 1 */);
984 if (!*endpoint)
985 return RPC_S_OUT_OF_RESOURCES;
986 sprintf(*endpoint, "%u", ntohs(tcp_floor->port));
989 if (networkaddr)
991 *networkaddr = I_RpcAllocate(INET_ADDRSTRLEN);
992 if (!*networkaddr)
994 if (endpoint)
996 I_RpcFree(*endpoint);
997 *endpoint = NULL;
999 return RPC_S_OUT_OF_RESOURCES;
1001 in_addr.s_addr = ipv4_floor->ipv4addr;
1002 if (!inet_ntop(AF_INET, &in_addr, *networkaddr, INET_ADDRSTRLEN))
1004 ERR("inet_ntop: %s\n", strerror(errno));
1005 I_RpcFree(*networkaddr);
1006 *networkaddr = NULL;
1007 if (endpoint)
1009 I_RpcFree(*endpoint);
1010 *endpoint = NULL;
1012 return EPT_S_NOT_REGISTERED;
1016 return RPC_S_OK;
1019 typedef struct _RpcConnection_tcp
1021 RpcConnection common;
1022 int sock;
1023 #ifdef HAVE_SOCKETPAIR
1024 int cancel_fds[2];
1025 #else
1026 HANDLE sock_event;
1027 HANDLE cancel_event;
1028 #endif
1029 } RpcConnection_tcp;
1031 #ifdef HAVE_SOCKETPAIR
1033 static BOOL rpcrt4_sock_wait_init(RpcConnection_tcp *tcpc)
1035 if (socketpair(PF_UNIX, SOCK_STREAM, 0, tcpc->cancel_fds) < 0)
1037 ERR("socketpair() failed: %s\n", strerror(errno));
1038 return FALSE;
1040 return TRUE;
1043 static BOOL rpcrt4_sock_wait_for_recv(RpcConnection_tcp *tcpc)
1045 struct pollfd pfds[2];
1046 pfds[0].fd = tcpc->sock;
1047 pfds[0].events = POLLIN;
1048 pfds[1].fd = tcpc->cancel_fds[0];
1049 pfds[1].events = POLLIN;
1050 if (poll(pfds, 2, -1 /* infinite */) == -1 && errno != EINTR)
1052 ERR("poll() failed: %s\n", strerror(errno));
1053 return FALSE;
1055 if (pfds[1].revents & POLLIN) /* canceled */
1057 char dummy;
1058 read(pfds[1].fd, &dummy, sizeof(dummy));
1059 return FALSE;
1061 return TRUE;
1064 static BOOL rpcrt4_sock_wait_for_send(RpcConnection_tcp *tcpc)
1066 struct pollfd pfd;
1067 pfd.fd = tcpc->sock;
1068 pfd.events = POLLOUT;
1069 if (poll(&pfd, 1, -1 /* infinite */) == -1 && errno != EINTR)
1071 ERR("poll() failed: %s\n", strerror(errno));
1072 return FALSE;
1074 return TRUE;
1077 static void rpcrt4_sock_wait_cancel(RpcConnection_tcp *tcpc)
1079 char dummy = 1;
1081 write(tcpc->cancel_fds[1], &dummy, 1);
1084 static void rpcrt4_sock_wait_destroy(RpcConnection_tcp *tcpc)
1086 close(tcpc->cancel_fds[0]);
1087 close(tcpc->cancel_fds[1]);
1090 #else /* HAVE_SOCKETPAIR */
1092 static BOOL rpcrt4_sock_wait_init(RpcConnection_tcp *tcpc)
1094 static BOOL wsa_inited;
1095 if (!wsa_inited)
1097 WSADATA wsadata;
1098 WSAStartup(MAKEWORD(2, 2), &wsadata);
1099 /* Note: WSAStartup can be called more than once so we don't bother with
1100 * making accesses to wsa_inited thread-safe */
1101 wsa_inited = TRUE;
1103 tcpc->sock_event = CreateEventW(NULL, FALSE, FALSE, NULL);
1104 tcpc->cancel_event = CreateEventW(NULL, FALSE, FALSE, NULL);
1105 if (!tcpc->sock_event || !tcpc->cancel_event)
1107 ERR("event creation failed\n");
1108 if (tcpc->sock_event) CloseHandle(tcpc->sock_event);
1109 return FALSE;
1111 return TRUE;
1114 static BOOL rpcrt4_sock_wait_for_recv(RpcConnection_tcp *tcpc)
1116 HANDLE wait_handles[2];
1117 DWORD res;
1118 if (WSAEventSelect(tcpc->sock, tcpc->sock_event, FD_READ | FD_CLOSE) == SOCKET_ERROR)
1120 ERR("WSAEventSelect() failed with error %d\n", WSAGetLastError());
1121 return FALSE;
1123 wait_handles[0] = tcpc->sock_event;
1124 wait_handles[1] = tcpc->cancel_event;
1125 res = WaitForMultipleObjects(2, wait_handles, FALSE, INFINITE);
1126 switch (res)
1128 case WAIT_OBJECT_0:
1129 return TRUE;
1130 case WAIT_OBJECT_0 + 1:
1131 return FALSE;
1132 default:
1133 ERR("WaitForMultipleObjects() failed with error %d\n", GetLastError());
1134 return FALSE;
1138 static BOOL rpcrt4_sock_wait_for_send(RpcConnection_tcp *tcpc)
1140 DWORD res;
1141 if (WSAEventSelect(tcpc->sock, tcpc->sock_event, FD_WRITE | FD_CLOSE) == SOCKET_ERROR)
1143 ERR("WSAEventSelect() failed with error %d\n", WSAGetLastError());
1144 return FALSE;
1146 res = WaitForSingleObject(tcpc->sock_event, INFINITE);
1147 switch (res)
1149 case WAIT_OBJECT_0:
1150 return TRUE;
1151 default:
1152 ERR("WaitForMultipleObjects() failed with error %d\n", GetLastError());
1153 return FALSE;
1157 static void rpcrt4_sock_wait_cancel(RpcConnection_tcp *tcpc)
1159 SetEvent(tcpc->cancel_event);
1162 static void rpcrt4_sock_wait_destroy(RpcConnection_tcp *tcpc)
1164 CloseHandle(tcpc->sock_event);
1165 CloseHandle(tcpc->cancel_event);
1168 #endif
1170 static RpcConnection *rpcrt4_conn_tcp_alloc(void)
1172 RpcConnection_tcp *tcpc;
1173 tcpc = HeapAlloc(GetProcessHeap(), 0, sizeof(RpcConnection_tcp));
1174 if (tcpc == NULL)
1175 return NULL;
1176 tcpc->sock = -1;
1177 if (!rpcrt4_sock_wait_init(tcpc))
1179 HeapFree(GetProcessHeap(), 0, tcpc);
1180 return NULL;
1182 return &tcpc->common;
1185 static RPC_STATUS rpcrt4_ncacn_ip_tcp_open(RpcConnection* Connection)
1187 RpcConnection_tcp *tcpc = (RpcConnection_tcp *) Connection;
1188 int sock;
1189 int ret;
1190 struct addrinfo *ai;
1191 struct addrinfo *ai_cur;
1192 struct addrinfo hints;
1194 TRACE("(%s, %s)\n", Connection->NetworkAddr, Connection->Endpoint);
1196 if (tcpc->sock != -1)
1197 return RPC_S_OK;
1199 hints.ai_flags = 0;
1200 hints.ai_family = PF_UNSPEC;
1201 hints.ai_socktype = SOCK_STREAM;
1202 hints.ai_protocol = IPPROTO_TCP;
1203 hints.ai_addrlen = 0;
1204 hints.ai_addr = NULL;
1205 hints.ai_canonname = NULL;
1206 hints.ai_next = NULL;
1208 ret = getaddrinfo(Connection->NetworkAddr, Connection->Endpoint, &hints, &ai);
1209 if (ret)
1211 ERR("getaddrinfo for %s:%s failed: %s\n", Connection->NetworkAddr,
1212 Connection->Endpoint, gai_strerror(ret));
1213 return RPC_S_SERVER_UNAVAILABLE;
1216 for (ai_cur = ai; ai_cur; ai_cur = ai_cur->ai_next)
1218 int val;
1219 u_long nonblocking;
1221 if (ai_cur->ai_family != AF_INET && ai_cur->ai_family != AF_INET6)
1223 TRACE("skipping non-IP/IPv6 address family\n");
1224 continue;
1227 if (TRACE_ON(rpc))
1229 char host[256];
1230 char service[256];
1231 getnameinfo(ai_cur->ai_addr, ai_cur->ai_addrlen,
1232 host, sizeof(host), service, sizeof(service),
1233 NI_NUMERICHOST | NI_NUMERICSERV);
1234 TRACE("trying %s:%s\n", host, service);
1237 sock = socket(ai_cur->ai_family, ai_cur->ai_socktype, ai_cur->ai_protocol);
1238 if (sock == -1)
1240 WARN("socket() failed: %s\n", strerror(errno));
1241 continue;
1244 if (0>connect(sock, ai_cur->ai_addr, ai_cur->ai_addrlen))
1246 WARN("connect() failed: %s\n", strerror(errno));
1247 closesocket(sock);
1248 continue;
1251 /* RPC depends on having minimal latency so disable the Nagle algorithm */
1252 val = 1;
1253 setsockopt(sock, SOL_TCP, TCP_NODELAY, (char *)&val, sizeof(val));
1254 nonblocking = 1;
1255 ioctlsocket(sock, FIONBIO, &nonblocking);
1257 tcpc->sock = sock;
1259 freeaddrinfo(ai);
1260 TRACE("connected\n");
1261 return RPC_S_OK;
1264 freeaddrinfo(ai);
1265 ERR("couldn't connect to %s:%s\n", Connection->NetworkAddr, Connection->Endpoint);
1266 return RPC_S_SERVER_UNAVAILABLE;
1269 static RPC_STATUS rpcrt4_protseq_ncacn_ip_tcp_open_endpoint(RpcServerProtseq *protseq, const char *endpoint)
1271 RPC_STATUS status = RPC_S_CANT_CREATE_ENDPOINT;
1272 int sock;
1273 int ret;
1274 struct addrinfo *ai;
1275 struct addrinfo *ai_cur;
1276 struct addrinfo hints;
1277 RpcConnection *first_connection = NULL;
1279 TRACE("(%p, %s)\n", protseq, endpoint);
1281 hints.ai_flags = AI_PASSIVE /* for non-localhost addresses */;
1282 hints.ai_family = PF_UNSPEC;
1283 hints.ai_socktype = SOCK_STREAM;
1284 hints.ai_protocol = IPPROTO_TCP;
1285 hints.ai_addrlen = 0;
1286 hints.ai_addr = NULL;
1287 hints.ai_canonname = NULL;
1288 hints.ai_next = NULL;
1290 ret = getaddrinfo(NULL, endpoint ? endpoint : "0", &hints, &ai);
1291 if (ret)
1293 ERR("getaddrinfo for port %s failed: %s\n", endpoint,
1294 gai_strerror(ret));
1295 if ((ret == EAI_SERVICE) || (ret == EAI_NONAME))
1296 return RPC_S_INVALID_ENDPOINT_FORMAT;
1297 return RPC_S_CANT_CREATE_ENDPOINT;
1300 for (ai_cur = ai; ai_cur; ai_cur = ai_cur->ai_next)
1302 RpcConnection_tcp *tcpc;
1303 RPC_STATUS create_status;
1304 struct sockaddr_storage sa;
1305 socklen_t sa_len;
1306 char service[NI_MAXSERV];
1307 u_long nonblocking;
1309 if (ai_cur->ai_family != AF_INET && ai_cur->ai_family != AF_INET6)
1311 TRACE("skipping non-IP/IPv6 address family\n");
1312 continue;
1315 if (TRACE_ON(rpc))
1317 char host[256];
1318 getnameinfo(ai_cur->ai_addr, ai_cur->ai_addrlen,
1319 host, sizeof(host), service, sizeof(service),
1320 NI_NUMERICHOST | NI_NUMERICSERV);
1321 TRACE("trying %s:%s\n", host, service);
1324 sock = socket(ai_cur->ai_family, ai_cur->ai_socktype, ai_cur->ai_protocol);
1325 if (sock == -1)
1327 WARN("socket() failed: %s\n", strerror(errno));
1328 status = RPC_S_CANT_CREATE_ENDPOINT;
1329 continue;
1332 ret = bind(sock, ai_cur->ai_addr, ai_cur->ai_addrlen);
1333 if (ret < 0)
1335 WARN("bind failed: %s\n", strerror(errno));
1336 closesocket(sock);
1337 if (errno == EADDRINUSE)
1338 status = RPC_S_DUPLICATE_ENDPOINT;
1339 else
1340 status = RPC_S_CANT_CREATE_ENDPOINT;
1341 continue;
1344 sa_len = sizeof(sa);
1345 if (getsockname(sock, (struct sockaddr *)&sa, &sa_len))
1347 WARN("getsockname() failed: %s\n", strerror(errno));
1348 closesocket(sock);
1349 status = RPC_S_CANT_CREATE_ENDPOINT;
1350 continue;
1353 ret = getnameinfo((struct sockaddr *)&sa, sa_len,
1354 NULL, 0, service, sizeof(service),
1355 NI_NUMERICSERV);
1356 if (ret)
1358 WARN("getnameinfo failed: %s\n", gai_strerror(ret));
1359 closesocket(sock);
1360 status = RPC_S_CANT_CREATE_ENDPOINT;
1361 continue;
1364 create_status = RPCRT4_CreateConnection((RpcConnection **)&tcpc, TRUE,
1365 protseq->Protseq, NULL,
1366 service, NULL, NULL, NULL, NULL);
1367 if (create_status != RPC_S_OK)
1369 closesocket(sock);
1370 status = create_status;
1371 continue;
1374 tcpc->sock = sock;
1375 ret = listen(sock, protseq->MaxCalls);
1376 if (ret < 0)
1378 WARN("listen failed: %s\n", strerror(errno));
1379 RPCRT4_ReleaseConnection(&tcpc->common);
1380 status = RPC_S_OUT_OF_RESOURCES;
1381 continue;
1383 /* need a non-blocking socket, otherwise accept() has a potential
1384 * race-condition (poll() says it is readable, connection drops,
1385 * and accept() blocks until the next connection comes...)
1387 nonblocking = 1;
1388 ret = ioctlsocket(sock, FIONBIO, &nonblocking);
1389 if (ret < 0)
1391 WARN("couldn't make socket non-blocking, error %d\n", ret);
1392 RPCRT4_ReleaseConnection(&tcpc->common);
1393 status = RPC_S_OUT_OF_RESOURCES;
1394 continue;
1397 tcpc->common.Next = first_connection;
1398 first_connection = &tcpc->common;
1400 /* since IPv4 and IPv6 share the same port space, we only need one
1401 * successful bind to listen for both */
1402 break;
1405 freeaddrinfo(ai);
1407 /* if at least one connection was created for an endpoint then
1408 * return success */
1409 if (first_connection)
1411 RpcConnection *conn;
1413 /* find last element in list */
1414 for (conn = first_connection; conn->Next; conn = conn->Next)
1417 EnterCriticalSection(&protseq->cs);
1418 conn->Next = protseq->conn;
1419 protseq->conn = first_connection;
1420 LeaveCriticalSection(&protseq->cs);
1422 TRACE("listening on %s\n", endpoint);
1423 return RPC_S_OK;
1426 ERR("couldn't listen on port %s\n", endpoint);
1427 return status;
1430 static RPC_STATUS rpcrt4_conn_tcp_handoff(RpcConnection *old_conn, RpcConnection *new_conn)
1432 int ret;
1433 struct sockaddr_in address;
1434 socklen_t addrsize;
1435 RpcConnection_tcp *server = (RpcConnection_tcp*) old_conn;
1436 RpcConnection_tcp *client = (RpcConnection_tcp*) new_conn;
1437 u_long nonblocking;
1439 addrsize = sizeof(address);
1440 ret = accept(server->sock, (struct sockaddr*) &address, &addrsize);
1441 if (ret < 0)
1443 ERR("Failed to accept a TCP connection: error %d\n", ret);
1444 return RPC_S_OUT_OF_RESOURCES;
1446 nonblocking = 1;
1447 ioctlsocket(ret, FIONBIO, &nonblocking);
1448 client->sock = ret;
1449 TRACE("Accepted a new TCP connection\n");
1450 return RPC_S_OK;
1453 static int rpcrt4_conn_tcp_read(RpcConnection *Connection,
1454 void *buffer, unsigned int count)
1456 RpcConnection_tcp *tcpc = (RpcConnection_tcp *) Connection;
1457 int bytes_read = 0;
1458 while (bytes_read != count)
1460 int r = recv(tcpc->sock, (char *)buffer + bytes_read, count - bytes_read, 0);
1461 if (!r)
1462 return -1;
1463 else if (r > 0)
1464 bytes_read += r;
1465 else if (errno != EAGAIN)
1467 WARN("recv() failed: %s\n", strerror(errno));
1468 return -1;
1470 else
1472 if (!rpcrt4_sock_wait_for_recv(tcpc))
1473 return -1;
1476 TRACE("%d %p %u -> %d\n", tcpc->sock, buffer, count, bytes_read);
1477 return bytes_read;
1480 static int rpcrt4_conn_tcp_write(RpcConnection *Connection,
1481 const void *buffer, unsigned int count)
1483 RpcConnection_tcp *tcpc = (RpcConnection_tcp *) Connection;
1484 int bytes_written = 0;
1485 while (bytes_written != count)
1487 int r = send(tcpc->sock, (const char *)buffer + bytes_written, count - bytes_written, 0);
1488 if (r >= 0)
1489 bytes_written += r;
1490 else if (errno != EAGAIN)
1491 return -1;
1492 else
1494 if (!rpcrt4_sock_wait_for_send(tcpc))
1495 return -1;
1498 TRACE("%d %p %u -> %d\n", tcpc->sock, buffer, count, bytes_written);
1499 return bytes_written;
1502 static int rpcrt4_conn_tcp_close(RpcConnection *Connection)
1504 RpcConnection_tcp *tcpc = (RpcConnection_tcp *) Connection;
1506 TRACE("%d\n", tcpc->sock);
1508 if (tcpc->sock != -1)
1509 closesocket(tcpc->sock);
1510 tcpc->sock = -1;
1511 rpcrt4_sock_wait_destroy(tcpc);
1512 return 0;
1515 static void rpcrt4_conn_tcp_cancel_call(RpcConnection *Connection)
1517 RpcConnection_tcp *tcpc = (RpcConnection_tcp *) Connection;
1518 TRACE("%p\n", Connection);
1519 rpcrt4_sock_wait_cancel(tcpc);
1522 static int rpcrt4_conn_tcp_wait_for_incoming_data(RpcConnection *Connection)
1524 RpcConnection_tcp *tcpc = (RpcConnection_tcp *) Connection;
1526 TRACE("%p\n", Connection);
1528 if (!rpcrt4_sock_wait_for_recv(tcpc))
1529 return -1;
1530 return 0;
1533 static size_t rpcrt4_ncacn_ip_tcp_get_top_of_tower(unsigned char *tower_data,
1534 const char *networkaddr,
1535 const char *endpoint)
1537 return rpcrt4_ip_tcp_get_top_of_tower(tower_data, networkaddr,
1538 EPM_PROTOCOL_TCP, endpoint);
1541 #ifdef HAVE_SOCKETPAIR
1543 typedef struct _RpcServerProtseq_sock
1545 RpcServerProtseq common;
1546 int mgr_event_rcv;
1547 int mgr_event_snd;
1548 } RpcServerProtseq_sock;
1550 static RpcServerProtseq *rpcrt4_protseq_sock_alloc(void)
1552 RpcServerProtseq_sock *ps = HeapAlloc(GetProcessHeap(), 0, sizeof(*ps));
1553 if (ps)
1555 int fds[2];
1556 if (!socketpair(PF_UNIX, SOCK_DGRAM, 0, fds))
1558 fcntl(fds[0], F_SETFL, O_NONBLOCK);
1559 fcntl(fds[1], F_SETFL, O_NONBLOCK);
1560 ps->mgr_event_rcv = fds[0];
1561 ps->mgr_event_snd = fds[1];
1563 else
1565 ERR("socketpair failed with error %s\n", strerror(errno));
1566 HeapFree(GetProcessHeap(), 0, ps);
1567 return NULL;
1570 return &ps->common;
1573 static void rpcrt4_protseq_sock_signal_state_changed(RpcServerProtseq *protseq)
1575 RpcServerProtseq_sock *sockps = CONTAINING_RECORD(protseq, RpcServerProtseq_sock, common);
1576 char dummy = 1;
1577 write(sockps->mgr_event_snd, &dummy, sizeof(dummy));
1580 static void *rpcrt4_protseq_sock_get_wait_array(RpcServerProtseq *protseq, void *prev_array, unsigned int *count)
1582 struct pollfd *poll_info = prev_array;
1583 RpcConnection_tcp *conn;
1584 RpcServerProtseq_sock *sockps = CONTAINING_RECORD(protseq, RpcServerProtseq_sock, common);
1586 EnterCriticalSection(&protseq->cs);
1588 /* open and count connections */
1589 *count = 1;
1590 conn = (RpcConnection_tcp *)protseq->conn;
1591 while (conn) {
1592 if (conn->sock != -1)
1593 (*count)++;
1594 conn = (RpcConnection_tcp *)conn->common.Next;
1597 /* make array of connections */
1598 if (poll_info)
1599 poll_info = HeapReAlloc(GetProcessHeap(), 0, poll_info, *count*sizeof(*poll_info));
1600 else
1601 poll_info = HeapAlloc(GetProcessHeap(), 0, *count*sizeof(*poll_info));
1602 if (!poll_info)
1604 ERR("couldn't allocate poll_info\n");
1605 LeaveCriticalSection(&protseq->cs);
1606 return NULL;
1609 poll_info[0].fd = sockps->mgr_event_rcv;
1610 poll_info[0].events = POLLIN;
1611 *count = 1;
1612 conn = CONTAINING_RECORD(protseq->conn, RpcConnection_tcp, common);
1613 while (conn) {
1614 if (conn->sock != -1)
1616 poll_info[*count].fd = conn->sock;
1617 poll_info[*count].events = POLLIN;
1618 (*count)++;
1620 conn = CONTAINING_RECORD(conn->common.Next, RpcConnection_tcp, common);
1622 LeaveCriticalSection(&protseq->cs);
1623 return poll_info;
1626 static void rpcrt4_protseq_sock_free_wait_array(RpcServerProtseq *protseq, void *array)
1628 HeapFree(GetProcessHeap(), 0, array);
1631 static int rpcrt4_protseq_sock_wait_for_new_connection(RpcServerProtseq *protseq, unsigned int count, void *wait_array)
1633 struct pollfd *poll_info = wait_array;
1634 int ret;
1635 unsigned int i;
1636 RpcConnection *cconn;
1637 RpcConnection_tcp *conn;
1639 if (!poll_info)
1640 return -1;
1642 ret = poll(poll_info, count, -1);
1643 if (ret < 0)
1645 ERR("poll failed with error %d\n", ret);
1646 return -1;
1649 for (i = 0; i < count; i++)
1650 if (poll_info[i].revents & POLLIN)
1652 /* RPC server event */
1653 if (i == 0)
1655 char dummy;
1656 read(poll_info[0].fd, &dummy, sizeof(dummy));
1657 return 0;
1660 /* find which connection got a RPC */
1661 EnterCriticalSection(&protseq->cs);
1662 conn = CONTAINING_RECORD(protseq->conn, RpcConnection_tcp, common);
1663 while (conn) {
1664 if (poll_info[i].fd == conn->sock) break;
1665 conn = CONTAINING_RECORD(conn->common.Next, RpcConnection_tcp, common);
1667 cconn = NULL;
1668 if (conn)
1669 RPCRT4_SpawnConnection(&cconn, &conn->common);
1670 else
1671 ERR("failed to locate connection for fd %d\n", poll_info[i].fd);
1672 LeaveCriticalSection(&protseq->cs);
1673 if (cconn)
1674 RPCRT4_new_client(cconn);
1675 else
1676 return -1;
1679 return 1;
1682 #else /* HAVE_SOCKETPAIR */
1684 typedef struct _RpcServerProtseq_sock
1686 RpcServerProtseq common;
1687 HANDLE mgr_event;
1688 } RpcServerProtseq_sock;
1690 static RpcServerProtseq *rpcrt4_protseq_sock_alloc(void)
1692 RpcServerProtseq_sock *ps = HeapAlloc(GetProcessHeap(), 0, sizeof(*ps));
1693 if (ps)
1695 static BOOL wsa_inited;
1696 if (!wsa_inited)
1698 WSADATA wsadata;
1699 WSAStartup(MAKEWORD(2, 2), &wsadata);
1700 /* Note: WSAStartup can be called more than once so we don't bother with
1701 * making accesses to wsa_inited thread-safe */
1702 wsa_inited = TRUE;
1704 ps->mgr_event = CreateEventW(NULL, FALSE, FALSE, NULL);
1706 return &ps->common;
1709 static void rpcrt4_protseq_sock_signal_state_changed(RpcServerProtseq *protseq)
1711 RpcServerProtseq_sock *sockps = CONTAINING_RECORD(protseq, RpcServerProtseq_sock, common);
1712 SetEvent(sockps->mgr_event);
1715 static void *rpcrt4_protseq_sock_get_wait_array(RpcServerProtseq *protseq, void *prev_array, unsigned int *count)
1717 HANDLE *objs = prev_array;
1718 RpcConnection_tcp *conn;
1719 RpcServerProtseq_sock *sockps = CONTAINING_RECORD(protseq, RpcServerProtseq_sock, common);
1721 EnterCriticalSection(&protseq->cs);
1723 /* open and count connections */
1724 *count = 1;
1725 conn = CONTAINING_RECORD(protseq->conn, RpcConnection_tcp, common);
1726 while (conn)
1728 if (conn->sock != -1)
1729 (*count)++;
1730 conn = CONTAINING_RECORD(conn->common.Next, RpcConnection_tcp, common);
1733 /* make array of connections */
1734 if (objs)
1735 objs = HeapReAlloc(GetProcessHeap(), 0, objs, *count*sizeof(HANDLE));
1736 else
1737 objs = HeapAlloc(GetProcessHeap(), 0, *count*sizeof(HANDLE));
1738 if (!objs)
1740 ERR("couldn't allocate objs\n");
1741 LeaveCriticalSection(&protseq->cs);
1742 return NULL;
1745 objs[0] = sockps->mgr_event;
1746 *count = 1;
1747 conn = CONTAINING_RECORD(protseq->conn, RpcConnection_tcp, common);
1748 while (conn)
1750 if (conn->sock != -1)
1752 int res = WSAEventSelect(conn->sock, conn->sock_event, FD_ACCEPT);
1753 if (res == SOCKET_ERROR)
1754 ERR("WSAEventSelect() failed with error %d\n", WSAGetLastError());
1755 else
1757 objs[*count] = conn->sock_event;
1758 (*count)++;
1761 conn = CONTAINING_RECORD(conn->common.Next, RpcConnection_tcp, common);
1763 LeaveCriticalSection(&protseq->cs);
1764 return objs;
1767 static void rpcrt4_protseq_sock_free_wait_array(RpcServerProtseq *protseq, void *array)
1769 HeapFree(GetProcessHeap(), 0, array);
1772 static int rpcrt4_protseq_sock_wait_for_new_connection(RpcServerProtseq *protseq, unsigned int count, void *wait_array)
1774 HANDLE b_handle;
1775 HANDLE *objs = wait_array;
1776 DWORD res;
1777 RpcConnection *cconn;
1778 RpcConnection_tcp *conn;
1780 if (!objs)
1781 return -1;
1785 /* an alertable wait isn't strictly necessary, but due to our
1786 * overlapped I/O implementation in Wine we need to free some memory
1787 * by the file user APC being called, even if no completion routine was
1788 * specified at the time of starting the async operation */
1789 res = WaitForMultipleObjectsEx(count, objs, FALSE, INFINITE, TRUE);
1790 } while (res == WAIT_IO_COMPLETION);
1792 if (res == WAIT_OBJECT_0)
1793 return 0;
1794 else if (res == WAIT_FAILED)
1796 ERR("wait failed with error %d\n", GetLastError());
1797 return -1;
1799 else
1801 b_handle = objs[res - WAIT_OBJECT_0];
1802 /* find which connection got a RPC */
1803 EnterCriticalSection(&protseq->cs);
1804 conn = CONTAINING_RECORD(protseq->conn, RpcConnection_tcp, common);
1805 while (conn)
1807 if (b_handle == conn->sock_event) break;
1808 conn = CONTAINING_RECORD(conn->common.Next, RpcConnection_tcp, common);
1810 cconn = NULL;
1811 if (conn)
1812 RPCRT4_SpawnConnection(&cconn, &conn->common);
1813 else
1814 ERR("failed to locate connection for handle %p\n", b_handle);
1815 LeaveCriticalSection(&protseq->cs);
1816 if (cconn)
1818 RPCRT4_new_client(cconn);
1819 return 1;
1821 else return -1;
1825 #endif /* HAVE_SOCKETPAIR */
1827 static RPC_STATUS rpcrt4_ncacn_ip_tcp_parse_top_of_tower(const unsigned char *tower_data,
1828 size_t tower_size,
1829 char **networkaddr,
1830 char **endpoint)
1832 return rpcrt4_ip_tcp_parse_top_of_tower(tower_data, tower_size,
1833 networkaddr, EPM_PROTOCOL_TCP,
1834 endpoint);
1837 /**** ncacn_http support ****/
1839 /* 60 seconds is the period native uses */
1840 #define HTTP_IDLE_TIME 60000
1842 /* reference counted to avoid a race between a cancelled call's connection
1843 * being destroyed and the asynchronous InternetReadFileEx call being
1844 * completed */
1845 typedef struct _RpcHttpAsyncData
1847 LONG refs;
1848 HANDLE completion_event;
1849 WORD async_result;
1850 INTERNET_BUFFERSA inet_buffers;
1851 CRITICAL_SECTION cs;
1852 } RpcHttpAsyncData;
1854 static ULONG RpcHttpAsyncData_AddRef(RpcHttpAsyncData *data)
1856 return InterlockedIncrement(&data->refs);
1859 static ULONG RpcHttpAsyncData_Release(RpcHttpAsyncData *data)
1861 ULONG refs = InterlockedDecrement(&data->refs);
1862 if (!refs)
1864 TRACE("destroying async data %p\n", data);
1865 CloseHandle(data->completion_event);
1866 HeapFree(GetProcessHeap(), 0, data->inet_buffers.lpvBuffer);
1867 data->cs.DebugInfo->Spare[0] = 0;
1868 DeleteCriticalSection(&data->cs);
1869 HeapFree(GetProcessHeap(), 0, data);
1871 return refs;
1874 static void prepare_async_request(RpcHttpAsyncData *async_data)
1876 ResetEvent(async_data->completion_event);
1877 RpcHttpAsyncData_AddRef(async_data);
1880 static RPC_STATUS wait_async_request(RpcHttpAsyncData *async_data, BOOL call_ret, HANDLE cancel_event)
1882 HANDLE handles[2] = { async_data->completion_event, cancel_event };
1883 DWORD res;
1885 if(call_ret) {
1886 RpcHttpAsyncData_Release(async_data);
1887 return RPC_S_OK;
1890 if(GetLastError() != ERROR_IO_PENDING) {
1891 RpcHttpAsyncData_Release(async_data);
1892 ERR("Request failed with error %d\n", GetLastError());
1893 return RPC_S_SERVER_UNAVAILABLE;
1896 res = WaitForMultipleObjects(2, handles, FALSE, DEFAULT_NCACN_HTTP_TIMEOUT);
1897 if(res != WAIT_OBJECT_0) {
1898 TRACE("Cancelled\n");
1899 return RPC_S_CALL_CANCELLED;
1902 if(async_data->async_result) {
1903 ERR("Async request failed with error %d\n", async_data->async_result);
1904 return RPC_S_SERVER_UNAVAILABLE;
1907 return RPC_S_OK;
1910 typedef struct _RpcConnection_http
1912 RpcConnection common;
1913 HINTERNET app_info;
1914 HINTERNET session;
1915 HINTERNET in_request;
1916 HINTERNET out_request;
1917 HANDLE timer_cancelled;
1918 HANDLE cancel_event;
1919 DWORD last_sent_time;
1920 ULONG bytes_received;
1921 ULONG flow_control_mark; /* send a control packet to the server when this many bytes received */
1922 ULONG flow_control_increment; /* number of bytes to increment flow_control_mark by */
1923 UUID connection_uuid;
1924 UUID in_pipe_uuid;
1925 UUID out_pipe_uuid;
1926 RpcHttpAsyncData *async_data;
1927 } RpcConnection_http;
1929 static RpcConnection *rpcrt4_ncacn_http_alloc(void)
1931 RpcConnection_http *httpc;
1932 httpc = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*httpc));
1933 if (!httpc) return NULL;
1934 httpc->async_data = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(RpcHttpAsyncData));
1935 if (!httpc->async_data)
1937 HeapFree(GetProcessHeap(), 0, httpc);
1938 return NULL;
1940 TRACE("async data = %p\n", httpc->async_data);
1941 httpc->cancel_event = CreateEventW(NULL, FALSE, FALSE, NULL);
1942 httpc->async_data->refs = 1;
1943 httpc->async_data->inet_buffers.dwStructSize = sizeof(INTERNET_BUFFERSA);
1944 httpc->async_data->inet_buffers.lpvBuffer = NULL;
1945 InitializeCriticalSection(&httpc->async_data->cs);
1946 httpc->async_data->cs.DebugInfo->Spare[0] = (DWORD_PTR)(__FILE__ ": RpcHttpAsyncData.cs");
1947 return &httpc->common;
1950 typedef struct _HttpTimerThreadData
1952 PVOID timer_param;
1953 DWORD *last_sent_time;
1954 HANDLE timer_cancelled;
1955 } HttpTimerThreadData;
1957 static VOID rpcrt4_http_keep_connection_active_timer_proc(PVOID param, BOOLEAN dummy)
1959 HINTERNET in_request = param;
1960 RpcPktHdr *idle_pkt;
1962 idle_pkt = RPCRT4_BuildHttpHeader(NDR_LOCAL_DATA_REPRESENTATION, 0x0001,
1963 0, 0);
1964 if (idle_pkt)
1966 DWORD bytes_written;
1967 InternetWriteFile(in_request, idle_pkt, idle_pkt->common.frag_len, &bytes_written);
1968 RPCRT4_FreeHeader(idle_pkt);
1972 static inline DWORD rpcrt4_http_timer_calc_timeout(DWORD *last_sent_time)
1974 DWORD cur_time = GetTickCount();
1975 DWORD cached_last_sent_time = *last_sent_time;
1976 return HTTP_IDLE_TIME - (cur_time - cached_last_sent_time > HTTP_IDLE_TIME ? 0 : cur_time - cached_last_sent_time);
1979 static DWORD CALLBACK rpcrt4_http_timer_thread(PVOID param)
1981 HttpTimerThreadData *data_in = param;
1982 HttpTimerThreadData data;
1983 DWORD timeout;
1985 data = *data_in;
1986 HeapFree(GetProcessHeap(), 0, data_in);
1988 for (timeout = HTTP_IDLE_TIME;
1989 WaitForSingleObject(data.timer_cancelled, timeout) == WAIT_TIMEOUT;
1990 timeout = rpcrt4_http_timer_calc_timeout(data.last_sent_time))
1992 /* are we too soon after last send? */
1993 if (GetTickCount() - *data.last_sent_time < HTTP_IDLE_TIME)
1994 continue;
1995 rpcrt4_http_keep_connection_active_timer_proc(data.timer_param, TRUE);
1998 CloseHandle(data.timer_cancelled);
1999 return 0;
2002 static VOID WINAPI rpcrt4_http_internet_callback(
2003 HINTERNET hInternet,
2004 DWORD_PTR dwContext,
2005 DWORD dwInternetStatus,
2006 LPVOID lpvStatusInformation,
2007 DWORD dwStatusInformationLength)
2009 RpcHttpAsyncData *async_data = (RpcHttpAsyncData *)dwContext;
2011 switch (dwInternetStatus)
2013 case INTERNET_STATUS_REQUEST_COMPLETE:
2014 TRACE("INTERNET_STATUS_REQUEST_COMPLETED\n");
2015 if (async_data)
2017 INTERNET_ASYNC_RESULT *async_result = lpvStatusInformation;
2019 async_data->async_result = async_result->dwResult ? ERROR_SUCCESS : async_result->dwError;
2020 SetEvent(async_data->completion_event);
2021 RpcHttpAsyncData_Release(async_data);
2023 break;
2027 static RPC_STATUS rpcrt4_http_check_response(HINTERNET hor)
2029 BOOL ret;
2030 DWORD status_code;
2031 DWORD size;
2032 DWORD index;
2033 WCHAR buf[32];
2034 WCHAR *status_text = buf;
2035 TRACE("\n");
2037 index = 0;
2038 size = sizeof(status_code);
2039 ret = HttpQueryInfoW(hor, HTTP_QUERY_STATUS_CODE|HTTP_QUERY_FLAG_NUMBER, &status_code, &size, &index);
2040 if (!ret)
2041 return GetLastError();
2042 if (status_code == HTTP_STATUS_OK)
2043 return RPC_S_OK;
2044 index = 0;
2045 size = sizeof(buf);
2046 ret = HttpQueryInfoW(hor, HTTP_QUERY_STATUS_TEXT, status_text, &size, &index);
2047 if (!ret && GetLastError() == ERROR_INSUFFICIENT_BUFFER)
2049 status_text = HeapAlloc(GetProcessHeap(), 0, size);
2050 ret = HttpQueryInfoW(hor, HTTP_QUERY_STATUS_TEXT, status_text, &size, &index);
2053 ERR("server returned: %d %s\n", status_code, ret ? debugstr_w(status_text) : "<status text unavailable>");
2054 if(status_text != buf) HeapFree(GetProcessHeap(), 0, status_text);
2056 if (status_code == HTTP_STATUS_DENIED)
2057 return ERROR_ACCESS_DENIED;
2058 return RPC_S_SERVER_UNAVAILABLE;
2061 static RPC_STATUS rpcrt4_http_internet_connect(RpcConnection_http *httpc)
2063 static const WCHAR wszUserAgent[] = {'M','S','R','P','C',0};
2064 LPWSTR proxy = NULL;
2065 LPWSTR user = NULL;
2066 LPWSTR password = NULL;
2067 LPWSTR servername = NULL;
2068 const WCHAR *option;
2069 INTERNET_PORT port;
2071 if (httpc->common.QOS &&
2072 (httpc->common.QOS->qos->AdditionalSecurityInfoType == RPC_C_AUTHN_INFO_TYPE_HTTP))
2074 const RPC_HTTP_TRANSPORT_CREDENTIALS_W *http_cred = httpc->common.QOS->qos->u.HttpCredentials;
2075 if (http_cred->TransportCredentials)
2077 WCHAR *p;
2078 const SEC_WINNT_AUTH_IDENTITY_W *cred = http_cred->TransportCredentials;
2079 ULONG len = cred->DomainLength + 1 + cred->UserLength;
2080 user = HeapAlloc(GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR));
2081 if (!user)
2082 return RPC_S_OUT_OF_RESOURCES;
2083 p = user;
2084 if (cred->DomainLength)
2086 memcpy(p, cred->Domain, cred->DomainLength * sizeof(WCHAR));
2087 p += cred->DomainLength;
2088 *p = '\\';
2089 p++;
2091 memcpy(p, cred->User, cred->UserLength * sizeof(WCHAR));
2092 p[cred->UserLength] = 0;
2094 password = RPCRT4_strndupW(cred->Password, cred->PasswordLength);
2098 for (option = httpc->common.NetworkOptions; option;
2099 option = (strchrW(option, ',') ? strchrW(option, ',')+1 : NULL))
2101 static const WCHAR wszRpcProxy[] = {'R','p','c','P','r','o','x','y','=',0};
2102 static const WCHAR wszHttpProxy[] = {'H','t','t','p','P','r','o','x','y','=',0};
2104 if (!strncmpiW(option, wszRpcProxy, sizeof(wszRpcProxy)/sizeof(wszRpcProxy[0])-1))
2106 const WCHAR *value_start = option + sizeof(wszRpcProxy)/sizeof(wszRpcProxy[0])-1;
2107 const WCHAR *value_end;
2108 const WCHAR *p;
2110 value_end = strchrW(option, ',');
2111 if (!value_end)
2112 value_end = value_start + strlenW(value_start);
2113 for (p = value_start; p < value_end; p++)
2114 if (*p == ':')
2116 port = atoiW(p+1);
2117 value_end = p;
2118 break;
2120 TRACE("RpcProxy value is %s\n", debugstr_wn(value_start, value_end-value_start));
2121 servername = RPCRT4_strndupW(value_start, value_end-value_start);
2123 else if (!strncmpiW(option, wszHttpProxy, sizeof(wszHttpProxy)/sizeof(wszHttpProxy[0])-1))
2125 const WCHAR *value_start = option + sizeof(wszHttpProxy)/sizeof(wszHttpProxy[0])-1;
2126 const WCHAR *value_end;
2128 value_end = strchrW(option, ',');
2129 if (!value_end)
2130 value_end = value_start + strlenW(value_start);
2131 TRACE("HttpProxy value is %s\n", debugstr_wn(value_start, value_end-value_start));
2132 proxy = RPCRT4_strndupW(value_start, value_end-value_start);
2134 else
2135 FIXME("unhandled option %s\n", debugstr_w(option));
2138 httpc->app_info = InternetOpenW(wszUserAgent, proxy ? INTERNET_OPEN_TYPE_PROXY : INTERNET_OPEN_TYPE_PRECONFIG,
2139 NULL, NULL, INTERNET_FLAG_ASYNC);
2140 if (!httpc->app_info)
2142 HeapFree(GetProcessHeap(), 0, password);
2143 HeapFree(GetProcessHeap(), 0, user);
2144 HeapFree(GetProcessHeap(), 0, proxy);
2145 HeapFree(GetProcessHeap(), 0, servername);
2146 ERR("InternetOpenW failed with error %d\n", GetLastError());
2147 return RPC_S_SERVER_UNAVAILABLE;
2149 InternetSetStatusCallbackW(httpc->app_info, rpcrt4_http_internet_callback);
2151 /* if no RpcProxy option specified, set the HTTP server address to the
2152 * RPC server address */
2153 if (!servername)
2155 servername = HeapAlloc(GetProcessHeap(), 0, (strlen(httpc->common.NetworkAddr) + 1)*sizeof(WCHAR));
2156 if (!servername)
2158 HeapFree(GetProcessHeap(), 0, password);
2159 HeapFree(GetProcessHeap(), 0, user);
2160 HeapFree(GetProcessHeap(), 0, proxy);
2161 return RPC_S_OUT_OF_RESOURCES;
2163 MultiByteToWideChar(CP_ACP, 0, httpc->common.NetworkAddr, -1, servername, strlen(httpc->common.NetworkAddr) + 1);
2166 port = (httpc->common.QOS &&
2167 (httpc->common.QOS->qos->AdditionalSecurityInfoType == RPC_C_AUTHN_INFO_TYPE_HTTP) &&
2168 (httpc->common.QOS->qos->u.HttpCredentials->Flags & RPC_C_HTTP_FLAG_USE_SSL)) ?
2169 INTERNET_DEFAULT_HTTPS_PORT : INTERNET_DEFAULT_HTTP_PORT;
2171 httpc->session = InternetConnectW(httpc->app_info, servername, port, user, password,
2172 INTERNET_SERVICE_HTTP, 0, 0);
2174 HeapFree(GetProcessHeap(), 0, password);
2175 HeapFree(GetProcessHeap(), 0, user);
2176 HeapFree(GetProcessHeap(), 0, proxy);
2177 HeapFree(GetProcessHeap(), 0, servername);
2179 if (!httpc->session)
2181 ERR("InternetConnectW failed with error %d\n", GetLastError());
2182 return RPC_S_SERVER_UNAVAILABLE;
2185 return RPC_S_OK;
2188 static RPC_STATUS send_echo_request(HINTERNET req, RpcHttpAsyncData *async_data, HANDLE cancel_event)
2190 DWORD bytes_read;
2191 BYTE buf[20];
2192 BOOL ret;
2193 RPC_STATUS status;
2195 prepare_async_request(async_data);
2196 ret = HttpSendRequestW(req, NULL, 0, NULL, 0);
2197 status = wait_async_request(async_data, ret, cancel_event);
2198 if (status != RPC_S_OK) return status;
2200 status = rpcrt4_http_check_response(req);
2201 if (status != RPC_S_OK) return status;
2203 InternetReadFile(req, buf, sizeof(buf), &bytes_read);
2204 /* FIXME: do something with retrieved data */
2206 return RPC_S_OK;
2209 /* prepare the in pipe for use by RPC packets */
2210 static RPC_STATUS rpcrt4_http_prepare_in_pipe(HINTERNET in_request, RpcHttpAsyncData *async_data, HANDLE cancel_event,
2211 const UUID *connection_uuid,
2212 const UUID *in_pipe_uuid,
2213 const UUID *association_uuid)
2215 BOOL ret;
2216 RPC_STATUS status;
2217 RpcPktHdr *hdr;
2218 INTERNET_BUFFERSW buffers_in;
2219 DWORD bytes_written;
2221 /* prepare in pipe */
2222 status = send_echo_request(in_request, async_data, cancel_event);
2223 if (status != RPC_S_OK) return status;
2225 memset(&buffers_in, 0, sizeof(buffers_in));
2226 buffers_in.dwStructSize = sizeof(buffers_in);
2227 /* FIXME: get this from the registry */
2228 buffers_in.dwBufferTotal = 1024 * 1024 * 1024; /* 1Gb */
2229 prepare_async_request(async_data);
2230 ret = HttpSendRequestExW(in_request, &buffers_in, NULL, 0, 0);
2231 status = wait_async_request(async_data, ret, cancel_event);
2232 if (status != RPC_S_OK) return status;
2234 TRACE("sending HTTP connect header to server\n");
2235 hdr = RPCRT4_BuildHttpConnectHeader(FALSE, connection_uuid, in_pipe_uuid, association_uuid);
2236 if (!hdr) return RPC_S_OUT_OF_RESOURCES;
2237 ret = InternetWriteFile(in_request, hdr, hdr->common.frag_len, &bytes_written);
2238 RPCRT4_FreeHeader(hdr);
2239 if (!ret)
2241 ERR("InternetWriteFile failed with error %d\n", GetLastError());
2242 return RPC_S_SERVER_UNAVAILABLE;
2245 return RPC_S_OK;
2248 static RPC_STATUS rpcrt4_http_read_http_packet(HINTERNET request, RpcPktHdr *hdr, BYTE **data)
2250 BOOL ret;
2251 DWORD bytes_read;
2252 unsigned short data_len;
2254 ret = InternetReadFile(request, hdr, sizeof(hdr->common), &bytes_read);
2255 if (!ret)
2256 return RPC_S_SERVER_UNAVAILABLE;
2257 if (hdr->common.ptype != PKT_HTTP || hdr->common.frag_len < sizeof(hdr->http))
2259 ERR("wrong packet type received %d or wrong frag_len %d\n",
2260 hdr->common.ptype, hdr->common.frag_len);
2261 return RPC_S_PROTOCOL_ERROR;
2264 ret = InternetReadFile(request, &hdr->common + 1, sizeof(hdr->http) - sizeof(hdr->common), &bytes_read);
2265 if (!ret)
2266 return RPC_S_SERVER_UNAVAILABLE;
2268 data_len = hdr->common.frag_len - sizeof(hdr->http);
2269 if (data_len)
2271 *data = HeapAlloc(GetProcessHeap(), 0, data_len);
2272 if (!*data)
2273 return RPC_S_OUT_OF_RESOURCES;
2274 ret = InternetReadFile(request, *data, data_len, &bytes_read);
2275 if (!ret)
2277 HeapFree(GetProcessHeap(), 0, *data);
2278 return RPC_S_SERVER_UNAVAILABLE;
2281 else
2282 *data = NULL;
2284 if (!RPCRT4_IsValidHttpPacket(hdr, *data, data_len))
2286 ERR("invalid http packet\n");
2287 return RPC_S_PROTOCOL_ERROR;
2290 return RPC_S_OK;
2293 /* prepare the out pipe for use by RPC packets */
2294 static RPC_STATUS rpcrt4_http_prepare_out_pipe(HINTERNET out_request,
2295 RpcHttpAsyncData *async_data,
2296 HANDLE cancel_event,
2297 const UUID *connection_uuid,
2298 const UUID *out_pipe_uuid,
2299 ULONG *flow_control_increment)
2301 BOOL ret;
2302 RPC_STATUS status;
2303 RpcPktHdr *hdr;
2304 BYTE *data_from_server;
2305 RpcPktHdr pkt_from_server;
2306 ULONG field1, field3;
2308 status = send_echo_request(out_request, async_data, cancel_event);
2309 if (status != RPC_S_OK) return status;
2311 hdr = RPCRT4_BuildHttpConnectHeader(TRUE, connection_uuid, out_pipe_uuid, NULL);
2312 if (!hdr) return RPC_S_OUT_OF_RESOURCES;
2314 prepare_async_request(async_data);
2315 ret = HttpSendRequestW(out_request, NULL, 0, hdr, hdr->common.frag_len);
2316 status = wait_async_request(async_data, ret, cancel_event);
2317 RPCRT4_FreeHeader(hdr);
2318 if (status != RPC_S_OK) return status;
2320 status = rpcrt4_http_check_response(out_request);
2321 if (status != RPC_S_OK) return status;
2323 status = rpcrt4_http_read_http_packet(out_request, &pkt_from_server,
2324 &data_from_server);
2325 if (status != RPC_S_OK) return status;
2326 status = RPCRT4_ParseHttpPrepareHeader1(&pkt_from_server, data_from_server,
2327 &field1);
2328 HeapFree(GetProcessHeap(), 0, data_from_server);
2329 if (status != RPC_S_OK) return status;
2330 TRACE("received (%d) from first prepare header\n", field1);
2332 for (;;)
2334 status = rpcrt4_http_read_http_packet(out_request, &pkt_from_server,
2335 &data_from_server);
2336 if (status != RPC_S_OK) return status;
2337 if (pkt_from_server.http.flags != 0x0001) break;
2339 TRACE("http idle packet, waiting for real packet\n");
2340 HeapFree(GetProcessHeap(), 0, data_from_server);
2341 if (pkt_from_server.http.num_data_items != 0)
2343 ERR("HTTP idle packet should have no data items instead of %d\n",
2344 pkt_from_server.http.num_data_items);
2345 return RPC_S_PROTOCOL_ERROR;
2348 status = RPCRT4_ParseHttpPrepareHeader2(&pkt_from_server, data_from_server,
2349 &field1, flow_control_increment,
2350 &field3);
2351 HeapFree(GetProcessHeap(), 0, data_from_server);
2352 if (status != RPC_S_OK) return status;
2353 TRACE("received (0x%08x 0x%08x %d) from second prepare header\n", field1, *flow_control_increment, field3);
2355 return RPC_S_OK;
2358 static UINT encode_base64(const char *bin, unsigned int len, WCHAR *base64)
2360 static char enc[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
2361 UINT i = 0, x;
2363 while (len > 0)
2365 /* first 6 bits, all from bin[0] */
2366 base64[i++] = enc[(bin[0] & 0xfc) >> 2];
2367 x = (bin[0] & 3) << 4;
2369 /* next 6 bits, 2 from bin[0] and 4 from bin[1] */
2370 if (len == 1)
2372 base64[i++] = enc[x];
2373 base64[i++] = '=';
2374 base64[i++] = '=';
2375 break;
2377 base64[i++] = enc[x | ((bin[1] & 0xf0) >> 4)];
2378 x = (bin[1] & 0x0f) << 2;
2380 /* next 6 bits 4 from bin[1] and 2 from bin[2] */
2381 if (len == 2)
2383 base64[i++] = enc[x];
2384 base64[i++] = '=';
2385 break;
2387 base64[i++] = enc[x | ((bin[2] & 0xc0) >> 6)];
2389 /* last 6 bits, all from bin [2] */
2390 base64[i++] = enc[bin[2] & 0x3f];
2391 bin += 3;
2392 len -= 3;
2394 base64[i] = 0;
2395 return i;
2398 static RPC_STATUS insert_authorization_header(HINTERNET request, RpcQualityOfService *qos)
2400 static const WCHAR basicW[] =
2401 {'A','u','t','h','o','r','i','z','a','t','i','o','n',':',' ','B','a','s','i','c',' '};
2402 RPC_HTTP_TRANSPORT_CREDENTIALS_W *creds;
2403 SEC_WINNT_AUTH_IDENTITY_W *id;
2404 int len, datalen, userlen, passlen;
2405 WCHAR *header, *ptr;
2406 char *data;
2407 RPC_STATUS status = RPC_S_SERVER_UNAVAILABLE;
2409 if (!qos || qos->qos->AdditionalSecurityInfoType != RPC_C_AUTHN_INFO_TYPE_HTTP)
2410 return RPC_S_OK;
2412 creds = qos->qos->u.HttpCredentials;
2413 if (creds->AuthenticationTarget != RPC_C_HTTP_AUTHN_TARGET_SERVER || !creds->NumberOfAuthnSchemes)
2414 return RPC_S_OK;
2416 if (creds->AuthnSchemes[0] != RPC_C_HTTP_AUTHN_SCHEME_BASIC)
2418 FIXME("scheme %u not supported\n", creds->AuthnSchemes[0]);
2419 return RPC_S_OK;
2421 id = creds->TransportCredentials;
2422 if (!id->User || !id->Password) return RPC_S_OK;
2424 userlen = WideCharToMultiByte(CP_UTF8, 0, id->User, id->UserLength, NULL, 0, NULL, NULL);
2425 passlen = WideCharToMultiByte(CP_UTF8, 0, id->Password, id->PasswordLength, NULL, 0, NULL, NULL);
2427 datalen = userlen + passlen + 1;
2428 if (!(data = HeapAlloc(GetProcessHeap(), 0, datalen))) return RPC_S_OUT_OF_MEMORY;
2430 WideCharToMultiByte(CP_UTF8, 0, id->User, id->UserLength, data, userlen, NULL, NULL);
2431 data[userlen] = ':';
2432 WideCharToMultiByte(CP_UTF8, 0, id->Password, id->PasswordLength, data + userlen + 1, passlen, NULL, NULL);
2434 len = ((datalen + 2) * 4) / 3;
2435 if ((header = HeapAlloc(GetProcessHeap(), 0, sizeof(basicW) + (len + 2) * sizeof(WCHAR))))
2437 memcpy(header, basicW, sizeof(basicW));
2438 ptr = header + sizeof(basicW) / sizeof(basicW[0]);
2439 len = encode_base64(data, datalen, ptr);
2440 ptr[len++] = '\r';
2441 ptr[len++] = '\n';
2442 ptr[len] = 0;
2443 if ((HttpAddRequestHeadersW(request, header, -1, HTTP_ADDREQ_FLAG_ADD_IF_NEW))) status = RPC_S_OK;
2444 HeapFree(GetProcessHeap(), 0, header);
2446 HeapFree(GetProcessHeap(), 0, data);
2447 return status;
2450 static RPC_STATUS insert_cookie_header(HINTERNET request, const WCHAR *value)
2452 static const WCHAR cookieW[] = {'C','o','o','k','i','e',':',' '};
2453 WCHAR *header, *ptr;
2454 int len;
2455 RPC_STATUS status = RPC_S_SERVER_UNAVAILABLE;
2457 if (!value) return RPC_S_OK;
2459 len = strlenW(value);
2460 if ((header = HeapAlloc(GetProcessHeap(), 0, sizeof(cookieW) + (len + 3) * sizeof(WCHAR))))
2462 memcpy(header, cookieW, sizeof(cookieW));
2463 ptr = header + sizeof(cookieW) / sizeof(cookieW[0]);
2464 memcpy(ptr, value, len * sizeof(WCHAR));
2465 ptr[len++] = '\r';
2466 ptr[len++] = '\n';
2467 ptr[len] = 0;
2468 if ((HttpAddRequestHeadersW(request, header, -1, HTTP_ADDREQ_FLAG_ADD_IF_NEW))) status = RPC_S_OK;
2469 HeapFree(GetProcessHeap(), 0, header);
2471 return status;
2474 static RPC_STATUS rpcrt4_ncacn_http_open(RpcConnection* Connection)
2476 RpcConnection_http *httpc = (RpcConnection_http *)Connection;
2477 static const WCHAR wszVerbIn[] = {'R','P','C','_','I','N','_','D','A','T','A',0};
2478 static const WCHAR wszVerbOut[] = {'R','P','C','_','O','U','T','_','D','A','T','A',0};
2479 static const WCHAR wszRpcProxyPrefix[] = {'/','r','p','c','/','r','p','c','p','r','o','x','y','.','d','l','l','?',0};
2480 static const WCHAR wszColon[] = {':',0};
2481 static const WCHAR wszAcceptType[] = {'a','p','p','l','i','c','a','t','i','o','n','/','r','p','c',0};
2482 LPCWSTR wszAcceptTypes[] = { wszAcceptType, NULL };
2483 DWORD flags;
2484 WCHAR *url;
2485 RPC_STATUS status;
2486 BOOL secure;
2487 HttpTimerThreadData *timer_data;
2488 HANDLE thread;
2490 TRACE("(%s, %s)\n", Connection->NetworkAddr, Connection->Endpoint);
2492 if (Connection->server)
2494 ERR("ncacn_http servers not supported yet\n");
2495 return RPC_S_SERVER_UNAVAILABLE;
2498 if (httpc->in_request)
2499 return RPC_S_OK;
2501 httpc->async_data->completion_event = CreateEventW(NULL, FALSE, FALSE, NULL);
2503 status = UuidCreate(&httpc->connection_uuid);
2504 status = UuidCreate(&httpc->in_pipe_uuid);
2505 status = UuidCreate(&httpc->out_pipe_uuid);
2507 status = rpcrt4_http_internet_connect(httpc);
2508 if (status != RPC_S_OK)
2509 return status;
2511 url = HeapAlloc(GetProcessHeap(), 0, sizeof(wszRpcProxyPrefix) + (strlen(Connection->NetworkAddr) + 1 + strlen(Connection->Endpoint))*sizeof(WCHAR));
2512 if (!url)
2513 return RPC_S_OUT_OF_MEMORY;
2514 memcpy(url, wszRpcProxyPrefix, sizeof(wszRpcProxyPrefix));
2515 MultiByteToWideChar(CP_ACP, 0, Connection->NetworkAddr, -1, url+sizeof(wszRpcProxyPrefix)/sizeof(wszRpcProxyPrefix[0])-1, strlen(Connection->NetworkAddr)+1);
2516 strcatW(url, wszColon);
2517 MultiByteToWideChar(CP_ACP, 0, Connection->Endpoint, -1, url+strlenW(url), strlen(Connection->Endpoint)+1);
2519 secure = httpc->common.QOS &&
2520 (httpc->common.QOS->qos->AdditionalSecurityInfoType == RPC_C_AUTHN_INFO_TYPE_HTTP) &&
2521 (httpc->common.QOS->qos->u.HttpCredentials->Flags & RPC_C_HTTP_FLAG_USE_SSL);
2523 flags = INTERNET_FLAG_KEEP_CONNECTION | INTERNET_FLAG_PRAGMA_NOCACHE | INTERNET_FLAG_NO_CACHE_WRITE |
2524 INTERNET_FLAG_NO_AUTO_REDIRECT;
2525 if (secure) flags |= INTERNET_FLAG_SECURE;
2527 httpc->in_request = HttpOpenRequestW(httpc->session, wszVerbIn, url, NULL, NULL, wszAcceptTypes,
2528 flags, (DWORD_PTR)httpc->async_data);
2529 if (!httpc->in_request)
2531 ERR("HttpOpenRequestW failed with error %d\n", GetLastError());
2532 HeapFree(GetProcessHeap(), 0, url);
2533 return RPC_S_SERVER_UNAVAILABLE;
2535 status = insert_authorization_header(httpc->in_request, httpc->common.QOS);
2536 if (status != RPC_S_OK) {
2537 HeapFree(GetProcessHeap(), 0, url);
2538 return status;
2541 status = insert_cookie_header(httpc->in_request, Connection->CookieAuth);
2542 if (status != RPC_S_OK) {
2543 HeapFree(GetProcessHeap(), 0, url);
2544 return status;
2547 httpc->out_request = HttpOpenRequestW(httpc->session, wszVerbOut, url, NULL, NULL, wszAcceptTypes,
2548 flags, (DWORD_PTR)httpc->async_data);
2549 HeapFree(GetProcessHeap(), 0, url);
2550 if (!httpc->out_request)
2552 ERR("HttpOpenRequestW failed with error %d\n", GetLastError());
2553 return RPC_S_SERVER_UNAVAILABLE;
2555 status = insert_authorization_header(httpc->out_request, httpc->common.QOS);
2556 if (status != RPC_S_OK)
2557 return status;
2559 status = insert_cookie_header(httpc->out_request, Connection->CookieAuth);
2560 if (status != RPC_S_OK)
2561 return status;
2563 status = rpcrt4_http_prepare_in_pipe(httpc->in_request,
2564 httpc->async_data,
2565 httpc->cancel_event,
2566 &httpc->connection_uuid,
2567 &httpc->in_pipe_uuid,
2568 &Connection->assoc->http_uuid);
2569 if (status != RPC_S_OK)
2570 return status;
2572 status = rpcrt4_http_prepare_out_pipe(httpc->out_request,
2573 httpc->async_data,
2574 httpc->cancel_event,
2575 &httpc->connection_uuid,
2576 &httpc->out_pipe_uuid,
2577 &httpc->flow_control_increment);
2578 if (status != RPC_S_OK)
2579 return status;
2581 httpc->flow_control_mark = httpc->flow_control_increment / 2;
2582 httpc->last_sent_time = GetTickCount();
2583 httpc->timer_cancelled = CreateEventW(NULL, FALSE, FALSE, NULL);
2585 timer_data = HeapAlloc(GetProcessHeap(), 0, sizeof(*timer_data));
2586 if (!timer_data)
2587 return ERROR_OUTOFMEMORY;
2588 timer_data->timer_param = httpc->in_request;
2589 timer_data->last_sent_time = &httpc->last_sent_time;
2590 timer_data->timer_cancelled = httpc->timer_cancelled;
2591 /* FIXME: should use CreateTimerQueueTimer when implemented */
2592 thread = CreateThread(NULL, 0, rpcrt4_http_timer_thread, timer_data, 0, NULL);
2593 if (!thread)
2595 HeapFree(GetProcessHeap(), 0, timer_data);
2596 return GetLastError();
2598 CloseHandle(thread);
2600 return RPC_S_OK;
2603 static RPC_STATUS rpcrt4_ncacn_http_handoff(RpcConnection *old_conn, RpcConnection *new_conn)
2605 assert(0);
2606 return RPC_S_SERVER_UNAVAILABLE;
2609 static int rpcrt4_ncacn_http_read(RpcConnection *Connection,
2610 void *buffer, unsigned int count)
2612 RpcConnection_http *httpc = (RpcConnection_http *) Connection;
2613 char *buf = buffer;
2614 BOOL ret;
2615 unsigned int bytes_left = count;
2616 RPC_STATUS status = RPC_S_OK;
2618 httpc->async_data->inet_buffers.lpvBuffer = HeapAlloc(GetProcessHeap(), 0, count);
2620 while (bytes_left)
2622 httpc->async_data->inet_buffers.dwBufferLength = bytes_left;
2623 prepare_async_request(httpc->async_data);
2624 ret = InternetReadFileExA(httpc->out_request, &httpc->async_data->inet_buffers, IRF_ASYNC, 0);
2625 status = wait_async_request(httpc->async_data, ret, httpc->cancel_event);
2626 if(status != RPC_S_OK) {
2627 if(status == RPC_S_CALL_CANCELLED)
2628 TRACE("call cancelled\n");
2629 break;
2632 if(!httpc->async_data->inet_buffers.dwBufferLength)
2633 break;
2634 memcpy(buf, httpc->async_data->inet_buffers.lpvBuffer,
2635 httpc->async_data->inet_buffers.dwBufferLength);
2637 bytes_left -= httpc->async_data->inet_buffers.dwBufferLength;
2638 buf += httpc->async_data->inet_buffers.dwBufferLength;
2641 HeapFree(GetProcessHeap(), 0, httpc->async_data->inet_buffers.lpvBuffer);
2642 httpc->async_data->inet_buffers.lpvBuffer = NULL;
2644 TRACE("%p %p %u -> %u\n", httpc->out_request, buffer, count, status);
2645 return status == RPC_S_OK ? count : -1;
2648 static RPC_STATUS rpcrt4_ncacn_http_receive_fragment(RpcConnection *Connection, RpcPktHdr **Header, void **Payload)
2650 RpcConnection_http *httpc = (RpcConnection_http *) Connection;
2651 RPC_STATUS status;
2652 DWORD hdr_length;
2653 LONG dwRead;
2654 RpcPktCommonHdr common_hdr;
2656 *Header = NULL;
2658 TRACE("(%p, %p, %p)\n", Connection, Header, Payload);
2660 again:
2661 /* read packet common header */
2662 dwRead = rpcrt4_ncacn_http_read(Connection, &common_hdr, sizeof(common_hdr));
2663 if (dwRead != sizeof(common_hdr)) {
2664 WARN("Short read of header, %d bytes\n", dwRead);
2665 status = RPC_S_PROTOCOL_ERROR;
2666 goto fail;
2668 if (!memcmp(&common_hdr, "HTTP/1.1", sizeof("HTTP/1.1")) ||
2669 !memcmp(&common_hdr, "HTTP/1.0", sizeof("HTTP/1.0")))
2671 FIXME("server returned %s\n", debugstr_a((const char *)&common_hdr));
2672 status = RPC_S_PROTOCOL_ERROR;
2673 goto fail;
2676 status = RPCRT4_ValidateCommonHeader(&common_hdr);
2677 if (status != RPC_S_OK) goto fail;
2679 hdr_length = RPCRT4_GetHeaderSize((RpcPktHdr*)&common_hdr);
2680 if (hdr_length == 0) {
2681 WARN("header length == 0\n");
2682 status = RPC_S_PROTOCOL_ERROR;
2683 goto fail;
2686 *Header = HeapAlloc(GetProcessHeap(), 0, hdr_length);
2687 if (!*Header)
2689 status = RPC_S_OUT_OF_RESOURCES;
2690 goto fail;
2692 memcpy(*Header, &common_hdr, sizeof(common_hdr));
2694 /* read the rest of packet header */
2695 dwRead = rpcrt4_ncacn_http_read(Connection, &(*Header)->common + 1, hdr_length - sizeof(common_hdr));
2696 if (dwRead != hdr_length - sizeof(common_hdr)) {
2697 WARN("bad header length, %d bytes, hdr_length %d\n", dwRead, hdr_length);
2698 status = RPC_S_PROTOCOL_ERROR;
2699 goto fail;
2702 if (common_hdr.frag_len - hdr_length)
2704 *Payload = HeapAlloc(GetProcessHeap(), 0, common_hdr.frag_len - hdr_length);
2705 if (!*Payload)
2707 status = RPC_S_OUT_OF_RESOURCES;
2708 goto fail;
2711 dwRead = rpcrt4_ncacn_http_read(Connection, *Payload, common_hdr.frag_len - hdr_length);
2712 if (dwRead != common_hdr.frag_len - hdr_length)
2714 WARN("bad data length, %d/%d\n", dwRead, common_hdr.frag_len - hdr_length);
2715 status = RPC_S_PROTOCOL_ERROR;
2716 goto fail;
2719 else
2720 *Payload = NULL;
2722 if ((*Header)->common.ptype == PKT_HTTP)
2724 if (!RPCRT4_IsValidHttpPacket(*Header, *Payload, common_hdr.frag_len - hdr_length))
2726 ERR("invalid http packet of length %d bytes\n", (*Header)->common.frag_len);
2727 status = RPC_S_PROTOCOL_ERROR;
2728 goto fail;
2730 if ((*Header)->http.flags == 0x0001)
2732 TRACE("http idle packet, waiting for real packet\n");
2733 if ((*Header)->http.num_data_items != 0)
2735 ERR("HTTP idle packet should have no data items instead of %d\n", (*Header)->http.num_data_items);
2736 status = RPC_S_PROTOCOL_ERROR;
2737 goto fail;
2740 else if ((*Header)->http.flags == 0x0002)
2742 ULONG bytes_transmitted;
2743 ULONG flow_control_increment;
2744 UUID pipe_uuid;
2745 status = RPCRT4_ParseHttpFlowControlHeader(*Header, *Payload,
2746 Connection->server,
2747 &bytes_transmitted,
2748 &flow_control_increment,
2749 &pipe_uuid);
2750 if (status != RPC_S_OK)
2751 goto fail;
2752 TRACE("received http flow control header (0x%x, 0x%x, %s)\n",
2753 bytes_transmitted, flow_control_increment, debugstr_guid(&pipe_uuid));
2754 /* FIXME: do something with parsed data */
2756 else
2758 FIXME("unrecognised http packet with flags 0x%04x\n", (*Header)->http.flags);
2759 status = RPC_S_PROTOCOL_ERROR;
2760 goto fail;
2762 RPCRT4_FreeHeader(*Header);
2763 *Header = NULL;
2764 HeapFree(GetProcessHeap(), 0, *Payload);
2765 *Payload = NULL;
2766 goto again;
2769 /* success */
2770 status = RPC_S_OK;
2772 httpc->bytes_received += common_hdr.frag_len;
2774 TRACE("httpc->bytes_received = 0x%x\n", httpc->bytes_received);
2776 if (httpc->bytes_received > httpc->flow_control_mark)
2778 RpcPktHdr *hdr = RPCRT4_BuildHttpFlowControlHeader(httpc->common.server,
2779 httpc->bytes_received,
2780 httpc->flow_control_increment,
2781 &httpc->out_pipe_uuid);
2782 if (hdr)
2784 DWORD bytes_written;
2785 BOOL ret2;
2786 TRACE("sending flow control packet at 0x%x\n", httpc->bytes_received);
2787 ret2 = InternetWriteFile(httpc->in_request, hdr, hdr->common.frag_len, &bytes_written);
2788 RPCRT4_FreeHeader(hdr);
2789 if (ret2)
2790 httpc->flow_control_mark = httpc->bytes_received + httpc->flow_control_increment / 2;
2794 fail:
2795 if (status != RPC_S_OK) {
2796 RPCRT4_FreeHeader(*Header);
2797 *Header = NULL;
2798 HeapFree(GetProcessHeap(), 0, *Payload);
2799 *Payload = NULL;
2801 return status;
2804 static int rpcrt4_ncacn_http_write(RpcConnection *Connection,
2805 const void *buffer, unsigned int count)
2807 RpcConnection_http *httpc = (RpcConnection_http *) Connection;
2808 DWORD bytes_written;
2809 BOOL ret;
2811 httpc->last_sent_time = ~0U; /* disable idle packet sending */
2812 ret = InternetWriteFile(httpc->in_request, buffer, count, &bytes_written);
2813 httpc->last_sent_time = GetTickCount();
2814 TRACE("%p %p %u -> %s\n", httpc->in_request, buffer, count, ret ? "TRUE" : "FALSE");
2815 return ret ? bytes_written : -1;
2818 static int rpcrt4_ncacn_http_close(RpcConnection *Connection)
2820 RpcConnection_http *httpc = (RpcConnection_http *) Connection;
2822 TRACE("\n");
2824 SetEvent(httpc->timer_cancelled);
2825 if (httpc->in_request)
2826 InternetCloseHandle(httpc->in_request);
2827 httpc->in_request = NULL;
2828 if (httpc->out_request)
2829 InternetCloseHandle(httpc->out_request);
2830 httpc->out_request = NULL;
2831 if (httpc->app_info)
2832 InternetCloseHandle(httpc->app_info);
2833 httpc->app_info = NULL;
2834 if (httpc->session)
2835 InternetCloseHandle(httpc->session);
2836 httpc->session = NULL;
2837 RpcHttpAsyncData_Release(httpc->async_data);
2838 if (httpc->cancel_event)
2839 CloseHandle(httpc->cancel_event);
2841 return 0;
2844 static void rpcrt4_ncacn_http_cancel_call(RpcConnection *Connection)
2846 RpcConnection_http *httpc = (RpcConnection_http *) Connection;
2848 SetEvent(httpc->cancel_event);
2851 static int rpcrt4_ncacn_http_wait_for_incoming_data(RpcConnection *Connection)
2853 RpcConnection_http *httpc = (RpcConnection_http *) Connection;
2854 BOOL ret;
2855 RPC_STATUS status;
2857 prepare_async_request(httpc->async_data);
2858 ret = InternetQueryDataAvailable(httpc->out_request,
2859 &httpc->async_data->inet_buffers.dwBufferLength, IRF_ASYNC, 0);
2860 status = wait_async_request(httpc->async_data, ret, httpc->cancel_event);
2861 return status == RPC_S_OK ? 0 : -1;
2864 static size_t rpcrt4_ncacn_http_get_top_of_tower(unsigned char *tower_data,
2865 const char *networkaddr,
2866 const char *endpoint)
2868 return rpcrt4_ip_tcp_get_top_of_tower(tower_data, networkaddr,
2869 EPM_PROTOCOL_HTTP, endpoint);
2872 static RPC_STATUS rpcrt4_ncacn_http_parse_top_of_tower(const unsigned char *tower_data,
2873 size_t tower_size,
2874 char **networkaddr,
2875 char **endpoint)
2877 return rpcrt4_ip_tcp_parse_top_of_tower(tower_data, tower_size,
2878 networkaddr, EPM_PROTOCOL_HTTP,
2879 endpoint);
2882 static const struct connection_ops conn_protseq_list[] = {
2883 { "ncacn_np",
2884 { EPM_PROTOCOL_NCACN, EPM_PROTOCOL_SMB },
2885 rpcrt4_conn_np_alloc,
2886 rpcrt4_ncacn_np_open,
2887 rpcrt4_ncacn_np_handoff,
2888 rpcrt4_conn_np_read,
2889 rpcrt4_conn_np_write,
2890 rpcrt4_conn_np_close,
2891 rpcrt4_conn_np_cancel_call,
2892 rpcrt4_conn_np_wait_for_incoming_data,
2893 rpcrt4_ncacn_np_get_top_of_tower,
2894 rpcrt4_ncacn_np_parse_top_of_tower,
2895 NULL,
2896 RPCRT4_default_is_authorized,
2897 RPCRT4_default_authorize,
2898 RPCRT4_default_secure_packet,
2899 rpcrt4_conn_np_impersonate_client,
2900 rpcrt4_conn_np_revert_to_self,
2901 RPCRT4_default_inquire_auth_client,
2903 { "ncalrpc",
2904 { EPM_PROTOCOL_NCALRPC, EPM_PROTOCOL_PIPE },
2905 rpcrt4_conn_np_alloc,
2906 rpcrt4_ncalrpc_open,
2907 rpcrt4_ncalrpc_handoff,
2908 rpcrt4_conn_np_read,
2909 rpcrt4_conn_np_write,
2910 rpcrt4_conn_np_close,
2911 rpcrt4_conn_np_cancel_call,
2912 rpcrt4_conn_np_wait_for_incoming_data,
2913 rpcrt4_ncalrpc_get_top_of_tower,
2914 rpcrt4_ncalrpc_parse_top_of_tower,
2915 NULL,
2916 rpcrt4_ncalrpc_is_authorized,
2917 rpcrt4_ncalrpc_authorize,
2918 rpcrt4_ncalrpc_secure_packet,
2919 rpcrt4_conn_np_impersonate_client,
2920 rpcrt4_conn_np_revert_to_self,
2921 rpcrt4_ncalrpc_inquire_auth_client,
2923 { "ncacn_ip_tcp",
2924 { EPM_PROTOCOL_NCACN, EPM_PROTOCOL_TCP },
2925 rpcrt4_conn_tcp_alloc,
2926 rpcrt4_ncacn_ip_tcp_open,
2927 rpcrt4_conn_tcp_handoff,
2928 rpcrt4_conn_tcp_read,
2929 rpcrt4_conn_tcp_write,
2930 rpcrt4_conn_tcp_close,
2931 rpcrt4_conn_tcp_cancel_call,
2932 rpcrt4_conn_tcp_wait_for_incoming_data,
2933 rpcrt4_ncacn_ip_tcp_get_top_of_tower,
2934 rpcrt4_ncacn_ip_tcp_parse_top_of_tower,
2935 NULL,
2936 RPCRT4_default_is_authorized,
2937 RPCRT4_default_authorize,
2938 RPCRT4_default_secure_packet,
2939 RPCRT4_default_impersonate_client,
2940 RPCRT4_default_revert_to_self,
2941 RPCRT4_default_inquire_auth_client,
2943 { "ncacn_http",
2944 { EPM_PROTOCOL_NCACN, EPM_PROTOCOL_HTTP },
2945 rpcrt4_ncacn_http_alloc,
2946 rpcrt4_ncacn_http_open,
2947 rpcrt4_ncacn_http_handoff,
2948 rpcrt4_ncacn_http_read,
2949 rpcrt4_ncacn_http_write,
2950 rpcrt4_ncacn_http_close,
2951 rpcrt4_ncacn_http_cancel_call,
2952 rpcrt4_ncacn_http_wait_for_incoming_data,
2953 rpcrt4_ncacn_http_get_top_of_tower,
2954 rpcrt4_ncacn_http_parse_top_of_tower,
2955 rpcrt4_ncacn_http_receive_fragment,
2956 RPCRT4_default_is_authorized,
2957 RPCRT4_default_authorize,
2958 RPCRT4_default_secure_packet,
2959 RPCRT4_default_impersonate_client,
2960 RPCRT4_default_revert_to_self,
2961 RPCRT4_default_inquire_auth_client,
2966 static const struct protseq_ops protseq_list[] =
2969 "ncacn_np",
2970 rpcrt4_protseq_np_alloc,
2971 rpcrt4_protseq_np_signal_state_changed,
2972 rpcrt4_protseq_np_get_wait_array,
2973 rpcrt4_protseq_np_free_wait_array,
2974 rpcrt4_protseq_np_wait_for_new_connection,
2975 rpcrt4_protseq_ncacn_np_open_endpoint,
2978 "ncalrpc",
2979 rpcrt4_protseq_np_alloc,
2980 rpcrt4_protseq_np_signal_state_changed,
2981 rpcrt4_protseq_np_get_wait_array,
2982 rpcrt4_protseq_np_free_wait_array,
2983 rpcrt4_protseq_np_wait_for_new_connection,
2984 rpcrt4_protseq_ncalrpc_open_endpoint,
2987 "ncacn_ip_tcp",
2988 rpcrt4_protseq_sock_alloc,
2989 rpcrt4_protseq_sock_signal_state_changed,
2990 rpcrt4_protseq_sock_get_wait_array,
2991 rpcrt4_protseq_sock_free_wait_array,
2992 rpcrt4_protseq_sock_wait_for_new_connection,
2993 rpcrt4_protseq_ncacn_ip_tcp_open_endpoint,
2997 #define ARRAYSIZE(a) (sizeof((a)) / sizeof((a)[0]))
2999 const struct protseq_ops *rpcrt4_get_protseq_ops(const char *protseq)
3001 unsigned int i;
3002 for(i=0; i<ARRAYSIZE(protseq_list); i++)
3003 if (!strcmp(protseq_list[i].name, protseq))
3004 return &protseq_list[i];
3005 return NULL;
3008 static const struct connection_ops *rpcrt4_get_conn_protseq_ops(const char *protseq)
3010 unsigned int i;
3011 for(i=0; i<ARRAYSIZE(conn_protseq_list); i++)
3012 if (!strcmp(conn_protseq_list[i].name, protseq))
3013 return &conn_protseq_list[i];
3014 return NULL;
3017 /**** interface to rest of code ****/
3019 RPC_STATUS RPCRT4_OpenClientConnection(RpcConnection* Connection)
3021 TRACE("(Connection == ^%p)\n", Connection);
3023 assert(!Connection->server);
3024 return Connection->ops->open_connection_client(Connection);
3027 RPC_STATUS RPCRT4_CloseConnection(RpcConnection* Connection)
3029 TRACE("(Connection == ^%p)\n", Connection);
3030 if (SecIsValidHandle(&Connection->ctx))
3032 DeleteSecurityContext(&Connection->ctx);
3033 SecInvalidateHandle(&Connection->ctx);
3035 rpcrt4_conn_close(Connection);
3036 return RPC_S_OK;
3039 RPC_STATUS RPCRT4_CreateConnection(RpcConnection** Connection, BOOL server,
3040 LPCSTR Protseq, LPCSTR NetworkAddr, LPCSTR Endpoint,
3041 LPCWSTR NetworkOptions, RpcAuthInfo* AuthInfo, RpcQualityOfService *QOS, LPCWSTR CookieAuth)
3043 static LONG next_id;
3044 const struct connection_ops *ops;
3045 RpcConnection* NewConnection;
3047 ops = rpcrt4_get_conn_protseq_ops(Protseq);
3048 if (!ops)
3050 FIXME("not supported for protseq %s\n", Protseq);
3051 return RPC_S_PROTSEQ_NOT_SUPPORTED;
3054 NewConnection = ops->alloc();
3055 NewConnection->ref = 1;
3056 NewConnection->Next = NULL;
3057 NewConnection->server_binding = NULL;
3058 NewConnection->server = server;
3059 NewConnection->ops = ops;
3060 NewConnection->NetworkAddr = RPCRT4_strdupA(NetworkAddr);
3061 NewConnection->Endpoint = RPCRT4_strdupA(Endpoint);
3062 NewConnection->NetworkOptions = RPCRT4_strdupW(NetworkOptions);
3063 NewConnection->CookieAuth = RPCRT4_strdupW(CookieAuth);
3064 NewConnection->MaxTransmissionSize = RPC_MAX_PACKET_SIZE;
3065 memset(&NewConnection->ActiveInterface, 0, sizeof(NewConnection->ActiveInterface));
3066 NewConnection->NextCallId = 1;
3068 SecInvalidateHandle(&NewConnection->ctx);
3069 memset(&NewConnection->exp, 0, sizeof(NewConnection->exp));
3070 NewConnection->attr = 0;
3071 if (AuthInfo) RpcAuthInfo_AddRef(AuthInfo);
3072 NewConnection->AuthInfo = AuthInfo;
3073 NewConnection->auth_context_id = InterlockedIncrement( &next_id );
3074 NewConnection->encryption_auth_len = 0;
3075 NewConnection->signature_auth_len = 0;
3076 if (QOS) RpcQualityOfService_AddRef(QOS);
3077 NewConnection->QOS = QOS;
3079 list_init(&NewConnection->conn_pool_entry);
3080 NewConnection->async_state = NULL;
3082 TRACE("connection: %p\n", NewConnection);
3083 *Connection = NewConnection;
3085 return RPC_S_OK;
3088 static RPC_STATUS RPCRT4_SpawnConnection(RpcConnection** Connection, RpcConnection* OldConnection)
3090 RPC_STATUS err;
3092 err = RPCRT4_CreateConnection(Connection, OldConnection->server, rpcrt4_conn_get_name(OldConnection),
3093 OldConnection->NetworkAddr, OldConnection->Endpoint, NULL,
3094 OldConnection->AuthInfo, OldConnection->QOS, OldConnection->CookieAuth);
3095 if (err == RPC_S_OK)
3096 rpcrt4_conn_handoff(OldConnection, *Connection);
3097 return err;
3100 RpcConnection *RPCRT4_GrabConnection( RpcConnection *conn )
3102 InterlockedIncrement( &conn->ref );
3103 return conn;
3106 RPC_STATUS RPCRT4_ReleaseConnection(RpcConnection* Connection)
3108 if (InterlockedDecrement( &Connection->ref ) > 0) return RPC_S_OK;
3110 TRACE("destroying connection %p\n", Connection);
3112 RPCRT4_CloseConnection(Connection);
3113 RPCRT4_strfree(Connection->Endpoint);
3114 RPCRT4_strfree(Connection->NetworkAddr);
3115 HeapFree(GetProcessHeap(), 0, Connection->NetworkOptions);
3116 HeapFree(GetProcessHeap(), 0, Connection->CookieAuth);
3117 if (Connection->AuthInfo) RpcAuthInfo_Release(Connection->AuthInfo);
3118 if (Connection->QOS) RpcQualityOfService_Release(Connection->QOS);
3120 /* server-only */
3121 if (Connection->server_binding) RPCRT4_ReleaseBinding(Connection->server_binding);
3123 HeapFree(GetProcessHeap(), 0, Connection);
3124 return RPC_S_OK;
3127 RPC_STATUS RpcTransport_GetTopOfTower(unsigned char *tower_data,
3128 size_t *tower_size,
3129 const char *protseq,
3130 const char *networkaddr,
3131 const char *endpoint)
3133 twr_empty_floor_t *protocol_floor;
3134 const struct connection_ops *protseq_ops = rpcrt4_get_conn_protseq_ops(protseq);
3136 *tower_size = 0;
3138 if (!protseq_ops)
3139 return RPC_S_INVALID_RPC_PROTSEQ;
3141 if (!tower_data)
3143 *tower_size = sizeof(*protocol_floor);
3144 *tower_size += protseq_ops->get_top_of_tower(NULL, networkaddr, endpoint);
3145 return RPC_S_OK;
3148 protocol_floor = (twr_empty_floor_t *)tower_data;
3149 protocol_floor->count_lhs = sizeof(protocol_floor->protid);
3150 protocol_floor->protid = protseq_ops->epm_protocols[0];
3151 protocol_floor->count_rhs = 0;
3153 tower_data += sizeof(*protocol_floor);
3155 *tower_size = protseq_ops->get_top_of_tower(tower_data, networkaddr, endpoint);
3156 if (!*tower_size)
3157 return EPT_S_NOT_REGISTERED;
3159 *tower_size += sizeof(*protocol_floor);
3161 return RPC_S_OK;
3164 RPC_STATUS RpcTransport_ParseTopOfTower(const unsigned char *tower_data,
3165 size_t tower_size,
3166 char **protseq,
3167 char **networkaddr,
3168 char **endpoint)
3170 const twr_empty_floor_t *protocol_floor;
3171 const twr_empty_floor_t *floor4;
3172 const struct connection_ops *protseq_ops = NULL;
3173 RPC_STATUS status;
3174 unsigned int i;
3176 if (tower_size < sizeof(*protocol_floor))
3177 return EPT_S_NOT_REGISTERED;
3179 protocol_floor = (const twr_empty_floor_t *)tower_data;
3180 tower_data += sizeof(*protocol_floor);
3181 tower_size -= sizeof(*protocol_floor);
3182 if ((protocol_floor->count_lhs != sizeof(protocol_floor->protid)) ||
3183 (protocol_floor->count_rhs > tower_size))
3184 return EPT_S_NOT_REGISTERED;
3185 tower_data += protocol_floor->count_rhs;
3186 tower_size -= protocol_floor->count_rhs;
3188 floor4 = (const twr_empty_floor_t *)tower_data;
3189 if ((tower_size < sizeof(*floor4)) ||
3190 (floor4->count_lhs != sizeof(floor4->protid)))
3191 return EPT_S_NOT_REGISTERED;
3193 for(i = 0; i < ARRAYSIZE(conn_protseq_list); i++)
3194 if ((protocol_floor->protid == conn_protseq_list[i].epm_protocols[0]) &&
3195 (floor4->protid == conn_protseq_list[i].epm_protocols[1]))
3197 protseq_ops = &conn_protseq_list[i];
3198 break;
3201 if (!protseq_ops)
3202 return EPT_S_NOT_REGISTERED;
3204 status = protseq_ops->parse_top_of_tower(tower_data, tower_size, networkaddr, endpoint);
3206 if ((status == RPC_S_OK) && protseq)
3208 *protseq = I_RpcAllocate(strlen(protseq_ops->name) + 1);
3209 strcpy(*protseq, protseq_ops->name);
3212 return status;
3215 /***********************************************************************
3216 * RpcNetworkIsProtseqValidW (RPCRT4.@)
3218 * Checks if the given protocol sequence is known by the RPC system.
3219 * If it is, returns RPC_S_OK, otherwise RPC_S_PROTSEQ_NOT_SUPPORTED.
3222 RPC_STATUS WINAPI RpcNetworkIsProtseqValidW(RPC_WSTR protseq)
3224 char ps[0x10];
3226 WideCharToMultiByte(CP_ACP, 0, protseq, -1,
3227 ps, sizeof ps, NULL, NULL);
3228 if (rpcrt4_get_conn_protseq_ops(ps))
3229 return RPC_S_OK;
3231 FIXME("Unknown protseq %s\n", debugstr_w(protseq));
3233 return RPC_S_INVALID_RPC_PROTSEQ;
3236 /***********************************************************************
3237 * RpcNetworkIsProtseqValidA (RPCRT4.@)
3239 RPC_STATUS WINAPI RpcNetworkIsProtseqValidA(RPC_CSTR protseq)
3241 UNICODE_STRING protseqW;
3243 if (RtlCreateUnicodeStringFromAsciiz(&protseqW, (char*)protseq))
3245 RPC_STATUS ret = RpcNetworkIsProtseqValidW(protseqW.Buffer);
3246 RtlFreeUnicodeString(&protseqW);
3247 return ret;
3249 return RPC_S_OUT_OF_MEMORY;
3252 /***********************************************************************
3253 * RpcProtseqVectorFreeA (RPCRT4.@)
3255 RPC_STATUS WINAPI RpcProtseqVectorFreeA(RPC_PROTSEQ_VECTORA **protseqs)
3257 TRACE("(%p)\n", protseqs);
3259 if (*protseqs)
3261 unsigned int i;
3262 for (i = 0; i < (*protseqs)->Count; i++)
3263 HeapFree(GetProcessHeap(), 0, (*protseqs)->Protseq[i]);
3264 HeapFree(GetProcessHeap(), 0, *protseqs);
3265 *protseqs = NULL;
3267 return RPC_S_OK;
3270 /***********************************************************************
3271 * RpcProtseqVectorFreeW (RPCRT4.@)
3273 RPC_STATUS WINAPI RpcProtseqVectorFreeW(RPC_PROTSEQ_VECTORW **protseqs)
3275 TRACE("(%p)\n", protseqs);
3277 if (*protseqs)
3279 unsigned int i;
3280 for (i = 0; i < (*protseqs)->Count; i++)
3281 HeapFree(GetProcessHeap(), 0, (*protseqs)->Protseq[i]);
3282 HeapFree(GetProcessHeap(), 0, *protseqs);
3283 *protseqs = NULL;
3285 return RPC_S_OK;
3288 /***********************************************************************
3289 * RpcNetworkInqProtseqsW (RPCRT4.@)
3291 RPC_STATUS WINAPI RpcNetworkInqProtseqsW( RPC_PROTSEQ_VECTORW** protseqs )
3293 RPC_PROTSEQ_VECTORW *pvector;
3294 unsigned int i;
3295 RPC_STATUS status = RPC_S_OUT_OF_MEMORY;
3297 TRACE("(%p)\n", protseqs);
3299 *protseqs = HeapAlloc(GetProcessHeap(), 0, sizeof(RPC_PROTSEQ_VECTORW)+(sizeof(unsigned short*)*ARRAYSIZE(protseq_list)));
3300 if (!*protseqs)
3301 goto end;
3302 pvector = *protseqs;
3303 pvector->Count = 0;
3304 for (i = 0; i < ARRAYSIZE(protseq_list); i++)
3306 pvector->Protseq[i] = HeapAlloc(GetProcessHeap(), 0, (strlen(protseq_list[i].name)+1)*sizeof(unsigned short));
3307 if (pvector->Protseq[i] == NULL)
3308 goto end;
3309 MultiByteToWideChar(CP_ACP, 0, (CHAR*)protseq_list[i].name, -1,
3310 (WCHAR*)pvector->Protseq[i], strlen(protseq_list[i].name) + 1);
3311 pvector->Count++;
3313 status = RPC_S_OK;
3315 end:
3316 if (status != RPC_S_OK)
3317 RpcProtseqVectorFreeW(protseqs);
3318 return status;
3321 /***********************************************************************
3322 * RpcNetworkInqProtseqsA (RPCRT4.@)
3324 RPC_STATUS WINAPI RpcNetworkInqProtseqsA(RPC_PROTSEQ_VECTORA** protseqs)
3326 RPC_PROTSEQ_VECTORA *pvector;
3327 unsigned int i;
3328 RPC_STATUS status = RPC_S_OUT_OF_MEMORY;
3330 TRACE("(%p)\n", protseqs);
3332 *protseqs = HeapAlloc(GetProcessHeap(), 0, sizeof(RPC_PROTSEQ_VECTORW)+(sizeof(unsigned char*)*ARRAYSIZE(protseq_list)));
3333 if (!*protseqs)
3334 goto end;
3335 pvector = *protseqs;
3336 pvector->Count = 0;
3337 for (i = 0; i < ARRAYSIZE(protseq_list); i++)
3339 pvector->Protseq[i] = HeapAlloc(GetProcessHeap(), 0, strlen(protseq_list[i].name)+1);
3340 if (pvector->Protseq[i] == NULL)
3341 goto end;
3342 strcpy((char*)pvector->Protseq[i], protseq_list[i].name);
3343 pvector->Count++;
3345 status = RPC_S_OK;
3347 end:
3348 if (status != RPC_S_OK)
3349 RpcProtseqVectorFreeA(protseqs);
3350 return status;