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