Sync with trunk r62754.
[reactos.git] / dll / win32 / rpcrt4 / rpc_transport.c
1 /*
2 * RPC transport layer
3 *
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
9 *
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.
14 *
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.
19 *
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
23 *
24 */
25
26 #include "precomp.h"
27
28 #if defined(__MINGW32__) || defined (_MSC_VER)
29 # include <ws2tcpip.h>
30 # ifndef EADDRINUSE
31 # define EADDRINUSE WSAEADDRINUSE
32 # endif
33 # ifndef EAGAIN
34 # define EAGAIN WSAEWOULDBLOCK
35 # endif
36 # undef errno
37 # define errno WSAGetLastError()
38 #else
39 # include <errno.h>
40 # ifdef HAVE_UNISTD_H
41 # include <unistd.h>
42 # endif
43 # include <fcntl.h>
44 # ifdef HAVE_SYS_SOCKET_H
45 # include <sys/socket.h>
46 # endif
47 # ifdef HAVE_NETINET_IN_H
48 # include <netinet/in.h>
49 # endif
50 # ifdef HAVE_NETINET_TCP_H
51 # include <netinet/tcp.h>
52 # endif
53 # ifdef HAVE_ARPA_INET_H
54 # include <arpa/inet.h>
55 # endif
56 # ifdef HAVE_NETDB_H
57 # include <netdb.h>
58 # endif
59 # ifdef HAVE_SYS_POLL_H
60 # include <sys/poll.h>
61 # endif
62 # ifdef HAVE_SYS_FILIO_H
63 # include <sys/filio.h>
64 # endif
65 # ifdef HAVE_SYS_IOCTL_H
66 # include <sys/ioctl.h>
67 # endif
68 # define closesocket close
69 # define ioctlsocket ioctl
70 #endif /* defined(__MINGW32__) || defined (_MSC_VER) */
71
72 #include <wininet.h>
73
74 #include "epm_towers.h"
75
76 #ifndef SOL_TCP
77 # define SOL_TCP IPPROTO_TCP
78 #endif
79
80 #define DEFAULT_NCACN_HTTP_TIMEOUT (60 * 1000)
81
82 WINE_DEFAULT_DEBUG_CHANNEL(rpc);
83
84 static RPC_STATUS RPCRT4_SpawnConnection(RpcConnection** Connection, RpcConnection* OldConnection);
85
86 /**** ncacn_np support ****/
87
88 typedef struct _RpcConnection_np
89 {
90 RpcConnection common;
91 HANDLE pipe;
92 OVERLAPPED ovl;
93 BOOL listening;
94 } RpcConnection_np;
95
96 static RpcConnection *rpcrt4_conn_np_alloc(void)
97 {
98 RpcConnection_np *npc = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(RpcConnection_np));
99 if (npc)
100 {
101 npc->pipe = NULL;
102 memset(&npc->ovl, 0, sizeof(npc->ovl));
103 npc->listening = FALSE;
104 }
105 return &npc->common;
106 }
107
108 static RPC_STATUS rpcrt4_conn_listen_pipe(RpcConnection_np *npc)
109 {
110 if (npc->listening)
111 return RPC_S_OK;
112
113 npc->listening = TRUE;
114 for (;;)
115 {
116 if (ConnectNamedPipe(npc->pipe, &npc->ovl))
117 return RPC_S_OK;
118
119 switch(GetLastError())
120 {
121 case ERROR_PIPE_CONNECTED:
122 SetEvent(npc->ovl.hEvent);
123 return RPC_S_OK;
124 case ERROR_IO_PENDING:
125 /* will be completed in rpcrt4_protseq_np_wait_for_new_connection */
126 return RPC_S_OK;
127 case ERROR_NO_DATA_DETECTED:
128 /* client has disconnected, retry */
129 DisconnectNamedPipe( npc->pipe );
130 break;
131 default:
132 npc->listening = FALSE;
133 WARN("Couldn't ConnectNamedPipe (error was %d)\n", GetLastError());
134 return RPC_S_OUT_OF_RESOURCES;
135 }
136 }
137 }
138
139 static RPC_STATUS rpcrt4_conn_create_pipe(RpcConnection *Connection, LPCSTR pname)
140 {
141 RpcConnection_np *npc = (RpcConnection_np *) Connection;
142 TRACE("listening on %s\n", pname);
143
144 npc->pipe = CreateNamedPipeA(pname, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
145 PIPE_TYPE_MESSAGE | PIPE_READMODE_MESSAGE,
146 PIPE_UNLIMITED_INSTANCES,
147 RPC_MAX_PACKET_SIZE, RPC_MAX_PACKET_SIZE, 5000, NULL);
148 if (npc->pipe == INVALID_HANDLE_VALUE) {
149 WARN("CreateNamedPipe failed with error %d\n", GetLastError());
150 if (GetLastError() == ERROR_FILE_EXISTS)
151 return RPC_S_DUPLICATE_ENDPOINT;
152 else
153 return RPC_S_CANT_CREATE_ENDPOINT;
154 }
155
156 memset(&npc->ovl, 0, sizeof(npc->ovl));
157 npc->ovl.hEvent = CreateEventW(NULL, TRUE, FALSE, NULL);
158
159 /* Note: we don't call ConnectNamedPipe here because it must be done in the
160 * server thread as the thread must be alertable */
161 return RPC_S_OK;
162 }
163
164 static RPC_STATUS rpcrt4_conn_open_pipe(RpcConnection *Connection, LPCSTR pname, BOOL wait)
165 {
166 RpcConnection_np *npc = (RpcConnection_np *) Connection;
167 HANDLE pipe;
168 DWORD err, dwMode;
169
170 TRACE("connecting to %s\n", pname);
171
172 while (TRUE) {
173 DWORD dwFlags = 0;
174 if (Connection->QOS)
175 {
176 dwFlags = SECURITY_SQOS_PRESENT;
177 switch (Connection->QOS->qos->ImpersonationType)
178 {
179 case RPC_C_IMP_LEVEL_DEFAULT:
180 /* FIXME: what to do here? */
181 break;
182 case RPC_C_IMP_LEVEL_ANONYMOUS:
183 dwFlags |= SECURITY_ANONYMOUS;
184 break;
185 case RPC_C_IMP_LEVEL_IDENTIFY:
186 dwFlags |= SECURITY_IDENTIFICATION;
187 break;
188 case RPC_C_IMP_LEVEL_IMPERSONATE:
189 dwFlags |= SECURITY_IMPERSONATION;
190 break;
191 case RPC_C_IMP_LEVEL_DELEGATE:
192 dwFlags |= SECURITY_DELEGATION;
193 break;
194 }
195 if (Connection->QOS->qos->IdentityTracking == RPC_C_QOS_IDENTITY_DYNAMIC)
196 dwFlags |= SECURITY_CONTEXT_TRACKING;
197 }
198 pipe = CreateFileA(pname, GENERIC_READ|GENERIC_WRITE, 0, NULL,
199 OPEN_EXISTING, dwFlags, 0);
200 if (pipe != INVALID_HANDLE_VALUE) break;
201 err = GetLastError();
202 if (err == ERROR_PIPE_BUSY) {
203 TRACE("connection failed, error=%x\n", err);
204 return RPC_S_SERVER_TOO_BUSY;
205 } else if (err == ERROR_BAD_NETPATH) {
206 TRACE("connection failed, error=%x\n", err);
207 return RPC_S_SERVER_UNAVAILABLE;
208 }
209 if (!wait || !WaitNamedPipeA(pname, NMPWAIT_WAIT_FOREVER)) {
210 err = GetLastError();
211 WARN("connection failed, error=%x\n", err);
212 return RPC_S_SERVER_UNAVAILABLE;
213 }
214 }
215
216 /* success */
217 memset(&npc->ovl, 0, sizeof(npc->ovl));
218 /* pipe is connected; change to message-read mode. */
219 dwMode = PIPE_READMODE_MESSAGE;
220 SetNamedPipeHandleState(pipe, &dwMode, NULL, NULL);
221 npc->ovl.hEvent = CreateEventW(NULL, TRUE, FALSE, NULL);
222 npc->pipe = pipe;
223
224 return RPC_S_OK;
225 }
226
227 static RPC_STATUS rpcrt4_ncalrpc_open(RpcConnection* Connection)
228 {
229 RpcConnection_np *npc = (RpcConnection_np *) Connection;
230 static const char prefix[] = "\\\\.\\pipe\\lrpc\\";
231 RPC_STATUS r;
232 LPSTR pname;
233
234 /* already connected? */
235 if (npc->pipe)
236 return RPC_S_OK;
237
238 /* protseq=ncalrpc: supposed to use NT LPC ports,
239 * but we'll implement it with named pipes for now */
240 pname = I_RpcAllocate(strlen(prefix) + strlen(Connection->Endpoint) + 1);
241 strcat(strcpy(pname, prefix), Connection->Endpoint);
242 r = rpcrt4_conn_open_pipe(Connection, pname, TRUE);
243 I_RpcFree(pname);
244
245 return r;
246 }
247
248 static RPC_STATUS rpcrt4_protseq_ncalrpc_open_endpoint(RpcServerProtseq* protseq, const char *endpoint)
249 {
250 static const char prefix[] = "\\\\.\\pipe\\lrpc\\";
251 RPC_STATUS r;
252 LPSTR pname;
253 RpcConnection *Connection;
254 char generated_endpoint[22];
255
256 if (!endpoint)
257 {
258 static LONG lrpc_nameless_id;
259 DWORD process_id = GetCurrentProcessId();
260 ULONG id = InterlockedIncrement(&lrpc_nameless_id);
261 snprintf(generated_endpoint, sizeof(generated_endpoint),
262 "LRPC%08x.%08x", process_id, id);
263 endpoint = generated_endpoint;
264 }
265
266 r = RPCRT4_CreateConnection(&Connection, TRUE, protseq->Protseq, NULL,
267 endpoint, NULL, NULL, NULL, NULL);
268 if (r != RPC_S_OK)
269 return r;
270
271 /* protseq=ncalrpc: supposed to use NT LPC ports,
272 * but we'll implement it with named pipes for now */
273 pname = I_RpcAllocate(strlen(prefix) + strlen(Connection->Endpoint) + 1);
274 strcat(strcpy(pname, prefix), Connection->Endpoint);
275 r = rpcrt4_conn_create_pipe(Connection, pname);
276 I_RpcFree(pname);
277
278 EnterCriticalSection(&protseq->cs);
279 Connection->Next = protseq->conn;
280 protseq->conn = Connection;
281 LeaveCriticalSection(&protseq->cs);
282
283 return r;
284 }
285
286 static RPC_STATUS rpcrt4_ncacn_np_open(RpcConnection* Connection)
287 {
288 RpcConnection_np *npc = (RpcConnection_np *) Connection;
289 static const char prefix[] = "\\\\";
290 static const char local[] =".";
291 RPC_STATUS r;
292 LPSTR pname;
293 INT size;
294
295 /* already connected? */
296 if (npc->pipe)
297 return RPC_S_OK;
298
299 /* protseq=ncacn_np: named pipes */
300 size = strlen(prefix);
301 if (Connection->NetworkAddr == NULL || strlen(Connection->NetworkAddr) == 0)
302 size += strlen(local);
303 else
304 size += strlen(Connection->NetworkAddr);
305 size += strlen(Connection->Endpoint) + 1;
306
307 pname = I_RpcAllocate(size);
308 strcpy(pname, prefix);
309 if (Connection->NetworkAddr == NULL || strlen(Connection->NetworkAddr) == 0)
310 strcat(pname, local);
311 else
312 strcat(pname, Connection->NetworkAddr);
313 strcat(pname, Connection->Endpoint);
314 r = rpcrt4_conn_open_pipe(Connection, pname, TRUE);
315 I_RpcFree(pname);
316
317 return r;
318 }
319
320 static RPC_STATUS rpcrt4_protseq_ncacn_np_open_endpoint(RpcServerProtseq *protseq, const char *endpoint)
321 {
322 static const char prefix[] = "\\\\.";
323 RPC_STATUS r;
324 LPSTR pname;
325 RpcConnection *Connection;
326 char generated_endpoint[21];
327
328 if (!endpoint)
329 {
330 static LONG np_nameless_id;
331 DWORD process_id = GetCurrentProcessId();
332 ULONG id = InterlockedExchangeAdd(&np_nameless_id, 1 );
333 snprintf(generated_endpoint, sizeof(generated_endpoint),
334 "\\\\pipe\\\\%08x.%03x", process_id, id);
335 endpoint = generated_endpoint;
336 }
337
338 r = RPCRT4_CreateConnection(&Connection, TRUE, protseq->Protseq, NULL,
339 endpoint, NULL, NULL, NULL, NULL);
340 if (r != RPC_S_OK)
341 return r;
342
343 /* protseq=ncacn_np: named pipes */
344 pname = I_RpcAllocate(strlen(prefix) + strlen(Connection->Endpoint) + 1);
345 strcat(strcpy(pname, prefix), Connection->Endpoint);
346 r = rpcrt4_conn_create_pipe(Connection, pname);
347 I_RpcFree(pname);
348
349 EnterCriticalSection(&protseq->cs);
350 Connection->Next = protseq->conn;
351 protseq->conn = Connection;
352 LeaveCriticalSection(&protseq->cs);
353
354 return r;
355 }
356
357 static void rpcrt4_conn_np_handoff(RpcConnection_np *old_npc, RpcConnection_np *new_npc)
358 {
359 /* because of the way named pipes work, we'll transfer the connected pipe
360 * to the child, then reopen the server binding to continue listening */
361
362 new_npc->pipe = old_npc->pipe;
363 new_npc->ovl = old_npc->ovl;
364 old_npc->pipe = 0;
365 memset(&old_npc->ovl, 0, sizeof(old_npc->ovl));
366 old_npc->listening = FALSE;
367 }
368
369 static RPC_STATUS rpcrt4_ncacn_np_handoff(RpcConnection *old_conn, RpcConnection *new_conn)
370 {
371 RPC_STATUS status;
372 LPSTR pname;
373 static const char prefix[] = "\\\\.";
374
375 rpcrt4_conn_np_handoff((RpcConnection_np *)old_conn, (RpcConnection_np *)new_conn);
376
377 pname = I_RpcAllocate(strlen(prefix) + strlen(old_conn->Endpoint) + 1);
378 strcat(strcpy(pname, prefix), old_conn->Endpoint);
379 status = rpcrt4_conn_create_pipe(old_conn, pname);
380 I_RpcFree(pname);
381
382 return status;
383 }
384
385 static RPC_STATUS rpcrt4_ncalrpc_handoff(RpcConnection *old_conn, RpcConnection *new_conn)
386 {
387 RPC_STATUS status;
388 LPSTR pname;
389 static const char prefix[] = "\\\\.\\pipe\\lrpc\\";
390
391 TRACE("%s\n", old_conn->Endpoint);
392
393 rpcrt4_conn_np_handoff((RpcConnection_np *)old_conn, (RpcConnection_np *)new_conn);
394
395 pname = I_RpcAllocate(strlen(prefix) + strlen(old_conn->Endpoint) + 1);
396 strcat(strcpy(pname, prefix), old_conn->Endpoint);
397 status = rpcrt4_conn_create_pipe(old_conn, pname);
398 I_RpcFree(pname);
399
400 return status;
401 }
402
403 static int rpcrt4_conn_np_read(RpcConnection *Connection,
404 void *buffer, unsigned int count)
405 {
406 RpcConnection_np *npc = (RpcConnection_np *) Connection;
407 char *buf = buffer;
408 BOOL ret = TRUE;
409 unsigned int bytes_left = count;
410 OVERLAPPED ovl;
411
412 ZeroMemory(&ovl, sizeof(ovl));
413 ovl.hEvent = CreateEventW(NULL, TRUE, FALSE, NULL);
414
415 while (bytes_left)
416 {
417 DWORD bytes_read;
418 ret = ReadFile(npc->pipe, buf, bytes_left, &bytes_read, &ovl);
419 if (!ret && GetLastError() == ERROR_IO_PENDING)
420 ret = GetOverlappedResult(npc->pipe, &ovl, &bytes_read, TRUE);
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;
427 }
428 CloseHandle(ovl.hEvent);
429 return ret ? count : -1;
430 }
431
432 static int rpcrt4_conn_np_write(RpcConnection *Connection,
433 const void *buffer, unsigned int count)
434 {
435 RpcConnection_np *npc = (RpcConnection_np *) Connection;
436 const char *buf = buffer;
437 BOOL ret = TRUE;
438 unsigned int bytes_left = count;
439 OVERLAPPED ovl;
440
441 ZeroMemory(&ovl, sizeof(ovl));
442 ovl.hEvent = CreateEventW(NULL, TRUE, FALSE, NULL);
443
444 while (bytes_left)
445 {
446 DWORD bytes_written;
447 ret = WriteFile(npc->pipe, buf, bytes_left, &bytes_written, &ovl);
448 if (!ret && GetLastError() == ERROR_IO_PENDING)
449 ret = GetOverlappedResult(npc->pipe, &ovl, &bytes_written, TRUE);
450 if (!ret || !bytes_written)
451 break;
452 bytes_left -= bytes_written;
453 buf += bytes_written;
454 }
455 CloseHandle(ovl.hEvent);
456 return ret ? count : -1;
457 }
458
459 static int rpcrt4_conn_np_close(RpcConnection *Connection)
460 {
461 RpcConnection_np *npc = (RpcConnection_np *) Connection;
462 if (npc->pipe) {
463 FlushFileBuffers(npc->pipe);
464 CloseHandle(npc->pipe);
465 npc->pipe = 0;
466 }
467 if (npc->ovl.hEvent) {
468 CloseHandle(npc->ovl.hEvent);
469 npc->ovl.hEvent = 0;
470 }
471 return 0;
472 }
473
474 static void rpcrt4_conn_np_cancel_call(RpcConnection *Connection)
475 {
476 /* FIXME: implement when named pipe writes use overlapped I/O */
477 }
478
479 static int rpcrt4_conn_np_wait_for_incoming_data(RpcConnection *Connection)
480 {
481 /* FIXME: implement when named pipe writes use overlapped I/O */
482 return -1;
483 }
484
485 static size_t rpcrt4_ncacn_np_get_top_of_tower(unsigned char *tower_data,
486 const char *networkaddr,
487 const char *endpoint)
488 {
489 twr_empty_floor_t *smb_floor;
490 twr_empty_floor_t *nb_floor;
491 size_t size;
492 size_t networkaddr_size;
493 size_t endpoint_size;
494
495 TRACE("(%p, %s, %s)\n", tower_data, networkaddr, endpoint);
496
497 networkaddr_size = networkaddr ? strlen(networkaddr) + 1 : 1;
498 endpoint_size = endpoint ? strlen(endpoint) + 1 : 1;
499 size = sizeof(*smb_floor) + endpoint_size + sizeof(*nb_floor) + networkaddr_size;
500
501 if (!tower_data)
502 return size;
503
504 smb_floor = (twr_empty_floor_t *)tower_data;
505
506 tower_data += sizeof(*smb_floor);
507
508 smb_floor->count_lhs = sizeof(smb_floor->protid);
509 smb_floor->protid = EPM_PROTOCOL_SMB;
510 smb_floor->count_rhs = endpoint_size;
511
512 if (endpoint)
513 memcpy(tower_data, endpoint, endpoint_size);
514 else
515 tower_data[0] = 0;
516 tower_data += endpoint_size;
517
518 nb_floor = (twr_empty_floor_t *)tower_data;
519
520 tower_data += sizeof(*nb_floor);
521
522 nb_floor->count_lhs = sizeof(nb_floor->protid);
523 nb_floor->protid = EPM_PROTOCOL_NETBIOS;
524 nb_floor->count_rhs = networkaddr_size;
525
526 if (networkaddr)
527 memcpy(tower_data, networkaddr, networkaddr_size);
528 else
529 tower_data[0] = 0;
530
531 return size;
532 }
533
534 static RPC_STATUS rpcrt4_ncacn_np_parse_top_of_tower(const unsigned char *tower_data,
535 size_t tower_size,
536 char **networkaddr,
537 char **endpoint)
538 {
539 const twr_empty_floor_t *smb_floor = (const twr_empty_floor_t *)tower_data;
540 const twr_empty_floor_t *nb_floor;
541
542 TRACE("(%p, %d, %p, %p)\n", tower_data, (int)tower_size, networkaddr, endpoint);
543
544 if (tower_size < sizeof(*smb_floor))
545 return EPT_S_NOT_REGISTERED;
546
547 tower_data += sizeof(*smb_floor);
548 tower_size -= sizeof(*smb_floor);
549
550 if ((smb_floor->count_lhs != sizeof(smb_floor->protid)) ||
551 (smb_floor->protid != EPM_PROTOCOL_SMB) ||
552 (smb_floor->count_rhs > tower_size) ||
553 (tower_data[smb_floor->count_rhs - 1] != '\0'))
554 return EPT_S_NOT_REGISTERED;
555
556 if (endpoint)
557 {
558 *endpoint = I_RpcAllocate(smb_floor->count_rhs);
559 if (!*endpoint)
560 return RPC_S_OUT_OF_RESOURCES;
561 memcpy(*endpoint, tower_data, smb_floor->count_rhs);
562 }
563 tower_data += smb_floor->count_rhs;
564 tower_size -= smb_floor->count_rhs;
565
566 if (tower_size < sizeof(*nb_floor))
567 return EPT_S_NOT_REGISTERED;
568
569 nb_floor = (const twr_empty_floor_t *)tower_data;
570
571 tower_data += sizeof(*nb_floor);
572 tower_size -= sizeof(*nb_floor);
573
574 if ((nb_floor->count_lhs != sizeof(nb_floor->protid)) ||
575 (nb_floor->protid != EPM_PROTOCOL_NETBIOS) ||
576 (nb_floor->count_rhs > tower_size) ||
577 (tower_data[nb_floor->count_rhs - 1] != '\0'))
578 return EPT_S_NOT_REGISTERED;
579
580 if (networkaddr)
581 {
582 *networkaddr = I_RpcAllocate(nb_floor->count_rhs);
583 if (!*networkaddr)
584 {
585 if (endpoint)
586 {
587 I_RpcFree(*endpoint);
588 *endpoint = NULL;
589 }
590 return RPC_S_OUT_OF_RESOURCES;
591 }
592 memcpy(*networkaddr, tower_data, nb_floor->count_rhs);
593 }
594
595 return RPC_S_OK;
596 }
597
598 static RPC_STATUS rpcrt4_conn_np_impersonate_client(RpcConnection *conn)
599 {
600 RpcConnection_np *npc = (RpcConnection_np *)conn;
601 BOOL ret;
602
603 TRACE("(%p)\n", conn);
604
605 if (conn->AuthInfo && SecIsValidHandle(&conn->ctx))
606 return RPCRT4_default_impersonate_client(conn);
607
608 ret = ImpersonateNamedPipeClient(npc->pipe);
609 if (!ret)
610 {
611 DWORD error = GetLastError();
612 WARN("ImpersonateNamedPipeClient failed with error %u\n", error);
613 switch (error)
614 {
615 case ERROR_CANNOT_IMPERSONATE:
616 return RPC_S_NO_CONTEXT_AVAILABLE;
617 }
618 }
619 return RPC_S_OK;
620 }
621
622 static RPC_STATUS rpcrt4_conn_np_revert_to_self(RpcConnection *conn)
623 {
624 BOOL ret;
625
626 TRACE("(%p)\n", conn);
627
628 if (conn->AuthInfo && SecIsValidHandle(&conn->ctx))
629 return RPCRT4_default_revert_to_self(conn);
630
631 ret = RevertToSelf();
632 if (!ret)
633 {
634 WARN("RevertToSelf failed with error %u\n", GetLastError());
635 return RPC_S_NO_CONTEXT_AVAILABLE;
636 }
637 return RPC_S_OK;
638 }
639
640 typedef struct _RpcServerProtseq_np
641 {
642 RpcServerProtseq common;
643 HANDLE mgr_event;
644 } RpcServerProtseq_np;
645
646 static RpcServerProtseq *rpcrt4_protseq_np_alloc(void)
647 {
648 RpcServerProtseq_np *ps = HeapAlloc(GetProcessHeap(), 0, sizeof(*ps));
649 if (ps)
650 ps->mgr_event = CreateEventW(NULL, FALSE, FALSE, NULL);
651 return &ps->common;
652 }
653
654 static void rpcrt4_protseq_np_signal_state_changed(RpcServerProtseq *protseq)
655 {
656 RpcServerProtseq_np *npps = CONTAINING_RECORD(protseq, RpcServerProtseq_np, common);
657 SetEvent(npps->mgr_event);
658 }
659
660 static void *rpcrt4_protseq_np_get_wait_array(RpcServerProtseq *protseq, void *prev_array, unsigned int *count)
661 {
662 HANDLE *objs = prev_array;
663 RpcConnection_np *conn;
664 RpcServerProtseq_np *npps = CONTAINING_RECORD(protseq, RpcServerProtseq_np, common);
665
666 EnterCriticalSection(&protseq->cs);
667
668 /* open and count connections */
669 *count = 1;
670 conn = CONTAINING_RECORD(protseq->conn, RpcConnection_np, common);
671 while (conn) {
672 rpcrt4_conn_listen_pipe(conn);
673 if (conn->ovl.hEvent)
674 (*count)++;
675 conn = CONTAINING_RECORD(conn->common.Next, RpcConnection_np, common);
676 }
677
678 /* make array of connections */
679 if (objs)
680 objs = HeapReAlloc(GetProcessHeap(), 0, objs, *count*sizeof(HANDLE));
681 else
682 objs = HeapAlloc(GetProcessHeap(), 0, *count*sizeof(HANDLE));
683 if (!objs)
684 {
685 ERR("couldn't allocate objs\n");
686 LeaveCriticalSection(&protseq->cs);
687 return NULL;
688 }
689
690 objs[0] = npps->mgr_event;
691 *count = 1;
692 conn = CONTAINING_RECORD(protseq->conn, RpcConnection_np, common);
693 while (conn) {
694 if ((objs[*count] = conn->ovl.hEvent))
695 (*count)++;
696 conn = CONTAINING_RECORD(conn->common.Next, RpcConnection_np, common);
697 }
698 LeaveCriticalSection(&protseq->cs);
699 return objs;
700 }
701
702 static void rpcrt4_protseq_np_free_wait_array(RpcServerProtseq *protseq, void *array)
703 {
704 HeapFree(GetProcessHeap(), 0, array);
705 }
706
707 static int rpcrt4_protseq_np_wait_for_new_connection(RpcServerProtseq *protseq, unsigned int count, void *wait_array)
708 {
709 HANDLE b_handle;
710 HANDLE *objs = wait_array;
711 DWORD res;
712 RpcConnection *cconn;
713 RpcConnection_np *conn;
714
715 if (!objs)
716 return -1;
717
718 do
719 {
720 /* an alertable wait isn't strictly necessary, but due to our
721 * overlapped I/O implementation in Wine we need to free some memory
722 * by the file user APC being called, even if no completion routine was
723 * specified at the time of starting the async operation */
724 res = WaitForMultipleObjectsEx(count, objs, FALSE, INFINITE, TRUE);
725 } while (res == WAIT_IO_COMPLETION);
726
727 if (res == WAIT_OBJECT_0)
728 return 0;
729 else if (res == WAIT_FAILED)
730 {
731 ERR("wait failed with error %d\n", GetLastError());
732 return -1;
733 }
734 else
735 {
736 b_handle = objs[res - WAIT_OBJECT_0];
737 /* find which connection got a RPC */
738 EnterCriticalSection(&protseq->cs);
739 conn = CONTAINING_RECORD(protseq->conn, RpcConnection_np, common);
740 while (conn) {
741 if (b_handle == conn->ovl.hEvent) break;
742 conn = CONTAINING_RECORD(conn->common.Next, RpcConnection_np, common);
743 }
744 cconn = NULL;
745 if (conn)
746 RPCRT4_SpawnConnection(&cconn, &conn->common);
747 else
748 ERR("failed to locate connection for handle %p\n", b_handle);
749 LeaveCriticalSection(&protseq->cs);
750 if (cconn)
751 {
752 RPCRT4_new_client(cconn);
753 return 1;
754 }
755 else return -1;
756 }
757 }
758
759 static size_t rpcrt4_ncalrpc_get_top_of_tower(unsigned char *tower_data,
760 const char *networkaddr,
761 const char *endpoint)
762 {
763 twr_empty_floor_t *pipe_floor;
764 size_t size;
765 size_t endpoint_size;
766
767 TRACE("(%p, %s, %s)\n", tower_data, networkaddr, endpoint);
768
769 endpoint_size = strlen(endpoint) + 1;
770 size = sizeof(*pipe_floor) + endpoint_size;
771
772 if (!tower_data)
773 return size;
774
775 pipe_floor = (twr_empty_floor_t *)tower_data;
776
777 tower_data += sizeof(*pipe_floor);
778
779 pipe_floor->count_lhs = sizeof(pipe_floor->protid);
780 pipe_floor->protid = EPM_PROTOCOL_PIPE;
781 pipe_floor->count_rhs = endpoint_size;
782
783 memcpy(tower_data, endpoint, endpoint_size);
784
785 return size;
786 }
787
788 static RPC_STATUS rpcrt4_ncalrpc_parse_top_of_tower(const unsigned char *tower_data,
789 size_t tower_size,
790 char **networkaddr,
791 char **endpoint)
792 {
793 const twr_empty_floor_t *pipe_floor = (const twr_empty_floor_t *)tower_data;
794
795 TRACE("(%p, %d, %p, %p)\n", tower_data, (int)tower_size, networkaddr, endpoint);
796
797 if (tower_size < sizeof(*pipe_floor))
798 return EPT_S_NOT_REGISTERED;
799
800 tower_data += sizeof(*pipe_floor);
801 tower_size -= sizeof(*pipe_floor);
802
803 if ((pipe_floor->count_lhs != sizeof(pipe_floor->protid)) ||
804 (pipe_floor->protid != EPM_PROTOCOL_PIPE) ||
805 (pipe_floor->count_rhs > tower_size) ||
806 (tower_data[pipe_floor->count_rhs - 1] != '\0'))
807 return EPT_S_NOT_REGISTERED;
808
809 if (networkaddr)
810 *networkaddr = NULL;
811
812 if (endpoint)
813 {
814 *endpoint = I_RpcAllocate(pipe_floor->count_rhs);
815 if (!*endpoint)
816 return RPC_S_OUT_OF_RESOURCES;
817 memcpy(*endpoint, tower_data, pipe_floor->count_rhs);
818 }
819
820 return RPC_S_OK;
821 }
822
823 static BOOL rpcrt4_ncalrpc_is_authorized(RpcConnection *conn)
824 {
825 return FALSE;
826 }
827
828 static RPC_STATUS rpcrt4_ncalrpc_authorize(RpcConnection *conn, BOOL first_time,
829 unsigned char *in_buffer,
830 unsigned int in_size,
831 unsigned char *out_buffer,
832 unsigned int *out_size)
833 {
834 /* since this protocol is local to the machine there is no need to
835 * authenticate the caller */
836 *out_size = 0;
837 return RPC_S_OK;
838 }
839
840 static RPC_STATUS rpcrt4_ncalrpc_secure_packet(RpcConnection *conn,
841 enum secure_packet_direction dir,
842 RpcPktHdr *hdr, unsigned int hdr_size,
843 unsigned char *stub_data, unsigned int stub_data_size,
844 RpcAuthVerifier *auth_hdr,
845 unsigned char *auth_value, unsigned int auth_value_size)
846 {
847 /* since this protocol is local to the machine there is no need to secure
848 * the packet */
849 return RPC_S_OK;
850 }
851
852 static RPC_STATUS rpcrt4_ncalrpc_inquire_auth_client(
853 RpcConnection *conn, RPC_AUTHZ_HANDLE *privs, RPC_WSTR *server_princ_name,
854 ULONG *authn_level, ULONG *authn_svc, ULONG *authz_svc, ULONG flags)
855 {
856 TRACE("(%p, %p, %p, %p, %p, %p, 0x%x)\n", conn, privs,
857 server_princ_name, authn_level, authn_svc, authz_svc, flags);
858
859 if (privs)
860 {
861 FIXME("privs not implemented\n");
862 *privs = NULL;
863 }
864 if (server_princ_name)
865 {
866 FIXME("server_princ_name not implemented\n");
867 *server_princ_name = NULL;
868 }
869 if (authn_level) *authn_level = RPC_C_AUTHN_LEVEL_PKT_PRIVACY;
870 if (authn_svc) *authn_svc = RPC_C_AUTHN_WINNT;
871 if (authz_svc)
872 {
873 FIXME("authorization service not implemented\n");
874 *authz_svc = RPC_C_AUTHZ_NONE;
875 }
876 if (flags)
877 FIXME("flags 0x%x not implemented\n", flags);
878
879 return RPC_S_OK;
880 }
881
882 /**** ncacn_ip_tcp support ****/
883
884 static size_t rpcrt4_ip_tcp_get_top_of_tower(unsigned char *tower_data,
885 const char *networkaddr,
886 unsigned char tcp_protid,
887 const char *endpoint)
888 {
889 twr_tcp_floor_t *tcp_floor;
890 twr_ipv4_floor_t *ipv4_floor;
891 struct addrinfo *ai;
892 struct addrinfo hints;
893 int ret;
894 size_t size = sizeof(*tcp_floor) + sizeof(*ipv4_floor);
895
896 TRACE("(%p, %s, %s)\n", tower_data, networkaddr, endpoint);
897
898 if (!tower_data)
899 return size;
900
901 tcp_floor = (twr_tcp_floor_t *)tower_data;
902 tower_data += sizeof(*tcp_floor);
903
904 ipv4_floor = (twr_ipv4_floor_t *)tower_data;
905
906 tcp_floor->count_lhs = sizeof(tcp_floor->protid);
907 tcp_floor->protid = tcp_protid;
908 tcp_floor->count_rhs = sizeof(tcp_floor->port);
909
910 ipv4_floor->count_lhs = sizeof(ipv4_floor->protid);
911 ipv4_floor->protid = EPM_PROTOCOL_IP;
912 ipv4_floor->count_rhs = sizeof(ipv4_floor->ipv4addr);
913
914 hints.ai_flags = AI_NUMERICHOST;
915 /* FIXME: only support IPv4 at the moment. how is IPv6 represented by the EPM? */
916 hints.ai_family = PF_INET;
917 hints.ai_socktype = SOCK_STREAM;
918 hints.ai_protocol = IPPROTO_TCP;
919 hints.ai_addrlen = 0;
920 hints.ai_addr = NULL;
921 hints.ai_canonname = NULL;
922 hints.ai_next = NULL;
923
924 ret = getaddrinfo(networkaddr, endpoint, &hints, &ai);
925 if (ret)
926 {
927 ret = getaddrinfo("0.0.0.0", endpoint, &hints, &ai);
928 if (ret)
929 {
930 ERR("getaddrinfo failed: %s\n", gai_strerror(ret));
931 return 0;
932 }
933 }
934
935 if (ai->ai_family == PF_INET)
936 {
937 const struct sockaddr_in *sin = (const struct sockaddr_in *)ai->ai_addr;
938 tcp_floor->port = sin->sin_port;
939 ipv4_floor->ipv4addr = sin->sin_addr.s_addr;
940 }
941 else
942 {
943 ERR("unexpected protocol family %d\n", ai->ai_family);
944 return 0;
945 }
946
947 freeaddrinfo(ai);
948
949 return size;
950 }
951
952 static RPC_STATUS rpcrt4_ip_tcp_parse_top_of_tower(const unsigned char *tower_data,
953 size_t tower_size,
954 char **networkaddr,
955 unsigned char tcp_protid,
956 char **endpoint)
957 {
958 const twr_tcp_floor_t *tcp_floor = (const twr_tcp_floor_t *)tower_data;
959 const twr_ipv4_floor_t *ipv4_floor;
960 struct in_addr in_addr;
961
962 TRACE("(%p, %d, %p, %p)\n", tower_data, (int)tower_size, networkaddr, endpoint);
963
964 if (tower_size < sizeof(*tcp_floor))
965 return EPT_S_NOT_REGISTERED;
966
967 tower_data += sizeof(*tcp_floor);
968 tower_size -= sizeof(*tcp_floor);
969
970 if (tower_size < sizeof(*ipv4_floor))
971 return EPT_S_NOT_REGISTERED;
972
973 ipv4_floor = (const twr_ipv4_floor_t *)tower_data;
974
975 if ((tcp_floor->count_lhs != sizeof(tcp_floor->protid)) ||
976 (tcp_floor->protid != tcp_protid) ||
977 (tcp_floor->count_rhs != sizeof(tcp_floor->port)) ||
978 (ipv4_floor->count_lhs != sizeof(ipv4_floor->protid)) ||
979 (ipv4_floor->protid != EPM_PROTOCOL_IP) ||
980 (ipv4_floor->count_rhs != sizeof(ipv4_floor->ipv4addr)))
981 return EPT_S_NOT_REGISTERED;
982
983 if (endpoint)
984 {
985 *endpoint = I_RpcAllocate(6 /* sizeof("65535") + 1 */);
986 if (!*endpoint)
987 return RPC_S_OUT_OF_RESOURCES;
988 sprintf(*endpoint, "%u", ntohs(tcp_floor->port));
989 }
990
991 if (networkaddr)
992 {
993 *networkaddr = I_RpcAllocate(INET_ADDRSTRLEN);
994 if (!*networkaddr)
995 {
996 if (endpoint)
997 {
998 I_RpcFree(*endpoint);
999 *endpoint = NULL;
1000 }
1001 return RPC_S_OUT_OF_RESOURCES;
1002 }
1003 in_addr.s_addr = ipv4_floor->ipv4addr;
1004 if (!inet_ntop(AF_INET, &in_addr, *networkaddr, INET_ADDRSTRLEN))
1005 {
1006 ERR("inet_ntop: %s\n", strerror(errno));
1007 I_RpcFree(*networkaddr);
1008 *networkaddr = NULL;
1009 if (endpoint)
1010 {
1011 I_RpcFree(*endpoint);
1012 *endpoint = NULL;
1013 }
1014 return EPT_S_NOT_REGISTERED;
1015 }
1016 }
1017
1018 return RPC_S_OK;
1019 }
1020
1021 typedef struct _RpcConnection_tcp
1022 {
1023 RpcConnection common;
1024 int sock;
1025 #ifdef HAVE_SOCKETPAIR
1026 int cancel_fds[2];
1027 #else
1028 HANDLE sock_event;
1029 HANDLE cancel_event;
1030 #endif
1031 } RpcConnection_tcp;
1032
1033 #ifdef HAVE_SOCKETPAIR
1034
1035 static BOOL rpcrt4_sock_wait_init(RpcConnection_tcp *tcpc)
1036 {
1037 if (socketpair(PF_UNIX, SOCK_STREAM, 0, tcpc->cancel_fds) < 0)
1038 {
1039 ERR("socketpair() failed: %s\n", strerror(errno));
1040 return FALSE;
1041 }
1042 return TRUE;
1043 }
1044
1045 static BOOL rpcrt4_sock_wait_for_recv(RpcConnection_tcp *tcpc)
1046 {
1047 struct pollfd pfds[2];
1048 pfds[0].fd = tcpc->sock;
1049 pfds[0].events = POLLIN;
1050 pfds[1].fd = tcpc->cancel_fds[0];
1051 pfds[1].events = POLLIN;
1052 if (poll(pfds, 2, -1 /* infinite */) == -1 && errno != EINTR)
1053 {
1054 ERR("poll() failed: %s\n", strerror(errno));
1055 return FALSE;
1056 }
1057 if (pfds[1].revents & POLLIN) /* canceled */
1058 {
1059 char dummy;
1060 read(pfds[1].fd, &dummy, sizeof(dummy));
1061 return FALSE;
1062 }
1063 return TRUE;
1064 }
1065
1066 static BOOL rpcrt4_sock_wait_for_send(RpcConnection_tcp *tcpc)
1067 {
1068 struct pollfd pfd;
1069 pfd.fd = tcpc->sock;
1070 pfd.events = POLLOUT;
1071 if (poll(&pfd, 1, -1 /* infinite */) == -1 && errno != EINTR)
1072 {
1073 ERR("poll() failed: %s\n", strerror(errno));
1074 return FALSE;
1075 }
1076 return TRUE;
1077 }
1078
1079 static void rpcrt4_sock_wait_cancel(RpcConnection_tcp *tcpc)
1080 {
1081 char dummy = 1;
1082
1083 write(tcpc->cancel_fds[1], &dummy, 1);
1084 }
1085
1086 static void rpcrt4_sock_wait_destroy(RpcConnection_tcp *tcpc)
1087 {
1088 close(tcpc->cancel_fds[0]);
1089 close(tcpc->cancel_fds[1]);
1090 }
1091
1092 #else /* HAVE_SOCKETPAIR */
1093
1094 static BOOL rpcrt4_sock_wait_init(RpcConnection_tcp *tcpc)
1095 {
1096 static BOOL wsa_inited;
1097 if (!wsa_inited)
1098 {
1099 WSADATA wsadata;
1100 WSAStartup(MAKEWORD(2, 2), &wsadata);
1101 /* Note: WSAStartup can be called more than once so we don't bother with
1102 * making accesses to wsa_inited thread-safe */
1103 wsa_inited = TRUE;
1104 }
1105 tcpc->sock_event = CreateEventW(NULL, FALSE, FALSE, NULL);
1106 tcpc->cancel_event = CreateEventW(NULL, FALSE, FALSE, NULL);
1107 if (!tcpc->sock_event || !tcpc->cancel_event)
1108 {
1109 ERR("event creation failed\n");
1110 if (tcpc->sock_event) CloseHandle(tcpc->sock_event);
1111 return FALSE;
1112 }
1113 return TRUE;
1114 }
1115
1116 static BOOL rpcrt4_sock_wait_for_recv(RpcConnection_tcp *tcpc)
1117 {
1118 HANDLE wait_handles[2];
1119 DWORD res;
1120 if (WSAEventSelect(tcpc->sock, tcpc->sock_event, FD_READ | FD_CLOSE) == SOCKET_ERROR)
1121 {
1122 ERR("WSAEventSelect() failed with error %d\n", WSAGetLastError());
1123 return FALSE;
1124 }
1125 wait_handles[0] = tcpc->sock_event;
1126 wait_handles[1] = tcpc->cancel_event;
1127 res = WaitForMultipleObjects(2, wait_handles, FALSE, INFINITE);
1128 switch (res)
1129 {
1130 case WAIT_OBJECT_0:
1131 return TRUE;
1132 case WAIT_OBJECT_0 + 1:
1133 return FALSE;
1134 default:
1135 ERR("WaitForMultipleObjects() failed with error %d\n", GetLastError());
1136 return FALSE;
1137 }
1138 }
1139
1140 static BOOL rpcrt4_sock_wait_for_send(RpcConnection_tcp *tcpc)
1141 {
1142 DWORD res;
1143 if (WSAEventSelect(tcpc->sock, tcpc->sock_event, FD_WRITE | FD_CLOSE) == SOCKET_ERROR)
1144 {
1145 ERR("WSAEventSelect() failed with error %d\n", WSAGetLastError());
1146 return FALSE;
1147 }
1148 res = WaitForSingleObject(tcpc->sock_event, INFINITE);
1149 switch (res)
1150 {
1151 case WAIT_OBJECT_0:
1152 return TRUE;
1153 default:
1154 ERR("WaitForMultipleObjects() failed with error %d\n", GetLastError());
1155 return FALSE;
1156 }
1157 }
1158
1159 static void rpcrt4_sock_wait_cancel(RpcConnection_tcp *tcpc)
1160 {
1161 SetEvent(tcpc->cancel_event);
1162 }
1163
1164 static void rpcrt4_sock_wait_destroy(RpcConnection_tcp *tcpc)
1165 {
1166 CloseHandle(tcpc->sock_event);
1167 CloseHandle(tcpc->cancel_event);
1168 }
1169
1170 #endif
1171
1172 static RpcConnection *rpcrt4_conn_tcp_alloc(void)
1173 {
1174 RpcConnection_tcp *tcpc;
1175 tcpc = HeapAlloc(GetProcessHeap(), 0, sizeof(RpcConnection_tcp));
1176 if (tcpc == NULL)
1177 return NULL;
1178 tcpc->sock = -1;
1179 if (!rpcrt4_sock_wait_init(tcpc))
1180 {
1181 HeapFree(GetProcessHeap(), 0, tcpc);
1182 return NULL;
1183 }
1184 return &tcpc->common;
1185 }
1186
1187 static RPC_STATUS rpcrt4_ncacn_ip_tcp_open(RpcConnection* Connection)
1188 {
1189 RpcConnection_tcp *tcpc = (RpcConnection_tcp *) Connection;
1190 int sock;
1191 int ret;
1192 struct addrinfo *ai;
1193 struct addrinfo *ai_cur;
1194 struct addrinfo hints;
1195
1196 TRACE("(%s, %s)\n", Connection->NetworkAddr, Connection->Endpoint);
1197
1198 if (tcpc->sock != -1)
1199 return RPC_S_OK;
1200
1201 hints.ai_flags = 0;
1202 hints.ai_family = PF_UNSPEC;
1203 hints.ai_socktype = SOCK_STREAM;
1204 hints.ai_protocol = IPPROTO_TCP;
1205 hints.ai_addrlen = 0;
1206 hints.ai_addr = NULL;
1207 hints.ai_canonname = NULL;
1208 hints.ai_next = NULL;
1209
1210 ret = getaddrinfo(Connection->NetworkAddr, Connection->Endpoint, &hints, &ai);
1211 if (ret)
1212 {
1213 ERR("getaddrinfo for %s:%s failed: %s\n", Connection->NetworkAddr,
1214 Connection->Endpoint, gai_strerror(ret));
1215 return RPC_S_SERVER_UNAVAILABLE;
1216 }
1217
1218 for (ai_cur = ai; ai_cur; ai_cur = ai_cur->ai_next)
1219 {
1220 int val;
1221 u_long nonblocking;
1222
1223 if (ai_cur->ai_family != AF_INET && ai_cur->ai_family != AF_INET6)
1224 {
1225 TRACE("skipping non-IP/IPv6 address family\n");
1226 continue;
1227 }
1228
1229 if (TRACE_ON(rpc))
1230 {
1231 char host[256];
1232 char service[256];
1233 getnameinfo(ai_cur->ai_addr, ai_cur->ai_addrlen,
1234 host, sizeof(host), service, sizeof(service),
1235 NI_NUMERICHOST | NI_NUMERICSERV);
1236 TRACE("trying %s:%s\n", host, service);
1237 }
1238
1239 sock = socket(ai_cur->ai_family, ai_cur->ai_socktype, ai_cur->ai_protocol);
1240 if (sock == -1)
1241 {
1242 WARN("socket() failed: %s\n", strerror(errno));
1243 continue;
1244 }
1245
1246 if (0>connect(sock, ai_cur->ai_addr, ai_cur->ai_addrlen))
1247 {
1248 WARN("connect() failed: %s\n", strerror(errno));
1249 closesocket(sock);
1250 continue;
1251 }
1252
1253 /* RPC depends on having minimal latency so disable the Nagle algorithm */
1254 val = 1;
1255 setsockopt(sock, SOL_TCP, TCP_NODELAY, (char *)&val, sizeof(val));
1256 nonblocking = 1;
1257 ioctlsocket(sock, FIONBIO, &nonblocking);
1258
1259 tcpc->sock = sock;
1260
1261 freeaddrinfo(ai);
1262 TRACE("connected\n");
1263 return RPC_S_OK;
1264 }
1265
1266 freeaddrinfo(ai);
1267 ERR("couldn't connect to %s:%s\n", Connection->NetworkAddr, Connection->Endpoint);
1268 return RPC_S_SERVER_UNAVAILABLE;
1269 }
1270
1271 static RPC_STATUS rpcrt4_protseq_ncacn_ip_tcp_open_endpoint(RpcServerProtseq *protseq, const char *endpoint)
1272 {
1273 RPC_STATUS status = RPC_S_CANT_CREATE_ENDPOINT;
1274 int sock;
1275 int ret;
1276 struct addrinfo *ai;
1277 struct addrinfo *ai_cur;
1278 struct addrinfo hints;
1279 RpcConnection *first_connection = NULL;
1280
1281 TRACE("(%p, %s)\n", protseq, endpoint);
1282
1283 hints.ai_flags = AI_PASSIVE /* for non-localhost addresses */;
1284 hints.ai_family = PF_UNSPEC;
1285 hints.ai_socktype = SOCK_STREAM;
1286 hints.ai_protocol = IPPROTO_TCP;
1287 hints.ai_addrlen = 0;
1288 hints.ai_addr = NULL;
1289 hints.ai_canonname = NULL;
1290 hints.ai_next = NULL;
1291
1292 ret = getaddrinfo(NULL, endpoint ? endpoint : "0", &hints, &ai);
1293 if (ret)
1294 {
1295 ERR("getaddrinfo for port %s failed: %s\n", endpoint,
1296 gai_strerror(ret));
1297 if ((ret == EAI_SERVICE) || (ret == EAI_NONAME))
1298 return RPC_S_INVALID_ENDPOINT_FORMAT;
1299 return RPC_S_CANT_CREATE_ENDPOINT;
1300 }
1301
1302 for (ai_cur = ai; ai_cur; ai_cur = ai_cur->ai_next)
1303 {
1304 RpcConnection_tcp *tcpc;
1305 RPC_STATUS create_status;
1306 struct sockaddr_storage sa;
1307 socklen_t sa_len;
1308 char service[NI_MAXSERV];
1309 u_long nonblocking;
1310
1311 if (ai_cur->ai_family != AF_INET && ai_cur->ai_family != AF_INET6)
1312 {
1313 TRACE("skipping non-IP/IPv6 address family\n");
1314 continue;
1315 }
1316
1317 if (TRACE_ON(rpc))
1318 {
1319 char host[256];
1320 getnameinfo(ai_cur->ai_addr, ai_cur->ai_addrlen,
1321 host, sizeof(host), service, sizeof(service),
1322 NI_NUMERICHOST | NI_NUMERICSERV);
1323 TRACE("trying %s:%s\n", host, service);
1324 }
1325
1326 sock = socket(ai_cur->ai_family, ai_cur->ai_socktype, ai_cur->ai_protocol);
1327 if (sock == -1)
1328 {
1329 WARN("socket() failed: %s\n", strerror(errno));
1330 status = RPC_S_CANT_CREATE_ENDPOINT;
1331 continue;
1332 }
1333
1334 ret = bind(sock, ai_cur->ai_addr, ai_cur->ai_addrlen);
1335 if (ret < 0)
1336 {
1337 WARN("bind failed: %s\n", strerror(errno));
1338 closesocket(sock);
1339 if (errno == EADDRINUSE)
1340 status = RPC_S_DUPLICATE_ENDPOINT;
1341 else
1342 status = RPC_S_CANT_CREATE_ENDPOINT;
1343 continue;
1344 }
1345
1346 sa_len = sizeof(sa);
1347 if (getsockname(sock, (struct sockaddr *)&sa, &sa_len))
1348 {
1349 WARN("getsockname() failed: %s\n", strerror(errno));
1350 closesocket(sock);
1351 status = RPC_S_CANT_CREATE_ENDPOINT;
1352 continue;
1353 }
1354
1355 ret = getnameinfo((struct sockaddr *)&sa, sa_len,
1356 NULL, 0, service, sizeof(service),
1357 NI_NUMERICSERV);
1358 if (ret)
1359 {
1360 WARN("getnameinfo failed: %s\n", gai_strerror(ret));
1361 closesocket(sock);
1362 status = RPC_S_CANT_CREATE_ENDPOINT;
1363 continue;
1364 }
1365
1366 create_status = RPCRT4_CreateConnection((RpcConnection **)&tcpc, TRUE,
1367 protseq->Protseq, NULL,
1368 service, NULL, NULL, NULL, NULL);
1369 if (create_status != RPC_S_OK)
1370 {
1371 closesocket(sock);
1372 status = create_status;
1373 continue;
1374 }
1375
1376 tcpc->sock = sock;
1377 ret = listen(sock, protseq->MaxCalls);
1378 if (ret < 0)
1379 {
1380 WARN("listen failed: %s\n", strerror(errno));
1381 RPCRT4_ReleaseConnection(&tcpc->common);
1382 status = RPC_S_OUT_OF_RESOURCES;
1383 continue;
1384 }
1385 /* need a non-blocking socket, otherwise accept() has a potential
1386 * race-condition (poll() says it is readable, connection drops,
1387 * and accept() blocks until the next connection comes...)
1388 */
1389 nonblocking = 1;
1390 ret = ioctlsocket(sock, FIONBIO, &nonblocking);
1391 if (ret < 0)
1392 {
1393 WARN("couldn't make socket non-blocking, error %d\n", ret);
1394 RPCRT4_ReleaseConnection(&tcpc->common);
1395 status = RPC_S_OUT_OF_RESOURCES;
1396 continue;
1397 }
1398
1399 tcpc->common.Next = first_connection;
1400 first_connection = &tcpc->common;
1401
1402 /* since IPv4 and IPv6 share the same port space, we only need one
1403 * successful bind to listen for both */
1404 break;
1405 }
1406
1407 freeaddrinfo(ai);
1408
1409 /* if at least one connection was created for an endpoint then
1410 * return success */
1411 if (first_connection)
1412 {
1413 RpcConnection *conn;
1414
1415 /* find last element in list */
1416 for (conn = first_connection; conn->Next; conn = conn->Next)
1417 ;
1418
1419 EnterCriticalSection(&protseq->cs);
1420 conn->Next = protseq->conn;
1421 protseq->conn = first_connection;
1422 LeaveCriticalSection(&protseq->cs);
1423
1424 TRACE("listening on %s\n", endpoint);
1425 return RPC_S_OK;
1426 }
1427
1428 ERR("couldn't listen on port %s\n", endpoint);
1429 return status;
1430 }
1431
1432 static RPC_STATUS rpcrt4_conn_tcp_handoff(RpcConnection *old_conn, RpcConnection *new_conn)
1433 {
1434 int ret;
1435 struct sockaddr_in address;
1436 socklen_t addrsize;
1437 RpcConnection_tcp *server = (RpcConnection_tcp*) old_conn;
1438 RpcConnection_tcp *client = (RpcConnection_tcp*) new_conn;
1439 u_long nonblocking;
1440
1441 addrsize = sizeof(address);
1442 ret = accept(server->sock, (struct sockaddr*) &address, &addrsize);
1443 if (ret < 0)
1444 {
1445 ERR("Failed to accept a TCP connection: error %d\n", ret);
1446 return RPC_S_OUT_OF_RESOURCES;
1447 }
1448 nonblocking = 1;
1449 ioctlsocket(ret, FIONBIO, &nonblocking);
1450 client->sock = ret;
1451 TRACE("Accepted a new TCP connection\n");
1452 return RPC_S_OK;
1453 }
1454
1455 static int rpcrt4_conn_tcp_read(RpcConnection *Connection,
1456 void *buffer, unsigned int count)
1457 {
1458 RpcConnection_tcp *tcpc = (RpcConnection_tcp *) Connection;
1459 int bytes_read = 0;
1460 while (bytes_read != count)
1461 {
1462 int r = recv(tcpc->sock, (char *)buffer + bytes_read, count - bytes_read, 0);
1463 if (!r)
1464 return -1;
1465 else if (r > 0)
1466 bytes_read += r;
1467 else if (errno != EAGAIN)
1468 {
1469 WARN("recv() failed: %s\n", strerror(errno));
1470 return -1;
1471 }
1472 else
1473 {
1474 if (!rpcrt4_sock_wait_for_recv(tcpc))
1475 return -1;
1476 }
1477 }
1478 TRACE("%d %p %u -> %d\n", tcpc->sock, buffer, count, bytes_read);
1479 return bytes_read;
1480 }
1481
1482 static int rpcrt4_conn_tcp_write(RpcConnection *Connection,
1483 const void *buffer, unsigned int count)
1484 {
1485 RpcConnection_tcp *tcpc = (RpcConnection_tcp *) Connection;
1486 int bytes_written = 0;
1487 while (bytes_written != count)
1488 {
1489 int r = send(tcpc->sock, (const char *)buffer + bytes_written, count - bytes_written, 0);
1490 if (r >= 0)
1491 bytes_written += r;
1492 else if (errno != EAGAIN)
1493 return -1;
1494 else
1495 {
1496 if (!rpcrt4_sock_wait_for_send(tcpc))
1497 return -1;
1498 }
1499 }
1500 TRACE("%d %p %u -> %d\n", tcpc->sock, buffer, count, bytes_written);
1501 return bytes_written;
1502 }
1503
1504 static int rpcrt4_conn_tcp_close(RpcConnection *Connection)
1505 {
1506 RpcConnection_tcp *tcpc = (RpcConnection_tcp *) Connection;
1507
1508 TRACE("%d\n", tcpc->sock);
1509
1510 if (tcpc->sock != -1)
1511 closesocket(tcpc->sock);
1512 tcpc->sock = -1;
1513 rpcrt4_sock_wait_destroy(tcpc);
1514 return 0;
1515 }
1516
1517 static void rpcrt4_conn_tcp_cancel_call(RpcConnection *Connection)
1518 {
1519 RpcConnection_tcp *tcpc = (RpcConnection_tcp *) Connection;
1520 TRACE("%p\n", Connection);
1521 rpcrt4_sock_wait_cancel(tcpc);
1522 }
1523
1524 static int rpcrt4_conn_tcp_wait_for_incoming_data(RpcConnection *Connection)
1525 {
1526 RpcConnection_tcp *tcpc = (RpcConnection_tcp *) Connection;
1527
1528 TRACE("%p\n", Connection);
1529
1530 if (!rpcrt4_sock_wait_for_recv(tcpc))
1531 return -1;
1532 return 0;
1533 }
1534
1535 static size_t rpcrt4_ncacn_ip_tcp_get_top_of_tower(unsigned char *tower_data,
1536 const char *networkaddr,
1537 const char *endpoint)
1538 {
1539 return rpcrt4_ip_tcp_get_top_of_tower(tower_data, networkaddr,
1540 EPM_PROTOCOL_TCP, endpoint);
1541 }
1542
1543 #ifdef HAVE_SOCKETPAIR
1544
1545 typedef struct _RpcServerProtseq_sock
1546 {
1547 RpcServerProtseq common;
1548 int mgr_event_rcv;
1549 int mgr_event_snd;
1550 } RpcServerProtseq_sock;
1551
1552 static RpcServerProtseq *rpcrt4_protseq_sock_alloc(void)
1553 {
1554 RpcServerProtseq_sock *ps = HeapAlloc(GetProcessHeap(), 0, sizeof(*ps));
1555 if (ps)
1556 {
1557 int fds[2];
1558 if (!socketpair(PF_UNIX, SOCK_DGRAM, 0, fds))
1559 {
1560 fcntl(fds[0], F_SETFL, O_NONBLOCK);
1561 fcntl(fds[1], F_SETFL, O_NONBLOCK);
1562 ps->mgr_event_rcv = fds[0];
1563 ps->mgr_event_snd = fds[1];
1564 }
1565 else
1566 {
1567 ERR("socketpair failed with error %s\n", strerror(errno));
1568 HeapFree(GetProcessHeap(), 0, ps);
1569 return NULL;
1570 }
1571 }
1572 return &ps->common;
1573 }
1574
1575 static void rpcrt4_protseq_sock_signal_state_changed(RpcServerProtseq *protseq)
1576 {
1577 RpcServerProtseq_sock *sockps = CONTAINING_RECORD(protseq, RpcServerProtseq_sock, common);
1578 char dummy = 1;
1579 write(sockps->mgr_event_snd, &dummy, sizeof(dummy));
1580 }
1581
1582 static void *rpcrt4_protseq_sock_get_wait_array(RpcServerProtseq *protseq, void *prev_array, unsigned int *count)
1583 {
1584 struct pollfd *poll_info = prev_array;
1585 RpcConnection_tcp *conn;
1586 RpcServerProtseq_sock *sockps = CONTAINING_RECORD(protseq, RpcServerProtseq_sock, common);
1587
1588 EnterCriticalSection(&protseq->cs);
1589
1590 /* open and count connections */
1591 *count = 1;
1592 conn = (RpcConnection_tcp *)protseq->conn;
1593 while (conn) {
1594 if (conn->sock != -1)
1595 (*count)++;
1596 conn = (RpcConnection_tcp *)conn->common.Next;
1597 }
1598
1599 /* make array of connections */
1600 if (poll_info)
1601 poll_info = HeapReAlloc(GetProcessHeap(), 0, poll_info, *count*sizeof(*poll_info));
1602 else
1603 poll_info = HeapAlloc(GetProcessHeap(), 0, *count*sizeof(*poll_info));
1604 if (!poll_info)
1605 {
1606 ERR("couldn't allocate poll_info\n");
1607 LeaveCriticalSection(&protseq->cs);
1608 return NULL;
1609 }
1610
1611 poll_info[0].fd = sockps->mgr_event_rcv;
1612 poll_info[0].events = POLLIN;
1613 *count = 1;
1614 conn = CONTAINING_RECORD(protseq->conn, RpcConnection_tcp, common);
1615 while (conn) {
1616 if (conn->sock != -1)
1617 {
1618 poll_info[*count].fd = conn->sock;
1619 poll_info[*count].events = POLLIN;
1620 (*count)++;
1621 }
1622 conn = CONTAINING_RECORD(conn->common.Next, RpcConnection_tcp, common);
1623 }
1624 LeaveCriticalSection(&protseq->cs);
1625 return poll_info;
1626 }
1627
1628 static void rpcrt4_protseq_sock_free_wait_array(RpcServerProtseq *protseq, void *array)
1629 {
1630 HeapFree(GetProcessHeap(), 0, array);
1631 }
1632
1633 static int rpcrt4_protseq_sock_wait_for_new_connection(RpcServerProtseq *protseq, unsigned int count, void *wait_array)
1634 {
1635 struct pollfd *poll_info = wait_array;
1636 int ret;
1637 unsigned int i;
1638 RpcConnection *cconn;
1639 RpcConnection_tcp *conn;
1640
1641 if (!poll_info)
1642 return -1;
1643
1644 ret = poll(poll_info, count, -1);
1645 if (ret < 0)
1646 {
1647 ERR("poll failed with error %d\n", ret);
1648 return -1;
1649 }
1650
1651 for (i = 0; i < count; i++)
1652 if (poll_info[i].revents & POLLIN)
1653 {
1654 /* RPC server event */
1655 if (i == 0)
1656 {
1657 char dummy;
1658 read(poll_info[0].fd, &dummy, sizeof(dummy));
1659 return 0;
1660 }
1661
1662 /* find which connection got a RPC */
1663 EnterCriticalSection(&protseq->cs);
1664 conn = CONTAINING_RECORD(protseq->conn, RpcConnection_tcp, common);
1665 while (conn) {
1666 if (poll_info[i].fd == conn->sock) break;
1667 conn = CONTAINING_RECORD(conn->common.Next, RpcConnection_tcp, common);
1668 }
1669 cconn = NULL;
1670 if (conn)
1671 RPCRT4_SpawnConnection(&cconn, &conn->common);
1672 else
1673 ERR("failed to locate connection for fd %d\n", poll_info[i].fd);
1674 LeaveCriticalSection(&protseq->cs);
1675 if (cconn)
1676 RPCRT4_new_client(cconn);
1677 else
1678 return -1;
1679 }
1680
1681 return 1;
1682 }
1683
1684 #else /* HAVE_SOCKETPAIR */
1685
1686 typedef struct _RpcServerProtseq_sock
1687 {
1688 RpcServerProtseq common;
1689 HANDLE mgr_event;
1690 } RpcServerProtseq_sock;
1691
1692 static RpcServerProtseq *rpcrt4_protseq_sock_alloc(void)
1693 {
1694 RpcServerProtseq_sock *ps = HeapAlloc(GetProcessHeap(), 0, sizeof(*ps));
1695 if (ps)
1696 {
1697 static BOOL wsa_inited;
1698 if (!wsa_inited)
1699 {
1700 WSADATA wsadata;
1701 WSAStartup(MAKEWORD(2, 2), &wsadata);
1702 /* Note: WSAStartup can be called more than once so we don't bother with
1703 * making accesses to wsa_inited thread-safe */
1704 wsa_inited = TRUE;
1705 }
1706 ps->mgr_event = CreateEventW(NULL, FALSE, FALSE, NULL);
1707 }
1708 return &ps->common;
1709 }
1710
1711 static void rpcrt4_protseq_sock_signal_state_changed(RpcServerProtseq *protseq)
1712 {
1713 RpcServerProtseq_sock *sockps = CONTAINING_RECORD(protseq, RpcServerProtseq_sock, common);
1714 SetEvent(sockps->mgr_event);
1715 }
1716
1717 static void *rpcrt4_protseq_sock_get_wait_array(RpcServerProtseq *protseq, void *prev_array, unsigned int *count)
1718 {
1719 HANDLE *objs = prev_array;
1720 RpcConnection_tcp *conn;
1721 RpcServerProtseq_sock *sockps = CONTAINING_RECORD(protseq, RpcServerProtseq_sock, common);
1722
1723 EnterCriticalSection(&protseq->cs);
1724
1725 /* open and count connections */
1726 *count = 1;
1727 conn = CONTAINING_RECORD(protseq->conn, RpcConnection_tcp, common);
1728 while (conn)
1729 {
1730 if (conn->sock != -1)
1731 (*count)++;
1732 conn = CONTAINING_RECORD(conn->common.Next, RpcConnection_tcp, common);
1733 }
1734
1735 /* make array of connections */
1736 if (objs)
1737 objs = HeapReAlloc(GetProcessHeap(), 0, objs, *count*sizeof(HANDLE));
1738 else
1739 objs = HeapAlloc(GetProcessHeap(), 0, *count*sizeof(HANDLE));
1740 if (!objs)
1741 {
1742 ERR("couldn't allocate objs\n");
1743 LeaveCriticalSection(&protseq->cs);
1744 return NULL;
1745 }
1746
1747 objs[0] = sockps->mgr_event;
1748 *count = 1;
1749 conn = CONTAINING_RECORD(protseq->conn, RpcConnection_tcp, common);
1750 while (conn)
1751 {
1752 if (conn->sock != -1)
1753 {
1754 int res = WSAEventSelect(conn->sock, conn->sock_event, FD_ACCEPT);
1755 if (res == SOCKET_ERROR)
1756 ERR("WSAEventSelect() failed with error %d\n", WSAGetLastError());
1757 else
1758 {
1759 objs[*count] = conn->sock_event;
1760 (*count)++;
1761 }
1762 }
1763 conn = CONTAINING_RECORD(conn->common.Next, RpcConnection_tcp, common);
1764 }
1765 LeaveCriticalSection(&protseq->cs);
1766 return objs;
1767 }
1768
1769 static void rpcrt4_protseq_sock_free_wait_array(RpcServerProtseq *protseq, void *array)
1770 {
1771 HeapFree(GetProcessHeap(), 0, array);
1772 }
1773
1774 static int rpcrt4_protseq_sock_wait_for_new_connection(RpcServerProtseq *protseq, unsigned int count, void *wait_array)
1775 {
1776 HANDLE b_handle;
1777 HANDLE *objs = wait_array;
1778 DWORD res;
1779 RpcConnection *cconn;
1780 RpcConnection_tcp *conn;
1781
1782 if (!objs)
1783 return -1;
1784
1785 do
1786 {
1787 /* an alertable wait isn't strictly necessary, but due to our
1788 * overlapped I/O implementation in Wine we need to free some memory
1789 * by the file user APC being called, even if no completion routine was
1790 * specified at the time of starting the async operation */
1791 res = WaitForMultipleObjectsEx(count, objs, FALSE, INFINITE, TRUE);
1792 } while (res == WAIT_IO_COMPLETION);
1793
1794 if (res == WAIT_OBJECT_0)
1795 return 0;
1796 else if (res == WAIT_FAILED)
1797 {
1798 ERR("wait failed with error %d\n", GetLastError());
1799 return -1;
1800 }
1801 else
1802 {
1803 b_handle = objs[res - WAIT_OBJECT_0];
1804 /* find which connection got a RPC */
1805 EnterCriticalSection(&protseq->cs);
1806 conn = CONTAINING_RECORD(protseq->conn, RpcConnection_tcp, common);
1807 while (conn)
1808 {
1809 if (b_handle == conn->sock_event) break;
1810 conn = CONTAINING_RECORD(conn->common.Next, RpcConnection_tcp, common);
1811 }
1812 cconn = NULL;
1813 if (conn)
1814 RPCRT4_SpawnConnection(&cconn, &conn->common);
1815 else
1816 ERR("failed to locate connection for handle %p\n", b_handle);
1817 LeaveCriticalSection(&protseq->cs);
1818 if (cconn)
1819 {
1820 RPCRT4_new_client(cconn);
1821 return 1;
1822 }
1823 else return -1;
1824 }
1825 }
1826
1827 #endif /* HAVE_SOCKETPAIR */
1828
1829 static RPC_STATUS rpcrt4_ncacn_ip_tcp_parse_top_of_tower(const unsigned char *tower_data,
1830 size_t tower_size,
1831 char **networkaddr,
1832 char **endpoint)
1833 {
1834 return rpcrt4_ip_tcp_parse_top_of_tower(tower_data, tower_size,
1835 networkaddr, EPM_PROTOCOL_TCP,
1836 endpoint);
1837 }
1838
1839 /**** ncacn_http support ****/
1840
1841 /* 60 seconds is the period native uses */
1842 #define HTTP_IDLE_TIME 60000
1843
1844 /* reference counted to avoid a race between a cancelled call's connection
1845 * being destroyed and the asynchronous InternetReadFileEx call being
1846 * completed */
1847 typedef struct _RpcHttpAsyncData
1848 {
1849 LONG refs;
1850 HANDLE completion_event;
1851 WORD async_result;
1852 INTERNET_BUFFERSA inet_buffers;
1853 CRITICAL_SECTION cs;
1854 } RpcHttpAsyncData;
1855
1856 static ULONG RpcHttpAsyncData_AddRef(RpcHttpAsyncData *data)
1857 {
1858 return InterlockedIncrement(&data->refs);
1859 }
1860
1861 static ULONG RpcHttpAsyncData_Release(RpcHttpAsyncData *data)
1862 {
1863 ULONG refs = InterlockedDecrement(&data->refs);
1864 if (!refs)
1865 {
1866 TRACE("destroying async data %p\n", data);
1867 CloseHandle(data->completion_event);
1868 HeapFree(GetProcessHeap(), 0, data->inet_buffers.lpvBuffer);
1869 data->cs.DebugInfo->Spare[0] = 0;
1870 DeleteCriticalSection(&data->cs);
1871 HeapFree(GetProcessHeap(), 0, data);
1872 }
1873 return refs;
1874 }
1875
1876 static void prepare_async_request(RpcHttpAsyncData *async_data)
1877 {
1878 ResetEvent(async_data->completion_event);
1879 RpcHttpAsyncData_AddRef(async_data);
1880 }
1881
1882 static RPC_STATUS wait_async_request(RpcHttpAsyncData *async_data, BOOL call_ret, HANDLE cancel_event)
1883 {
1884 HANDLE handles[2] = { async_data->completion_event, cancel_event };
1885 DWORD res;
1886
1887 if(call_ret) {
1888 RpcHttpAsyncData_Release(async_data);
1889 return RPC_S_OK;
1890 }
1891
1892 if(GetLastError() != ERROR_IO_PENDING) {
1893 RpcHttpAsyncData_Release(async_data);
1894 ERR("Request failed with error %d\n", GetLastError());
1895 return RPC_S_SERVER_UNAVAILABLE;
1896 }
1897
1898 res = WaitForMultipleObjects(2, handles, FALSE, DEFAULT_NCACN_HTTP_TIMEOUT);
1899 if(res != WAIT_OBJECT_0) {
1900 TRACE("Cancelled\n");
1901 return RPC_S_CALL_CANCELLED;
1902 }
1903
1904 if(async_data->async_result) {
1905 ERR("Async request failed with error %d\n", async_data->async_result);
1906 return RPC_S_SERVER_UNAVAILABLE;
1907 }
1908
1909 return RPC_S_OK;
1910 }
1911
1912 typedef struct _RpcConnection_http
1913 {
1914 RpcConnection common;
1915 HINTERNET app_info;
1916 HINTERNET session;
1917 HINTERNET in_request;
1918 HINTERNET out_request;
1919 HANDLE timer_cancelled;
1920 HANDLE cancel_event;
1921 DWORD last_sent_time;
1922 ULONG bytes_received;
1923 ULONG flow_control_mark; /* send a control packet to the server when this many bytes received */
1924 ULONG flow_control_increment; /* number of bytes to increment flow_control_mark by */
1925 UUID connection_uuid;
1926 UUID in_pipe_uuid;
1927 UUID out_pipe_uuid;
1928 RpcHttpAsyncData *async_data;
1929 } RpcConnection_http;
1930
1931 static RpcConnection *rpcrt4_ncacn_http_alloc(void)
1932 {
1933 RpcConnection_http *httpc;
1934 httpc = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*httpc));
1935 if (!httpc) return NULL;
1936 httpc->async_data = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(RpcHttpAsyncData));
1937 if (!httpc->async_data)
1938 {
1939 HeapFree(GetProcessHeap(), 0, httpc);
1940 return NULL;
1941 }
1942 TRACE("async data = %p\n", httpc->async_data);
1943 httpc->cancel_event = CreateEventW(NULL, FALSE, FALSE, NULL);
1944 httpc->async_data->refs = 1;
1945 httpc->async_data->inet_buffers.dwStructSize = sizeof(INTERNET_BUFFERSA);
1946 httpc->async_data->inet_buffers.lpvBuffer = NULL;
1947 InitializeCriticalSection(&httpc->async_data->cs);
1948 httpc->async_data->cs.DebugInfo->Spare[0] = (DWORD_PTR)(__FILE__ ": RpcHttpAsyncData.cs");
1949 return &httpc->common;
1950 }
1951
1952 typedef struct _HttpTimerThreadData
1953 {
1954 PVOID timer_param;
1955 DWORD *last_sent_time;
1956 HANDLE timer_cancelled;
1957 } HttpTimerThreadData;
1958
1959 static VOID rpcrt4_http_keep_connection_active_timer_proc(PVOID param, BOOLEAN dummy)
1960 {
1961 HINTERNET in_request = param;
1962 RpcPktHdr *idle_pkt;
1963
1964 idle_pkt = RPCRT4_BuildHttpHeader(NDR_LOCAL_DATA_REPRESENTATION, 0x0001,
1965 0, 0);
1966 if (idle_pkt)
1967 {
1968 DWORD bytes_written;
1969 InternetWriteFile(in_request, idle_pkt, idle_pkt->common.frag_len, &bytes_written);
1970 RPCRT4_FreeHeader(idle_pkt);
1971 }
1972 }
1973
1974 static inline DWORD rpcrt4_http_timer_calc_timeout(DWORD *last_sent_time)
1975 {
1976 DWORD cur_time = GetTickCount();
1977 DWORD cached_last_sent_time = *last_sent_time;
1978 return HTTP_IDLE_TIME - (cur_time - cached_last_sent_time > HTTP_IDLE_TIME ? 0 : cur_time - cached_last_sent_time);
1979 }
1980
1981 static DWORD CALLBACK rpcrt4_http_timer_thread(PVOID param)
1982 {
1983 HttpTimerThreadData *data_in = param;
1984 HttpTimerThreadData data;
1985 DWORD timeout;
1986
1987 data = *data_in;
1988 HeapFree(GetProcessHeap(), 0, data_in);
1989
1990 for (timeout = HTTP_IDLE_TIME;
1991 WaitForSingleObject(data.timer_cancelled, timeout) == WAIT_TIMEOUT;
1992 timeout = rpcrt4_http_timer_calc_timeout(data.last_sent_time))
1993 {
1994 /* are we too soon after last send? */
1995 if (GetTickCount() - *data.last_sent_time < HTTP_IDLE_TIME)
1996 continue;
1997 rpcrt4_http_keep_connection_active_timer_proc(data.timer_param, TRUE);
1998 }
1999
2000 CloseHandle(data.timer_cancelled);
2001 return 0;
2002 }
2003
2004 static VOID WINAPI rpcrt4_http_internet_callback(
2005 HINTERNET hInternet,
2006 DWORD_PTR dwContext,
2007 DWORD dwInternetStatus,
2008 LPVOID lpvStatusInformation,
2009 DWORD dwStatusInformationLength)
2010 {
2011 RpcHttpAsyncData *async_data = (RpcHttpAsyncData *)dwContext;
2012
2013 switch (dwInternetStatus)
2014 {
2015 case INTERNET_STATUS_REQUEST_COMPLETE:
2016 TRACE("INTERNET_STATUS_REQUEST_COMPLETED\n");
2017 if (async_data)
2018 {
2019 INTERNET_ASYNC_RESULT *async_result = lpvStatusInformation;
2020
2021 async_data->async_result = async_result->dwResult ? ERROR_SUCCESS : async_result->dwError;
2022 SetEvent(async_data->completion_event);
2023 RpcHttpAsyncData_Release(async_data);
2024 }
2025 break;
2026 }
2027 }
2028
2029 static RPC_STATUS rpcrt4_http_check_response(HINTERNET hor)
2030 {
2031 BOOL ret;
2032 DWORD status_code;
2033 DWORD size;
2034 DWORD index;
2035 WCHAR buf[32];
2036 WCHAR *status_text = buf;
2037 TRACE("\n");
2038
2039 index = 0;
2040 size = sizeof(status_code);
2041 ret = HttpQueryInfoW(hor, HTTP_QUERY_STATUS_CODE|HTTP_QUERY_FLAG_NUMBER, &status_code, &size, &index);
2042 if (!ret)
2043 return GetLastError();
2044 if (status_code == HTTP_STATUS_OK)
2045 return RPC_S_OK;
2046 index = 0;
2047 size = sizeof(buf);
2048 ret = HttpQueryInfoW(hor, HTTP_QUERY_STATUS_TEXT, status_text, &size, &index);
2049 if (!ret && GetLastError() == ERROR_INSUFFICIENT_BUFFER)
2050 {
2051 status_text = HeapAlloc(GetProcessHeap(), 0, size);
2052 ret = HttpQueryInfoW(hor, HTTP_QUERY_STATUS_TEXT, status_text, &size, &index);
2053 }
2054
2055 ERR("server returned: %d %s\n", status_code, ret ? debugstr_w(status_text) : "<status text unavailable>");
2056 if(status_text != buf) HeapFree(GetProcessHeap(), 0, status_text);
2057
2058 if (status_code == HTTP_STATUS_DENIED)
2059 return ERROR_ACCESS_DENIED;
2060 return RPC_S_SERVER_UNAVAILABLE;
2061 }
2062
2063 static RPC_STATUS rpcrt4_http_internet_connect(RpcConnection_http *httpc)
2064 {
2065 static const WCHAR wszUserAgent[] = {'M','S','R','P','C',0};
2066 LPWSTR proxy = NULL;
2067 LPWSTR user = NULL;
2068 LPWSTR password = NULL;
2069 LPWSTR servername = NULL;
2070 const WCHAR *option;
2071 INTERNET_PORT port;
2072
2073 if (httpc->common.QOS &&
2074 (httpc->common.QOS->qos->AdditionalSecurityInfoType == RPC_C_AUTHN_INFO_TYPE_HTTP))
2075 {
2076 const RPC_HTTP_TRANSPORT_CREDENTIALS_W *http_cred = httpc->common.QOS->qos->u.HttpCredentials;
2077 if (http_cred->TransportCredentials)
2078 {
2079 WCHAR *p;
2080 const SEC_WINNT_AUTH_IDENTITY_W *cred = http_cred->TransportCredentials;
2081 ULONG len = cred->DomainLength + 1 + cred->UserLength;
2082 user = HeapAlloc(GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR));
2083 if (!user)
2084 return RPC_S_OUT_OF_RESOURCES;
2085 p = user;
2086 if (cred->DomainLength)
2087 {
2088 memcpy(p, cred->Domain, cred->DomainLength * sizeof(WCHAR));
2089 p += cred->DomainLength;
2090 *p = '\\';
2091 p++;
2092 }
2093 memcpy(p, cred->User, cred->UserLength * sizeof(WCHAR));
2094 p[cred->UserLength] = 0;
2095
2096 password = RPCRT4_strndupW(cred->Password, cred->PasswordLength);
2097 }
2098 }
2099
2100 for (option = httpc->common.NetworkOptions; option;
2101 option = (strchrW(option, ',') ? strchrW(option, ',')+1 : NULL))
2102 {
2103 static const WCHAR wszRpcProxy[] = {'R','p','c','P','r','o','x','y','=',0};
2104 static const WCHAR wszHttpProxy[] = {'H','t','t','p','P','r','o','x','y','=',0};
2105
2106 if (!strncmpiW(option, wszRpcProxy, sizeof(wszRpcProxy)/sizeof(wszRpcProxy[0])-1))
2107 {
2108 const WCHAR *value_start = option + sizeof(wszRpcProxy)/sizeof(wszRpcProxy[0])-1;
2109 const WCHAR *value_end;
2110 const WCHAR *p;
2111
2112 value_end = strchrW(option, ',');
2113 if (!value_end)
2114 value_end = value_start + strlenW(value_start);
2115 for (p = value_start; p < value_end; p++)
2116 if (*p == ':')
2117 {
2118 port = atoiW(p+1);
2119 value_end = p;
2120 break;
2121 }
2122 TRACE("RpcProxy value is %s\n", debugstr_wn(value_start, value_end-value_start));
2123 servername = RPCRT4_strndupW(value_start, value_end-value_start);
2124 }
2125 else if (!strncmpiW(option, wszHttpProxy, sizeof(wszHttpProxy)/sizeof(wszHttpProxy[0])-1))
2126 {
2127 const WCHAR *value_start = option + sizeof(wszHttpProxy)/sizeof(wszHttpProxy[0])-1;
2128 const WCHAR *value_end;
2129
2130 value_end = strchrW(option, ',');
2131 if (!value_end)
2132 value_end = value_start + strlenW(value_start);
2133 TRACE("HttpProxy value is %s\n", debugstr_wn(value_start, value_end-value_start));
2134 proxy = RPCRT4_strndupW(value_start, value_end-value_start);
2135 }
2136 else
2137 FIXME("unhandled option %s\n", debugstr_w(option));
2138 }
2139
2140 httpc->app_info = InternetOpenW(wszUserAgent, proxy ? INTERNET_OPEN_TYPE_PROXY : INTERNET_OPEN_TYPE_PRECONFIG,
2141 NULL, NULL, INTERNET_FLAG_ASYNC);
2142 if (!httpc->app_info)
2143 {
2144 HeapFree(GetProcessHeap(), 0, password);
2145 HeapFree(GetProcessHeap(), 0, user);
2146 HeapFree(GetProcessHeap(), 0, proxy);
2147 HeapFree(GetProcessHeap(), 0, servername);
2148 ERR("InternetOpenW failed with error %d\n", GetLastError());
2149 return RPC_S_SERVER_UNAVAILABLE;
2150 }
2151 InternetSetStatusCallbackW(httpc->app_info, rpcrt4_http_internet_callback);
2152
2153 /* if no RpcProxy option specified, set the HTTP server address to the
2154 * RPC server address */
2155 if (!servername)
2156 {
2157 servername = HeapAlloc(GetProcessHeap(), 0, (strlen(httpc->common.NetworkAddr) + 1)*sizeof(WCHAR));
2158 if (!servername)
2159 {
2160 HeapFree(GetProcessHeap(), 0, password);
2161 HeapFree(GetProcessHeap(), 0, user);
2162 HeapFree(GetProcessHeap(), 0, proxy);
2163 return RPC_S_OUT_OF_RESOURCES;
2164 }
2165 MultiByteToWideChar(CP_ACP, 0, httpc->common.NetworkAddr, -1, servername, strlen(httpc->common.NetworkAddr) + 1);
2166 }
2167
2168 port = (httpc->common.QOS &&
2169 (httpc->common.QOS->qos->AdditionalSecurityInfoType == RPC_C_AUTHN_INFO_TYPE_HTTP) &&
2170 (httpc->common.QOS->qos->u.HttpCredentials->Flags & RPC_C_HTTP_FLAG_USE_SSL)) ?
2171 INTERNET_DEFAULT_HTTPS_PORT : INTERNET_DEFAULT_HTTP_PORT;
2172
2173 httpc->session = InternetConnectW(httpc->app_info, servername, port, user, password,
2174 INTERNET_SERVICE_HTTP, 0, 0);
2175
2176 HeapFree(GetProcessHeap(), 0, password);
2177 HeapFree(GetProcessHeap(), 0, user);
2178 HeapFree(GetProcessHeap(), 0, proxy);
2179 HeapFree(GetProcessHeap(), 0, servername);
2180
2181 if (!httpc->session)
2182 {
2183 ERR("InternetConnectW failed with error %d\n", GetLastError());
2184 return RPC_S_SERVER_UNAVAILABLE;
2185 }
2186
2187 return RPC_S_OK;
2188 }
2189
2190 static RPC_STATUS send_echo_request(HINTERNET req, RpcHttpAsyncData *async_data, HANDLE cancel_event)
2191 {
2192 DWORD bytes_read;
2193 BYTE buf[20];
2194 BOOL ret;
2195 RPC_STATUS status;
2196
2197 prepare_async_request(async_data);
2198 ret = HttpSendRequestW(req, NULL, 0, NULL, 0);
2199 status = wait_async_request(async_data, ret, cancel_event);
2200 if (status != RPC_S_OK) return status;
2201
2202 status = rpcrt4_http_check_response(req);
2203 if (status != RPC_S_OK) return status;
2204
2205 InternetReadFile(req, buf, sizeof(buf), &bytes_read);
2206 /* FIXME: do something with retrieved data */
2207
2208 return RPC_S_OK;
2209 }
2210
2211 /* prepare the in pipe for use by RPC packets */
2212 static RPC_STATUS rpcrt4_http_prepare_in_pipe(HINTERNET in_request, RpcHttpAsyncData *async_data, HANDLE cancel_event,
2213 const UUID *connection_uuid,
2214 const UUID *in_pipe_uuid,
2215 const UUID *association_uuid)
2216 {
2217 BOOL ret;
2218 RPC_STATUS status;
2219 RpcPktHdr *hdr;
2220 INTERNET_BUFFERSW buffers_in;
2221 DWORD bytes_written;
2222
2223 /* prepare in pipe */
2224 status = send_echo_request(in_request, async_data, cancel_event);
2225 if (status != RPC_S_OK) return status;
2226
2227 memset(&buffers_in, 0, sizeof(buffers_in));
2228 buffers_in.dwStructSize = sizeof(buffers_in);
2229 /* FIXME: get this from the registry */
2230 buffers_in.dwBufferTotal = 1024 * 1024 * 1024; /* 1Gb */
2231 prepare_async_request(async_data);
2232 ret = HttpSendRequestExW(in_request, &buffers_in, NULL, 0, 0);
2233 status = wait_async_request(async_data, ret, cancel_event);
2234 if (status != RPC_S_OK) return status;
2235
2236 TRACE("sending HTTP connect header to server\n");
2237 hdr = RPCRT4_BuildHttpConnectHeader(FALSE, connection_uuid, in_pipe_uuid, association_uuid);
2238 if (!hdr) return RPC_S_OUT_OF_RESOURCES;
2239 ret = InternetWriteFile(in_request, hdr, hdr->common.frag_len, &bytes_written);
2240 RPCRT4_FreeHeader(hdr);
2241 if (!ret)
2242 {
2243 ERR("InternetWriteFile failed with error %d\n", GetLastError());
2244 return RPC_S_SERVER_UNAVAILABLE;
2245 }
2246
2247 return RPC_S_OK;
2248 }
2249
2250 static RPC_STATUS rpcrt4_http_read_http_packet(HINTERNET request, RpcPktHdr *hdr, BYTE **data)
2251 {
2252 BOOL ret;
2253 DWORD bytes_read;
2254 unsigned short data_len;
2255
2256 ret = InternetReadFile(request, hdr, sizeof(hdr->common), &bytes_read);
2257 if (!ret)
2258 return RPC_S_SERVER_UNAVAILABLE;
2259 if (hdr->common.ptype != PKT_HTTP || hdr->common.frag_len < sizeof(hdr->http))
2260 {
2261 ERR("wrong packet type received %d or wrong frag_len %d\n",
2262 hdr->common.ptype, hdr->common.frag_len);
2263 return RPC_S_PROTOCOL_ERROR;
2264 }
2265
2266 ret = InternetReadFile(request, &hdr->common + 1, sizeof(hdr->http) - sizeof(hdr->common), &bytes_read);
2267 if (!ret)
2268 return RPC_S_SERVER_UNAVAILABLE;
2269
2270 data_len = hdr->common.frag_len - sizeof(hdr->http);
2271 if (data_len)
2272 {
2273 *data = HeapAlloc(GetProcessHeap(), 0, data_len);
2274 if (!*data)
2275 return RPC_S_OUT_OF_RESOURCES;
2276 ret = InternetReadFile(request, *data, data_len, &bytes_read);
2277 if (!ret)
2278 {
2279 HeapFree(GetProcessHeap(), 0, *data);
2280 return RPC_S_SERVER_UNAVAILABLE;
2281 }
2282 }
2283 else
2284 *data = NULL;
2285
2286 if (!RPCRT4_IsValidHttpPacket(hdr, *data, data_len))
2287 {
2288 ERR("invalid http packet\n");
2289 return RPC_S_PROTOCOL_ERROR;
2290 }
2291
2292 return RPC_S_OK;
2293 }
2294
2295 /* prepare the out pipe for use by RPC packets */
2296 static RPC_STATUS rpcrt4_http_prepare_out_pipe(HINTERNET out_request,
2297 RpcHttpAsyncData *async_data,
2298 HANDLE cancel_event,
2299 const UUID *connection_uuid,
2300 const UUID *out_pipe_uuid,
2301 ULONG *flow_control_increment)
2302 {
2303 BOOL ret;
2304 RPC_STATUS status;
2305 RpcPktHdr *hdr;
2306 BYTE *data_from_server;
2307 RpcPktHdr pkt_from_server;
2308 ULONG field1, field3;
2309
2310 status = send_echo_request(out_request, async_data, cancel_event);
2311 if (status != RPC_S_OK) return status;
2312
2313 hdr = RPCRT4_BuildHttpConnectHeader(TRUE, connection_uuid, out_pipe_uuid, NULL);
2314 if (!hdr) return RPC_S_OUT_OF_RESOURCES;
2315
2316 prepare_async_request(async_data);
2317 ret = HttpSendRequestW(out_request, NULL, 0, hdr, hdr->common.frag_len);
2318 status = wait_async_request(async_data, ret, cancel_event);
2319 RPCRT4_FreeHeader(hdr);
2320 if (status != RPC_S_OK) return status;
2321
2322 status = rpcrt4_http_check_response(out_request);
2323 if (status != RPC_S_OK) return status;
2324
2325 status = rpcrt4_http_read_http_packet(out_request, &pkt_from_server,
2326 &data_from_server);
2327 if (status != RPC_S_OK) return status;
2328 status = RPCRT4_ParseHttpPrepareHeader1(&pkt_from_server, data_from_server,
2329 &field1);
2330 HeapFree(GetProcessHeap(), 0, data_from_server);
2331 if (status != RPC_S_OK) return status;
2332 TRACE("received (%d) from first prepare header\n", field1);
2333
2334 for (;;)
2335 {
2336 status = rpcrt4_http_read_http_packet(out_request, &pkt_from_server,
2337 &data_from_server);
2338 if (status != RPC_S_OK) return status;
2339 if (pkt_from_server.http.flags != 0x0001) break;
2340
2341 TRACE("http idle packet, waiting for real packet\n");
2342 HeapFree(GetProcessHeap(), 0, data_from_server);
2343 if (pkt_from_server.http.num_data_items != 0)
2344 {
2345 ERR("HTTP idle packet should have no data items instead of %d\n",
2346 pkt_from_server.http.num_data_items);
2347 return RPC_S_PROTOCOL_ERROR;
2348 }
2349 }
2350 status = RPCRT4_ParseHttpPrepareHeader2(&pkt_from_server, data_from_server,
2351 &field1, flow_control_increment,
2352 &field3);
2353 HeapFree(GetProcessHeap(), 0, data_from_server);
2354 if (status != RPC_S_OK) return status;
2355 TRACE("received (0x%08x 0x%08x %d) from second prepare header\n", field1, *flow_control_increment, field3);
2356
2357 return RPC_S_OK;
2358 }
2359
2360 static UINT encode_base64(const char *bin, unsigned int len, WCHAR *base64)
2361 {
2362 static char enc[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
2363 UINT i = 0, x;
2364
2365 while (len > 0)
2366 {
2367 /* first 6 bits, all from bin[0] */
2368 base64[i++] = enc[(bin[0] & 0xfc) >> 2];
2369 x = (bin[0] & 3) << 4;
2370
2371 /* next 6 bits, 2 from bin[0] and 4 from bin[1] */
2372 if (len == 1)
2373 {
2374 base64[i++] = enc[x];
2375 base64[i++] = '=';
2376 base64[i++] = '=';
2377 break;
2378 }
2379 base64[i++] = enc[x | ((bin[1] & 0xf0) >> 4)];
2380 x = (bin[1] & 0x0f) << 2;
2381
2382 /* next 6 bits 4 from bin[1] and 2 from bin[2] */
2383 if (len == 2)
2384 {
2385 base64[i++] = enc[x];
2386 base64[i++] = '=';
2387 break;
2388 }
2389 base64[i++] = enc[x | ((bin[2] & 0xc0) >> 6)];
2390
2391 /* last 6 bits, all from bin [2] */
2392 base64[i++] = enc[bin[2] & 0x3f];
2393 bin += 3;
2394 len -= 3;
2395 }
2396 base64[i] = 0;
2397 return i;
2398 }
2399
2400 static RPC_STATUS insert_authorization_header(HINTERNET request, RpcQualityOfService *qos)
2401 {
2402 static const WCHAR basicW[] =
2403 {'A','u','t','h','o','r','i','z','a','t','i','o','n',':',' ','B','a','s','i','c',' '};
2404 RPC_HTTP_TRANSPORT_CREDENTIALS_W *creds;
2405 SEC_WINNT_AUTH_IDENTITY_W *id;
2406 int len, datalen, userlen, passlen;
2407 WCHAR *header, *ptr;
2408 char *data;
2409 RPC_STATUS status = RPC_S_SERVER_UNAVAILABLE;
2410
2411 if (!qos || qos->qos->AdditionalSecurityInfoType != RPC_C_AUTHN_INFO_TYPE_HTTP)
2412 return RPC_S_OK;
2413
2414 creds = qos->qos->u.HttpCredentials;
2415 if (creds->AuthenticationTarget != RPC_C_HTTP_AUTHN_TARGET_SERVER || !creds->NumberOfAuthnSchemes)
2416 return RPC_S_OK;
2417
2418 if (creds->AuthnSchemes[0] != RPC_C_HTTP_AUTHN_SCHEME_BASIC)
2419 {
2420 FIXME("scheme %u not supported\n", creds->AuthnSchemes[0]);
2421 return RPC_S_OK;
2422 }
2423 id = creds->TransportCredentials;
2424 if (!id->User || !id->Password) return RPC_S_OK;
2425
2426 userlen = WideCharToMultiByte(CP_UTF8, 0, id->User, id->UserLength, NULL, 0, NULL, NULL);
2427 passlen = WideCharToMultiByte(CP_UTF8, 0, id->Password, id->PasswordLength, NULL, 0, NULL, NULL);
2428
2429 datalen = userlen + passlen + 1;
2430 if (!(data = HeapAlloc(GetProcessHeap(), 0, datalen))) return RPC_S_OUT_OF_MEMORY;
2431
2432 WideCharToMultiByte(CP_UTF8, 0, id->User, id->UserLength, data, userlen, NULL, NULL);
2433 data[userlen] = ':';
2434 WideCharToMultiByte(CP_UTF8, 0, id->Password, id->PasswordLength, data + userlen + 1, passlen, NULL, NULL);
2435
2436 len = ((datalen + 2) * 4) / 3;
2437 if ((header = HeapAlloc(GetProcessHeap(), 0, sizeof(basicW) + (len + 2) * sizeof(WCHAR))))
2438 {
2439 memcpy(header, basicW, sizeof(basicW));
2440 ptr = header + sizeof(basicW) / sizeof(basicW[0]);
2441 len = encode_base64(data, datalen, ptr);
2442 ptr[len++] = '\r';
2443 ptr[len++] = '\n';
2444 ptr[len] = 0;
2445 if ((HttpAddRequestHeadersW(request, header, -1, HTTP_ADDREQ_FLAG_ADD_IF_NEW))) status = RPC_S_OK;
2446 HeapFree(GetProcessHeap(), 0, header);
2447 }
2448 HeapFree(GetProcessHeap(), 0, data);
2449 return status;
2450 }
2451
2452 static RPC_STATUS insert_cookie_header(HINTERNET request, const WCHAR *value)
2453 {
2454 static const WCHAR cookieW[] = {'C','o','o','k','i','e',':',' '};
2455 WCHAR *header, *ptr;
2456 int len;
2457 RPC_STATUS status = RPC_S_SERVER_UNAVAILABLE;
2458
2459 if (!value) return RPC_S_OK;
2460
2461 len = strlenW(value);
2462 if ((header = HeapAlloc(GetProcessHeap(), 0, sizeof(cookieW) + (len + 3) * sizeof(WCHAR))))
2463 {
2464 memcpy(header, cookieW, sizeof(cookieW));
2465 ptr = header + sizeof(cookieW) / sizeof(cookieW[0]);
2466 memcpy(ptr, value, len * sizeof(WCHAR));
2467 ptr[len++] = '\r';
2468 ptr[len++] = '\n';
2469 ptr[len] = 0;
2470 if ((HttpAddRequestHeadersW(request, header, -1, HTTP_ADDREQ_FLAG_ADD_IF_NEW))) status = RPC_S_OK;
2471 HeapFree(GetProcessHeap(), 0, header);
2472 }
2473 return status;
2474 }
2475
2476 static RPC_STATUS rpcrt4_ncacn_http_open(RpcConnection* Connection)
2477 {
2478 RpcConnection_http *httpc = (RpcConnection_http *)Connection;
2479 static const WCHAR wszVerbIn[] = {'R','P','C','_','I','N','_','D','A','T','A',0};
2480 static const WCHAR wszVerbOut[] = {'R','P','C','_','O','U','T','_','D','A','T','A',0};
2481 static const WCHAR wszRpcProxyPrefix[] = {'/','r','p','c','/','r','p','c','p','r','o','x','y','.','d','l','l','?',0};
2482 static const WCHAR wszColon[] = {':',0};
2483 static const WCHAR wszAcceptType[] = {'a','p','p','l','i','c','a','t','i','o','n','/','r','p','c',0};
2484 LPCWSTR wszAcceptTypes[] = { wszAcceptType, NULL };
2485 DWORD flags;
2486 WCHAR *url;
2487 RPC_STATUS status;
2488 BOOL secure;
2489 HttpTimerThreadData *timer_data;
2490 HANDLE thread;
2491
2492 TRACE("(%s, %s)\n", Connection->NetworkAddr, Connection->Endpoint);
2493
2494 if (Connection->server)
2495 {
2496 ERR("ncacn_http servers not supported yet\n");
2497 return RPC_S_SERVER_UNAVAILABLE;
2498 }
2499
2500 if (httpc->in_request)
2501 return RPC_S_OK;
2502
2503 httpc->async_data->completion_event = CreateEventW(NULL, FALSE, FALSE, NULL);
2504
2505 status = UuidCreate(&httpc->connection_uuid);
2506 status = UuidCreate(&httpc->in_pipe_uuid);
2507 status = UuidCreate(&httpc->out_pipe_uuid);
2508
2509 status = rpcrt4_http_internet_connect(httpc);
2510 if (status != RPC_S_OK)
2511 return status;
2512
2513 url = HeapAlloc(GetProcessHeap(), 0, sizeof(wszRpcProxyPrefix) + (strlen(Connection->NetworkAddr) + 1 + strlen(Connection->Endpoint))*sizeof(WCHAR));
2514 if (!url)
2515 return RPC_S_OUT_OF_MEMORY;
2516 memcpy(url, wszRpcProxyPrefix, sizeof(wszRpcProxyPrefix));
2517 MultiByteToWideChar(CP_ACP, 0, Connection->NetworkAddr, -1, url+sizeof(wszRpcProxyPrefix)/sizeof(wszRpcProxyPrefix[0])-1, strlen(Connection->NetworkAddr)+1);
2518 strcatW(url, wszColon);
2519 MultiByteToWideChar(CP_ACP, 0, Connection->Endpoint, -1, url+strlenW(url), strlen(Connection->Endpoint)+1);
2520
2521 secure = httpc->common.QOS &&
2522 (httpc->common.QOS->qos->AdditionalSecurityInfoType == RPC_C_AUTHN_INFO_TYPE_HTTP) &&
2523 (httpc->common.QOS->qos->u.HttpCredentials->Flags & RPC_C_HTTP_FLAG_USE_SSL);
2524
2525 flags = INTERNET_FLAG_KEEP_CONNECTION | INTERNET_FLAG_PRAGMA_NOCACHE | INTERNET_FLAG_NO_CACHE_WRITE |
2526 INTERNET_FLAG_NO_AUTO_REDIRECT;
2527 if (secure) flags |= INTERNET_FLAG_SECURE;
2528
2529 httpc->in_request = HttpOpenRequestW(httpc->session, wszVerbIn, url, NULL, NULL, wszAcceptTypes,
2530 flags, (DWORD_PTR)httpc->async_data);
2531 if (!httpc->in_request)
2532 {
2533 ERR("HttpOpenRequestW failed with error %d\n", GetLastError());
2534 HeapFree(GetProcessHeap(), 0, url);
2535 return RPC_S_SERVER_UNAVAILABLE;
2536 }
2537 status = insert_authorization_header(httpc->in_request, httpc->common.QOS);
2538 if (status != RPC_S_OK)
2539 return status;
2540
2541 status = insert_cookie_header(httpc->in_request, Connection->CookieAuth);
2542 if (status != RPC_S_OK)
2543 return status;
2544
2545 httpc->out_request = HttpOpenRequestW(httpc->session, wszVerbOut, url, NULL, NULL, wszAcceptTypes,
2546 flags, (DWORD_PTR)httpc->async_data);
2547 HeapFree(GetProcessHeap(), 0, url);
2548 if (!httpc->out_request)
2549 {
2550 ERR("HttpOpenRequestW failed with error %d\n", GetLastError());
2551 return RPC_S_SERVER_UNAVAILABLE;
2552 }
2553 status = insert_authorization_header(httpc->out_request, httpc->common.QOS);
2554 if (status != RPC_S_OK)
2555 return status;
2556
2557 status = insert_cookie_header(httpc->out_request, Connection->CookieAuth);
2558 if (status != RPC_S_OK)
2559 return status;
2560
2561 status = rpcrt4_http_prepare_in_pipe(httpc->in_request,
2562 httpc->async_data,
2563 httpc->cancel_event,
2564 &httpc->connection_uuid,
2565 &httpc->in_pipe_uuid,
2566 &Connection->assoc->http_uuid);
2567 if (status != RPC_S_OK)
2568 return status;
2569
2570 status = rpcrt4_http_prepare_out_pipe(httpc->out_request,
2571 httpc->async_data,
2572 httpc->cancel_event,
2573 &httpc->connection_uuid,
2574 &httpc->out_pipe_uuid,
2575 &httpc->flow_control_increment);
2576 if (status != RPC_S_OK)
2577 return status;
2578
2579 httpc->flow_control_mark = httpc->flow_control_increment / 2;
2580 httpc->last_sent_time = GetTickCount();
2581 httpc->timer_cancelled = CreateEventW(NULL, FALSE, FALSE, NULL);
2582
2583 timer_data = HeapAlloc(GetProcessHeap(), 0, sizeof(*timer_data));
2584 if (!timer_data)
2585 return ERROR_OUTOFMEMORY;
2586 timer_data->timer_param = httpc->in_request;
2587 timer_data->last_sent_time = &httpc->last_sent_time;
2588 timer_data->timer_cancelled = httpc->timer_cancelled;
2589 /* FIXME: should use CreateTimerQueueTimer when implemented */
2590 thread = CreateThread(NULL, 0, rpcrt4_http_timer_thread, timer_data, 0, NULL);
2591 if (!thread)
2592 {
2593 HeapFree(GetProcessHeap(), 0, timer_data);
2594 return GetLastError();
2595 }
2596 CloseHandle(thread);
2597
2598 return RPC_S_OK;
2599 }
2600
2601 static RPC_STATUS rpcrt4_ncacn_http_handoff(RpcConnection *old_conn, RpcConnection *new_conn)
2602 {
2603 assert(0);
2604 return RPC_S_SERVER_UNAVAILABLE;
2605 }
2606
2607 static int rpcrt4_ncacn_http_read(RpcConnection *Connection,
2608 void *buffer, unsigned int count)
2609 {
2610 RpcConnection_http *httpc = (RpcConnection_http *) Connection;
2611 char *buf = buffer;
2612 BOOL ret;
2613 unsigned int bytes_left = count;
2614 RPC_STATUS status = RPC_S_OK;
2615
2616 httpc->async_data->inet_buffers.lpvBuffer = HeapAlloc(GetProcessHeap(), 0, count);
2617
2618 while (bytes_left)
2619 {
2620 httpc->async_data->inet_buffers.dwBufferLength = bytes_left;
2621 prepare_async_request(httpc->async_data);
2622 ret = InternetReadFileExA(httpc->out_request, &httpc->async_data->inet_buffers, IRF_ASYNC, 0);
2623 status = wait_async_request(httpc->async_data, ret, httpc->cancel_event);
2624 if(status != RPC_S_OK) {
2625 if(status == RPC_S_CALL_CANCELLED)
2626 TRACE("call cancelled\n");
2627 break;
2628 }
2629
2630 if(!httpc->async_data->inet_buffers.dwBufferLength)
2631 break;
2632 memcpy(buf, httpc->async_data->inet_buffers.lpvBuffer,
2633 httpc->async_data->inet_buffers.dwBufferLength);
2634
2635 bytes_left -= httpc->async_data->inet_buffers.dwBufferLength;
2636 buf += httpc->async_data->inet_buffers.dwBufferLength;
2637 }
2638
2639 HeapFree(GetProcessHeap(), 0, httpc->async_data->inet_buffers.lpvBuffer);
2640 httpc->async_data->inet_buffers.lpvBuffer = NULL;
2641
2642 TRACE("%p %p %u -> %u\n", httpc->out_request, buffer, count, status);
2643 return status == RPC_S_OK ? count : -1;
2644 }
2645
2646 static RPC_STATUS rpcrt4_ncacn_http_receive_fragment(RpcConnection *Connection, RpcPktHdr **Header, void **Payload)
2647 {
2648 RpcConnection_http *httpc = (RpcConnection_http *) Connection;
2649 RPC_STATUS status;
2650 DWORD hdr_length;
2651 LONG dwRead;
2652 RpcPktCommonHdr common_hdr;
2653
2654 *Header = NULL;
2655
2656 TRACE("(%p, %p, %p)\n", Connection, Header, Payload);
2657
2658 again:
2659 /* read packet common header */
2660 dwRead = rpcrt4_ncacn_http_read(Connection, &common_hdr, sizeof(common_hdr));
2661 if (dwRead != sizeof(common_hdr)) {
2662 WARN("Short read of header, %d bytes\n", dwRead);
2663 status = RPC_S_PROTOCOL_ERROR;
2664 goto fail;
2665 }
2666 if (!memcmp(&common_hdr, "HTTP/1.1", sizeof("HTTP/1.1")) ||
2667 !memcmp(&common_hdr, "HTTP/1.0", sizeof("HTTP/1.0")))
2668 {
2669 FIXME("server returned %s\n", debugstr_a((const char *)&common_hdr));
2670 status = RPC_S_PROTOCOL_ERROR;
2671 goto fail;
2672 }
2673
2674 status = RPCRT4_ValidateCommonHeader(&common_hdr);
2675 if (status != RPC_S_OK) goto fail;
2676
2677 hdr_length = RPCRT4_GetHeaderSize((RpcPktHdr*)&common_hdr);
2678 if (hdr_length == 0) {
2679 WARN("header length == 0\n");
2680 status = RPC_S_PROTOCOL_ERROR;
2681 goto fail;
2682 }
2683
2684 *Header = HeapAlloc(GetProcessHeap(), 0, hdr_length);
2685 if (!*Header)
2686 {
2687 status = RPC_S_OUT_OF_RESOURCES;
2688 goto fail;
2689 }
2690 memcpy(*Header, &common_hdr, sizeof(common_hdr));
2691
2692 /* read the rest of packet header */
2693 dwRead = rpcrt4_ncacn_http_read(Connection, &(*Header)->common + 1, hdr_length - sizeof(common_hdr));
2694 if (dwRead != hdr_length - sizeof(common_hdr)) {
2695 WARN("bad header length, %d bytes, hdr_length %d\n", dwRead, hdr_length);
2696 status = RPC_S_PROTOCOL_ERROR;
2697 goto fail;
2698 }
2699
2700 if (common_hdr.frag_len - hdr_length)
2701 {
2702 *Payload = HeapAlloc(GetProcessHeap(), 0, common_hdr.frag_len - hdr_length);
2703 if (!*Payload)
2704 {
2705 status = RPC_S_OUT_OF_RESOURCES;
2706 goto fail;
2707 }
2708
2709 dwRead = rpcrt4_ncacn_http_read(Connection, *Payload, common_hdr.frag_len - hdr_length);
2710 if (dwRead != common_hdr.frag_len - hdr_length)
2711 {
2712 WARN("bad data length, %d/%d\n", dwRead, common_hdr.frag_len - hdr_length);
2713 status = RPC_S_PROTOCOL_ERROR;
2714 goto fail;
2715 }
2716 }
2717 else
2718 *Payload = NULL;
2719
2720 if ((*Header)->common.ptype == PKT_HTTP)
2721 {
2722 if (!RPCRT4_IsValidHttpPacket(*Header, *Payload, common_hdr.frag_len - hdr_length))
2723 {
2724 ERR("invalid http packet of length %d bytes\n", (*Header)->common.frag_len);
2725 status = RPC_S_PROTOCOL_ERROR;
2726 goto fail;
2727 }
2728 if ((*Header)->http.flags == 0x0001)
2729 {
2730 TRACE("http idle packet, waiting for real packet\n");
2731 if ((*Header)->http.num_data_items != 0)
2732 {
2733 ERR("HTTP idle packet should have no data items instead of %d\n", (*Header)->http.num_data_items);
2734 status = RPC_S_PROTOCOL_ERROR;
2735 goto fail;
2736 }
2737 }
2738 else if ((*Header)->http.flags == 0x0002)
2739 {
2740 ULONG bytes_transmitted;
2741 ULONG flow_control_increment;
2742 UUID pipe_uuid;
2743 status = RPCRT4_ParseHttpFlowControlHeader(*Header, *Payload,
2744 Connection->server,
2745 &bytes_transmitted,
2746 &flow_control_increment,
2747 &pipe_uuid);
2748 if (status != RPC_S_OK)
2749 goto fail;
2750 TRACE("received http flow control header (0x%x, 0x%x, %s)\n",
2751 bytes_transmitted, flow_control_increment, debugstr_guid(&pipe_uuid));
2752 /* FIXME: do something with parsed data */
2753 }
2754 else
2755 {
2756 FIXME("unrecognised http packet with flags 0x%04x\n", (*Header)->http.flags);
2757 status = RPC_S_PROTOCOL_ERROR;
2758 goto fail;
2759 }
2760 RPCRT4_FreeHeader(*Header);
2761 *Header = NULL;
2762 HeapFree(GetProcessHeap(), 0, *Payload);
2763 *Payload = NULL;
2764 goto again;
2765 }
2766
2767 /* success */
2768 status = RPC_S_OK;
2769
2770 httpc->bytes_received += common_hdr.frag_len;
2771
2772 TRACE("httpc->bytes_received = 0x%x\n", httpc->bytes_received);
2773
2774 if (httpc->bytes_received > httpc->flow_control_mark)
2775 {
2776 RpcPktHdr *hdr = RPCRT4_BuildHttpFlowControlHeader(httpc->common.server,
2777 httpc->bytes_received,
2778 httpc->flow_control_increment,
2779 &httpc->out_pipe_uuid);
2780 if (hdr)
2781 {
2782 DWORD bytes_written;
2783 BOOL ret2;
2784 TRACE("sending flow control packet at 0x%x\n", httpc->bytes_received);
2785 ret2 = InternetWriteFile(httpc->in_request, hdr, hdr->common.frag_len, &bytes_written);
2786 RPCRT4_FreeHeader(hdr);
2787 if (ret2)
2788 httpc->flow_control_mark = httpc->bytes_received + httpc->flow_control_increment / 2;
2789 }
2790 }
2791
2792 fail:
2793 if (status != RPC_S_OK) {
2794 RPCRT4_FreeHeader(*Header);
2795 *Header = NULL;
2796 HeapFree(GetProcessHeap(), 0, *Payload);
2797 *Payload = NULL;
2798 }
2799 return status;
2800 }
2801
2802 static int rpcrt4_ncacn_http_write(RpcConnection *Connection,
2803 const void *buffer, unsigned int count)
2804 {
2805 RpcConnection_http *httpc = (RpcConnection_http *) Connection;
2806 DWORD bytes_written;
2807 BOOL ret;
2808
2809 httpc->last_sent_time = ~0U; /* disable idle packet sending */
2810 ret = InternetWriteFile(httpc->in_request, buffer, count, &bytes_written);
2811 httpc->last_sent_time = GetTickCount();
2812 TRACE("%p %p %u -> %s\n", httpc->in_request, buffer, count, ret ? "TRUE" : "FALSE");
2813 return ret ? bytes_written : -1;
2814 }
2815
2816 static int rpcrt4_ncacn_http_close(RpcConnection *Connection)
2817 {
2818 RpcConnection_http *httpc = (RpcConnection_http *) Connection;
2819
2820 TRACE("\n");
2821
2822 SetEvent(httpc->timer_cancelled);
2823 if (httpc->in_request)
2824 InternetCloseHandle(httpc->in_request);
2825 httpc->in_request = NULL;
2826 if (httpc->out_request)
2827 InternetCloseHandle(httpc->out_request);
2828 httpc->out_request = NULL;
2829 if (httpc->app_info)
2830 InternetCloseHandle(httpc->app_info);
2831 httpc->app_info = NULL;
2832 if (httpc->session)
2833 InternetCloseHandle(httpc->session);
2834 httpc->session = NULL;
2835 RpcHttpAsyncData_Release(httpc->async_data);
2836 if (httpc->cancel_event)
2837 CloseHandle(httpc->cancel_event);
2838
2839 return 0;
2840 }
2841
2842 static void rpcrt4_ncacn_http_cancel_call(RpcConnection *Connection)
2843 {
2844 RpcConnection_http *httpc = (RpcConnection_http *) Connection;
2845
2846 SetEvent(httpc->cancel_event);
2847 }
2848
2849 static int rpcrt4_ncacn_http_wait_for_incoming_data(RpcConnection *Connection)
2850 {
2851 RpcConnection_http *httpc = (RpcConnection_http *) Connection;
2852 BOOL ret;
2853 RPC_STATUS status;
2854
2855 prepare_async_request(httpc->async_data);
2856 ret = InternetQueryDataAvailable(httpc->out_request,
2857 &httpc->async_data->inet_buffers.dwBufferLength, IRF_ASYNC, 0);
2858 status = wait_async_request(httpc->async_data, ret, httpc->cancel_event);
2859 return status == RPC_S_OK ? 0 : -1;
2860 }
2861
2862 static size_t rpcrt4_ncacn_http_get_top_of_tower(unsigned char *tower_data,
2863 const char *networkaddr,
2864 const char *endpoint)
2865 {
2866 return rpcrt4_ip_tcp_get_top_of_tower(tower_data, networkaddr,
2867 EPM_PROTOCOL_HTTP, endpoint);
2868 }
2869
2870 static RPC_STATUS rpcrt4_ncacn_http_parse_top_of_tower(const unsigned char *tower_data,
2871 size_t tower_size,
2872 char **networkaddr,
2873 char **endpoint)
2874 {
2875 return rpcrt4_ip_tcp_parse_top_of_tower(tower_data, tower_size,
2876 networkaddr, EPM_PROTOCOL_HTTP,
2877 endpoint);
2878 }
2879
2880 static const struct connection_ops conn_protseq_list[] = {
2881 { "ncacn_np",
2882 { EPM_PROTOCOL_NCACN, EPM_PROTOCOL_SMB },
2883 rpcrt4_conn_np_alloc,
2884 rpcrt4_ncacn_np_open,
2885 rpcrt4_ncacn_np_handoff,
2886 rpcrt4_conn_np_read,
2887 rpcrt4_conn_np_write,
2888 rpcrt4_conn_np_close,
2889 rpcrt4_conn_np_cancel_call,
2890 rpcrt4_conn_np_wait_for_incoming_data,
2891 rpcrt4_ncacn_np_get_top_of_tower,
2892 rpcrt4_ncacn_np_parse_top_of_tower,
2893 NULL,
2894 RPCRT4_default_is_authorized,
2895 RPCRT4_default_authorize,
2896 RPCRT4_default_secure_packet,
2897 rpcrt4_conn_np_impersonate_client,
2898 rpcrt4_conn_np_revert_to_self,
2899 RPCRT4_default_inquire_auth_client,
2900 },
2901 { "ncalrpc",
2902 { EPM_PROTOCOL_NCALRPC, EPM_PROTOCOL_PIPE },
2903 rpcrt4_conn_np_alloc,
2904 rpcrt4_ncalrpc_open,
2905 rpcrt4_ncalrpc_handoff,
2906 rpcrt4_conn_np_read,
2907 rpcrt4_conn_np_write,
2908 rpcrt4_conn_np_close,
2909 rpcrt4_conn_np_cancel_call,
2910 rpcrt4_conn_np_wait_for_incoming_data,
2911 rpcrt4_ncalrpc_get_top_of_tower,
2912 rpcrt4_ncalrpc_parse_top_of_tower,
2913 NULL,
2914 rpcrt4_ncalrpc_is_authorized,
2915 rpcrt4_ncalrpc_authorize,
2916 rpcrt4_ncalrpc_secure_packet,
2917 rpcrt4_conn_np_impersonate_client,
2918 rpcrt4_conn_np_revert_to_self,
2919 rpcrt4_ncalrpc_inquire_auth_client,
2920 },
2921 { "ncacn_ip_tcp",
2922 { EPM_PROTOCOL_NCACN, EPM_PROTOCOL_TCP },
2923 rpcrt4_conn_tcp_alloc,
2924 rpcrt4_ncacn_ip_tcp_open,
2925 rpcrt4_conn_tcp_handoff,
2926 rpcrt4_conn_tcp_read,
2927 rpcrt4_conn_tcp_write,
2928 rpcrt4_conn_tcp_close,
2929 rpcrt4_conn_tcp_cancel_call,
2930 rpcrt4_conn_tcp_wait_for_incoming_data,
2931 rpcrt4_ncacn_ip_tcp_get_top_of_tower,
2932 rpcrt4_ncacn_ip_tcp_parse_top_of_tower,
2933 NULL,
2934 RPCRT4_default_is_authorized,
2935 RPCRT4_default_authorize,
2936 RPCRT4_default_secure_packet,
2937 RPCRT4_default_impersonate_client,
2938 RPCRT4_default_revert_to_self,
2939 RPCRT4_default_inquire_auth_client,
2940 },
2941 { "ncacn_http",
2942 { EPM_PROTOCOL_NCACN, EPM_PROTOCOL_HTTP },
2943 rpcrt4_ncacn_http_alloc,
2944 rpcrt4_ncacn_http_open,
2945 rpcrt4_ncacn_http_handoff,
2946 rpcrt4_ncacn_http_read,
2947 rpcrt4_ncacn_http_write,
2948 rpcrt4_ncacn_http_close,
2949 rpcrt4_ncacn_http_cancel_call,
2950 rpcrt4_ncacn_http_wait_for_incoming_data,
2951 rpcrt4_ncacn_http_get_top_of_tower,
2952 rpcrt4_ncacn_http_parse_top_of_tower,
2953 rpcrt4_ncacn_http_receive_fragment,
2954 RPCRT4_default_is_authorized,
2955 RPCRT4_default_authorize,
2956 RPCRT4_default_secure_packet,
2957 RPCRT4_default_impersonate_client,
2958 RPCRT4_default_revert_to_self,
2959 RPCRT4_default_inquire_auth_client,
2960 },
2961 };
2962
2963
2964 static const struct protseq_ops protseq_list[] =
2965 {
2966 {
2967 "ncacn_np",
2968 rpcrt4_protseq_np_alloc,
2969 rpcrt4_protseq_np_signal_state_changed,
2970 rpcrt4_protseq_np_get_wait_array,
2971 rpcrt4_protseq_np_free_wait_array,
2972 rpcrt4_protseq_np_wait_for_new_connection,
2973 rpcrt4_protseq_ncacn_np_open_endpoint,
2974 },
2975 {
2976 "ncalrpc",
2977 rpcrt4_protseq_np_alloc,
2978 rpcrt4_protseq_np_signal_state_changed,
2979 rpcrt4_protseq_np_get_wait_array,
2980 rpcrt4_protseq_np_free_wait_array,
2981 rpcrt4_protseq_np_wait_for_new_connection,
2982 rpcrt4_protseq_ncalrpc_open_endpoint,
2983 },
2984 {
2985 "ncacn_ip_tcp",
2986 rpcrt4_protseq_sock_alloc,
2987 rpcrt4_protseq_sock_signal_state_changed,
2988 rpcrt4_protseq_sock_get_wait_array,
2989 rpcrt4_protseq_sock_free_wait_array,
2990 rpcrt4_protseq_sock_wait_for_new_connection,
2991 rpcrt4_protseq_ncacn_ip_tcp_open_endpoint,
2992 },
2993 };
2994
2995 #define ARRAYSIZE(a) (sizeof((a)) / sizeof((a)[0]))
2996
2997 const struct protseq_ops *rpcrt4_get_protseq_ops(const char *protseq)
2998 {
2999 unsigned int i;
3000 for(i=0; i<ARRAYSIZE(protseq_list); i++)
3001 if (!strcmp(protseq_list[i].name, protseq))
3002 return &protseq_list[i];
3003 return NULL;
3004 }
3005
3006 static const struct connection_ops *rpcrt4_get_conn_protseq_ops(const char *protseq)
3007 {
3008 unsigned int i;
3009 for(i=0; i<ARRAYSIZE(conn_protseq_list); i++)
3010 if (!strcmp(conn_protseq_list[i].name, protseq))
3011 return &conn_protseq_list[i];
3012 return NULL;
3013 }
3014
3015 /**** interface to rest of code ****/
3016
3017 RPC_STATUS RPCRT4_OpenClientConnection(RpcConnection* Connection)
3018 {
3019 TRACE("(Connection == ^%p)\n", Connection);
3020
3021 assert(!Connection->server);
3022 return Connection->ops->open_connection_client(Connection);
3023 }
3024
3025 RPC_STATUS RPCRT4_CloseConnection(RpcConnection* Connection)
3026 {
3027 TRACE("(Connection == ^%p)\n", Connection);
3028 if (SecIsValidHandle(&Connection->ctx))
3029 {
3030 DeleteSecurityContext(&Connection->ctx);
3031 SecInvalidateHandle(&Connection->ctx);
3032 }
3033 rpcrt4_conn_close(Connection);
3034 return RPC_S_OK;
3035 }
3036
3037 RPC_STATUS RPCRT4_CreateConnection(RpcConnection** Connection, BOOL server,
3038 LPCSTR Protseq, LPCSTR NetworkAddr, LPCSTR Endpoint,
3039 LPCWSTR NetworkOptions, RpcAuthInfo* AuthInfo, RpcQualityOfService *QOS, LPCWSTR CookieAuth)
3040 {
3041 static LONG next_id;
3042 const struct connection_ops *ops;
3043 RpcConnection* NewConnection;
3044
3045 ops = rpcrt4_get_conn_protseq_ops(Protseq);
3046 if (!ops)
3047 {
3048 FIXME("not supported for protseq %s\n", Protseq);
3049 return RPC_S_PROTSEQ_NOT_SUPPORTED;
3050 }
3051
3052 NewConnection = ops->alloc();
3053 NewConnection->ref = 1;
3054 NewConnection->Next = NULL;
3055 NewConnection->server_binding = NULL;
3056 NewConnection->server = server;
3057 NewConnection->ops = ops;
3058 NewConnection->NetworkAddr = RPCRT4_strdupA(NetworkAddr);
3059 NewConnection->Endpoint = RPCRT4_strdupA(Endpoint);
3060 NewConnection->NetworkOptions = RPCRT4_strdupW(NetworkOptions);
3061 NewConnection->CookieAuth = RPCRT4_strdupW(CookieAuth);
3062 NewConnection->MaxTransmissionSize = RPC_MAX_PACKET_SIZE;
3063 memset(&NewConnection->ActiveInterface, 0, sizeof(NewConnection->ActiveInterface));
3064 NewConnection->NextCallId = 1;
3065
3066 SecInvalidateHandle(&NewConnection->ctx);
3067 memset(&NewConnection->exp, 0, sizeof(NewConnection->exp));
3068 NewConnection->attr = 0;
3069 if (AuthInfo) RpcAuthInfo_AddRef(AuthInfo);
3070 NewConnection->AuthInfo = AuthInfo;
3071 NewConnection->auth_context_id = InterlockedIncrement( &next_id );
3072 NewConnection->encryption_auth_len = 0;
3073 NewConnection->signature_auth_len = 0;
3074 if (QOS) RpcQualityOfService_AddRef(QOS);
3075 NewConnection->QOS = QOS;
3076
3077 list_init(&NewConnection->conn_pool_entry);
3078 NewConnection->async_state = NULL;
3079
3080 TRACE("connection: %p\n", NewConnection);
3081 *Connection = NewConnection;
3082
3083 return RPC_S_OK;
3084 }
3085
3086 static RPC_STATUS RPCRT4_SpawnConnection(RpcConnection** Connection, RpcConnection* OldConnection)
3087 {
3088 RPC_STATUS err;
3089
3090 err = RPCRT4_CreateConnection(Connection, OldConnection->server, rpcrt4_conn_get_name(OldConnection),
3091 OldConnection->NetworkAddr, OldConnection->Endpoint, NULL,
3092 OldConnection->AuthInfo, OldConnection->QOS, OldConnection->CookieAuth);
3093 if (err == RPC_S_OK)
3094 rpcrt4_conn_handoff(OldConnection, *Connection);
3095 return err;
3096 }
3097
3098 RpcConnection *RPCRT4_GrabConnection( RpcConnection *conn )
3099 {
3100 InterlockedIncrement( &conn->ref );
3101 return conn;
3102 }
3103
3104 RPC_STATUS RPCRT4_ReleaseConnection(RpcConnection* Connection)
3105 {
3106 if (InterlockedDecrement( &Connection->ref ) > 0) return RPC_S_OK;
3107
3108 TRACE("destroying connection %p\n", Connection);
3109
3110 RPCRT4_CloseConnection(Connection);
3111 RPCRT4_strfree(Connection->Endpoint);
3112 RPCRT4_strfree(Connection->NetworkAddr);
3113 HeapFree(GetProcessHeap(), 0, Connection->NetworkOptions);
3114 HeapFree(GetProcessHeap(), 0, Connection->CookieAuth);
3115 if (Connection->AuthInfo) RpcAuthInfo_Release(Connection->AuthInfo);
3116 if (Connection->QOS) RpcQualityOfService_Release(Connection->QOS);
3117
3118 /* server-only */
3119 if (Connection->server_binding) RPCRT4_ReleaseBinding(Connection->server_binding);
3120
3121 HeapFree(GetProcessHeap(), 0, Connection);
3122 return RPC_S_OK;
3123 }
3124
3125 RPC_STATUS RpcTransport_GetTopOfTower(unsigned char *tower_data,
3126 size_t *tower_size,
3127 const char *protseq,
3128 const char *networkaddr,
3129 const char *endpoint)
3130 {
3131 twr_empty_floor_t *protocol_floor;
3132 const struct connection_ops *protseq_ops = rpcrt4_get_conn_protseq_ops(protseq);
3133
3134 *tower_size = 0;
3135
3136 if (!protseq_ops)
3137 return RPC_S_INVALID_RPC_PROTSEQ;
3138
3139 if (!tower_data)
3140 {
3141 *tower_size = sizeof(*protocol_floor);
3142 *tower_size += protseq_ops->get_top_of_tower(NULL, networkaddr, endpoint);
3143 return RPC_S_OK;
3144 }
3145
3146 protocol_floor = (twr_empty_floor_t *)tower_data;
3147 protocol_floor->count_lhs = sizeof(protocol_floor->protid);
3148 protocol_floor->protid = protseq_ops->epm_protocols[0];
3149 protocol_floor->count_rhs = 0;
3150
3151 tower_data += sizeof(*protocol_floor);
3152
3153 *tower_size = protseq_ops->get_top_of_tower(tower_data, networkaddr, endpoint);
3154 if (!*tower_size)
3155 return EPT_S_NOT_REGISTERED;
3156
3157 *tower_size += sizeof(*protocol_floor);
3158
3159 return RPC_S_OK;
3160 }
3161
3162 RPC_STATUS RpcTransport_ParseTopOfTower(const unsigned char *tower_data,
3163 size_t tower_size,
3164 char **protseq,
3165 char **networkaddr,
3166 char **endpoint)
3167 {
3168 const twr_empty_floor_t *protocol_floor;
3169 const twr_empty_floor_t *floor4;
3170 const struct connection_ops *protseq_ops = NULL;
3171 RPC_STATUS status;
3172 unsigned int i;
3173
3174 if (tower_size < sizeof(*protocol_floor))
3175 return EPT_S_NOT_REGISTERED;
3176
3177 protocol_floor = (const twr_empty_floor_t *)tower_data;
3178 tower_data += sizeof(*protocol_floor);
3179 tower_size -= sizeof(*protocol_floor);
3180 if ((protocol_floor->count_lhs != sizeof(protocol_floor->protid)) ||
3181 (protocol_floor->count_rhs > tower_size))
3182 return EPT_S_NOT_REGISTERED;
3183 tower_data += protocol_floor->count_rhs;
3184 tower_size -= protocol_floor->count_rhs;
3185
3186 floor4 = (const twr_empty_floor_t *)tower_data;
3187 if ((tower_size < sizeof(*floor4)) ||
3188 (floor4->count_lhs != sizeof(floor4->protid)))
3189 return EPT_S_NOT_REGISTERED;
3190
3191 for(i = 0; i < ARRAYSIZE(conn_protseq_list); i++)
3192 if ((protocol_floor->protid == conn_protseq_list[i].epm_protocols[0]) &&
3193 (floor4->protid == conn_protseq_list[i].epm_protocols[1]))
3194 {
3195 protseq_ops = &conn_protseq_list[i];
3196 break;
3197 }
3198
3199 if (!protseq_ops)
3200 return EPT_S_NOT_REGISTERED;
3201
3202 status = protseq_ops->parse_top_of_tower(tower_data, tower_size, networkaddr, endpoint);
3203
3204 if ((status == RPC_S_OK) && protseq)
3205 {
3206 *protseq = I_RpcAllocate(strlen(protseq_ops->name) + 1);
3207 strcpy(*protseq, protseq_ops->name);
3208 }
3209
3210 return status;
3211 }
3212
3213 /***********************************************************************
3214 * RpcNetworkIsProtseqValidW (RPCRT4.@)
3215 *
3216 * Checks if the given protocol sequence is known by the RPC system.
3217 * If it is, returns RPC_S_OK, otherwise RPC_S_PROTSEQ_NOT_SUPPORTED.
3218 *
3219 */
3220 RPC_STATUS WINAPI RpcNetworkIsProtseqValidW(RPC_WSTR protseq)
3221 {
3222 char ps[0x10];
3223
3224 WideCharToMultiByte(CP_ACP, 0, protseq, -1,
3225 ps, sizeof ps, NULL, NULL);
3226 if (rpcrt4_get_conn_protseq_ops(ps))
3227 return RPC_S_OK;
3228
3229 FIXME("Unknown protseq %s\n", debugstr_w(protseq));
3230
3231 return RPC_S_INVALID_RPC_PROTSEQ;
3232 }
3233
3234 /***********************************************************************
3235 * RpcNetworkIsProtseqValidA (RPCRT4.@)
3236 */
3237 RPC_STATUS WINAPI RpcNetworkIsProtseqValidA(RPC_CSTR protseq)
3238 {
3239 UNICODE_STRING protseqW;
3240
3241 if (RtlCreateUnicodeStringFromAsciiz(&protseqW, (char*)protseq))
3242 {
3243 RPC_STATUS ret = RpcNetworkIsProtseqValidW(protseqW.Buffer);
3244 RtlFreeUnicodeString(&protseqW);
3245 return ret;
3246 }
3247 return RPC_S_OUT_OF_MEMORY;
3248 }
3249
3250 /***********************************************************************
3251 * RpcProtseqVectorFreeA (RPCRT4.@)
3252 */
3253 RPC_STATUS WINAPI RpcProtseqVectorFreeA(RPC_PROTSEQ_VECTORA **protseqs)
3254 {
3255 TRACE("(%p)\n", protseqs);
3256
3257 if (*protseqs)
3258 {
3259 unsigned int i;
3260 for (i = 0; i < (*protseqs)->Count; i++)
3261 HeapFree(GetProcessHeap(), 0, (*protseqs)->Protseq[i]);
3262 HeapFree(GetProcessHeap(), 0, *protseqs);
3263 *protseqs = NULL;
3264 }
3265 return RPC_S_OK;
3266 }
3267
3268 /***********************************************************************
3269 * RpcProtseqVectorFreeW (RPCRT4.@)
3270 */
3271 RPC_STATUS WINAPI RpcProtseqVectorFreeW(RPC_PROTSEQ_VECTORW **protseqs)
3272 {
3273 TRACE("(%p)\n", protseqs);
3274
3275 if (*protseqs)
3276 {
3277 unsigned int i;
3278 for (i = 0; i < (*protseqs)->Count; i++)
3279 HeapFree(GetProcessHeap(), 0, (*protseqs)->Protseq[i]);
3280 HeapFree(GetProcessHeap(), 0, *protseqs);
3281 *protseqs = NULL;
3282 }
3283 return RPC_S_OK;
3284 }
3285
3286 /***********************************************************************
3287 * RpcNetworkInqProtseqsW (RPCRT4.@)
3288 */
3289 RPC_STATUS WINAPI RpcNetworkInqProtseqsW( RPC_PROTSEQ_VECTORW** protseqs )
3290 {
3291 RPC_PROTSEQ_VECTORW *pvector;
3292 unsigned int i;
3293 RPC_STATUS status = RPC_S_OUT_OF_MEMORY;
3294
3295 TRACE("(%p)\n", protseqs);
3296
3297 *protseqs = HeapAlloc(GetProcessHeap(), 0, sizeof(RPC_PROTSEQ_VECTORW)+(sizeof(unsigned short*)*ARRAYSIZE(protseq_list)));
3298 if (!*protseqs)
3299 goto end;
3300 pvector = *protseqs;
3301 pvector->Count = 0;
3302 for (i = 0; i < ARRAYSIZE(protseq_list); i++)
3303 {
3304 pvector->Protseq[i] = HeapAlloc(GetProcessHeap(), 0, (strlen(protseq_list[i].name)+1)*sizeof(unsigned short));
3305 if (pvector->Protseq[i] == NULL)
3306 goto end;
3307 MultiByteToWideChar(CP_ACP, 0, (CHAR*)protseq_list[i].name, -1,
3308 (WCHAR*)pvector->Protseq[i], strlen(protseq_list[i].name) + 1);
3309 pvector->Count++;
3310 }
3311 status = RPC_S_OK;
3312
3313 end:
3314 if (status != RPC_S_OK)
3315 RpcProtseqVectorFreeW(protseqs);
3316 return status;
3317 }
3318
3319 /***********************************************************************
3320 * RpcNetworkInqProtseqsA (RPCRT4.@)
3321 */
3322 RPC_STATUS WINAPI RpcNetworkInqProtseqsA(RPC_PROTSEQ_VECTORA** protseqs)
3323 {
3324 RPC_PROTSEQ_VECTORA *pvector;
3325 unsigned int i;
3326 RPC_STATUS status = RPC_S_OUT_OF_MEMORY;
3327
3328 TRACE("(%p)\n", protseqs);
3329
3330 *protseqs = HeapAlloc(GetProcessHeap(), 0, sizeof(RPC_PROTSEQ_VECTORW)+(sizeof(unsigned char*)*ARRAYSIZE(protseq_list)));
3331 if (!*protseqs)
3332 goto end;
3333 pvector = *protseqs;
3334 pvector->Count = 0;
3335 for (i = 0; i < ARRAYSIZE(protseq_list); i++)
3336 {
3337 pvector->Protseq[i] = HeapAlloc(GetProcessHeap(), 0, strlen(protseq_list[i].name)+1);
3338 if (pvector->Protseq[i] == NULL)
3339 goto end;
3340 strcpy((char*)pvector->Protseq[i], protseq_list[i].name);
3341 pvector->Count++;
3342 }
3343 status = RPC_S_OK;
3344
3345 end:
3346 if (status != RPC_S_OK)
3347 RpcProtseqVectorFreeA(protseqs);
3348 return status;
3349 }