Tor 0.4.9.0-alpha-dev
connection_edge.c
Go to the documentation of this file.
1/* Copyright (c) 2001 Matej Pfajfar.
2 * Copyright (c) 2001-2004, Roger Dingledine.
3 * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
4 * Copyright (c) 2007-2021, The Tor Project, Inc. */
5/* See LICENSE for licensing information */
6
7/**
8 * \file connection_edge.c
9 * \brief Handle edge streams.
10 *
11 * An edge_connection_t is a subtype of a connection_t, and represents two
12 * critical concepts in Tor: a stream, and an edge connection. From the Tor
13 * protocol's point of view, a stream is a bi-directional channel that is
14 * multiplexed on a single circuit. Each stream on a circuit is identified
15 * with a separate 16-bit stream ID, local to the (circuit,exit) pair.
16 * Streams are created in response to client requests.
17 *
18 * An edge connection is one thing that can implement a stream: it is either a
19 * TCP application socket that has arrived via (e.g.) a SOCKS request, or an
20 * exit connection.
21 *
22 * Not every instance of edge_connection_t truly represents an edge connection,
23 * however. (Sorry!) We also create edge_connection_t objects for streams that
24 * we will not be handling with TCP. The types of these streams are:
25 * <ul>
26 * <li>DNS lookup streams, created on the client side in response to
27 * a UDP DNS request received on a DNSPort, or a RESOLVE command
28 * on a controller.
29 * <li>DNS lookup streams, created on the exit side in response to
30 * a RELAY_RESOLVE cell from a client.
31 * <li>Tunneled directory streams, created on the directory cache side
32 * in response to a RELAY_BEGIN_DIR cell. These streams attach directly
33 * to a dir_connection_t object without ever using TCP.
34 * </ul>
35 *
36 * This module handles general-purpose functionality having to do with
37 * edge_connection_t. On the client side, it accepts various types of
38 * application requests on SocksPorts, TransPorts, and NATDPorts, and
39 * creates streams appropriately.
40 *
41 * This module is also responsible for implementing stream isolation:
42 * ensuring that streams that should not be linkable to one another are
43 * kept to different circuits.
44 *
45 * On the exit side, this module handles the various stream-creating
46 * type of RELAY cells by launching appropriate outgoing connections,
47 * DNS requests, or directory connection objects.
48 *
49 * And for all edge connections, this module is responsible for handling
50 * incoming and outdoing data as it arrives or leaves in the relay.c
51 * module. (Outgoing data will be packaged in
52 * connection_edge_process_inbuf() as it calls
53 * connection_edge_package_raw_inbuf(); incoming data from RELAY_DATA
54 * cells is applied in connection_edge_process_relay_cell().)
55 **/
56#define CONNECTION_EDGE_PRIVATE
57
58#include "core/or/or.h"
59
60#include "lib/err/backtrace.h"
61
62#include "app/config/config.h"
66#include "core/or/channel.h"
68#include "core/or/circuitlist.h"
69#include "core/or/circuituse.h"
76#include "core/or/dos.h"
77#include "core/or/extendinfo.h"
78#include "core/or/policies.h"
79#include "core/or/reasons.h"
80#include "core/or/relay.h"
81#include "core/or/sendme.h"
85#include "feature/client/circpathbias.h"
91#include "feature/hs/hs_cache.h"
100#include "feature/relay/dns.h"
101#include "feature/relay/router.h"
106#include "lib/buf/buffers.h"
110
111#include "core/or/cell_st.h"
117#include "core/or/or_circuit_st.h"
119#include "core/or/half_edge_st.h"
122
123#ifdef HAVE_LINUX_TYPES_H
124#include <linux/types.h>
125#endif
126#ifdef HAVE_LINUX_NETFILTER_IPV4_H
127#include <linux/netfilter_ipv4.h>
128#define TRANS_NETFILTER
129#define TRANS_NETFILTER_IPV4
130#endif
131
132#ifdef HAVE_LINUX_IF_H
133#include <linux/if.h>
134#endif
135
136#ifdef HAVE_LINUX_NETFILTER_IPV6_IP6_TABLES_H
137#include <linux/netfilter_ipv6/ip6_tables.h>
138#if defined(IP6T_SO_ORIGINAL_DST)
139#define TRANS_NETFILTER
140#define TRANS_NETFILTER_IPV6
141#endif
142#endif /* defined(HAVE_LINUX_NETFILTER_IPV6_IP6_TABLES_H) */
143
144#ifdef HAVE_FCNTL_H
145#include <fcntl.h>
146#endif
147#ifdef HAVE_SYS_IOCTL_H
148#include <sys/ioctl.h>
149#endif
150#ifdef HAVE_SYS_PARAM_H
151#include <sys/param.h>
152#endif
153
154#if defined(HAVE_NET_IF_H) && defined(HAVE_NET_PFVAR_H)
155#include <net/if.h>
156#include <net/pfvar.h>
157#define TRANS_PF
158#endif
159
160#ifdef IP_TRANSPARENT
161#define TRANS_TPROXY
162#endif
163
164#define SOCKS4_GRANTED 90
165#define SOCKS4_REJECT 91
166
170static int consider_plaintext_ports(entry_connection_t *conn, uint16_t port);
172static bool network_reentry_is_allowed(void);
173
174/**
175 * Cast a `connection_t *` to an `edge_connection_t *`.
176 *
177 * Exit with an assertion failure if the input is not an
178 * `edge_connection_t`.
179 **/
182{
183 tor_assert(c->magic == EDGE_CONNECTION_MAGIC ||
184 c->magic == ENTRY_CONNECTION_MAGIC);
185 return DOWNCAST(edge_connection_t, c);
186}
187
188/**
189 * Cast a `const connection_t *` to a `const edge_connection_t *`.
190 *
191 * Exit with an assertion failure if the input is not an
192 * `edge_connection_t`.
193 **/
194const edge_connection_t *
196{
197 return TO_EDGE_CONN((connection_t *)c);
198}
199
200/**
201 * Cast a `connection_t *` to an `entry_connection_t *`.
202 *
203 * Exit with an assertion failure if the input is not an
204 * `entry_connection_t`.
205 **/
208{
209 tor_assert(c->magic == ENTRY_CONNECTION_MAGIC);
210 return (entry_connection_t*) SUBTYPE_P(c, entry_connection_t, edge_.base_);
211}
212
213/**
214 * Cast a `const connection_t *` to a `const entry_connection_t *`.
215 *
216 * Exit with an assertion failure if the input is not an
217 * `entry_connection_t`.
218 **/
219const entry_connection_t *
221{
222 return TO_ENTRY_CONN((connection_t*) c);
223}
224
225/**
226 * Cast an `edge_connection_t *` to an `entry_connection_t *`.
227 *
228 * Exit with an assertion failure if the input is not an
229 * `entry_connection_t`.
230 **/
233{
234 tor_assert(c->base_.magic == ENTRY_CONNECTION_MAGIC);
236}
237
238/**
239 * Cast a `const edge_connection_t *` to a `const entry_connection_t *`.
240 *
241 * Exit with an assertion failure if the input is not an
242 * `entry_connection_t`.
243 **/
244const entry_connection_t *
246{
248}
249
250/** An AP stream has failed/finished. If it hasn't already sent back
251 * a socks reply, send one now (based on endreason). Also set
252 * has_sent_end to 1, and mark the conn.
253 */
254MOCK_IMPL(void,
256 int line, const char *file))
257{
258 connection_t *base_conn = ENTRY_TO_CONN(conn);
259 tor_assert(base_conn->type == CONN_TYPE_AP);
260 ENTRY_TO_EDGE_CONN(conn)->edge_has_sent_end = 1; /* no circ yet */
261
262 if (base_conn->marked_for_close) {
263 /* This call will warn as appropriate. */
264 connection_mark_for_close_(base_conn, line, file);
265 return;
266 }
267
268 if (!conn->socks_request->has_finished) {
270 log_warn(LD_BUG,
271 "stream (marked at %s:%d) sending two socks replies?",
272 file, line);
273
274 if (SOCKS_COMMAND_IS_CONNECT(conn->socks_request->command))
275 connection_ap_handshake_socks_reply(conn, NULL, 0, endreason);
276 else if (SOCKS_COMMAND_IS_RESOLVE(conn->socks_request->command))
278 RESOLVED_TYPE_ERROR_TRANSIENT,
279 0, NULL, -1, -1);
280 else /* unknown or no handshake at all. send no response. */
281 conn->socks_request->has_finished = 1;
282 }
283
284 connection_mark_and_flush_(base_conn, line, file);
285
286 ENTRY_TO_EDGE_CONN(conn)->end_reason = endreason;
287}
288
289/** There was an EOF. Send an end and mark the connection for close.
290 */
291int
293{
294 if (connection_get_inbuf_len(TO_CONN(conn)) &&
296 /* it still has stuff to process. don't let it die yet. */
297 return 0;
298 }
299 log_info(LD_EDGE,"conn (fd "TOR_SOCKET_T_FORMAT") reached eof. Closing.",
300 conn->base_.s);
301 if (!conn->base_.marked_for_close) {
302 /* only mark it if not already marked. it's possible to
303 * get the 'end' right around when the client hangs up on us. */
304 connection_edge_end(conn, END_STREAM_REASON_DONE);
305 if (conn->base_.type == CONN_TYPE_AP) {
306 /* eof, so don't send a socks reply back */
307 if (EDGE_TO_ENTRY_CONN(conn)->socks_request)
309 }
310 connection_mark_for_close(TO_CONN(conn));
311 }
312 return 0;
313}
314
315/** Handle new bytes on conn->inbuf based on state:
316 * - If it's waiting for socks info, try to read another step of the
317 * socks handshake out of conn->inbuf.
318 * - If it's waiting for the original destination, fetch it.
319 * - If it's open, then package more relay cells from the stream.
320 * - Else, leave the bytes on inbuf alone for now.
321 *
322 * Mark and return -1 if there was an unexpected error with the conn,
323 * else return 0.
324 */
325int
327{
328 tor_assert(conn);
329
330 switch (conn->base_.state) {
333 /* already marked */
334 return -1;
335 }
336 return 0;
339 /* already marked */
340 return -1;
341 }
342 return 0;
345 return -1;
346 }
347 return 0;
349 if (! conn->base_.linked) {
351 }
352
353 FALLTHROUGH;
355 if (connection_edge_package_raw_inbuf(conn, package_partial, NULL) < 0) {
356 /* (We already sent an end cell if possible) */
357 connection_mark_for_close(TO_CONN(conn));
358 return -1;
359 }
360 return 0;
363 log_info(LD_EDGE,
364 "data from edge while in '%s' state. Sending it anyway. "
365 "package_partial=%d, buflen=%ld",
366 conn_state_to_string(conn->base_.type, conn->base_.state),
367 package_partial,
368 (long)connection_get_inbuf_len(TO_CONN(conn)));
369 if (connection_edge_package_raw_inbuf(conn, package_partial, NULL)<0) {
370 /* (We already sent an end cell if possible) */
371 connection_mark_for_close(TO_CONN(conn));
372 return -1;
373 }
374 return 0;
375 }
376 /* Fall through if the connection is on a circuit without optimistic
377 * data support. */
378 FALLTHROUGH;
384 log_info(LD_EDGE,
385 "data from edge while in '%s' state. Leaving it on buffer.",
386 conn_state_to_string(conn->base_.type, conn->base_.state));
387 return 0;
388 }
389 log_warn(LD_BUG,"Got unexpected state %d. Closing.",conn->base_.state);
391 connection_edge_end(conn, END_STREAM_REASON_INTERNAL);
392 connection_mark_for_close(TO_CONN(conn));
393 return -1;
394}
395
396/** This edge needs to be closed, because its circuit has closed.
397 * Mark it for close and return 0.
398 */
399int
401{
402 if (!conn->base_.marked_for_close) {
403 log_info(LD_EDGE, "CircID %u: At an edge. Marking connection for close.",
404 (unsigned) circ_id);
405 if (conn->base_.type == CONN_TYPE_AP) {
406 entry_connection_t *entry_conn = EDGE_TO_ENTRY_CONN(conn);
407 connection_mark_unattached_ap(entry_conn, END_STREAM_REASON_DESTROY);
409 control_event_stream_status(entry_conn, STREAM_EVENT_CLOSED,
410 END_STREAM_REASON_DESTROY);
412 } else {
413 /* closing the circuit, nothing to send an END to */
414 conn->edge_has_sent_end = 1;
415 conn->end_reason = END_STREAM_REASON_DESTROY;
417 connection_mark_and_flush(TO_CONN(conn));
418 }
419 }
420 conn->cpath_layer = NULL;
421 conn->on_circuit = NULL;
422 return 0;
423}
424
425/** Send a raw end cell to the stream with ID <b>stream_id</b> out over the
426 * <b>circ</b> towards the hop identified with <b>cpath_layer</b>. If this
427 * is not a client connection, set the relay end cell's reason for closing
428 * as <b>reason</b> */
429static int
431 uint8_t reason, crypt_path_t *cpath_layer)
432{
433 char payload[1];
434
436 /* Never send the server an informative reason code; it doesn't need to
437 * know why the client stream is failing. */
438 reason = END_STREAM_REASON_MISC;
439 }
440
441 payload[0] = (char) reason;
442
443 /* Note: we have to use relay_send_command_from_edge here, not
444 * connection_edge_end or connection_edge_send_command, since those require
445 * that we have a stream connected to a circuit, and we don't connect to a
446 * circuit until we have a pending/successful resolve. */
447 return relay_send_command_from_edge(stream_id, circ, RELAY_COMMAND_END,
448 payload, 1, cpath_layer);
449}
450
451/* If the connection <b>conn</b> is attempting to connect to an external
452 * destination that is an hidden service and the reason is a connection
453 * refused or timeout, log it so the operator can take appropriate actions.
454 * The log statement is a rate limited warning. */
455static void
456warn_if_hs_unreachable(const edge_connection_t *conn, uint8_t reason)
457{
458 tor_assert(conn);
459
460 if (conn->base_.type == CONN_TYPE_EXIT &&
462 (reason == END_STREAM_REASON_CONNECTREFUSED ||
463 reason == END_STREAM_REASON_TIMEOUT)) {
464#define WARN_FAILED_HS_CONNECTION 300
465 static ratelim_t warn_limit = RATELIM_INIT(WARN_FAILED_HS_CONNECTION);
466 char *m;
467 if ((m = rate_limit_log(&warn_limit, approx_time()))) {
468 log_warn(LD_EDGE, "Onion service connection to %s failed (%s)",
471 tor_free(m);
472 }
473 }
474}
475
476/** Given a TTL (in seconds) from a DNS response or from a relay, determine
477 * what TTL clients and relays should actually use for caching it. */
478uint32_t
479clip_dns_ttl(uint32_t ttl)
480{
481 /* This logic is a defense against "DefectTor" DNS-based traffic
482 * confirmation attacks, as in https://nymity.ch/tor-dns/tor-dns.pdf .
483 * We only give two values: a "low" value and a "high" value.
484 */
485 if (ttl < MIN_DNS_TTL)
486 return MIN_DNS_TTL;
487 else
488 return MAX_DNS_TTL;
489}
490
491/** Given a TTL (in seconds), determine what TTL an exit relay should use by
492 * first clipping as usual and then adding some randomness which is sampled
493 * uniformly at random from [-FUZZY_DNS_TTL, FUZZY_DNS_TTL]. This facilitates
494 * fuzzy TTLs, which makes it harder to infer when a website was visited via
495 * side-channels like DNS (see "Website Fingerprinting with Website Oracles").
496 *
497 * Note that this can't underflow because FUZZY_DNS_TTL < MIN_DNS_TTL.
498 */
499uint32_t
501{
502 return clip_dns_ttl(ttl) +
504}
505
506/** Send a relay end cell from stream <b>conn</b> down conn's circuit, and
507 * remember that we've done so. If this is not a client connection, set the
508 * relay end cell's reason for closing as <b>reason</b>.
509 *
510 * Return -1 if this function has already been called on this conn,
511 * else return 0.
512 */
513int
515{
516 char payload[RELAY_PAYLOAD_SIZE];
517 size_t payload_len=1;
518 circuit_t *circ;
519 uint8_t control_reason = reason;
520
521 if (conn->edge_has_sent_end) {
522 log_warn(LD_BUG,"(Harmless.) Calling connection_edge_end (reason %d) "
523 "on an already ended stream?", reason);
525 return -1;
526 }
527
528 if (conn->base_.marked_for_close) {
529 log_warn(LD_BUG,
530 "called on conn that's already marked for close at %s:%d.",
531 conn->base_.marked_for_close_file, conn->base_.marked_for_close);
532 return 0;
533 }
534
535 circ = circuit_get_by_edge_conn(conn);
536 if (circ && CIRCUIT_PURPOSE_IS_CLIENT(circ->purpose)) {
537 /* If this is a client circuit, don't send the server an informative
538 * reason code; it doesn't need to know why the client stream is
539 * failing. */
540 reason = END_STREAM_REASON_MISC;
541 }
542
543 payload[0] = (char)reason;
544 if (reason == END_STREAM_REASON_EXITPOLICY &&
546 int addrlen;
547 if (tor_addr_family(&conn->base_.addr) == AF_INET) {
548 set_uint32(payload+1, tor_addr_to_ipv4n(&conn->base_.addr));
549 addrlen = 4;
550 } else {
551 memcpy(payload+1, tor_addr_to_in6_addr8(&conn->base_.addr), 16);
552 addrlen = 16;
553 }
554 set_uint32(payload+1+addrlen, htonl(conn->address_ttl));
555 payload_len += 4+addrlen;
556 }
557
558 if (circ && !circ->marked_for_close) {
559 log_debug(LD_EDGE,"Sending end on conn (fd "TOR_SOCKET_T_FORMAT").",
560 conn->base_.s);
561
562 if (CIRCUIT_IS_ORIGIN(circ)) {
563 origin_circuit_t *origin_circ = TO_ORIGIN_CIRCUIT(circ);
564 connection_half_edge_add(conn, origin_circ);
565 }
566
567 connection_edge_send_command(conn, RELAY_COMMAND_END,
568 payload, payload_len);
569 /* We'll log warn if the connection was an hidden service and couldn't be
570 * made because the service wasn't available. */
571 warn_if_hs_unreachable(conn, control_reason);
572 } else {
573 log_debug(LD_EDGE,"No circ to send end on conn "
574 "(fd "TOR_SOCKET_T_FORMAT").",
575 conn->base_.s);
576 }
577
578 conn->edge_has_sent_end = 1;
579 conn->end_reason = control_reason;
580 return 0;
581}
582
583/**
584 * Helper function for bsearch.
585 *
586 * As per smartlist_bsearch, return < 0 if key precedes member,
587 * > 0 if member precedes key, and 0 if they are equal.
588 *
589 * This is equivalent to subtraction of the values of key - member
590 * (why does no one ever say that explicitly?).
591 */
592static int
593connection_half_edge_compare_bsearch(const void *key, const void **member)
594{
595 const half_edge_t *e2;
596 tor_assert(key);
597 tor_assert(member && *(half_edge_t**)member);
598 e2 = *(const half_edge_t **)member;
599
600 return *(const streamid_t*)key - e2->stream_id;
601}
602
603/** Total number of half_edge_t objects allocated */
604static size_t n_half_conns_allocated = 0;
605
606/**
607 * Add a half-closed connection to the list, to watch for activity.
608 *
609 * These connections are removed from the list upon receiving an end
610 * cell.
611 */
612STATIC void
614 origin_circuit_t *circ)
615{
616 half_edge_t *half_conn = NULL;
617 int insert_at = 0;
618 int ignored;
619
620 /* Double-check for re-insertion. This should not happen,
621 * but this check is cheap compared to the sort anyway */
623 conn->stream_id)) {
624 log_warn(LD_BUG, "Duplicate stream close for stream %d on circuit %d",
625 conn->stream_id, circ->global_identifier);
626 return;
627 }
628
629 half_conn = tor_malloc_zero(sizeof(half_edge_t));
631
632 if (!circ->half_streams) {
633 circ->half_streams = smartlist_new();
635 }
636
637 half_conn->stream_id = conn->stream_id;
638
639 // Is there a connected cell pending?
640 half_conn->connected_pending = conn->base_.state ==
642
643 if (edge_uses_flow_control(conn)) {
644 /* If the edge uses the new congestion control flow control, we must use
645 * time-based limits on half-edge activity. */
646 uint64_t timeout_usec = (uint64_t)(get_circuit_build_timeout_ms()*1000);
647 half_conn->used_ccontrol = 1;
648
649 /* If this is an onion service circuit, double the CBT as an approximate
650 * value for the other half of the circuit */
651 if (conn->hs_ident) {
652 timeout_usec *= 2;
653 }
654
655 /* The stream should stop seeing any use after the larger of the circuit
656 * RTT and the overall circuit build timeout */
657 half_conn->end_ack_expected_usec = MAX(timeout_usec,
658 edge_get_max_rtt(conn)) +
660 } else {
661 // How many sendme's should I expect?
662 half_conn->sendmes_pending =
664
665 /* Data should only arrive if we're not waiting on a resolved cell.
666 * It can arrive after waiting on connected, because of optimistic
667 * data. */
668 if (conn->base_.state != AP_CONN_STATE_RESOLVE_WAIT) {
669 // How many more data cells can arrive on this id?
670 half_conn->data_pending = conn->deliver_window;
671 }
672 }
673
674 insert_at = smartlist_bsearch_idx(circ->half_streams, &half_conn->stream_id,
676 &ignored);
677 smartlist_insert(circ->half_streams, insert_at, half_conn);
678}
679
680/**
681 * Return true if the circuit has any half-closed connections
682 * that are still within the end_ack_expected_usec timestamp
683 * from now.
684 */
685bool
687{
688 if (!circ->half_streams)
689 return false;
690
691 SMARTLIST_FOREACH_BEGIN(circ->half_streams, const half_edge_t *, half_conn) {
692 if (half_conn->end_ack_expected_usec > monotime_absolute_usec())
693 return true;
694 } SMARTLIST_FOREACH_END(half_conn);
695
696 return false;
697}
698
699/** Release space held by <b>he</b> */
700void
702{
703 if (!he)
704 return;
706 tor_free(he);
707}
708
709/** Return the number of bytes devoted to storing info on half-open streams. */
710size_t
712{
713 return n_half_conns_allocated * sizeof(half_edge_t);
714}
715
716/**
717 * Find a stream_id_t in the list in O(lg(n)).
718 *
719 * Returns NULL if the list is empty or element is not found.
720 * Returns a pointer to the element if found.
721 */
724 streamid_t stream_id)
725{
726 if (!half_conns)
727 return NULL;
728
729 return smartlist_bsearch(half_conns, &stream_id,
731}
732
733/**
734 * Check if this stream_id is in a half-closed state. If so,
735 * check if it still has data cells pending, and decrement that
736 * window if so.
737 *
738 * Return 1 if the data window was not empty.
739 * Return 0 otherwise.
740 */
741int
743 streamid_t stream_id)
744{
746 stream_id);
747
748 if (!half)
749 return 0;
750
751 if (half->used_ccontrol) {
753 return 0;
754 return 1;
755 }
756
757 if (half->data_pending > 0) {
758 half->data_pending--;
759 return 1;
760 }
761
762 return 0;
763}
764
765/**
766 * Check if this stream_id is in a half-closed state. If so,
767 * check if it still has a connected cell pending, and decrement
768 * that window if so.
769 *
770 * Return 1 if the connected window was not empty.
771 * Return 0 otherwise.
772 */
773int
775 streamid_t stream_id)
776{
778 stream_id);
779
780 if (!half)
781 return 0;
782
783 if (half->connected_pending) {
784 half->connected_pending = 0;
785 return 1;
786 }
787
788 return 0;
789}
790
791/**
792 * Check if this stream_id is in a half-closed state. If so,
793 * check if it still has sendme cells pending, and decrement that
794 * window if so.
795 *
796 * Return 1 if the sendme window was not empty.
797 * Return 0 otherwise.
798 */
799int
801 streamid_t stream_id)
802{
804 stream_id);
805
806 if (!half)
807 return 0;
808
809 /* congestion control edges don't use sendmes */
810 if (half->used_ccontrol)
811 return 0;
812
813 if (half->sendmes_pending > 0) {
814 half->sendmes_pending--;
815 return 1;
816 }
817
818 return 0;
819}
820
821/**
822 * Check if this stream_id is in a half-closed state. If so, remove
823 * it from the list. No other data should come after the END cell.
824 *
825 * Return 1 if stream_id was in half-closed state.
826 * Return 0 otherwise.
827 */
828int
830 streamid_t stream_id)
831{
832 half_edge_t *half;
833 int found, remove_idx;
834
835 if (!half_conns)
836 return 0;
837
838 remove_idx = smartlist_bsearch_idx(half_conns, &stream_id,
840 &found);
841 if (!found)
842 return 0;
843
844 half = smartlist_get(half_conns, remove_idx);
845 smartlist_del_keeporder(half_conns, remove_idx);
846 half_edge_free(half);
847 return 1;
848}
849
850/**
851 * Streams that were used to send a RESOLVE cell are closed
852 * when they get the RESOLVED, without an end. So treat
853 * a RESOLVED just like an end, and remove from the list.
854 */
855int
857 streamid_t stream_id)
858{
859 return connection_half_edge_is_valid_end(half_conns, stream_id);
860}
861
862/** An error has just occurred on an operation on an edge connection
863 * <b>conn</b>. Extract the errno; convert it to an end reason, and send an
864 * appropriate relay end cell to the other end of the connection's circuit.
865 **/
866int
868{
869 uint8_t reason;
870 tor_assert(conn);
871 reason = errno_to_stream_end_reason(tor_socket_errno(conn->base_.s));
872 return connection_edge_end(conn, reason);
873}
874
875/** We just wrote some data to <b>conn</b>; act appropriately.
876 *
877 * (That is, if it's open, consider sending a stream-level sendme cell if we
878 * have just flushed enough.)
879 */
880int
882{
883 switch (conn->base_.state) {
885 if (! conn->base_.linked) {
887 }
888
889 FALLTHROUGH;
892 break;
893 }
894 return 0;
895}
896
897/** Connection <b>conn</b> has finished writing and has no bytes left on
898 * its outbuf.
899 *
900 * If it's in state 'open', stop writing, consider responding with a
901 * sendme, and return.
902 * Otherwise, stop writing and return.
903 *
904 * If <b>conn</b> is broken, mark it for close and return -1, else
905 * return 0.
906 */
907int
909{
910 tor_assert(conn);
911
912 switch (conn->base_.state) {
916 return 0;
925 return 0;
926 default:
927 log_warn(LD_BUG, "Called in unexpected state %d.",conn->base_.state);
929 return -1;
930 }
931 return 0;
932}
933
934/** Longest size for the relay payload of a RELAY_CONNECTED cell that we're
935 * able to generate. */
936/* 4 zero bytes; 1 type byte; 16 byte IPv6 address; 4 byte TTL. */
937#define MAX_CONNECTED_CELL_PAYLOAD_LEN 25
938
939/** Set the buffer at <b>payload_out</b> -- which must have at least
940 * MAX_CONNECTED_CELL_PAYLOAD_LEN bytes available -- to the body of a
941 * RELAY_CONNECTED cell indicating that we have connected to <b>addr</b>, and
942 * that the name resolution that led us to <b>addr</b> will be valid for
943 * <b>ttl</b> seconds. Return -1 on error, or the number of bytes used on
944 * success. */
945STATIC int
946connected_cell_format_payload(uint8_t *payload_out,
947 const tor_addr_t *addr,
948 uint32_t ttl)
949{
950 const sa_family_t family = tor_addr_family(addr);
951 int connected_payload_len;
952
953 /* should be needless */
954 memset(payload_out, 0, MAX_CONNECTED_CELL_PAYLOAD_LEN);
955
956 if (family == AF_INET) {
957 set_uint32(payload_out, tor_addr_to_ipv4n(addr));
958 connected_payload_len = 4;
959 } else if (family == AF_INET6) {
960 set_uint32(payload_out, 0);
961 set_uint8(payload_out + 4, 6);
962 memcpy(payload_out + 5, tor_addr_to_in6_addr8(addr), 16);
963 connected_payload_len = 21;
964 } else {
965 return -1;
966 }
967
968 set_uint32(payload_out + connected_payload_len, htonl(ttl));
969 connected_payload_len += 4;
970
971 tor_assert(connected_payload_len <= MAX_CONNECTED_CELL_PAYLOAD_LEN);
972
973 return connected_payload_len;
974}
975
976/* This is an onion service client connection: Export the client circuit ID
977 * according to the HAProxy proxy protocol. */
978STATIC void
979export_hs_client_circuit_id(edge_connection_t *edge_conn,
981{
982 /* We only support HAProxy right now. */
983 if (protocol != HS_CIRCUIT_ID_PROTOCOL_HAPROXY)
984 return;
985
986 char *buf = NULL;
987 const char dst_ipv6[] = "::1";
988 /* See RFC4193 regarding fc00::/7 */
989 const char src_ipv6_prefix[] = "fc00:dead:beef:4dad:";
990 uint16_t dst_port = 0;
991 uint16_t src_port = 1; /* default value */
992 uint32_t gid = 0; /* default value */
993
994 /* Generate a GID and source port for this client */
995 if (edge_conn->on_circuit != NULL) {
997 src_port = gid & 0x0000ffff;
998 }
999
1000 /* Grab the original dest port from the hs ident */
1001 if (edge_conn->hs_ident) {
1002 dst_port = edge_conn->hs_ident->orig_virtual_port;
1003 }
1004
1005 /* Build the string */
1006 tor_asprintf(&buf, "PROXY TCP6 %s:%x:%x %s %d %d\r\n",
1007 src_ipv6_prefix,
1008 gid >> 16, gid & 0x0000ffff,
1009 dst_ipv6, src_port, dst_port);
1010
1011 connection_buf_add(buf, strlen(buf), TO_CONN(edge_conn));
1012
1013 tor_free(buf);
1014}
1015
1016/** Connected handler for exit connections: start writing pending
1017 * data, deliver 'CONNECTED' relay cells as appropriate, and check
1018 * any pending data that may have been received. */
1019int
1021{
1022 connection_t *conn;
1023
1024 tor_assert(edge_conn);
1025 tor_assert(edge_conn->base_.type == CONN_TYPE_EXIT);
1026 conn = TO_CONN(edge_conn);
1028
1029 log_info(LD_EXIT,"%s established.",
1030 connection_describe(conn));
1031
1033
1035
1036 connection_watch_events(conn, READ_EVENT); /* stop writing, keep reading */
1037 if (connection_get_outbuf_len(conn)) /* in case there are any queued relay
1038 * cells */
1040 /* deliver a 'connected' relay cell back through the circuit. */
1041 if (connection_edge_is_rendezvous_stream(edge_conn)) {
1042 if (connection_edge_send_command(edge_conn,
1043 RELAY_COMMAND_CONNECTED, NULL, 0) < 0)
1044 return 0; /* circuit is closed, don't continue */
1045 } else {
1046 uint8_t connected_payload[MAX_CONNECTED_CELL_PAYLOAD_LEN];
1047 int connected_payload_len =
1048 connected_cell_format_payload(connected_payload, &conn->addr,
1049 edge_conn->address_ttl);
1050 if (connected_payload_len < 0)
1051 return -1;
1052
1053 if (connection_edge_send_command(edge_conn,
1054 RELAY_COMMAND_CONNECTED,
1055 (char*)connected_payload, connected_payload_len) < 0)
1056 return 0; /* circuit is closed, don't continue */
1057 }
1058 tor_assert(edge_conn->package_window > 0);
1059 /* in case the server has written anything */
1060 return connection_edge_process_inbuf(edge_conn, 1);
1061}
1062
1063/** A list of all the entry_connection_t * objects that are not marked
1064 * for close, and are in AP_CONN_STATE_CIRCUIT_WAIT.
1065 *
1066 * (Right now, we check in several places to make sure that this list is
1067 * correct. When it's incorrect, we'll fix it, and log a BUG message.)
1068 */
1070
1071static int untried_pending_connections = 0;
1072
1073/**
1074 * Mainloop event to tell us to scan for pending connections that can
1075 * be attached.
1076 */
1078
1079/** Common code to connection_(ap|exit)_about_to_close. */
1080static void
1082{
1083 if (!edge_conn->edge_has_sent_end) {
1084 connection_t *conn = TO_CONN(edge_conn);
1085 log_warn(LD_BUG, "(Harmless.) Edge connection (marked at %s:%d) "
1086 "hasn't sent end yet?",
1089 }
1090}
1091
1092/** Called when we're about to finally unlink and free an AP (client)
1093 * connection: perform necessary accounting and cleanup */
1094void
1096{
1097 circuit_t *circ;
1098 edge_connection_t *edge_conn = ENTRY_TO_EDGE_CONN(entry_conn);
1099 connection_t *conn = ENTRY_TO_CONN(entry_conn);
1100
1102
1103 if (entry_conn->socks_request->has_finished == 0) {
1104 /* since conn gets removed right after this function finishes,
1105 * there's no point trying to send back a reply at this point. */
1106 log_warn(LD_BUG,"Closing stream (marked at %s:%d) without sending"
1107 " back a socks reply.",
1109 }
1110 if (!edge_conn->end_reason) {
1111 log_warn(LD_BUG,"Closing stream (marked at %s:%d) without having"
1112 " set end_reason.",
1114 }
1115 if (entry_conn->dns_server_request) {
1116 log_warn(LD_BUG,"Closing stream (marked at %s:%d) without having"
1117 " replied to DNS request.",
1119 dnsserv_reject_request(entry_conn);
1120 }
1121
1122 if (TO_CONN(edge_conn)->state == AP_CONN_STATE_CIRCUIT_WAIT) {
1124 }
1125
1126#if 1
1127 /* Check to make sure that this isn't in pending_entry_connections if it
1128 * didn't actually belong there. */
1129 if (TO_CONN(edge_conn)->type == CONN_TYPE_AP) {
1130 connection_ap_warn_and_unmark_if_pending_circ(entry_conn,
1131 "about_to_close");
1132 }
1133#endif /* 1 */
1134
1136 control_event_stream_status(entry_conn, STREAM_EVENT_CLOSED,
1137 edge_conn->end_reason);
1138 circ = circuit_get_by_edge_conn(edge_conn);
1139 if (circ)
1140 circuit_detach_stream(circ, edge_conn);
1141}
1142
1143/** Called when we're about to finally unlink and free an exit
1144 * connection: perform necessary accounting and cleanup */
1145void
1147{
1148 circuit_t *circ;
1149 connection_t *conn = TO_CONN(edge_conn);
1150
1152
1153 circ = circuit_get_by_edge_conn(edge_conn);
1154 if (circ)
1155 circuit_detach_stream(circ, edge_conn);
1156 if (conn->state == EXIT_CONN_STATE_RESOLVING) {
1157 connection_dns_remove(edge_conn);
1158 }
1159}
1160
1161/** Define a schedule for how long to wait between retrying
1162 * application connections. Rather than waiting a fixed amount of
1163 * time between each retry, we wait 10 seconds each for the first
1164 * two tries, and 15 seconds for each retry after
1165 * that. Hopefully this will improve the expected user experience. */
1166static int
1168{
1170 if (timeout) /* if our config options override the default, use them */
1171 return timeout;
1172 if (conn->num_socks_retries < 2) /* try 0 and try 1 */
1173 return 10;
1174 return 15;
1175}
1176
1177/** Find all general-purpose AP streams waiting for a response that sent their
1178 * begin/resolve cell too long ago. Detach from their current circuit, and
1179 * mark their current circuit as unsuitable for new streams. Then call
1180 * connection_ap_handshake_attach_circuit() to attach to a new circuit (if
1181 * available) or launch a new one.
1182 *
1183 * For rendezvous streams, simply give up after SocksTimeout seconds (with no
1184 * retry attempt).
1185 */
1186void
1188{
1189 edge_connection_t *conn;
1190 entry_connection_t *entry_conn;
1191 circuit_t *circ;
1192 time_t now = time(NULL);
1193 const or_options_t *options = get_options();
1194 int severity;
1195 int cutoff;
1196 int seconds_idle, seconds_since_born;
1198
1199 SMARTLIST_FOREACH_BEGIN(conns, connection_t *, base_conn) {
1200 if (base_conn->type != CONN_TYPE_AP || base_conn->marked_for_close)
1201 continue;
1202 entry_conn = TO_ENTRY_CONN(base_conn);
1203 conn = ENTRY_TO_EDGE_CONN(entry_conn);
1204 /* if it's an internal linked connection, don't yell its status. */
1205 severity = (tor_addr_is_null(&base_conn->addr) && !base_conn->port)
1206 ? LOG_INFO : LOG_NOTICE;
1207 seconds_idle = (int)( now - base_conn->timestamp_last_read_allowed );
1208 seconds_since_born = (int)( now - base_conn->timestamp_created );
1209
1210 if (base_conn->state == AP_CONN_STATE_OPEN)
1211 continue;
1212
1213 /* We already consider SocksTimeout in
1214 * connection_ap_handshake_attach_circuit(), but we need to consider
1215 * it here too because controllers that put streams in controller_wait
1216 * state never ask Tor to attach the circuit. */
1217 if (AP_CONN_STATE_IS_UNATTACHED(base_conn->state)) {
1218 /* If this is a connection to an HS with PoW defenses enabled, we need to
1219 * wait longer than the usual Socks timeout. */
1220 if (seconds_since_born >= options->SocksTimeout &&
1221 !entry_conn->hs_with_pow_conn) {
1222 log_fn(severity, LD_APP,
1223 "Tried for %d seconds to get a connection to %s:%d. "
1224 "Giving up. (%s)",
1225 seconds_since_born,
1226 safe_str_client(entry_conn->socks_request->address),
1227 entry_conn->socks_request->port,
1228 conn_state_to_string(CONN_TYPE_AP, base_conn->state));
1229 connection_mark_unattached_ap(entry_conn, END_STREAM_REASON_TIMEOUT);
1230 }
1231 continue;
1232 }
1233
1234 /* We're in state connect_wait or resolve_wait now -- waiting for a
1235 * reply to our relay cell. See if we want to retry/give up. */
1236
1237 cutoff = compute_retry_timeout(entry_conn);
1238 if (seconds_idle < cutoff)
1239 continue;
1240 circ = circuit_get_by_edge_conn(conn);
1241 if (!circ) { /* it's vanished? */
1242 log_info(LD_APP,"Conn is waiting (address %s), but lost its circ.",
1243 safe_str_client(entry_conn->socks_request->address));
1244 connection_mark_unattached_ap(entry_conn, END_STREAM_REASON_TIMEOUT);
1245 continue;
1246 }
1248 if (seconds_idle >= options->SocksTimeout) {
1249 log_fn(severity, LD_REND,
1250 "Rend stream is %d seconds late. Giving up on address"
1251 " '%s.onion'.",
1252 seconds_idle,
1253 safe_str_client(entry_conn->socks_request->address));
1254 /* Roll back path bias use state so that we probe the circuit
1255 * if nothing else succeeds on it */
1257
1258 connection_edge_end(conn, END_STREAM_REASON_TIMEOUT);
1259 connection_mark_unattached_ap(entry_conn, END_STREAM_REASON_TIMEOUT);
1260 }
1261 continue;
1262 }
1263
1264 if (circ->purpose != CIRCUIT_PURPOSE_C_GENERAL &&
1265 circ->purpose != CIRCUIT_PURPOSE_CONFLUX_LINKED &&
1271 log_warn(LD_BUG, "circuit->purpose == CIRCUIT_PURPOSE_C_GENERAL failed. "
1272 "The purpose on the circuit was %s; it was in state %s, "
1273 "path_state %s.",
1276 CIRCUIT_IS_ORIGIN(circ) ?
1277 pathbias_state_to_string(TO_ORIGIN_CIRCUIT(circ)->path_state) :
1278 "none");
1279 }
1280 log_fn(cutoff < 15 ? LOG_INFO : severity, LD_APP,
1281 "We tried for %d seconds to connect to '%s' using exit %s."
1282 " Retrying on a new circuit.",
1283 seconds_idle,
1284 safe_str_client(entry_conn->socks_request->address),
1285 conn->cpath_layer ?
1287 "*unnamed*");
1288 /* send an end down the circuit */
1289 connection_edge_end(conn, END_STREAM_REASON_TIMEOUT);
1290 /* un-mark it as ending, since we're going to reuse it */
1291 conn->edge_has_sent_end = 0;
1292 conn->end_reason = 0;
1293 /* make us not try this circuit again, but allow
1294 * current streams on it to survive if they can */
1296
1297 /* give our stream another 'cutoff' seconds to try */
1298 conn->base_.timestamp_last_read_allowed += cutoff;
1299 if (entry_conn->num_socks_retries < 250) /* avoid overflow */
1300 entry_conn->num_socks_retries++;
1301 /* move it back into 'pending' state, and try to attach. */
1303 END_STREAM_REASON_TIMEOUT)<0) {
1304 if (!base_conn->marked_for_close)
1305 connection_mark_unattached_ap(entry_conn,
1307 }
1308 } SMARTLIST_FOREACH_END(base_conn);
1309}
1310
1311/**
1312 * As connection_ap_attach_pending, but first scans the entire connection
1313 * array to see if any elements are missing.
1314 */
1315void
1317{
1318 entry_connection_t *entry_conn;
1320
1321 if (PREDICT_UNLIKELY(NULL == pending_entry_connections))
1323
1324 SMARTLIST_FOREACH_BEGIN(conns, connection_t *, conn) {
1325 if (conn->marked_for_close ||
1326 conn->type != CONN_TYPE_AP ||
1327 conn->state != AP_CONN_STATE_CIRCUIT_WAIT)
1328 continue;
1329
1330 entry_conn = TO_ENTRY_CONN(conn);
1331 tor_assert(entry_conn);
1332 if (! smartlist_contains(pending_entry_connections, entry_conn)) {
1333 log_warn(LD_BUG, "Found a connection %p that was supposed to be "
1334 "in pending_entry_connections, but wasn't. No worries; "
1335 "adding it.",
1337 untried_pending_connections = 1;
1338 connection_ap_mark_as_pending_circuit(entry_conn);
1339 }
1340
1341 } SMARTLIST_FOREACH_END(conn);
1342
1344}
1345
1346/** Tell any AP streams that are listed as waiting for a new circuit to try
1347 * again. If there is an available circuit for a stream, attach it. Otherwise,
1348 * launch a new circuit.
1349 *
1350 * If <b>retry</b> is false, only check the list if it contains at least one
1351 * streams that we have not yet tried to attach to a circuit.
1352 */
1353void
1355{
1356 if (PREDICT_UNLIKELY(!pending_entry_connections)) {
1357 return;
1358 }
1359
1360 if (untried_pending_connections == 0 && !retry)
1361 return;
1362
1363 /* Don't allow any modifications to list while we are iterating over
1364 * it. We'll put streams back on this list if we can't attach them
1365 * immediately. */
1368
1370 entry_connection_t *, entry_conn) {
1371 connection_t *conn = ENTRY_TO_CONN(entry_conn);
1372 tor_assert(conn && entry_conn);
1373 if (conn->marked_for_close) {
1374 continue;
1375 }
1376 if (conn->magic != ENTRY_CONNECTION_MAGIC) {
1377 log_warn(LD_BUG, "%p has impossible magic value %u.",
1378 entry_conn, (unsigned)conn->magic);
1379 continue;
1380 }
1381 if (conn->state != AP_CONN_STATE_CIRCUIT_WAIT) {
1382 /* The connection_ap_handshake_attach_circuit() call, for onion service,
1383 * can lead to more than one connections in the "pending" list to change
1384 * state and so it is OK to get here. Ignore it because this connection
1385 * won't be in pending_entry_connections list after this point. */
1386 continue;
1387 }
1388
1389 /* Okay, we're through the sanity checks. Try to handle this stream. */
1390 if (connection_ap_handshake_attach_circuit(entry_conn) < 0) {
1391 if (!conn->marked_for_close)
1392 connection_mark_unattached_ap(entry_conn,
1394 }
1395
1396 if (! conn->marked_for_close &&
1397 conn->type == CONN_TYPE_AP &&
1399 /* Is it still waiting for a circuit? If so, we didn't attach it,
1400 * so it's still pending. Put it back on the list.
1401 */
1404 continue;
1405 }
1406 }
1407
1408 /* If we got here, then we either closed the connection, or
1409 * we attached it. */
1410 } SMARTLIST_FOREACH_END(entry_conn);
1411
1412 smartlist_free(pending);
1413 untried_pending_connections = 0;
1414}
1415
1416static void
1417attach_pending_entry_connections_cb(mainloop_event_t *ev, void *arg)
1418{
1419 (void)ev;
1420 (void)arg;
1422}
1423
1424/** Mark <b>entry_conn</b> as needing to get attached to a circuit.
1425 *
1426 * And <b>entry_conn</b> must be in AP_CONN_STATE_CIRCUIT_WAIT,
1427 * should not already be pending a circuit. The circuit will get
1428 * launched or the connection will get attached the next time we
1429 * call connection_ap_attach_pending().
1430 */
1431void
1433 const char *fname, int lineno)
1434{
1435 connection_t *conn = ENTRY_TO_CONN(entry_conn);
1437 tor_assert(conn->magic == ENTRY_CONNECTION_MAGIC);
1438 if (conn->marked_for_close)
1439 return;
1440
1441 if (PREDICT_UNLIKELY(NULL == pending_entry_connections)) {
1443 }
1444 if (PREDICT_UNLIKELY(NULL == attach_pending_entry_connections_ev)) {
1446 attach_pending_entry_connections_cb, NULL);
1447 }
1448 if (PREDICT_UNLIKELY(smartlist_contains(pending_entry_connections,
1449 entry_conn))) {
1450 log_warn(LD_BUG, "What?? pending_entry_connections already contains %p! "
1451 "(Called from %s:%d.)",
1452 entry_conn, fname, lineno);
1453#ifdef DEBUGGING_17659
1454 const char *f2 = entry_conn->marked_pending_circ_file;
1455 log_warn(LD_BUG, "(Previously called from %s:%d.)\n",
1456 f2 ? f2 : "<NULL>",
1457 entry_conn->marked_pending_circ_line);
1458#endif /* defined(DEBUGGING_17659) */
1459 log_backtrace(LOG_WARN, LD_BUG, "To debug, this may help");
1460 return;
1461 }
1462
1463#ifdef DEBUGGING_17659
1464 entry_conn->marked_pending_circ_line = (uint16_t) lineno;
1465 entry_conn->marked_pending_circ_file = fname;
1466#endif
1467
1468 untried_pending_connections = 1;
1470
1472}
1473
1474/** Mark <b>entry_conn</b> as no longer waiting for a circuit. */
1475void
1477{
1478 if (PREDICT_UNLIKELY(NULL == pending_entry_connections))
1479 return;
1481}
1482
1483/** Mark <b>entry_conn</b> as waiting for a rendezvous descriptor. This
1484 * function will remove the entry connection from the waiting for a circuit
1485 * list (pending_entry_connections).
1486 *
1487 * This pattern is used across the code base because a connection in state
1488 * AP_CONN_STATE_RENDDESC_WAIT must not be in the pending list. */
1489void
1491{
1492 tor_assert(entry_conn);
1493
1495 ENTRY_TO_CONN(entry_conn)->state = AP_CONN_STATE_RENDDESC_WAIT;
1496}
1497
1498/* DOCDOC */
1499void
1500connection_ap_warn_and_unmark_if_pending_circ(entry_connection_t *entry_conn,
1501 const char *where)
1502{
1505 log_warn(LD_BUG, "What was %p doing in pending_entry_connections in %s?",
1506 entry_conn, where);
1508 }
1509}
1510
1511/** Tell any AP streams that are waiting for a one-hop tunnel to
1512 * <b>failed_digest</b> that they are going to fail. */
1513/* XXXX We should get rid of this function, and instead attach
1514 * one-hop streams to circ->p_streams so they get marked in
1515 * circuit_mark_for_close like normal p_streams. */
1516void
1517connection_ap_fail_onehop(const char *failed_digest,
1518 cpath_build_state_t *build_state)
1519{
1520 entry_connection_t *entry_conn;
1521 char digest[DIGEST_LEN];
1523 SMARTLIST_FOREACH_BEGIN(conns, connection_t *, conn) {
1524 if (conn->marked_for_close ||
1525 conn->type != CONN_TYPE_AP ||
1526 conn->state != AP_CONN_STATE_CIRCUIT_WAIT)
1527 continue;
1528 entry_conn = TO_ENTRY_CONN(conn);
1529 if (!entry_conn->want_onehop)
1530 continue;
1531 if (hexdigest_to_digest(entry_conn->chosen_exit_name, digest) < 0 ||
1532 tor_memneq(digest, failed_digest, DIGEST_LEN))
1533 continue;
1534 if (tor_digest_is_zero(digest)) {
1535 /* we don't know the digest; have to compare addr:port */
1536 tor_addr_t addr;
1537 if (!build_state || !build_state->chosen_exit ||
1538 !entry_conn->socks_request) {
1539 continue;
1540 }
1541 if (tor_addr_parse(&addr, entry_conn->socks_request->address)<0 ||
1542 !extend_info_has_orport(build_state->chosen_exit, &addr,
1543 entry_conn->socks_request->port))
1544 continue;
1545 }
1546 log_info(LD_APP, "Closing one-hop stream to '%s/%s' because the OR conn "
1547 "just failed.", entry_conn->chosen_exit_name,
1548 entry_conn->socks_request->address);
1549 connection_mark_unattached_ap(entry_conn, END_STREAM_REASON_TIMEOUT);
1550 } SMARTLIST_FOREACH_END(conn);
1551}
1552
1553/** A circuit failed to finish on its last hop <b>info</b>. If there
1554 * are any streams waiting with this exit node in mind, but they
1555 * don't absolutely require it, make them give up on it.
1556 */
1557void
1559{
1560 entry_connection_t *entry_conn;
1561 const node_t *r1, *r2;
1562
1564 SMARTLIST_FOREACH_BEGIN(conns, connection_t *, conn) {
1565 if (conn->marked_for_close ||
1566 conn->type != CONN_TYPE_AP ||
1567 conn->state != AP_CONN_STATE_CIRCUIT_WAIT)
1568 continue;
1569 entry_conn = TO_ENTRY_CONN(conn);
1570 if (!entry_conn->chosen_exit_optional &&
1571 !entry_conn->chosen_exit_retries)
1572 continue;
1573 r1 = node_get_by_nickname(entry_conn->chosen_exit_name,
1574 NNF_NO_WARN_UNNAMED);
1575 r2 = node_get_by_id(info->identity_digest);
1576 if (!r1 || !r2 || r1 != r2)
1577 continue;
1578 tor_assert(entry_conn->socks_request);
1579 if (entry_conn->chosen_exit_optional) {
1580 log_info(LD_APP, "Giving up on enclave exit '%s' for destination %s.",
1581 safe_str_client(entry_conn->chosen_exit_name),
1583 entry_conn->chosen_exit_optional = 0;
1584 tor_free(entry_conn->chosen_exit_name); /* clears it */
1585 /* if this port is dangerous, warn or reject it now that we don't
1586 * think it'll be using an enclave. */
1587 consider_plaintext_ports(entry_conn, entry_conn->socks_request->port);
1588 }
1589 if (entry_conn->chosen_exit_retries) {
1590 if (--entry_conn->chosen_exit_retries == 0) { /* give up! */
1592 tor_free(entry_conn->chosen_exit_name); /* clears it */
1593 /* if this port is dangerous, warn or reject it now that we don't
1594 * think it'll be using an enclave. */
1595 consider_plaintext_ports(entry_conn, entry_conn->socks_request->port);
1596 }
1597 }
1598 } SMARTLIST_FOREACH_END(conn);
1599}
1600
1601/** Set the connection state to CONTROLLER_WAIT and send an control port event.
1602 */
1603void
1605{
1606 CONNECTION_AP_EXPECT_NONPENDING(conn);
1608 control_event_stream_status(conn, STREAM_EVENT_CONTROLLER_WAIT, 0);
1609}
1610
1611/** The AP connection <b>conn</b> has just failed while attaching or
1612 * sending a BEGIN or resolving on <b>circ</b>, but another circuit
1613 * might work. Detach the circuit, and either reattach it, launch a
1614 * new circuit, tell the controller, or give up as appropriate.
1615 *
1616 * Returns -1 on err, 1 on success, 0 on not-yet-sure.
1617 */
1618int
1620 origin_circuit_t *circ,
1621 int reason)
1622{
1623 control_event_stream_status(conn, STREAM_EVENT_FAILED_RETRIABLE, reason);
1624 ENTRY_TO_CONN(conn)->timestamp_last_read_allowed = time(NULL);
1625
1626 /* Roll back path bias use state so that we probe the circuit
1627 * if nothing else succeeds on it */
1629
1630 if (conn->pending_optimistic_data) {
1631 buf_set_to_copy(&conn->sending_optimistic_data,
1633 }
1634
1635 if (!get_options()->LeaveStreamsUnattached || conn->use_begindir) {
1636 /* If we're attaching streams ourself, or if this connection is
1637 * a tunneled directory connection, then just attach it. */
1640 connection_ap_mark_as_pending_circuit(conn);
1641 } else {
1644 }
1645 return 0;
1646}
1647
1648/** Check if <b>conn</b> is using a dangerous port. Then warn and/or
1649 * reject depending on our config options. */
1650static int
1652{
1653 const or_options_t *options = get_options();
1655 options->RejectPlaintextPorts, port);
1656
1658 log_warn(LD_APP, "Application request to port %d: this port is "
1659 "commonly used for unencrypted protocols. Please make sure "
1660 "you don't send anything you would mind the rest of the "
1661 "Internet reading!%s", port, reject ? " Closing." : "");
1662 control_event_client_status(LOG_WARN, "DANGEROUS_PORT PORT=%d RESULT=%s",
1663 port, reject ? "REJECT" : "WARN");
1664 }
1665
1666 if (reject) {
1667 log_info(LD_APP, "Port %d listed in RejectPlaintextPorts. Closing.", port);
1668 connection_mark_unattached_ap(conn, END_STREAM_REASON_ENTRYPOLICY);
1669 return -1;
1670 }
1671
1672 return 0;
1673}
1674
1675/** Parse the given hostname in address. Returns true if the parsing was
1676 * successful and type_out contains the type of the hostname. Else, false is
1677 * returned which means it was not recognized and type_out is set to
1678 * BAD_HOSTNAME.
1679 *
1680 * The possible recognized forms are (where true is returned):
1681 *
1682 * If address is of the form "y.onion" with a well-formed handle y:
1683 * Put a NUL after y, lower-case it, and return ONION_V3_HOSTNAME
1684 * depending on the HS version.
1685 *
1686 * If address is of the form "x.y.onion" with a well-formed handle x:
1687 * Drop "x.", put a NUL after y, lower-case it, and return
1688 * ONION_V3_HOSTNAME depending on the HS version.
1689 *
1690 * If address is of the form "y.onion" with a badly-formed handle y:
1691 * Return BAD_HOSTNAME and log a message.
1692 *
1693 * If address is of the form "y.exit":
1694 * Put a NUL after y and return EXIT_HOSTNAME.
1695 *
1696 * Otherwise:
1697 * Return NORMAL_HOSTNAME and change nothing.
1698 */
1699STATIC bool
1701{
1702 char *s;
1703 char *q;
1704 char query[HS_SERVICE_ADDR_LEN_BASE32+1];
1705
1706 s = strrchr(address,'.');
1707 if (!s) {
1708 *type_out = NORMAL_HOSTNAME; /* no dot, thus normal */
1709 goto success;
1710 }
1711 if (!strcmp(s+1,"exit")) {
1712 *s = 0; /* NUL-terminate it */
1713 *type_out = EXIT_HOSTNAME; /* .exit */
1714 goto success;
1715 }
1716 if (strcmp(s+1,"onion")) {
1717 *type_out = NORMAL_HOSTNAME; /* neither .exit nor .onion, thus normal */
1718 goto success;
1719 }
1720
1721 /* so it is .onion */
1722 *s = 0; /* NUL-terminate it */
1723 /* locate a 'sub-domain' component, in order to remove it */
1724 q = strrchr(address, '.');
1725 if (q == address) {
1726 *type_out = BAD_HOSTNAME;
1727 goto failed; /* reject sub-domain, as DNS does */
1728 }
1729 q = (NULL == q) ? address : q + 1;
1730 if (strlcpy(query, q, HS_SERVICE_ADDR_LEN_BASE32+1) >=
1732 *type_out = BAD_HOSTNAME;
1733 goto failed;
1734 }
1735 if (q != address) {
1736 memmove(address, q, strlen(q) + 1 /* also get \0 */);
1737 }
1738
1739 /* v3 onion address check. */
1740 if (strlen(query) == HS_SERVICE_ADDR_LEN_BASE32) {
1741 *type_out = ONION_V3_HOSTNAME;
1742 if (hs_address_is_valid(query)) {
1743 goto success;
1744 }
1745 goto failed;
1746 }
1747
1748 /* Reaching this point, nothing was recognized. */
1749 *type_out = BAD_HOSTNAME;
1750 goto failed;
1751
1752 success:
1753 return true;
1754 failed:
1755 /* otherwise, return to previous state and return 0 */
1756 *s = '.';
1757 const bool is_onion = (*type_out == ONION_V3_HOSTNAME);
1758 log_warn(LD_APP, "Invalid %shostname %s; rejecting",
1759 is_onion ? "onion " : "",
1760 safe_str_client(address));
1761 if (*type_out == ONION_V3_HOSTNAME) {
1762 *type_out = BAD_HOSTNAME;
1763 }
1764 return false;
1765}
1766
1767/** How many times do we try connecting with an exit configured via
1768 * TrackHostExits before concluding that it won't work any more and trying a
1769 * different one? */
1770#define TRACKHOSTEXITS_RETRIES 5
1771
1772/** Call connection_ap_handshake_rewrite_and_attach() unless a controller
1773 * asked us to leave streams unattached. Return 0 in that case.
1774 *
1775 * See connection_ap_handshake_rewrite_and_attach()'s
1776 * documentation for arguments and return value.
1777 */
1778MOCK_IMPL(int,
1780 origin_circuit_t *circ,
1782{
1783 const or_options_t *options = get_options();
1784
1785 if (options->LeaveStreamsUnattached) {
1787 return 0;
1788 }
1789 return connection_ap_handshake_rewrite_and_attach(conn, circ, cpath);
1790}
1791
1792/* Try to perform any map-based rewriting of the target address in
1793 * <b>conn</b>, filling in the fields of <b>out</b> as we go, and modifying
1794 * conn->socks_request.address as appropriate.
1795 */
1796STATIC void
1797connection_ap_handshake_rewrite(entry_connection_t *conn,
1798 rewrite_result_t *out)
1799{
1800 socks_request_t *socks = conn->socks_request;
1801 const or_options_t *options = get_options();
1802 tor_addr_t addr_tmp;
1803
1804 /* Initialize all the fields of 'out' to reasonable defaults */
1805 out->automap = 0;
1806 out->exit_source = ADDRMAPSRC_NONE;
1807 out->map_expires = TIME_MAX;
1808 out->end_reason = 0;
1809 out->should_close = 0;
1810 out->orig_address[0] = 0;
1811
1812 /* We convert all incoming addresses to lowercase. */
1813 tor_strlower(socks->address);
1814 /* Remember the original address. */
1815 strlcpy(out->orig_address, socks->address, sizeof(out->orig_address));
1816 log_debug(LD_APP,"Client asked for %s:%d",
1817 safe_str_client(socks->address),
1818 socks->port);
1819
1820 /* Check for whether this is a .exit address. By default, those are
1821 * disallowed when they're coming straight from the client, but you're
1822 * allowed to have them in MapAddress commands and so forth. */
1823 if (!strcmpend(socks->address, ".exit")) {
1824 static ratelim_t exit_warning_limit = RATELIM_INIT(60*15);
1825 log_fn_ratelim(&exit_warning_limit, LOG_WARN, LD_APP,
1826 "The \".exit\" notation is disabled in Tor due to "
1827 "security risks.");
1828 control_event_client_status(LOG_WARN, "SOCKS_BAD_HOSTNAME HOSTNAME=%s",
1829 escaped(socks->address));
1830 out->end_reason = END_STREAM_REASON_TORPROTOCOL;
1831 out->should_close = 1;
1832 return;
1833 }
1834
1835 /* Remember the original address so we can tell the user about what
1836 * they actually said, not just what it turned into. */
1837 /* XXX yes, this is the same as out->orig_address above. One is
1838 * in the output, and one is in the connection. */
1839 if (! conn->original_dest_address) {
1840 /* Is the 'if' necessary here? XXXX */
1841 conn->original_dest_address = tor_strdup(conn->socks_request->address);
1842 }
1843
1844 /* First, apply MapAddress and MAPADDRESS mappings. We need to do
1845 * these only for non-reverse lookups, since they don't exist for those.
1846 * We also need to do this before we consider automapping, since we might
1847 * e.g. resolve irc.oftc.net into irconionaddress.onion, at which point
1848 * we'd need to automap it. */
1849 if (socks->command != SOCKS_COMMAND_RESOLVE_PTR) {
1850 const unsigned rewrite_flags = AMR_FLAG_USE_MAPADDRESS;
1851 if (addressmap_rewrite(socks->address, sizeof(socks->address),
1852 rewrite_flags, &out->map_expires, &out->exit_source)) {
1853 control_event_stream_status(conn, STREAM_EVENT_REMAP,
1855 }
1856 }
1857
1858 /* Now see if we need to create or return an existing Hostname->IP
1859 * automapping. Automapping happens when we're asked to resolve a
1860 * hostname, and AutomapHostsOnResolve is set, and the hostname has a
1861 * suffix listed in AutomapHostsSuffixes. It's a handy feature
1862 * that lets you have Tor assign e.g. IPv6 addresses for .onion
1863 * names, and return them safely from DNSPort.
1864 */
1865 if (socks->command == SOCKS_COMMAND_RESOLVE &&
1866 tor_addr_parse(&addr_tmp, socks->address)<0 &&
1867 options->AutomapHostsOnResolve) {
1868 /* Check the suffix... */
1869 out->automap = addressmap_address_should_automap(socks->address, options);
1870 if (out->automap) {
1871 /* If we get here, then we should apply an automapping for this. */
1872 const char *new_addr;
1873 /* We return an IPv4 address by default, or an IPv6 address if we
1874 * are allowed to do so. */
1875 int addr_type = RESOLVED_TYPE_IPV4;
1876 if (conn->socks_request->socks_version != 4) {
1877 if (!conn->entry_cfg.ipv4_traffic ||
1878 (conn->entry_cfg.ipv6_traffic && conn->entry_cfg.prefer_ipv6) ||
1879 conn->entry_cfg.prefer_ipv6_virtaddr)
1880 addr_type = RESOLVED_TYPE_IPV6;
1881 }
1882 /* Okay, register the target address as automapped, and find the new
1883 * address we're supposed to give as a resolve answer. (Return a cached
1884 * value if we've looked up this address before.
1885 */
1887 addr_type, tor_strdup(socks->address));
1888 if (! new_addr) {
1889 log_warn(LD_APP, "Unable to automap address %s",
1890 escaped_safe_str(socks->address));
1891 out->end_reason = END_STREAM_REASON_INTERNAL;
1892 out->should_close = 1;
1893 return;
1894 }
1895 log_info(LD_APP, "Automapping %s to %s",
1897 safe_str_client(new_addr));
1898 strlcpy(socks->address, new_addr, sizeof(socks->address));
1899 }
1900 }
1901
1902 /* Now handle reverse lookups, if they're in the cache. This doesn't
1903 * happen too often, since client-side DNS caching is off by default,
1904 * and very deprecated. */
1905 if (socks->command == SOCKS_COMMAND_RESOLVE_PTR) {
1906 unsigned rewrite_flags = 0;
1907 if (conn->entry_cfg.use_cached_ipv4_answers)
1908 rewrite_flags |= AMR_FLAG_USE_IPV4_DNS;
1909 if (conn->entry_cfg.use_cached_ipv6_answers)
1910 rewrite_flags |= AMR_FLAG_USE_IPV6_DNS;
1911
1912 if (addressmap_rewrite_reverse(socks->address, sizeof(socks->address),
1913 rewrite_flags, &out->map_expires)) {
1914 char *result = tor_strdup(socks->address);
1915 /* remember _what_ is supposed to have been resolved. */
1916 tor_snprintf(socks->address, sizeof(socks->address), "REVERSE[%s]",
1917 out->orig_address);
1918 connection_ap_handshake_socks_resolved(conn, RESOLVED_TYPE_HOSTNAME,
1919 strlen(result), (uint8_t*)result,
1920 -1,
1921 out->map_expires);
1922 tor_free(result);
1923 out->end_reason = END_STREAM_REASON_DONE |
1925 out->should_close = 1;
1926 return;
1927 }
1928
1929 /* Hang on, did we find an answer saying that this is a reverse lookup for
1930 * an internal address? If so, we should reject it if we're configured to
1931 * do so. */
1932 if (options->ClientDNSRejectInternalAddresses) {
1933 /* Don't let clients try to do a reverse lookup on 10.0.0.1. */
1934 tor_addr_t addr;
1935 int ok;
1937 &addr, socks->address, AF_UNSPEC, 1);
1938 if (ok == 1 && tor_addr_is_internal(&addr, 0)) {
1939 connection_ap_handshake_socks_resolved(conn, RESOLVED_TYPE_ERROR,
1940 0, NULL, -1, TIME_MAX);
1941 out->end_reason = END_STREAM_REASON_SOCKSPROTOCOL |
1943 out->should_close = 1;
1944 return;
1945 }
1946 }
1947 }
1948
1949 /* If we didn't automap it before, then this is still the address that
1950 * came straight from the user, mapped according to any
1951 * MapAddress/MAPADDRESS commands. Now apply other mappings,
1952 * including previously registered Automap entries (IP back to
1953 * hostname), TrackHostExits entries, and client-side DNS cache
1954 * entries (if they're turned on).
1955 */
1956 if (socks->command != SOCKS_COMMAND_RESOLVE_PTR &&
1957 !out->automap) {
1958 unsigned rewrite_flags = AMR_FLAG_USE_AUTOMAP | AMR_FLAG_USE_TRACKEXIT;
1959 addressmap_entry_source_t exit_source2;
1960 if (conn->entry_cfg.use_cached_ipv4_answers)
1961 rewrite_flags |= AMR_FLAG_USE_IPV4_DNS;
1962 if (conn->entry_cfg.use_cached_ipv6_answers)
1963 rewrite_flags |= AMR_FLAG_USE_IPV6_DNS;
1964 if (addressmap_rewrite(socks->address, sizeof(socks->address),
1965 rewrite_flags, &out->map_expires, &exit_source2)) {
1966 control_event_stream_status(conn, STREAM_EVENT_REMAP,
1968 }
1969 if (out->exit_source == ADDRMAPSRC_NONE) {
1970 /* If it wasn't a .exit before, maybe it turned into a .exit. Remember
1971 * the original source of a .exit. */
1972 out->exit_source = exit_source2;
1973 }
1974 }
1975
1976 /* Check to see whether we're about to use an address in the virtual
1977 * range without actually having gotten it from an Automap. */
1978 if (!out->automap && address_is_in_virtual_range(socks->address)) {
1979 /* This address was probably handed out by
1980 * client_dns_get_unmapped_address, but the mapping was discarded for some
1981 * reason. Or the user typed in a virtual address range manually. We
1982 * *don't* want to send the address through Tor; that's likely to fail,
1983 * and may leak information.
1984 */
1985 log_warn(LD_APP,"Missing mapping for virtual address '%s'. Refusing.",
1986 safe_str_client(socks->address));
1987 out->end_reason = END_STREAM_REASON_INTERNAL;
1988 out->should_close = 1;
1989 return;
1990 }
1991}
1992
1993/** We just received a SOCKS request in <b>conn</b> to a v3 onion. Start
1994 * connecting to the onion service. */
1995static int
1997 socks_request_t *socks,
1998 origin_circuit_t *circ)
1999{
2000 int retval;
2001 time_t now = approx_time();
2002 connection_t *base_conn = ENTRY_TO_CONN(conn);
2003
2004 /* If .onion address requests are disabled, refuse the request */
2005 if (!conn->entry_cfg.onion_traffic) {
2006 log_warn(LD_APP, "Onion address %s requested from a port with .onion "
2007 "disabled", safe_str_client(socks->address));
2008 connection_mark_unattached_ap(conn, END_STREAM_REASON_ENTRYPOLICY);
2009 return -1;
2010 }
2011
2012 /* Check whether it's RESOLVE or RESOLVE_PTR. We don't handle those
2013 * for hidden service addresses. */
2014 if (SOCKS_COMMAND_IS_RESOLVE(socks->command)) {
2015 /* if it's a resolve request, fail it right now, rather than
2016 * building all the circuits and then realizing it won't work. */
2017 log_warn(LD_APP,
2018 "Resolve requests to hidden services not allowed. Failing.");
2019 connection_ap_handshake_socks_resolved(conn,RESOLVED_TYPE_ERROR,
2020 0,NULL,-1,TIME_MAX);
2021 connection_mark_unattached_ap(conn,
2024 return -1;
2025 }
2026
2027 /* If we were passed a circuit, then we need to fail. .onion addresses
2028 * only work when we launch our own circuits for now. */
2029 if (circ) {
2030 log_warn(LD_CONTROL, "Attachstream to a circuit is not "
2031 "supported for .onion addresses currently. Failing.");
2032 connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
2033 return -1;
2034 }
2035
2036 int descriptor_is_usable = 0;
2037
2038 /* Create HS conn identifier with HS pubkey */
2039 hs_ident_edge_conn_t *hs_conn_ident =
2040 tor_malloc_zero(sizeof(hs_ident_edge_conn_t));
2041
2042 retval = hs_parse_address(socks->address, &hs_conn_ident->identity_pk,
2043 NULL, NULL);
2044 if (retval < 0) {
2045 log_warn(LD_GENERAL, "failed to parse hs address");
2046 tor_free(hs_conn_ident);
2047 return -1;
2048 }
2049 ENTRY_TO_EDGE_CONN(conn)->hs_ident = hs_conn_ident;
2050
2051 /* Check the v3 desc cache */
2052 const hs_descriptor_t *cached_desc = NULL;
2053 unsigned int refetch_desc = 0;
2054 cached_desc = hs_cache_lookup_as_client(&hs_conn_ident->identity_pk);
2055 if (cached_desc) {
2056 descriptor_is_usable =
2058 cached_desc);
2059 /* Check if PoW parameters have expired. If yes, the descriptor is
2060 * unusable. */
2061 if (cached_desc->encrypted_data.pow_params) {
2062 if (cached_desc->encrypted_data.pow_params->expiration_time <
2063 approx_time()) {
2064 log_info(LD_REND, "Descriptor PoW parameters have expired.");
2065 descriptor_is_usable = 0;
2066 } else {
2067 /* Mark that the connection is to an HS with PoW defenses on. */
2068 conn->hs_with_pow_conn = 1;
2069 }
2070 }
2071
2072 log_info(LD_GENERAL, "Found %s descriptor in cache for %s. %s.",
2073 (descriptor_is_usable) ? "usable" : "unusable",
2074 safe_str_client(socks->address),
2075 (descriptor_is_usable) ? "Not fetching." : "Refetching.");
2076 } else {
2077 /* We couldn't find this descriptor; we should look it up. */
2078 log_info(LD_REND, "No descriptor found in our cache for %s. Fetching.",
2079 safe_str_client(socks->address));
2080 refetch_desc = 1;
2081 }
2082
2083 /* Help predict that we'll want to do hidden service circuits in the
2084 * future. We're not sure if it will need a stable circuit yet, but
2085 * we know we'll need *something*. */
2086 rep_hist_note_used_internal(now, 0, 1);
2087
2088 /* Now we have a descriptor but is it usable or not? If not, refetch.
2089 * Also, a fetch could have been requested if the onion address was not
2090 * found in the cache previously. */
2091 if (refetch_desc || !descriptor_is_usable) {
2092 edge_connection_t *edge_conn = ENTRY_TO_EDGE_CONN(conn);
2095 tor_assert(edge_conn->hs_ident);
2096 /* Attempt to fetch the hsv3 descriptor. Check the retval to see how it
2097 * went and act accordingly. */
2098 int ret = hs_client_refetch_hsdesc(&edge_conn->hs_ident->identity_pk);
2099 switch (ret) {
2101 /* Keeping the connection in descriptor wait state is fine because
2102 * once we get enough dirinfo or a new live consensus, the HS client
2103 * subsystem is notified and every connection in that state will
2104 * trigger a fetch for the service key. */
2108 return 0;
2112 /* Can't proceed further and better close the SOCKS request. */
2113 return -1;
2114 }
2115 }
2116
2117 /* We have the descriptor! So launch a connection to the HS. */
2118 log_info(LD_REND, "Descriptor is here. Great.");
2119
2120 base_conn->state = AP_CONN_STATE_CIRCUIT_WAIT;
2121 /* We'll try to attach it at the next event loop, or whenever
2122 * we call connection_ap_attach_pending() */
2123 connection_ap_mark_as_pending_circuit(conn);
2124 return 0;
2125}
2126
2127/** Connection <b>conn</b> just finished its socks handshake, or the
2128 * controller asked us to take care of it. If <b>circ</b> is defined,
2129 * then that's where we'll want to attach it. Otherwise we have to
2130 * figure it out ourselves.
2131 *
2132 * First, parse whether it's a .exit address, remap it, and so on. Then
2133 * if it's for a general circuit, try to attach it to a circuit (or launch
2134 * one as needed), else if it's for a rendezvous circuit, fetch a
2135 * rendezvous descriptor first (or attach/launch a circuit if the
2136 * rendezvous descriptor is already here and fresh enough).
2137 *
2138 * The stream will exit from the hop
2139 * indicated by <b>cpath</b>, or from the last hop in circ's cpath if
2140 * <b>cpath</b> is NULL.
2141 */
2142int
2144 origin_circuit_t *circ,
2145 crypt_path_t *cpath)
2146{
2147 socks_request_t *socks = conn->socks_request;
2148 const or_options_t *options = get_options();
2149 connection_t *base_conn = ENTRY_TO_CONN(conn);
2150 time_t now = time(NULL);
2151 rewrite_result_t rr;
2152
2153 /* First we'll do the rewrite part. Let's see if we get a reasonable
2154 * answer.
2155 */
2156 memset(&rr, 0, sizeof(rr));
2157 connection_ap_handshake_rewrite(conn,&rr);
2158
2159 if (rr.should_close) {
2160 /* connection_ap_handshake_rewrite told us to close the connection:
2161 * either because it sent back an answer, or because it sent back an
2162 * error */
2163 connection_mark_unattached_ap(conn, rr.end_reason);
2164 if (END_STREAM_REASON_DONE == (rr.end_reason & END_STREAM_REASON_MASK))
2165 return 0;
2166 else
2167 return -1;
2168 }
2169
2170 const time_t map_expires = rr.map_expires;
2171 const int automap = rr.automap;
2172 const addressmap_entry_source_t exit_source = rr.exit_source;
2173
2174 /* Now see whether the hostname is bogus. This could happen because of an
2175 * onion hostname whose format we don't recognize. */
2176 hostname_type_t addresstype;
2177 if (!parse_extended_hostname(socks->address, &addresstype)) {
2178 control_event_client_status(LOG_WARN, "SOCKS_BAD_HOSTNAME HOSTNAME=%s",
2179 escaped(socks->address));
2180 if (addresstype == BAD_HOSTNAME) {
2181 conn->socks_request->socks_extended_error_code = SOCKS5_HS_BAD_ADDRESS;
2182 }
2183 connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
2184 return -1;
2185 }
2186
2187 /* If this is a .exit hostname, strip off the .name.exit part, and
2188 * see whether we're willing to connect there, and otherwise handle the
2189 * .exit address.
2190 *
2191 * We'll set chosen_exit_name and/or close the connection as appropriate.
2192 */
2193 if (addresstype == EXIT_HOSTNAME) {
2194 /* If StrictNodes is not set, then .exit overrides ExcludeNodes but
2195 * not ExcludeExitNodes. */
2196 routerset_t *excludeset = options->StrictNodes ?
2197 options->ExcludeExitNodesUnion_ : options->ExcludeExitNodes;
2198 const node_t *node = NULL;
2199
2200 /* If this .exit was added by an AUTOMAP, then it came straight from
2201 * a user. That's not safe. */
2202 if (exit_source == ADDRMAPSRC_AUTOMAP) {
2203 /* Whoops; this one is stale. It must have gotten added earlier?
2204 * (Probably this is not possible, since AllowDotExit no longer
2205 * exists.) */
2206 log_warn(LD_APP,"Stale automapped address for '%s.exit'. Refusing.",
2207 safe_str_client(socks->address));
2208 control_event_client_status(LOG_WARN, "SOCKS_BAD_HOSTNAME HOSTNAME=%s",
2209 escaped(socks->address));
2210 connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
2212 return -1;
2213 }
2214
2215 /* Double-check to make sure there are no .exits coming from
2216 * impossible/weird sources. */
2217 if (exit_source == ADDRMAPSRC_DNS || exit_source == ADDRMAPSRC_NONE) {
2218 /* It shouldn't be possible to get a .exit address from any of these
2219 * sources. */
2220 log_warn(LD_BUG,"Address '%s.exit', with impossible source for the "
2221 ".exit part. Refusing.",
2222 safe_str_client(socks->address));
2223 control_event_client_status(LOG_WARN, "SOCKS_BAD_HOSTNAME HOSTNAME=%s",
2224 escaped(socks->address));
2225 connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
2226 return -1;
2227 }
2228
2229 tor_assert(!automap);
2230
2231 /* Now, find the character before the .(name) part.
2232 * (The ".exit" part got stripped off by "parse_extended_hostname").
2233 *
2234 * We're going to put the exit name into conn->chosen_exit_name, and
2235 * look up a node correspondingly. */
2236 char *s = strrchr(socks->address,'.');
2237 if (s) {
2238 /* The address was of the form "(stuff).(name).exit */
2239 if (s[1] != '\0') {
2240 /* Looks like a real .exit one. */
2241 conn->chosen_exit_name = tor_strdup(s+1);
2242 node = node_get_by_nickname(conn->chosen_exit_name, 0);
2243
2244 if (exit_source == ADDRMAPSRC_TRACKEXIT) {
2245 /* We 5 tries before it expires the addressmap */
2247 }
2248 *s = 0;
2249 } else {
2250 /* Oops, the address was (stuff)..exit. That's not okay. */
2251 log_warn(LD_APP,"Malformed exit address '%s.exit'. Refusing.",
2252 safe_str_client(socks->address));
2253 control_event_client_status(LOG_WARN, "SOCKS_BAD_HOSTNAME HOSTNAME=%s",
2254 escaped(socks->address));
2255 connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
2256 return -1;
2257 }
2258 } else {
2259 /* It looks like they just asked for "foo.exit". That's a special
2260 * form that means (foo's address).foo.exit. */
2261
2262 conn->chosen_exit_name = tor_strdup(socks->address);
2263 node = node_get_by_nickname(conn->chosen_exit_name, 0);
2264 if (node) {
2265 *socks->address = 0;
2266 node_get_address_string(node, socks->address, sizeof(socks->address));
2267 }
2268 }
2269
2270 /* Now make sure that the chosen exit exists... */
2271 if (!node) {
2272 log_warn(LD_APP,
2273 "Unrecognized relay in exit address '%s.exit'. Refusing.",
2274 safe_str_client(socks->address));
2275 connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
2276 return -1;
2277 }
2278 /* ...and make sure that it isn't excluded. */
2279 if (routerset_contains_node(excludeset, node)) {
2280 log_warn(LD_APP,
2281 "Excluded relay in exit address '%s.exit'. Refusing.",
2282 safe_str_client(socks->address));
2283 connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
2284 return -1;
2285 }
2286 /* XXXX-1090 Should we also allow foo.bar.exit if ExitNodes is set and
2287 Bar is not listed in it? I say yes, but our revised manpage branch
2288 implies no. */
2289 }
2290
2291 /* Now, we handle everything that isn't a .onion address. */
2292 if (addresstype != ONION_V3_HOSTNAME) {
2293 /* Not a hidden-service request. It's either a hostname or an IP,
2294 * possibly with a .exit that we stripped off. We're going to check
2295 * if we're allowed to connect/resolve there, and then launch the
2296 * appropriate request. */
2297
2298 /* Check for funny characters in the address. */
2299 if (address_is_invalid_destination(socks->address, 1)) {
2300 control_event_client_status(LOG_WARN, "SOCKS_BAD_HOSTNAME HOSTNAME=%s",
2301 escaped(socks->address));
2302 log_warn(LD_APP,
2303 "Destination '%s' seems to be an invalid hostname. Failing.",
2304 safe_str_client(socks->address));
2305 connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
2306 return -1;
2307 }
2308
2309 /* socks->address is a non-onion hostname or IP address.
2310 * If we can't do any non-onion requests, refuse the connection.
2311 * If we have a hostname but can't do DNS, refuse the connection.
2312 * If we have an IP address, but we can't use that address family,
2313 * refuse the connection.
2314 *
2315 * If we can do DNS requests, and we can use at least one address family,
2316 * then we have to resolve the address first. Then we'll know if it
2317 * resolves to a usable address family. */
2318
2319 /* First, check if all non-onion traffic is disabled */
2320 if (!conn->entry_cfg.dns_request && !conn->entry_cfg.ipv4_traffic
2321 && !conn->entry_cfg.ipv6_traffic) {
2322 log_warn(LD_APP, "Refusing to connect to non-hidden-service hostname "
2323 "or IP address %s because Port has OnionTrafficOnly set (or "
2324 "NoDNSRequest, NoIPv4Traffic, and NoIPv6Traffic).",
2325 safe_str_client(socks->address));
2326 connection_mark_unattached_ap(conn, END_STREAM_REASON_ENTRYPOLICY);
2327 return -1;
2328 }
2329
2330 /* Then check if we have a hostname or IP address, and whether DNS or
2331 * the IP address family are permitted. Reject if not. */
2332 tor_addr_t dummy_addr;
2333 int socks_family = tor_addr_parse(&dummy_addr, socks->address);
2334 /* family will be -1 for a non-onion hostname that's not an IP */
2335 if (socks_family == -1) {
2336 if (!conn->entry_cfg.dns_request) {
2337 log_warn(LD_APP, "Refusing to connect to hostname %s "
2338 "because Port has NoDNSRequest set.",
2339 safe_str_client(socks->address));
2340 connection_mark_unattached_ap(conn, END_STREAM_REASON_ENTRYPOLICY);
2341 return -1;
2342 }
2343 } else if (socks_family == AF_INET) {
2344 if (!conn->entry_cfg.ipv4_traffic) {
2345 log_warn(LD_APP, "Refusing to connect to IPv4 address %s because "
2346 "Port has NoIPv4Traffic set.",
2347 safe_str_client(socks->address));
2348 connection_mark_unattached_ap(conn, END_STREAM_REASON_ENTRYPOLICY);
2349 return -1;
2350 }
2351 } else if (socks_family == AF_INET6) {
2352 if (!conn->entry_cfg.ipv6_traffic) {
2353 log_warn(LD_APP, "Refusing to connect to IPv6 address %s because "
2354 "Port has NoIPv6Traffic set.",
2355 safe_str_client(socks->address));
2356 connection_mark_unattached_ap(conn, END_STREAM_REASON_ENTRYPOLICY);
2357 return -1;
2358 }
2359 } else {
2360 tor_assert_nonfatal_unreached_once();
2361 }
2362
2363 /* See if this is a hostname lookup that we can answer immediately.
2364 * (For example, an attempt to look up the IP address for an IP address.)
2365 */
2366 if (socks->command == SOCKS_COMMAND_RESOLVE) {
2367 tor_addr_t answer;
2368 /* Reply to resolves immediately if we can. */
2369 if (tor_addr_parse(&answer, socks->address) >= 0) {/* is it an IP? */
2370 /* remember _what_ is supposed to have been resolved. */
2371 strlcpy(socks->address, rr.orig_address, sizeof(socks->address));
2373 map_expires);
2374 connection_mark_unattached_ap(conn,
2375 END_STREAM_REASON_DONE |
2377 return 0;
2378 }
2379 tor_assert(!automap);
2380 rep_hist_note_used_resolve(now); /* help predict this next time */
2381 } else if (socks->command == SOCKS_COMMAND_CONNECT) {
2382 /* Now see if this is a connect request that we can reject immediately */
2383
2384 tor_assert(!automap);
2385 /* Don't allow connections to port 0. */
2386 if (socks->port == 0) {
2387 log_notice(LD_APP,"Application asked to connect to port 0. Refusing.");
2388 connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
2389 return -1;
2390 }
2391 /* You can't make connections to internal addresses, by default.
2392 * Exceptions are begindir requests (where the address is meaningless),
2393 * or cases where you've hand-configured a particular exit, thereby
2394 * making the local address meaningful. */
2395 if (options->ClientRejectInternalAddresses &&
2396 !conn->use_begindir && !conn->chosen_exit_name && !circ) {
2397 /* If we reach this point then we don't want to allow internal
2398 * addresses. Check if we got one. */
2399 tor_addr_t addr;
2400 if (tor_addr_hostname_is_local(socks->address) ||
2401 (tor_addr_parse(&addr, socks->address) >= 0 &&
2402 tor_addr_is_internal(&addr, 0))) {
2403 /* If this is an explicit private address with no chosen exit node,
2404 * then we really don't want to try to connect to it. That's
2405 * probably an error. */
2406 if (conn->is_transparent_ap) {
2407#define WARN_INTRVL_LOOP 300
2408 static ratelim_t loop_warn_limit = RATELIM_INIT(WARN_INTRVL_LOOP);
2409 char *m;
2410 if ((m = rate_limit_log(&loop_warn_limit, approx_time()))) {
2411 log_warn(LD_NET,
2412 "Rejecting request for anonymous connection to private "
2413 "address %s on a TransPort or NATDPort. Possible loop "
2414 "in your NAT rules?%s", safe_str_client(socks->address),
2415 m);
2416 tor_free(m);
2417 }
2418 } else {
2419#define WARN_INTRVL_PRIV 300
2420 static ratelim_t priv_warn_limit = RATELIM_INIT(WARN_INTRVL_PRIV);
2421 char *m;
2422 if ((m = rate_limit_log(&priv_warn_limit, approx_time()))) {
2423 log_warn(LD_NET,
2424 "Rejecting SOCKS request for anonymous connection to "
2425 "private address %s.%s",
2426 safe_str_client(socks->address),m);
2427 tor_free(m);
2428 }
2429 }
2430 connection_mark_unattached_ap(conn, END_STREAM_REASON_PRIVATE_ADDR);
2431 return -1;
2432 }
2433 } /* end "if we should check for internal addresses" */
2434
2435 /* Okay. We're still doing a CONNECT, and it wasn't a private
2436 * address. Here we do special handling for literal IP addresses,
2437 * to see if we should reject this preemptively, and to set up
2438 * fields in conn->entry_cfg to tell the exit what AF we want. */
2439 {
2440 tor_addr_t addr;
2441 /* XXX Duplicate call to tor_addr_parse. */
2442 if (tor_addr_parse(&addr, socks->address) >= 0) {
2443 /* If we reach this point, it's an IPv4 or an IPv6 address. */
2444 sa_family_t family = tor_addr_family(&addr);
2445
2446 if ((family == AF_INET && ! conn->entry_cfg.ipv4_traffic) ||
2447 (family == AF_INET6 && ! conn->entry_cfg.ipv6_traffic)) {
2448 /* You can't do an IPv4 address on a v6-only socks listener,
2449 * or vice versa. */
2450 log_warn(LD_NET, "Rejecting SOCKS request for an IP address "
2451 "family that this listener does not support.");
2452 connection_mark_unattached_ap(conn, END_STREAM_REASON_ENTRYPOLICY);
2453 return -1;
2454 } else if (family == AF_INET6 && socks->socks_version == 4) {
2455 /* You can't make a socks4 request to an IPv6 address. Socks4
2456 * doesn't support that. */
2457 log_warn(LD_NET, "Rejecting SOCKS4 request for an IPv6 address.");
2458 connection_mark_unattached_ap(conn, END_STREAM_REASON_ENTRYPOLICY);
2459 return -1;
2460 } else if (socks->socks_version == 4 &&
2461 !conn->entry_cfg.ipv4_traffic) {
2462 /* You can't do any kind of Socks4 request when IPv4 is forbidden.
2463 *
2464 * XXX raise this check outside the enclosing block? */
2465 log_warn(LD_NET, "Rejecting SOCKS4 request on a listener with "
2466 "no IPv4 traffic supported.");
2467 connection_mark_unattached_ap(conn, END_STREAM_REASON_ENTRYPOLICY);
2468 return -1;
2469 } else if (family == AF_INET6) {
2470 /* Tell the exit: we won't accept any ipv4 connection to an IPv6
2471 * address. */
2472 conn->entry_cfg.ipv4_traffic = 0;
2473 } else if (family == AF_INET) {
2474 /* Tell the exit: we won't accept any ipv6 connection to an IPv4
2475 * address. */
2476 conn->entry_cfg.ipv6_traffic = 0;
2477 }
2478
2479 /* Next, yet another check: we know it's a direct IP address. Is it
2480 * the IP address of a known relay and its ORPort, or of a directory
2481 * authority and its OR or Dir Port? If so, and if a consensus param
2482 * says to, then exit relays will refuse this request (see ticket
2483 * 2667 for details). Let's just refuse it locally right now, to
2484 * save time and network load but also to give the user a more
2485 * useful log message. */
2487 nodelist_reentry_contains(&addr, socks->port)) {
2488 log_warn(LD_APP, "Not attempting connection to %s:%d because "
2489 "the network would reject it. Are you trying to send "
2490 "Tor traffic over Tor? This traffic can be harmful to "
2491 "the Tor network. If you really need it, try using "
2492 "a bridge as a workaround.",
2493 safe_str_client(socks->address), socks->port);
2494 connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
2495 return -1;
2496 }
2497 }
2498 }
2499
2500 /* we never allow IPv6 answers on socks4. (TODO: Is this smart?) */
2501 if (socks->socks_version == 4)
2502 conn->entry_cfg.ipv6_traffic = 0;
2503
2504 /* Still handling CONNECT. Now, check for exit enclaves. (Which we
2505 * don't do on BEGIN_DIR, or when there is a chosen exit.)
2506 *
2507 * TODO: Should we remove this? Exit enclaves are nutty and don't
2508 * work very well
2509 */
2510 if (!conn->use_begindir && !conn->chosen_exit_name && !circ) {
2511 /* see if we can find a suitable enclave exit */
2512 const node_t *r =
2514 if (r) {
2515 log_info(LD_APP,
2516 "Redirecting address %s to exit at enclave router %s",
2517 safe_str_client(socks->address), node_describe(r));
2518 /* use the hex digest, not nickname, in case there are two
2519 routers with this nickname */
2520 conn->chosen_exit_name =
2521 tor_strdup(hex_str(r->identity, DIGEST_LEN));
2522 conn->chosen_exit_optional = 1;
2523 }
2524 }
2525
2526 /* Still handling CONNECT: warn or reject if it's using a dangerous
2527 * port. */
2528 if (!conn->use_begindir && !conn->chosen_exit_name && !circ)
2529 if (consider_plaintext_ports(conn, socks->port) < 0)
2530 return -1;
2531
2532 /* Remember the port so that we will predict that more requests
2533 there will happen in the future. */
2534 if (!conn->use_begindir) {
2535 /* help predict this next time */
2536 rep_hist_note_used_port(now, socks->port);
2537 }
2538 } else if (socks->command == SOCKS_COMMAND_RESOLVE_PTR) {
2539 rep_hist_note_used_resolve(now); /* help predict this next time */
2540 /* no extra processing needed */
2541 } else {
2542 /* We should only be doing CONNECT, RESOLVE, or RESOLVE_PTR! */
2544 }
2545
2546 /* Okay. At this point we've set chosen_exit_name if needed, rewritten the
2547 * address, and decided not to reject it for any number of reasons. Now
2548 * mark the connection as waiting for a circuit, and try to attach it!
2549 */
2550 base_conn->state = AP_CONN_STATE_CIRCUIT_WAIT;
2551
2552 /* If we were given a circuit to attach to, try to attach. Otherwise,
2553 * try to find a good one and attach to that. */
2554 int rv;
2555 if (circ) {
2556 rv = connection_ap_handshake_attach_chosen_circuit(conn, circ, cpath);
2557 } else {
2558 /* We'll try to attach it at the next event loop, or whenever
2559 * we call connection_ap_attach_pending() */
2560 connection_ap_mark_as_pending_circuit(conn);
2561 rv = 0;
2562 }
2563
2564 /* If the above function returned 0 then we're waiting for a circuit.
2565 * if it returned 1, we're attached. Both are okay. But if it returned
2566 * -1, there was an error, so make sure the connection is marked, and
2567 * return -1. */
2568 if (rv < 0) {
2569 if (!base_conn->marked_for_close)
2570 connection_mark_unattached_ap(conn, END_STREAM_REASON_CANT_ATTACH);
2571 return -1;
2572 }
2573
2574 return 0;
2575 } else {
2576 /* If we get here, it's a request for a .onion address! */
2577 tor_assert(addresstype == ONION_V3_HOSTNAME);
2578 tor_assert(!automap);
2579 return connection_ap_handle_onion(conn, socks, circ);
2580 }
2581
2582 return 0; /* unreached but keeps the compiler happy */
2583}
2584
2585#ifdef TRANS_PF
2586static int pf_socket = -1;
2587int
2588get_pf_socket(void)
2589{
2590 int pf;
2591 /* This should be opened before dropping privileges. */
2592 if (pf_socket >= 0)
2593 return pf_socket;
2594
2595#if defined(OpenBSD)
2596 /* only works on OpenBSD */
2597 pf = tor_open_cloexec("/dev/pf", O_RDONLY, 0);
2598#else
2599 /* works on NetBSD and FreeBSD */
2600 pf = tor_open_cloexec("/dev/pf", O_RDWR, 0);
2601#endif /* defined(OpenBSD) */
2602
2603 if (pf < 0) {
2604 log_warn(LD_NET, "open(\"/dev/pf\") failed: %s", strerror(errno));
2605 return -1;
2606 }
2607
2608 pf_socket = pf;
2609 return pf_socket;
2610}
2611#endif /* defined(TRANS_PF) */
2612
2613#if defined(TRANS_NETFILTER) || defined(TRANS_PF) || \
2614 defined(TRANS_TPROXY)
2615/** Try fill in the address of <b>req</b> from the socket configured
2616 * with <b>conn</b>. */
2617static int
2618destination_from_socket(entry_connection_t *conn, socks_request_t *req)
2619{
2620 struct sockaddr_storage orig_dst;
2621 socklen_t orig_dst_len = sizeof(orig_dst);
2622 tor_addr_t addr;
2623
2624#ifdef TRANS_TPROXY
2625 if (get_options()->TransProxyType_parsed == TPT_TPROXY) {
2626 if (getsockname(ENTRY_TO_CONN(conn)->s, (struct sockaddr*)&orig_dst,
2627 &orig_dst_len) < 0) {
2628 int e = tor_socket_errno(ENTRY_TO_CONN(conn)->s);
2629 log_warn(LD_NET, "getsockname() failed: %s", tor_socket_strerror(e));
2630 return -1;
2631 }
2632 goto done;
2633 }
2634#endif /* defined(TRANS_TPROXY) */
2635
2636#ifdef TRANS_NETFILTER
2637 int rv = -1;
2638 switch (ENTRY_TO_CONN(conn)->socket_family) {
2639#ifdef TRANS_NETFILTER_IPV4
2640 case AF_INET:
2641 rv = getsockopt(ENTRY_TO_CONN(conn)->s, SOL_IP, SO_ORIGINAL_DST,
2642 (struct sockaddr*)&orig_dst, &orig_dst_len);
2643 break;
2644#endif /* defined(TRANS_NETFILTER_IPV4) */
2645#ifdef TRANS_NETFILTER_IPV6
2646 case AF_INET6:
2647 rv = getsockopt(ENTRY_TO_CONN(conn)->s, SOL_IPV6, IP6T_SO_ORIGINAL_DST,
2648 (struct sockaddr*)&orig_dst, &orig_dst_len);
2649 break;
2650#endif /* defined(TRANS_NETFILTER_IPV6) */
2651 default:
2652 log_warn(LD_BUG, "Received transparent data from an unsupported "
2653 "socket family %d",
2654 ENTRY_TO_CONN(conn)->socket_family);
2655 return -1;
2656 }
2657 if (rv < 0) {
2658 int e = tor_socket_errno(ENTRY_TO_CONN(conn)->s);
2659 log_warn(LD_NET, "getsockopt() failed: %s", tor_socket_strerror(e));
2660 return -1;
2661 }
2662 goto done;
2663#elif defined(TRANS_PF)
2664 if (getsockname(ENTRY_TO_CONN(conn)->s, (struct sockaddr*)&orig_dst,
2665 &orig_dst_len) < 0) {
2666 int e = tor_socket_errno(ENTRY_TO_CONN(conn)->s);
2667 log_warn(LD_NET, "getsockname() failed: %s", tor_socket_strerror(e));
2668 return -1;
2669 }
2670 goto done;
2671#else
2672 (void)conn;
2673 (void)req;
2674 log_warn(LD_BUG, "Unable to determine destination from socket.");
2675 return -1;
2676#endif /* defined(TRANS_NETFILTER) || ... */
2677
2678 done:
2679 tor_addr_from_sockaddr(&addr, (struct sockaddr*)&orig_dst, &req->port);
2680 tor_addr_to_str(req->address, &addr, sizeof(req->address), 1);
2681
2682 return 0;
2683}
2684#endif /* defined(TRANS_NETFILTER) || defined(TRANS_PF) || ... */
2685
2686#ifdef TRANS_PF
2687static int
2688destination_from_pf(entry_connection_t *conn, socks_request_t *req)
2689{
2690 struct sockaddr_storage proxy_addr;
2691 socklen_t proxy_addr_len = sizeof(proxy_addr);
2692 struct sockaddr *proxy_sa = (struct sockaddr*) &proxy_addr;
2693 struct pfioc_natlook pnl;
2694 tor_addr_t addr;
2695 int pf = -1;
2696
2697 if (getsockname(ENTRY_TO_CONN(conn)->s, (struct sockaddr*)&proxy_addr,
2698 &proxy_addr_len) < 0) {
2699 int e = tor_socket_errno(ENTRY_TO_CONN(conn)->s);
2700 log_warn(LD_NET, "getsockname() to determine transocks destination "
2701 "failed: %s", tor_socket_strerror(e));
2702 return -1;
2703 }
2704
2705#ifdef __FreeBSD__
2706 if (get_options()->TransProxyType_parsed == TPT_IPFW) {
2707 /* ipfw(8) is used and in this case getsockname returned the original
2708 destination */
2709 if (tor_addr_from_sockaddr(&addr, proxy_sa, &req->port) < 0) {
2711 return -1;
2712 }
2713
2714 tor_addr_to_str(req->address, &addr, sizeof(req->address), 0);
2715
2716 return 0;
2717 }
2718#endif /* defined(__FreeBSD__) */
2719
2720 memset(&pnl, 0, sizeof(pnl));
2721 pnl.proto = IPPROTO_TCP;
2722 pnl.direction = PF_OUT;
2723 if (proxy_sa->sa_family == AF_INET) {
2724 struct sockaddr_in *sin = (struct sockaddr_in *)proxy_sa;
2725 pnl.af = AF_INET;
2726 pnl.saddr.v4.s_addr = tor_addr_to_ipv4n(&ENTRY_TO_CONN(conn)->addr);
2727 pnl.sport = htons(ENTRY_TO_CONN(conn)->port);
2728 pnl.daddr.v4.s_addr = sin->sin_addr.s_addr;
2729 pnl.dport = sin->sin_port;
2730 } else if (proxy_sa->sa_family == AF_INET6) {
2731 struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *)proxy_sa;
2732 pnl.af = AF_INET6;
2733 const struct in6_addr *dest_in6 =
2734 tor_addr_to_in6(&ENTRY_TO_CONN(conn)->addr);
2735 if (BUG(!dest_in6))
2736 return -1;
2737 memcpy(&pnl.saddr.v6, dest_in6, sizeof(struct in6_addr));
2738 pnl.sport = htons(ENTRY_TO_CONN(conn)->port);
2739 memcpy(&pnl.daddr.v6, &sin6->sin6_addr, sizeof(struct in6_addr));
2740 pnl.dport = sin6->sin6_port;
2741 } else {
2742 log_warn(LD_NET, "getsockname() gave an unexpected address family (%d)",
2743 (int)proxy_sa->sa_family);
2744 return -1;
2745 }
2746
2747 pf = get_pf_socket();
2748 if (pf<0)
2749 return -1;
2750
2751 if (ioctl(pf, DIOCNATLOOK, &pnl) < 0) {
2752 log_warn(LD_NET, "ioctl(DIOCNATLOOK) failed: %s", strerror(errno));
2753 return -1;
2754 }
2755
2756 if (pnl.af == AF_INET) {
2757 tor_addr_from_ipv4n(&addr, pnl.rdaddr.v4.s_addr);
2758 } else if (pnl.af == AF_INET6) {
2759 tor_addr_from_in6(&addr, &pnl.rdaddr.v6);
2760 } else {
2762 return -1;
2763 }
2764
2765 tor_addr_to_str(req->address, &addr, sizeof(req->address), 1);
2766 req->port = ntohs(pnl.rdport);
2767
2768 return 0;
2769}
2770#endif /* defined(TRANS_PF) */
2771
2772/** Fetch the original destination address and port from a
2773 * system-specific interface and put them into a
2774 * socks_request_t as if they came from a socks request.
2775 *
2776 * Return -1 if an error prevents fetching the destination,
2777 * else return 0.
2778 */
2779static int
2781 socks_request_t *req)
2782{
2783#ifdef TRANS_NETFILTER
2784 return destination_from_socket(conn, req);
2785#elif defined(TRANS_PF)
2786 const or_options_t *options = get_options();
2787
2788 if (options->TransProxyType_parsed == TPT_PF_DIVERT)
2789 return destination_from_socket(conn, req);
2790
2791 if (options->TransProxyType_parsed == TPT_DEFAULT ||
2792 options->TransProxyType_parsed == TPT_IPFW)
2793 return destination_from_pf(conn, req);
2794
2795 (void)conn;
2796 (void)req;
2797 log_warn(LD_BUG, "Proxy destination determination mechanism %s unknown.",
2798 options->TransProxyType);
2799 return -1;
2800#else
2801 (void)conn;
2802 (void)req;
2803 log_warn(LD_BUG, "Called connection_ap_get_original_destination, but no "
2804 "transparent proxy method was configured.");
2805 return -1;
2806#endif /* defined(TRANS_NETFILTER) || ... */
2807}
2808
2809/** connection_edge_process_inbuf() found a conn in state
2810 * socks_wait. See if conn->inbuf has the right bytes to proceed with
2811 * the socks handshake.
2812 *
2813 * If the handshake is complete, send it to
2814 * connection_ap_handshake_rewrite_and_attach().
2815 *
2816 * Return -1 if an unexpected error with conn occurs (and mark it for close),
2817 * else return 0.
2818 */
2819static int
2821{
2822 socks_request_t *socks;
2823 int sockshere;
2824 const or_options_t *options = get_options();
2825 int had_reply = 0;
2826 connection_t *base_conn = ENTRY_TO_CONN(conn);
2827
2828 tor_assert(conn);
2829 tor_assert(base_conn->type == CONN_TYPE_AP);
2832 socks = conn->socks_request;
2833
2834 log_debug(LD_APP,"entered.");
2835
2836 sockshere = fetch_from_buf_socks(base_conn->inbuf, socks,
2837 options->TestSocks, options->SafeSocks);
2838
2839 if (socks->replylen) {
2840 had_reply = 1;
2841 connection_buf_add((const char*)socks->reply, socks->replylen,
2842 base_conn);
2843 socks->replylen = 0;
2844 if (sockshere == -1) {
2845 /* An invalid request just got a reply, no additional
2846 * one is necessary. */
2847 socks->has_finished = 1;
2848 }
2849 }
2850
2851 if (sockshere == 0) {
2852 log_debug(LD_APP,"socks handshake not all here yet.");
2853 return 0;
2854 } else if (sockshere == -1) {
2855 if (!had_reply) {
2856 log_warn(LD_APP,"Fetching socks handshake failed. Closing.");
2859 }
2860 connection_mark_unattached_ap(conn,
2863 return -1;
2864 } /* else socks handshake is done, continue processing */
2865
2866 if (SOCKS_COMMAND_IS_CONNECT(socks->command))
2867 control_event_stream_status(conn, STREAM_EVENT_NEW, 0);
2868 else
2869 control_event_stream_status(conn, STREAM_EVENT_NEW_RESOLVE, 0);
2870
2871 return connection_ap_rewrite_and_attach_if_allowed(conn, NULL, NULL);
2872}
2873
2874/** connection_init_accepted_conn() found a new trans AP conn.
2875 * Get the original destination and send it to
2876 * connection_ap_handshake_rewrite_and_attach().
2877 *
2878 * Return -1 if an unexpected error with conn (and it should be marked
2879 * for close), else return 0.
2880 */
2881int
2883{
2884 socks_request_t *socks;
2885
2886 tor_assert(conn);
2888 socks = conn->socks_request;
2889
2890 /* pretend that a socks handshake completed so we don't try to
2891 * send a socks reply down a transparent conn */
2893 socks->has_finished = 1;
2894
2895 log_debug(LD_APP,"entered.");
2896
2897 if (connection_ap_get_original_destination(conn, socks) < 0) {
2898 log_warn(LD_APP,"Fetching original destination failed. Closing.");
2899 connection_mark_unattached_ap(conn,
2901 return -1;
2902 }
2903 /* we have the original destination */
2904
2905 control_event_stream_status(conn, STREAM_EVENT_NEW, 0);
2906
2907 return connection_ap_rewrite_and_attach_if_allowed(conn, NULL, NULL);
2908}
2909
2910/** connection_edge_process_inbuf() found a conn in state natd_wait. See if
2911 * conn->inbuf has the right bytes to proceed. See FreeBSD's libalias(3) and
2912 * ProxyEncodeTcpStream() in src/lib/libalias/alias_proxy.c for the encoding
2913 * form of the original destination.
2914 *
2915 * If the original destination is complete, send it to
2916 * connection_ap_handshake_rewrite_and_attach().
2917 *
2918 * Return -1 if an unexpected error with conn (and it should be marked
2919 * for close), else return 0.
2920 */
2921static int
2923{
2924 char tmp_buf[36], *tbuf, *daddr;
2925 size_t tlen = 30;
2926 int err, port_ok;
2927 socks_request_t *socks;
2928
2929 tor_assert(conn);
2932 socks = conn->socks_request;
2933
2934 log_debug(LD_APP,"entered.");
2935
2936 /* look for LF-terminated "[DEST ip_addr port]"
2937 * where ip_addr is a dotted-quad and port is in string form */
2938 err = connection_buf_get_line(ENTRY_TO_CONN(conn), tmp_buf, &tlen);
2939 if (err == 0)
2940 return 0;
2941 if (err < 0) {
2942 log_warn(LD_APP,"NATD handshake failed (DEST too long). Closing");
2943 connection_mark_unattached_ap(conn, END_STREAM_REASON_INVALID_NATD_DEST);
2944 return -1;
2945 }
2946
2947 if (strcmpstart(tmp_buf, "[DEST ")) {
2948 log_warn(LD_APP,"NATD handshake was ill-formed; closing. The client "
2949 "said: %s",
2950 escaped(tmp_buf));
2951 connection_mark_unattached_ap(conn, END_STREAM_REASON_INVALID_NATD_DEST);
2952 return -1;
2953 }
2954
2955 daddr = tbuf = &tmp_buf[0] + 6; /* after end of "[DEST " */
2956 if (!(tbuf = strchr(tbuf, ' '))) {
2957 log_warn(LD_APP,"NATD handshake was ill-formed; closing. The client "
2958 "said: %s",
2959 escaped(tmp_buf));
2960 connection_mark_unattached_ap(conn, END_STREAM_REASON_INVALID_NATD_DEST);
2961 return -1;
2962 }
2963 *tbuf++ = '\0';
2964
2965 /* pretend that a socks handshake completed so we don't try to
2966 * send a socks reply down a natd conn */
2967 strlcpy(socks->address, daddr, sizeof(socks->address));
2968 socks->port = (uint16_t)
2969 tor_parse_long(tbuf, 10, 1, 65535, &port_ok, &daddr);
2970 if (!port_ok) {
2971 log_warn(LD_APP,"NATD handshake failed; port %s is ill-formed or out "
2972 "of range.", escaped(tbuf));
2973 connection_mark_unattached_ap(conn, END_STREAM_REASON_INVALID_NATD_DEST);
2974 return -1;
2975 }
2976
2978 socks->has_finished = 1;
2979
2980 control_event_stream_status(conn, STREAM_EVENT_NEW, 0);
2981
2983
2984 return connection_ap_rewrite_and_attach_if_allowed(conn, NULL, NULL);
2985}
2986
2987static const char HTTP_CONNECT_IS_NOT_AN_HTTP_PROXY_MSG[] =
2988 "HTTP/1.0 405 Method Not Allowed\r\n"
2989 "Content-Type: text/html; charset=iso-8859-1\r\n\r\n"
2990 "<html>\n"
2991 "<head>\n"
2992 "<title>This is an HTTP CONNECT tunnel, not a full HTTP Proxy</title>\n"
2993 "</head>\n"
2994 "<body>\n"
2995 "<h1>This is an HTTP CONNECT tunnel, not an HTTP proxy.</h1>\n"
2996 "<p>\n"
2997 "It appears you have configured your web browser to use this Tor port as\n"
2998 "an HTTP proxy.\n"
2999 "</p><p>\n"
3000 "This is not correct: This port is configured as a CONNECT tunnel, not\n"
3001 "an HTTP proxy. Please configure your client accordingly. You can also\n"
3002 "use HTTPS; then the client should automatically use HTTP CONNECT."
3003 "</p>\n"
3004 "<p>\n"
3005 "See <a href=\"https://www.torproject.org/documentation.html\">"
3006 "https://www.torproject.org/documentation.html</a> for more "
3007 "information.\n"
3008 "</p>\n"
3009 "</body>\n"
3010 "</html>\n";
3011
3012/** Called on an HTTP CONNECT entry connection when some bytes have arrived,
3013 * but we have not yet received a full HTTP CONNECT request. Try to parse an
3014 * HTTP CONNECT request from the connection's inbuf. On success, set up the
3015 * connection's socks_request field and try to attach the connection. On
3016 * failure, send an HTTP reply, and mark the connection.
3017 */
3018STATIC int
3020{
3021 if (BUG(ENTRY_TO_CONN(conn)->state != AP_CONN_STATE_HTTP_CONNECT_WAIT))
3022 return -1;
3023
3024 char *headers = NULL, *body = NULL;
3025 char *command = NULL, *addrport = NULL;
3026 char *addr = NULL;
3027 size_t bodylen = 0;
3028
3029 const char *errmsg = NULL;
3030 int rv = 0;
3031
3032 const int http_status =
3033 fetch_from_buf_http(ENTRY_TO_CONN(conn)->inbuf, &headers, 8192,
3034 &body, &bodylen, 1024, 0);
3035 if (http_status < 0) {
3036 /* Bad http status */
3037 errmsg = "HTTP/1.0 400 Bad Request\r\n\r\n";
3038 goto err;
3039 } else if (http_status == 0) {
3040 /* no HTTP request yet. */
3041 goto done;
3042 }
3043
3044 const int cmd_status = parse_http_command(headers, &command, &addrport);
3045 if (cmd_status < 0) {
3046 errmsg = "HTTP/1.0 400 Bad Request\r\n\r\n";
3047 goto err;
3048 }
3050 tor_assert(addrport);
3051 if (strcasecmp(command, "connect")) {
3052 errmsg = HTTP_CONNECT_IS_NOT_AN_HTTP_PROXY_MSG;
3053 goto err;
3054 }
3055
3057 socks_request_t *socks = conn->socks_request;
3058 uint16_t port;
3059 if (tor_addr_port_split(LOG_WARN, addrport, &addr, &port) < 0) {
3060 errmsg = "HTTP/1.0 400 Bad Request\r\n\r\n";
3061 goto err;
3062 }
3063 if (strlen(addr) >= MAX_SOCKS_ADDR_LEN) {
3064 errmsg = "HTTP/1.0 414 Request-URI Too Long\r\n\r\n";
3065 goto err;
3066 }
3067
3068 /* Abuse the 'username' and 'password' fields here. They are already an
3069 * abuse. */
3070 {
3071 char *authorization = http_get_header(headers, "Proxy-Authorization: ");
3072 if (authorization) {
3073 socks->username = authorization; // steal reference
3074 socks->usernamelen = strlen(authorization);
3075 }
3076 char *isolation = http_get_header(headers, "X-Tor-Stream-Isolation: ");
3077 if (isolation) {
3078 socks->password = isolation; // steal reference
3079 socks->passwordlen = strlen(isolation);
3080 }
3081 }
3082
3085 strlcpy(socks->address, addr, sizeof(socks->address));
3086 socks->port = port;
3087
3088 control_event_stream_status(conn, STREAM_EVENT_NEW, 0);
3089
3090 rv = connection_ap_rewrite_and_attach_if_allowed(conn, NULL, NULL);
3091
3092 // XXXX send a "100 Continue" message?
3093
3094 goto done;
3095
3096 err:
3097 if (BUG(errmsg == NULL))
3098 errmsg = "HTTP/1.0 400 Bad Request\r\n\r\n";
3099 log_info(LD_EDGE, "HTTP tunnel error: saying %s", escaped(errmsg));
3100 connection_buf_add(errmsg, strlen(errmsg), ENTRY_TO_CONN(conn));
3101 /* Mark it as "has_finished" so that we don't try to send an extra socks
3102 * reply. */
3103 conn->socks_request->has_finished = 1;
3104 connection_mark_unattached_ap(conn,
3107
3108 done:
3109 tor_free(headers);
3110 tor_free(body);
3112 tor_free(addrport);
3113 tor_free(addr);
3114 return rv;
3115}
3116
3117/** Iterate over the two bytes of stream_id until we get one that is not
3118 * already in use; return it. Return 0 if can't get a unique stream_id.
3119 */
3122{
3123 edge_connection_t *tmpconn;
3124 streamid_t test_stream_id;
3125 uint32_t attempts=0;
3126
3127 again:
3128 test_stream_id = circ->next_stream_id++;
3129 if (++attempts > 1<<16) {
3130 /* Make sure we don't loop forever if all stream_id's are used. */
3131 log_warn(LD_APP,"No unused stream IDs. Failing.");
3132 return 0;
3133 }
3134 if (test_stream_id == 0)
3135 goto again;
3136 for (tmpconn = circ->p_streams; tmpconn; tmpconn=tmpconn->next_stream)
3137 if (tmpconn->stream_id == test_stream_id)
3138 goto again;
3139
3141 test_stream_id))
3142 goto again;
3143
3144 if (TO_CIRCUIT(circ)->conflux) {
3145 conflux_sync_circ_fields(TO_CIRCUIT(circ)->conflux, circ);
3146 }
3147
3148 return test_stream_id;
3149}
3150
3151/** Return true iff <b>conn</b> is linked to a circuit and configured to use
3152 * an exit that supports optimistic data. */
3153static int
3155{
3156 const edge_connection_t *edge_conn = ENTRY_TO_EDGE_CONN(conn);
3157 /* We can only send optimistic data if we're connected to an open
3158 general circuit. */
3159 // TODO-329-PURPOSE: Can conflux circuits use optimistic data?
3160 // Does anything use optimistic data?
3161 if (edge_conn->on_circuit == NULL ||
3162 edge_conn->on_circuit->state != CIRCUIT_STATE_OPEN ||
3167 return 0;
3168
3169 return conn->may_use_optimistic_data;
3170}
3171
3172/** Return a bitmask of BEGIN_FLAG_* flags that we should transmit in the
3173 * RELAY_BEGIN cell for <b>ap_conn</b>. */
3174static uint32_t
3176{
3177 edge_connection_t *edge_conn = ENTRY_TO_EDGE_CONN(ap_conn);
3178 const node_t *exitnode = NULL;
3179 const crypt_path_t *cpath_layer = edge_conn->cpath_layer;
3180 uint32_t flags = 0;
3181
3182 /* No flags for begindir */
3183 if (ap_conn->use_begindir)
3184 return 0;
3185
3186 /* No flags for hidden services. */
3187 if (edge_conn->on_circuit->purpose != CIRCUIT_PURPOSE_C_GENERAL &&
3188 edge_conn->on_circuit->purpose != CIRCUIT_PURPOSE_CONFLUX_LINKED)
3189 return 0;
3190
3191 /* If only IPv4 is supported, no flags */
3192 if (ap_conn->entry_cfg.ipv4_traffic && !ap_conn->entry_cfg.ipv6_traffic)
3193 return 0;
3194
3195 if (! cpath_layer ||
3196 ! cpath_layer->extend_info)
3197 return 0;
3198
3199 if (!ap_conn->entry_cfg.ipv4_traffic)
3200 flags |= BEGIN_FLAG_IPV4_NOT_OK;
3201
3202 exitnode = node_get_by_id(cpath_layer->extend_info->identity_digest);
3203
3204 if (ap_conn->entry_cfg.ipv6_traffic && exitnode) {
3205 tor_addr_t a;
3206 tor_addr_make_null(&a, AF_INET6);
3208 exitnode)
3210 /* Only say "IPv6 OK" if the exit node supports IPv6. Otherwise there's
3211 * no point. */
3212 flags |= BEGIN_FLAG_IPV6_OK;
3213 }
3214 }
3215
3216 if (flags == BEGIN_FLAG_IPV6_OK) {
3217 /* When IPv4 and IPv6 are both allowed, consider whether to say we
3218 * prefer IPv6. Otherwise there's no point in declaring a preference */
3219 if (ap_conn->entry_cfg.prefer_ipv6)
3221 }
3222
3223 if (flags == BEGIN_FLAG_IPV4_NOT_OK) {
3224 log_warn(LD_EDGE, "I'm about to ask a node for a connection that I "
3225 "am telling it to fulfil with neither IPv4 nor IPv6. That's "
3226 "not going to work. Did you perhaps ask for an IPv6 address "
3227 "on an IPv4Only port, or vice versa?");
3228 }
3229
3230 return flags;
3231}
3232
3233/** Write a relay begin cell, using destaddr and destport from ap_conn's
3234 * socks_request field, and send it down circ.
3235 *
3236 * If ap_conn is broken, mark it for close and return -1. Else return 0.
3237 */
3238MOCK_IMPL(int,
3240{
3241 char payload[CELL_PAYLOAD_SIZE];
3242 int payload_len;
3243 int begin_type;
3244 const or_options_t *options = get_options();
3245 origin_circuit_t *circ;
3246 edge_connection_t *edge_conn = ENTRY_TO_EDGE_CONN(ap_conn);
3247 connection_t *base_conn = TO_CONN(edge_conn);
3248 tor_assert(edge_conn->on_circuit);
3249 circ = TO_ORIGIN_CIRCUIT(edge_conn->on_circuit);
3250
3251 tor_assert(base_conn->type == CONN_TYPE_AP);
3253 tor_assert(ap_conn->socks_request);
3254 tor_assert(SOCKS_COMMAND_IS_CONNECT(ap_conn->socks_request->command));
3255
3256 edge_conn->stream_id = get_unique_stream_id_by_circ(circ);
3257 if (edge_conn->stream_id==0) {
3258 /* XXXX+ Instead of closing this stream, we should make it get
3259 * retried on another circuit. */
3260 connection_mark_unattached_ap(ap_conn, END_STREAM_REASON_INTERNAL);
3261
3262 /* Mark this circuit "unusable for new streams". */
3264 return -1;
3265 }
3266
3267 /* Set up begin cell flags. */
3268 edge_conn->begincell_flags = connection_ap_get_begincell_flags(ap_conn);
3269
3270 tor_snprintf(payload,RELAY_PAYLOAD_SIZE, "%s:%d",
3271 (circ->base_.purpose == CIRCUIT_PURPOSE_C_GENERAL ||
3272 circ->base_.purpose == CIRCUIT_PURPOSE_CONFLUX_LINKED ||
3273 circ->base_.purpose == CIRCUIT_PURPOSE_CONTROLLER) ?
3274 ap_conn->socks_request->address : "",
3275 ap_conn->socks_request->port);
3276 payload_len = (int)strlen(payload)+1;
3277 if (payload_len <= RELAY_PAYLOAD_SIZE - 4 && edge_conn->begincell_flags) {
3278 set_uint32(payload + payload_len, htonl(edge_conn->begincell_flags));
3279 payload_len += 4;
3280 }
3281
3282 log_info(LD_APP,
3283 "Sending relay cell %d on circ %u to begin stream %d.",
3284 (int)ap_conn->use_begindir,
3285 (unsigned)circ->base_.n_circ_id,
3286 edge_conn->stream_id);
3287
3288 begin_type = ap_conn->use_begindir ?
3289 RELAY_COMMAND_BEGIN_DIR : RELAY_COMMAND_BEGIN;
3290
3291 /* Check that circuits are anonymised, based on their type. */
3292 if (begin_type == RELAY_COMMAND_BEGIN) {
3293 /* This connection is a standard OR connection.
3294 * Make sure its path length is anonymous, or that we're in a
3295 * non-anonymous mode. */
3296 assert_circ_anonymity_ok(circ, options);
3297 } else if (begin_type == RELAY_COMMAND_BEGIN_DIR) {
3298 /* This connection is a begindir directory connection.
3299 * Look at the linked directory connection to access the directory purpose.
3300 * If a BEGINDIR connection is ever not linked, that's a bug. */
3301 if (BUG(!base_conn->linked)) {
3302 return -1;
3303 }
3304 connection_t *linked_dir_conn_base = base_conn->linked_conn;
3305 /* If the linked connection has been unlinked by other code, we can't send
3306 * a begin cell on it. */
3307 if (!linked_dir_conn_base) {
3308 return -1;
3309 }
3310 /* Sensitive directory connections must have an anonymous path length.
3311 * Otherwise, directory connections are typically one-hop.
3312 * This matches the earlier check for directory connection path anonymity
3313 * in directory_initiate_request(). */
3314 if (purpose_needs_anonymity(linked_dir_conn_base->purpose,
3315 TO_DIR_CONN(linked_dir_conn_base)->router_purpose,
3316 TO_DIR_CONN(linked_dir_conn_base)->requested_resource)) {
3317 assert_circ_anonymity_ok(circ, options);
3318 }
3319 } else {
3320 /* This code was written for the two connection types BEGIN and BEGIN_DIR
3321 */
3322 tor_assert_unreached();
3323 }
3324
3325 if (connection_edge_send_command(edge_conn, begin_type,
3326 begin_type == RELAY_COMMAND_BEGIN ? payload : NULL,
3327 begin_type == RELAY_COMMAND_BEGIN ? payload_len : 0) < 0)
3328 return -1; /* circuit is closed, don't continue */
3329
3332 base_conn->state = AP_CONN_STATE_CONNECT_WAIT;
3333 log_info(LD_APP,"Address/port sent, ap socket "TOR_SOCKET_T_FORMAT
3334 ", n_circ_id %u",
3335 base_conn->s, (unsigned)circ->base_.n_circ_id);
3336 control_event_stream_status(ap_conn, STREAM_EVENT_SENT_CONNECT, 0);
3337
3338 /* If there's queued-up data, send it now */
3339 if ((connection_get_inbuf_len(base_conn) ||
3340 ap_conn->sending_optimistic_data) &&
3342 log_info(LD_APP, "Sending up to %ld + %ld bytes of queued-up data",
3343 (long)connection_get_inbuf_len(base_conn),
3344 ap_conn->sending_optimistic_data ?
3345 (long)buf_datalen(ap_conn->sending_optimistic_data) : 0);
3346 if (connection_edge_package_raw_inbuf(edge_conn, 1, NULL) < 0) {
3347 connection_mark_for_close(base_conn);
3348 }
3349 }
3350
3351 return 0;
3352}
3353
3354/** Write a relay resolve cell, using destaddr and destport from ap_conn's
3355 * socks_request field, and send it down circ.
3356 *
3357 * If ap_conn is broken, mark it for close and return -1. Else return 0.
3358 */
3359int
3361{
3362 int payload_len, command;
3363 const char *string_addr;
3364 char inaddr_buf[REVERSE_LOOKUP_NAME_BUF_LEN];
3365 origin_circuit_t *circ;
3366 edge_connection_t *edge_conn = ENTRY_TO_EDGE_CONN(ap_conn);
3367 connection_t *base_conn = TO_CONN(edge_conn);
3368 tor_assert(edge_conn->on_circuit);
3369 circ = TO_ORIGIN_CIRCUIT(edge_conn->on_circuit);
3370
3371 tor_assert(base_conn->type == CONN_TYPE_AP);
3373 tor_assert(ap_conn->socks_request);
3375 circ->base_.purpose == CIRCUIT_PURPOSE_CONFLUX_LINKED);
3376
3377 command = ap_conn->socks_request->command;
3378 tor_assert(SOCKS_COMMAND_IS_RESOLVE(command));
3379
3380 edge_conn->stream_id = get_unique_stream_id_by_circ(circ);
3381 if (edge_conn->stream_id==0) {
3382 /* XXXX+ Instead of closing this stream, we should make it get
3383 * retried on another circuit. */
3384 connection_mark_unattached_ap(ap_conn, END_STREAM_REASON_INTERNAL);
3385
3386 /* Mark this circuit "unusable for new streams". */
3388 return -1;
3389 }
3390
3392 string_addr = ap_conn->socks_request->address;
3393 payload_len = (int)strlen(string_addr)+1;
3394 } else {
3395 /* command == SOCKS_COMMAND_RESOLVE_PTR */
3396 const char *a = ap_conn->socks_request->address;
3397 tor_addr_t addr;
3398 int r;
3399
3400 /* We're doing a reverse lookup. The input could be an IP address, or
3401 * could be an .in-addr.arpa or .ip6.arpa address */
3402 r = tor_addr_parse_PTR_name(&addr, a, AF_UNSPEC, 1);
3403 if (r <= 0) {
3404 log_warn(LD_APP, "Rejecting ill-formed reverse lookup of %s",
3405 safe_str_client(a));
3406 connection_mark_unattached_ap(ap_conn, END_STREAM_REASON_INTERNAL);
3407 return -1;
3408 }
3409
3410 r = tor_addr_to_PTR_name(inaddr_buf, sizeof(inaddr_buf), &addr);
3411 if (r < 0) {
3412 log_warn(LD_BUG, "Couldn't generate reverse lookup hostname of %s",
3413 safe_str_client(a));
3414 connection_mark_unattached_ap(ap_conn, END_STREAM_REASON_INTERNAL);
3415 return -1;
3416 }
3417
3418 string_addr = inaddr_buf;
3419 payload_len = (int)strlen(inaddr_buf)+1;
3420 tor_assert(payload_len <= (int)sizeof(inaddr_buf));
3421 }
3422
3423 log_debug(LD_APP,
3424 "Sending relay cell to begin stream %d.", edge_conn->stream_id);
3425
3426 if (connection_edge_send_command(edge_conn,
3427 RELAY_COMMAND_RESOLVE,
3428 string_addr, payload_len) < 0)
3429 return -1; /* circuit is closed, don't continue */
3430
3431 if (!base_conn->address) {
3432 /* This might be unnecessary. XXXX */
3433 base_conn->address = tor_addr_to_str_dup(&base_conn->addr);
3434 }
3435 base_conn->state = AP_CONN_STATE_RESOLVE_WAIT;
3436 log_info(LD_APP,"Address sent for resolve, ap socket "TOR_SOCKET_T_FORMAT
3437 ", n_circ_id %u",
3438 base_conn->s, (unsigned)circ->base_.n_circ_id);
3439 control_event_stream_status(ap_conn, STREAM_EVENT_SENT_RESOLVE, 0);
3440 return 0;
3441}
3442
3443/** Make an AP connection_t linked to the connection_t <b>partner</b>. make a
3444 * new linked connection pair, and attach one side to the conn, connection_add
3445 * it, initialize it to circuit_wait, and call
3446 * connection_ap_handshake_attach_circuit(conn) on it.
3447 *
3448 * Return the newly created end of the linked connection pair, or -1 if error.
3449 */
3452 char *address, uint16_t port,
3453 const char *digest,
3454 int session_group, int isolation_flags,
3455 int use_begindir, int want_onehop)
3456{
3457 entry_connection_t *conn;
3458 connection_t *base_conn;
3459
3460 log_info(LD_APP,"Making internal %s tunnel to %s:%d ...",
3461 want_onehop ? "direct" : "anonymized",
3462 safe_str_client(address), port);
3463
3465 base_conn = ENTRY_TO_CONN(conn);
3466 base_conn->linked = 1; /* so that we can add it safely below. */
3467
3468 /* populate conn->socks_request */
3469
3470 /* leave version at zero, so the socks_reply is empty */
3471 conn->socks_request->socks_version = 0;
3472 conn->socks_request->has_finished = 0; /* waiting for 'connected' */
3473 strlcpy(conn->socks_request->address, address,
3474 sizeof(conn->socks_request->address));
3475 conn->socks_request->port = port;
3477 conn->want_onehop = want_onehop;
3478 conn->use_begindir = use_begindir;
3479 if (use_begindir) {
3480 conn->chosen_exit_name = tor_malloc(HEX_DIGEST_LEN+2);
3481 conn->chosen_exit_name[0] = '$';
3482 tor_assert(digest);
3484 digest, DIGEST_LEN);
3485 }
3486
3487 /* Populate isolation fields. */
3489 conn->original_dest_address = tor_strdup(address);
3490 conn->entry_cfg.session_group = session_group;
3491 conn->entry_cfg.isolation_flags = isolation_flags;
3492
3493 base_conn->address = tor_strdup("(Tor_internal)");
3494 tor_addr_make_unspec(&base_conn->addr);
3495 base_conn->port = 0;
3496
3497 connection_link_connections(partner, base_conn);
3498
3499 if (connection_add(base_conn) < 0) { /* no space, forget it */
3500 connection_free(base_conn);
3501 return NULL;
3502 }
3503
3504 base_conn->state = AP_CONN_STATE_CIRCUIT_WAIT;
3505
3506 control_event_stream_status(conn, STREAM_EVENT_NEW, 0);
3507
3508 /* attaching to a dirty circuit is fine */
3509 connection_ap_mark_as_pending_circuit(conn);
3510 log_info(LD_APP,"... application connection created and linked.");
3511 return conn;
3512}
3513
3514/** Notify any interested controller connections about a new hostname resolve
3515 * or resolve error. Takes the same arguments as does
3516 * connection_ap_handshake_socks_resolved(). */
3517static void
3519 int answer_type,
3520 size_t answer_len,
3521 const char *answer,
3522 int ttl,
3523 time_t expires)
3524{
3525 uint64_t stream_id = 0;
3526
3527 if (BUG(!conn)) {
3528 return;
3529 }
3530
3531 stream_id = ENTRY_TO_CONN(conn)->global_identifier;
3532
3533 expires = time(NULL) + ttl;
3534 if (answer_type == RESOLVED_TYPE_IPV4 && answer_len >= 4) {
3535 char *cp = tor_dup_ip(ntohl(get_uint32(answer)));
3536 if (cp)
3538 cp, expires, NULL, 0, stream_id);
3539 tor_free(cp);
3540 } else if (answer_type == RESOLVED_TYPE_HOSTNAME && answer_len < 256) {
3541 char *cp = tor_strndup(answer, answer_len);
3543 cp, expires, NULL, 0, stream_id);
3544 tor_free(cp);
3545 } else {
3547 "<error>", time(NULL)+ttl,
3548 "error=yes", 0, stream_id);
3549 }
3550}
3551
3552/**
3553 * As connection_ap_handshake_socks_resolved, but take a tor_addr_t to send
3554 * as the answer.
3555 */
3556void
3558 const tor_addr_t *answer,
3559 int ttl,
3560 time_t expires)
3561{
3562 if (tor_addr_family(answer) == AF_INET) {
3563 uint32_t a = tor_addr_to_ipv4n(answer); /* network order */
3564 connection_ap_handshake_socks_resolved(conn,RESOLVED_TYPE_IPV4,4,
3565 (uint8_t*)&a,
3566 ttl, expires);
3567 } else if (tor_addr_family(answer) == AF_INET6) {
3568 const uint8_t *a = tor_addr_to_in6_addr8(answer);
3569 connection_ap_handshake_socks_resolved(conn,RESOLVED_TYPE_IPV6,16,
3570 a,
3571 ttl, expires);
3572 } else {
3573 log_warn(LD_BUG, "Got called with address of unexpected family %d",
3574 tor_addr_family(answer));
3576 RESOLVED_TYPE_ERROR,0,NULL,-1,-1);
3577 }
3578}
3579
3580/** Send an answer to an AP connection that has requested a DNS lookup via
3581 * SOCKS. The type should be one of RESOLVED_TYPE_(IPV4|IPV6|HOSTNAME) or -1
3582 * for unreachable; the answer should be in the format specified in the socks
3583 * extensions document. <b>ttl</b> is the ttl for the answer, or -1 on
3584 * certain errors or for values that didn't come via DNS. <b>expires</b> is
3585 * a time when the answer expires, or -1 or TIME_MAX if there's a good TTL.
3586 **/
3587/* XXXX the use of the ttl and expires fields is nutty. Let's make this
3588 * interface and those that use it less ugly. */
3589MOCK_IMPL(void,
3591 int answer_type,
3592 size_t answer_len,
3593 const uint8_t *answer,
3594 int ttl,
3595 time_t expires))
3596{
3597 char buf[384];
3598 size_t replylen;
3599
3600 if (ttl >= 0) {
3601 if (answer_type == RESOLVED_TYPE_IPV4 && answer_len == 4) {
3602 tor_addr_t a;
3603 tor_addr_from_ipv4n(&a, get_uint32(answer));
3604 if (! tor_addr_is_null(&a)) {
3606 conn->socks_request->address, &a,
3607 conn->chosen_exit_name, ttl);
3608 }
3609 } else if (answer_type == RESOLVED_TYPE_IPV6 && answer_len == 16) {
3610 tor_addr_t a;
3611 tor_addr_from_ipv6_bytes(&a, answer);
3612 if (! tor_addr_is_null(&a)) {
3614 conn->socks_request->address, &a,
3615 conn->chosen_exit_name, ttl);
3616 }
3617 } else if (answer_type == RESOLVED_TYPE_HOSTNAME && answer_len < 256) {
3618 char *cp = tor_strndup((char*)answer, answer_len);
3620 conn->socks_request->address,
3621 cp,
3622 conn->chosen_exit_name, ttl);
3623 tor_free(cp);
3624 }
3625 }
3626
3627 if (ENTRY_TO_EDGE_CONN(conn)->is_dns_request) {
3628 if (conn->dns_server_request) {
3629 /* We had a request on our DNS port: answer it. */
3630 dnsserv_resolved(conn, answer_type, answer_len, (char*)answer, ttl);
3631 conn->socks_request->has_finished = 1;
3632 return;
3633 } else {
3634 /* This must be a request from the controller. Since answers to those
3635 * requests are not cached, they do not generate an ADDRMAP event on
3636 * their own. */
3637 tell_controller_about_resolved_result(conn, answer_type, answer_len,
3638 (char*)answer, ttl, expires);
3639 conn->socks_request->has_finished = 1;
3640 return;
3641 }
3642 /* We shouldn't need to free conn here; it gets marked by the caller. */
3643 }
3644
3645 if (conn->socks_request->socks_version == 4) {
3646 buf[0] = 0x00; /* version */
3647 if (answer_type == RESOLVED_TYPE_IPV4 && answer_len == 4) {
3648 buf[1] = SOCKS4_GRANTED;
3649 set_uint16(buf+2, 0);
3650 memcpy(buf+4, answer, 4); /* address */
3651 replylen = SOCKS4_NETWORK_LEN;
3652 } else { /* "error" */
3653 buf[1] = SOCKS4_REJECT;
3654 memset(buf+2, 0, 6);
3655 replylen = SOCKS4_NETWORK_LEN;
3656 }
3657 } else if (conn->socks_request->socks_version == 5) {
3658 /* SOCKS5 */
3659 buf[0] = 0x05; /* version */
3660 if (answer_type == RESOLVED_TYPE_IPV4 && answer_len == 4) {
3661 buf[1] = SOCKS5_SUCCEEDED;
3662 buf[2] = 0; /* reserved */
3663 buf[3] = 0x01; /* IPv4 address type */
3664 memcpy(buf+4, answer, 4); /* address */
3665 set_uint16(buf+8, 0); /* port == 0. */
3666 replylen = 10;
3667 } else if (answer_type == RESOLVED_TYPE_IPV6 && answer_len == 16) {
3668 buf[1] = SOCKS5_SUCCEEDED;
3669 buf[2] = 0; /* reserved */
3670 buf[3] = 0x04; /* IPv6 address type */
3671 memcpy(buf+4, answer, 16); /* address */
3672 set_uint16(buf+20, 0); /* port == 0. */
3673 replylen = 22;
3674 } else if (answer_type == RESOLVED_TYPE_HOSTNAME && answer_len < 256) {
3675 buf[1] = SOCKS5_SUCCEEDED;
3676 buf[2] = 0; /* reserved */
3677 buf[3] = 0x03; /* Domainname address type */
3678 buf[4] = (char)answer_len;
3679 memcpy(buf+5, answer, answer_len); /* address */
3680 set_uint16(buf+5+answer_len, 0); /* port == 0. */
3681 replylen = 5+answer_len+2;
3682 } else {
3683 buf[1] = SOCKS5_HOST_UNREACHABLE;
3684 memset(buf+2, 0, 8);
3685 replylen = 10;
3686 }
3687 } else {
3688 /* no socks version info; don't send anything back */
3689 return;
3690 }
3691 connection_ap_handshake_socks_reply(conn, buf, replylen,
3692 (answer_type == RESOLVED_TYPE_IPV4 ||
3693 answer_type == RESOLVED_TYPE_IPV6 ||
3694 answer_type == RESOLVED_TYPE_HOSTNAME) ?
3695 0 : END_STREAM_REASON_RESOLVEFAILED);
3696}
3697
3698/** Send a socks reply to stream <b>conn</b>, using the appropriate
3699 * socks version, etc, and mark <b>conn</b> as completed with SOCKS
3700 * handshaking.
3701 *
3702 * If <b>reply</b> is defined, then write <b>replylen</b> bytes of it to conn
3703 * and return, else reply based on <b>endreason</b> (one of
3704 * END_STREAM_REASON_*). If <b>reply</b> is undefined, <b>endreason</b> can't
3705 * be 0 or REASON_DONE. Send endreason to the controller, if appropriate.
3706 */
3707void
3709 size_t replylen, int endreason)
3710{
3711 char buf[256];
3712 socks5_reply_status_t status;
3713
3714 tor_assert(conn->socks_request); /* make sure it's an AP stream */
3715
3719 } else {
3720 status = stream_end_reason_to_socks5_response(endreason);
3721 }
3722
3723 if (!SOCKS_COMMAND_IS_RESOLVE(conn->socks_request->command)) {
3724 control_event_stream_status(conn, status==SOCKS5_SUCCEEDED ?
3725 STREAM_EVENT_SUCCEEDED : STREAM_EVENT_FAILED,
3726 endreason);
3727 }
3728
3729 /* Flag this stream's circuit as having completed a stream successfully
3730 * (for path bias) */
3731 if (status == SOCKS5_SUCCEEDED ||
3732 endreason == END_STREAM_REASON_RESOLVEFAILED ||
3733 endreason == END_STREAM_REASON_CONNECTREFUSED ||
3734 endreason == END_STREAM_REASON_CONNRESET ||
3735 endreason == END_STREAM_REASON_NOROUTE ||
3736 endreason == END_STREAM_REASON_RESOURCELIMIT) {
3737 if (!conn->edge_.on_circuit ||
3738 !CIRCUIT_IS_ORIGIN(conn->edge_.on_circuit)) {
3739 if (endreason != END_STREAM_REASON_RESOLVEFAILED) {
3740 log_info(LD_BUG,
3741 "No origin circuit for successful SOCKS stream %"PRIu64
3742 ". Reason: %d",
3743 (ENTRY_TO_CONN(conn)->global_identifier),
3744 endreason);
3745 }
3746 /*
3747 * Else DNS remaps and failed hidden service lookups can send us
3748 * here with END_STREAM_REASON_RESOLVEFAILED; ignore it
3749 *
3750 * Perhaps we could make the test more precise; we can tell hidden
3751 * services by conn->edge_.renddata != NULL; anything analogous for
3752 * the DNS remap case?
3753 */
3754 } else {
3755 // XXX: Hrmm. It looks like optimistic data can't go through this
3756 // codepath, but someone should probably test it and make sure.
3757 // We don't want to mark optimistically opened streams as successful.
3759 }
3760 }
3761
3762 if (conn->socks_request->has_finished) {
3763 log_warn(LD_BUG, "(Harmless.) duplicate calls to "
3764 "connection_ap_handshake_socks_reply.");
3765 return;
3766 }
3767 if (replylen) { /* we already have a reply in mind */
3768 connection_buf_add(reply, replylen, ENTRY_TO_CONN(conn));
3769 conn->socks_request->has_finished = 1;
3770 return;
3771 }
3772 if (conn->socks_request->listener_type ==
3774 const char *response = end_reason_to_http_connect_response_line(endreason);
3775 if (!response) {
3776 response = "HTTP/1.0 400 Bad Request\r\n\r\n";
3777 }
3778 connection_buf_add(response, strlen(response), ENTRY_TO_CONN(conn));
3779 } else if (conn->socks_request->socks_version == 4) {
3780 memset(buf,0,SOCKS4_NETWORK_LEN);
3781 buf[1] = (status==SOCKS5_SUCCEEDED ? SOCKS4_GRANTED : SOCKS4_REJECT);
3782 /* leave version, destport, destip zero */
3783 connection_buf_add(buf, SOCKS4_NETWORK_LEN, ENTRY_TO_CONN(conn));
3784 } else if (conn->socks_request->socks_version == 5) {
3785 size_t buf_len;
3786 memset(buf,0,sizeof(buf));
3787 if (tor_addr_family(&conn->edge_.base_.addr) == AF_INET) {
3788 buf[0] = 5; /* version 5 */
3789 buf[1] = (char)status;
3790 buf[2] = 0;
3791 buf[3] = 1; /* ipv4 addr */
3792 /* 4 bytes for the header, 2 bytes for the port, 4 for the address. */
3793 buf_len = 10;
3794 } else { /* AF_INET6. */
3795 buf[0] = 5; /* version 5 */
3796 buf[1] = (char)status;
3797 buf[2] = 0;
3798 buf[3] = 4; /* ipv6 addr */
3799 /* 4 bytes for the header, 2 bytes for the port, 16 for the address. */
3800 buf_len = 22;
3801 }
3802 connection_buf_add(buf,buf_len,ENTRY_TO_CONN(conn));
3803 }
3804 /* If socks_version isn't 4 or 5, don't send anything.
3805 * This can happen in the case of AP bridges. */
3806 conn->socks_request->has_finished = 1;
3807 return;
3808}
3809
3810/** Read a RELAY_BEGIN or RELAY_BEGIN_DIR cell from <b>cell</b>, decode it, and
3811 * place the result in <b>bcell</b>. On success return 0; on failure return
3812 * <0 and set *<b>end_reason_out</b> to the end reason we should send back to
3813 * the client.
3814 *
3815 * Return -1 in the case where we want to send a RELAY_END cell, and < -1 when
3816 * we don't.
3817 **/
3818STATIC int
3819begin_cell_parse(const cell_t *cell, begin_cell_t *bcell,
3820 uint8_t *end_reason_out)
3821{
3822 relay_header_t rh;
3823 const uint8_t *body, *nul;
3824
3825 memset(bcell, 0, sizeof(*bcell));
3826 *end_reason_out = END_STREAM_REASON_MISC;
3827
3828 relay_header_unpack(&rh, cell->payload);
3829 if (rh.length > RELAY_PAYLOAD_SIZE) {
3830 return -2; /*XXXX why not TORPROTOCOL? */
3831 }
3832
3833 bcell->stream_id = rh.stream_id;
3834
3835 if (rh.command == RELAY_COMMAND_BEGIN_DIR) {
3836 bcell->is_begindir = 1;
3837 return 0;
3838 } else if (rh.command != RELAY_COMMAND_BEGIN) {
3839 log_warn(LD_BUG, "Got an unexpected command %d", (int)rh.command);
3840 *end_reason_out = END_STREAM_REASON_INTERNAL;
3841 return -1;
3842 }
3843
3844 body = cell->payload + RELAY_HEADER_SIZE;
3845 nul = memchr(body, 0, rh.length);
3846 if (! nul) {
3847 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
3848 "Relay begin cell has no \\0. Closing.");
3849 *end_reason_out = END_STREAM_REASON_TORPROTOCOL;
3850 return -1;
3851 }
3852
3853 if (tor_addr_port_split(LOG_PROTOCOL_WARN,
3854 (char*)(body),
3855 &bcell->address,&bcell->port)<0) {
3856 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
3857 "Unable to parse addr:port in relay begin cell. Closing.");
3858 *end_reason_out = END_STREAM_REASON_TORPROTOCOL;
3859 return -1;
3860 }
3861 if (bcell->port == 0) {
3862 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
3863 "Missing port in relay begin cell. Closing.");
3864 tor_free(bcell->address);
3865 *end_reason_out = END_STREAM_REASON_TORPROTOCOL;
3866 return -1;
3867 }
3868 if (body + rh.length >= nul + 4)
3869 bcell->flags = ntohl(get_uint32(nul+1));
3870
3871 return 0;
3872}
3873
3874/** For the given <b>circ</b> and the edge connection <b>conn</b>, setup the
3875 * connection, attach it to the circ and connect it. Return 0 on success
3876 * or END_CIRC_AT_ORIGIN if we can't find the requested hidden service port
3877 * where the caller should close the circuit. */
3878static int
3880{
3881 int ret;
3882 origin_circuit_t *origin_circ;
3883
3884 assert_circuit_ok(circ);
3886 tor_assert(conn);
3887
3888 log_debug(LD_REND, "Connecting the hidden service rendezvous circuit "
3889 "to the service destination.");
3890
3891 origin_circ = TO_ORIGIN_CIRCUIT(circ);
3892 conn->base_.address = tor_strdup("(rendezvous)");
3893 conn->base_.state = EXIT_CONN_STATE_CONNECTING;
3894
3895 if (origin_circ->hs_ident) {
3896 /* Setup the identifier to be the one for the circuit service. */
3897 conn->hs_ident =
3900 ret = hs_service_set_conn_addr_port(origin_circ, conn);
3901 } else {
3902 /* We should never get here if the circuit's purpose is rendezvous. */
3904 return -1;
3905 }
3906 if (ret < 0) {
3907 log_info(LD_REND, "Didn't find rendezvous service at %s",
3909 /* Send back reason DONE because we want to make hidden service port
3910 * scanning harder thus instead of returning that the exit policy
3911 * didn't match, which makes it obvious that the port is closed,
3912 * return DONE and kill the circuit. That way, a user (malicious or
3913 * not) needs one circuit per bad port unless it matches the policy of
3914 * the hidden service. */
3916 END_STREAM_REASON_DONE,
3917 origin_circ->cpath->prev);
3919
3920 /* Drop the circuit here since it might be someone deliberately
3921 * scanning the hidden service ports. Note that this mitigates port
3922 * scanning by adding more work on the attacker side to successfully
3923 * scan but does not fully solve it. */
3924 if (ret < -1) {
3925 return END_CIRC_AT_ORIGIN;
3926 } else {
3927 return 0;
3928 }
3929 }
3930
3931 /* Link the circuit and the connection crypt path. */
3932 conn->cpath_layer = origin_circ->cpath->prev;
3933
3934 /* If this is the first stream on this circuit, tell circpad */
3935 if (!origin_circ->p_streams)
3937
3938 /* Add it into the linked list of p_streams on this circuit */
3939 conn->next_stream = origin_circ->p_streams;
3940 origin_circ->p_streams = conn;
3941 conn->on_circuit = circ;
3942 assert_circuit_ok(circ);
3943
3944 hs_inc_rdv_stream_counter(origin_circ);
3945
3946 /* If it's an onion service connection, we might want to include the proxy
3947 * protocol header: */
3948 if (conn->hs_ident) {
3949 hs_circuit_id_protocol_t circuit_id_protocol =
3951 export_hs_client_circuit_id(conn, circuit_id_protocol);
3952 }
3953
3954 /* Connect tor to the hidden service destination. */
3956
3957 /* For path bias: This circuit was used successfully */
3958 pathbias_mark_use_success(origin_circ);
3959 return 0;
3960}
3961
3962/** A relay 'begin' or 'begin_dir' cell has arrived, and either we are
3963 * an exit hop for the circuit, or we are the origin and it is a
3964 * rendezvous begin.
3965 *
3966 * Launch a new exit connection and initialize things appropriately.
3967 *
3968 * If it's a rendezvous stream, call connection_exit_connect() on
3969 * it.
3970 *
3971 * For general streams, call dns_resolve() on it first, and only call
3972 * connection_exit_connect() if the dns answer is already known.
3973 *
3974 * Note that we don't call connection_add() on the new stream! We wait
3975 * for connection_exit_connect() to do that.
3976 *
3977 * Return -(some circuit end reason) if we want to tear down <b>circ</b>.
3978 * Else return 0.
3979 */
3980int
3982{
3983 edge_connection_t *n_stream;
3984 relay_header_t rh;
3985 char *address = NULL;
3986 uint16_t port = 0;
3987 or_circuit_t *or_circ = NULL;
3988 origin_circuit_t *origin_circ = NULL;
3989 crypt_path_t *layer_hint = NULL;
3990 const or_options_t *options = get_options();
3991 begin_cell_t bcell;
3992 int rv;
3993 uint8_t end_reason=0;
3994 dos_stream_defense_type_t dos_defense_type;
3995
3996 assert_circuit_ok(circ);
3997 if (!CIRCUIT_IS_ORIGIN(circ)) {
3998 or_circ = TO_OR_CIRCUIT(circ);
3999 } else {
4001 origin_circ = TO_ORIGIN_CIRCUIT(circ);
4002 layer_hint = origin_circ->cpath->prev;
4003 }
4004
4005 relay_header_unpack(&rh, cell->payload);
4006 if (rh.length > RELAY_PAYLOAD_SIZE)
4007 return -END_CIRC_REASON_TORPROTOCOL;
4008
4009 if (!server_mode(options) &&
4011 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
4012 "Relay begin cell at non-server. Closing.");
4014 END_STREAM_REASON_EXITPOLICY, NULL);
4015 return 0;
4016 }
4017
4018 rv = begin_cell_parse(cell, &bcell, &end_reason);
4019 if (rv < -1) {
4020 return -END_CIRC_REASON_TORPROTOCOL;
4021 } else if (rv == -1) {
4022 tor_free(bcell.address);
4023 relay_send_end_cell_from_edge(rh.stream_id, circ, end_reason, layer_hint);
4024 return 0;
4025 }
4026
4027 if (! bcell.is_begindir) {
4028 /* Steal reference */
4029 tor_assert(bcell.address);
4030 address = bcell.address;
4031 port = bcell.port;
4032
4033 if (or_circ && or_circ->p_chan) {
4034 const int client_chan = channel_is_client(or_circ->p_chan);
4035 if ((client_chan ||
4037 or_circ->p_chan->identity_digest) &&
4038 should_refuse_unknown_exits(options)))) {
4039 /* Don't let clients use us as a single-hop proxy. It attracts
4040 * attackers and users who'd be better off with, well, single-hop
4041 * proxies. */
4042 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
4043 "Attempt by %s to open a stream %s. Closing.",
4044 safe_str(channel_describe_peer(or_circ->p_chan)),
4045 client_chan ? "on first hop of circuit" :
4046 "from unknown relay");
4048 client_chan ?
4049 END_STREAM_REASON_TORPROTOCOL :
4050 END_STREAM_REASON_MISC,
4051 NULL);
4052 tor_free(address);
4053 return 0;
4054 }
4055 }
4056 } else if (rh.command == RELAY_COMMAND_BEGIN_DIR) {
4058 circ->purpose != CIRCUIT_PURPOSE_OR) {
4060 END_STREAM_REASON_NOTDIRECTORY, layer_hint);
4061 return 0;
4062 }
4063 /* Make sure to get the 'real' address of the previous hop: the
4064 * caller might want to know whether the remote IP address has changed,
4065 * and we might already have corrected base_.addr[ess] for the relay's
4066 * canonical IP address. */
4067 tor_addr_t chan_addr;
4068 if (or_circ && or_circ->p_chan &&
4069 channel_get_addr_if_possible(or_circ->p_chan, &chan_addr)) {
4070 address = tor_addr_to_str_dup(&chan_addr);
4071 } else {
4072 address = tor_strdup("127.0.0.1");
4073 }
4074 port = 1; /* XXXX This value is never actually used anywhere, and there
4075 * isn't "really" a connection here. But we
4076 * need to set it to something nonzero. */
4077 } else {
4078 log_warn(LD_BUG, "Got an unexpected command %d", (int)rh.command);
4080 END_STREAM_REASON_INTERNAL, layer_hint);
4081 return 0;
4082 }
4083
4084 if (! options->IPv6Exit) {
4085 /* I don't care if you prefer IPv6; I can't give you any. */
4086 bcell.flags &= ~BEGIN_FLAG_IPV6_PREFERRED;
4087 /* If you don't want IPv4, I can't help. */
4088 if (bcell.flags & BEGIN_FLAG_IPV4_NOT_OK) {
4089 tor_free(address);
4091 END_STREAM_REASON_EXITPOLICY, layer_hint);
4092 return 0;
4093 }
4094 }
4095
4096 log_debug(LD_EXIT,"Creating new exit connection.");
4097 /* The 'AF_INET' here is temporary; we might need to change it later in
4098 * connection_exit_connect(). */
4099 n_stream = edge_connection_new(CONN_TYPE_EXIT, AF_INET);
4100
4101 /* Remember the tunneled request ID in the new edge connection, so that
4102 * we can measure download times. */
4103 n_stream->dirreq_id = circ->dirreq_id;
4104
4105 n_stream->base_.purpose = EXIT_PURPOSE_CONNECT;
4106 n_stream->begincell_flags = bcell.flags;
4107 n_stream->stream_id = rh.stream_id;
4108 n_stream->base_.port = port;
4109 /* leave n_stream->s at -1, because it's not yet valid */
4112
4114 int ret;
4115 tor_free(address);
4116 /* We handle this circuit and stream in this function for all supported
4117 * hidden service version. */
4118 ret = handle_hs_exit_conn(circ, n_stream);
4119
4120 if (ret == 0) {
4121 /* This was a valid cell. Count it as delivered + overhead. */
4122 circuit_read_valid_data(origin_circ, rh.length);
4123 }
4124 return ret;
4125 }
4126 tor_strlower(address);
4127 n_stream->base_.address = address;
4128 n_stream->base_.state = EXIT_CONN_STATE_RESOLVEFAILED;
4129 /* default to failed, change in dns_resolve if it turns out not to fail */
4130
4131 /* If we're hibernating or shutting down, we refuse to open new streams. */
4132 if (we_are_hibernating()) {
4134 END_STREAM_REASON_HIBERNATING, NULL);
4135 connection_free_(TO_CONN(n_stream));
4136 return 0;
4137 }
4138
4139 n_stream->on_circuit = circ;
4140
4141 if (rh.command == RELAY_COMMAND_BEGIN_DIR) {
4142 tor_addr_t tmp_addr;
4143 tor_assert(or_circ);
4144 if (or_circ->p_chan &&
4145 channel_get_addr_if_possible(or_circ->p_chan, &tmp_addr)) {
4146 tor_addr_copy(&n_stream->base_.addr, &tmp_addr);
4147 }
4148 return connection_exit_connect_dir(n_stream);
4149 }
4150
4151 log_debug(LD_EXIT,"about to start the dns_resolve().");
4152
4153 // in the future we may want to have a similar defense for BEGIN_DIR and
4154 // BEGIN sent to OS.
4155 dos_defense_type = dos_stream_new_begin_or_resolve_cell(or_circ);
4156 switch (dos_defense_type) {
4157 case DOS_STREAM_DEFENSE_NONE:
4158 break;
4159 case DOS_STREAM_DEFENSE_REFUSE_STREAM:
4160 // we don't use END_STREAM_REASON_RESOURCELIMIT because it would make a
4161 // client mark us as non-functional until they get a new consensus.
4162 relay_send_end_cell_from_edge(rh.stream_id, circ, END_STREAM_REASON_MISC,
4163 layer_hint);
4164 connection_free_(TO_CONN(n_stream));
4165 return 0;
4166 case DOS_STREAM_DEFENSE_CLOSE_CIRCUIT:
4167 connection_free_(TO_CONN(n_stream));
4168 return -END_CIRC_REASON_RESOURCELIMIT;
4169 }
4170
4171 /* send it off to the gethostbyname farm */
4172 switch (dns_resolve(n_stream)) {
4173 case 1: /* resolve worked; now n_stream is attached to circ. */
4174 assert_circuit_ok(circ);
4175 log_debug(LD_EXIT,"about to call connection_exit_connect().");
4176 connection_exit_connect(n_stream);
4177 return 0;
4178 case -1: /* resolve failed */
4180 END_STREAM_REASON_RESOLVEFAILED, NULL);
4181 /* n_stream got freed. don't touch it. */
4182 break;
4183 case 0: /* resolve added to pending list */
4184 assert_circuit_ok(circ);
4185 break;
4186 }
4187 return 0;
4188}
4189
4190/**
4191 * Called when we receive a RELAY_COMMAND_RESOLVE cell 'cell' along the
4192 * circuit <b>circ</b>;
4193 * begin resolving the hostname, and (eventually) reply with a RESOLVED cell.
4194 *
4195 * Return -(some circuit end reason) if we want to tear down <b>circ</b>.
4196 * Else return 0.
4197 */
4198int
4200{
4201 edge_connection_t *dummy_conn;
4202 relay_header_t rh;
4203 dos_stream_defense_type_t dos_defense_type;
4204
4206 relay_header_unpack(&rh, cell->payload);
4207 if (rh.length > RELAY_PAYLOAD_SIZE)
4208 return 0;
4209
4210 /* Note the RESOLVE stream as seen. */
4211 rep_hist_note_exit_stream(RELAY_COMMAND_RESOLVE);
4212
4213 /* This 'dummy_conn' only exists to remember the stream ID
4214 * associated with the resolve request; and to make the
4215 * implementation of dns.c more uniform. (We really only need to
4216 * remember the circuit, the stream ID, and the hostname to be
4217 * resolved; but if we didn't store them in a connection like this,
4218 * the housekeeping in dns.c would get way more complicated.)
4219 */
4220 dummy_conn = edge_connection_new(CONN_TYPE_EXIT, AF_INET);
4221 dummy_conn->stream_id = rh.stream_id;
4222 dummy_conn->base_.address = tor_strndup(
4223 (char*)cell->payload+RELAY_HEADER_SIZE,
4224 rh.length);
4225 dummy_conn->base_.port = 0;
4226 dummy_conn->base_.state = EXIT_CONN_STATE_RESOLVEFAILED;
4227 dummy_conn->base_.purpose = EXIT_PURPOSE_RESOLVE;
4228
4229 dummy_conn->on_circuit = TO_CIRCUIT(circ);
4230
4231 dos_defense_type = dos_stream_new_begin_or_resolve_cell(circ);
4232 switch (dos_defense_type) {
4233 case DOS_STREAM_DEFENSE_NONE:
4234 break;
4235 case DOS_STREAM_DEFENSE_REFUSE_STREAM:
4236 dns_send_resolved_error_cell(dummy_conn, RESOLVED_TYPE_ERROR_TRANSIENT);
4237 connection_free_(TO_CONN(dummy_conn));
4238 return 0;
4239 case DOS_STREAM_DEFENSE_CLOSE_CIRCUIT:
4240 connection_free_(TO_CONN(dummy_conn));
4241 return -END_CIRC_REASON_RESOURCELIMIT;
4242 }
4243
4244 /* send it off to the gethostbyname farm */
4245 switch (dns_resolve(dummy_conn)) {
4246 case -1: /* Impossible to resolve; a resolved cell was sent. */
4247 /* Connection freed; don't touch it. */
4248 return 0;
4249 case 1: /* The result was cached; a resolved cell was sent. */
4250 if (!dummy_conn->base_.marked_for_close)
4251 connection_free_(TO_CONN(dummy_conn));
4252 return 0;
4253 case 0: /* resolve added to pending list */
4255 break;
4256 }
4257 return 0;
4258}
4259
4260/** Helper: Return true and set *<b>why_rejected</b> to an optional clarifying
4261 * message message iff we do not allow connections to <b>addr</b>:<b>port</b>.
4262 */
4263static int
4265 uint16_t port,
4266 const char **why_rejected)
4267{
4268 if (router_compare_to_my_exit_policy(addr, port)) {
4269 *why_rejected = "";
4270 return 1;
4271 } else if (tor_addr_family(addr) == AF_INET6 && !get_options()->IPv6Exit) {
4272 *why_rejected = " (IPv6 address without IPv6Exit configured)";
4273 return 1;
4274 }
4275 return 0;
4276}
4277
4278/* Reapply exit policy to existing connections, possibly terminating
4279 * connections
4280 * no longer allowed by the policy.
4281 */
4282void
4283connection_reapply_exit_policy(config_line_t *changes)
4284{
4285 int marked_for_close = 0;
4286 smartlist_t *conn_list = NULL;
4287 smartlist_t *policy = NULL;
4288 int config_change_relevant = 0;
4289
4290 if (get_options()->ReevaluateExitPolicy == 0) {
4291 return;
4292 }
4293
4294 for (const config_line_t *line = changes;
4295 line && !config_change_relevant;
4296 line = line->next) {
4297 const char* exit_policy_options[] = {
4298 "ExitRelay",
4299 "ExitPolicy",
4300 "ReducedExitPolicy",
4301 "ReevaluateExitPolicy",
4302 "IPv6Exit",
4303 NULL
4304 };
4305 for (unsigned int i = 0; exit_policy_options[i] != NULL; ++i) {
4306 if (strcmp(line->key, exit_policy_options[i]) == 0) {
4307 config_change_relevant = 1;
4308 break;
4309 }
4310 }
4311 }
4312
4313 if (!config_change_relevant) {
4314 /* Policy did not change: no need to iterate over connections */
4315 return;
4316 }
4317
4318 // we can't use router_compare_to_my_exit_policy as it depend on the
4319 // descriptor, which is regenerated asynchronously, so we have to parse the
4320 // policy ourselves.
4321 // We don't verify for our own IP, it's not part of the configuration.
4323 &policy) != 0)) {
4324 return;
4325 }
4326
4327 conn_list = connection_list_by_type_purpose(CONN_TYPE_EXIT,
4329
4330 SMARTLIST_FOREACH_BEGIN(conn_list, connection_t *, conn) {
4332 conn->port,
4333 policy);
4334 if (verdict != ADDR_POLICY_ACCEPTED) {
4335 connection_edge_end(TO_EDGE_CONN(conn), END_STREAM_REASON_EXITPOLICY);
4336 connection_mark_for_close(conn);
4337 ++marked_for_close;
4338 }
4339 } SMARTLIST_FOREACH_END(conn);
4340
4341 smartlist_free(conn_list);
4342 smartlist_free(policy);
4343
4344 log_info(LD_GENERAL, "Marked %d connections to be closed as no longer "
4345 "allowed per ExitPolicy", marked_for_close);
4346}
4347
4348/** Return true iff the consensus allows network reentry. The default value is
4349 * false if the parameter is not found. */
4350static bool
4352{
4353 /* Default is false, re-entry is not allowed. */
4354 return !!networkstatus_get_param(NULL, "allow-network-reentry", 0, 0, 1);
4355}
4356
4357/** Connect to conn's specified addr and port. If it worked, conn
4358 * has now been added to the connection_array.
4359 *
4360 * Send back a connected cell. Include the resolved IP of the destination
4361 * address, but <em>only</em> if it's a general exit stream. (Rendezvous
4362 * streams must not reveal what IP they connected to.)
4363 */
4364void
4366{
4367 const tor_addr_t *addr;
4368 uint16_t port;
4369 connection_t *conn = TO_CONN(edge_conn);
4370 int socket_error = 0, result;
4371 const char *why_failed_exit_policy = NULL;
4372
4373 /* Apply exit policy to non-rendezvous connections. */
4374 if (! connection_edge_is_rendezvous_stream(edge_conn) &&
4375 my_exit_policy_rejects(&edge_conn->base_.addr,
4376 edge_conn->base_.port,
4377 &why_failed_exit_policy)) {
4378 if (BUG(!why_failed_exit_policy))
4379 why_failed_exit_policy = "";
4380 log_info(LD_EXIT,"%s failed exit policy%s. Closing.",
4381 connection_describe(conn),
4382 why_failed_exit_policy);
4384 connection_edge_end(edge_conn, END_STREAM_REASON_EXITPOLICY);
4385 circuit_detach_stream(circuit_get_by_edge_conn(edge_conn), edge_conn);
4386 connection_free(conn);
4387 return;
4388 }
4389
4390 /* Next, check for attempts to connect back into the Tor network. We don't
4391 * want to allow these for the same reason we don't want to allow
4392 * infinite-length circuits (see "A Practical Congestion Attack on Tor Using
4393 * Long Paths", Usenix Security 2009). See also ticket 2667.
4394 *
4395 * Skip this if the network reentry is allowed (known from the consensus).
4396 *
4397 * The TORPROTOCOL reason is used instead of EXITPOLICY so client do NOT
4398 * attempt to retry connecting onto another circuit that will also fail
4399 * bringing considerable more load on the network if so.
4400 *
4401 * Since the address+port set here is a bloomfilter, in very rare cases, the
4402 * check will create a false positive meaning that the destination could
4403 * actually be legit and thus being denied exit. However, sending back a
4404 * reason that makes the client retry results in much worst consequences in
4405 * case of an attack so this is a small price to pay. */
4406 if (!connection_edge_is_rendezvous_stream(edge_conn) &&
4408 nodelist_reentry_contains(&conn->addr, conn->port)) {
4409 log_info(LD_EXIT, "%s tried to connect back to a known relay address. "
4410 "Closing.", connection_describe(conn));
4412 connection_edge_end(edge_conn, END_STREAM_REASON_CONNECTREFUSED);
4413 circuit_detach_stream(circuit_get_by_edge_conn(edge_conn), edge_conn);
4414 connection_free(conn);
4415 return;
4416 }
4417
4418 /* Note the BEGIN stream as seen. We do this after the Exit policy check in
4419 * order to only account for valid streams. */
4420 rep_hist_note_exit_stream(RELAY_COMMAND_BEGIN);
4421
4422#ifdef HAVE_SYS_UN_H
4423 if (conn->socket_family != AF_UNIX) {
4424#else
4425 {
4426#endif /* defined(HAVE_SYS_UN_H) */
4427 addr = &conn->addr;
4428 port = conn->port;
4429
4430 if (tor_addr_family(addr) == AF_INET6)
4431 conn->socket_family = AF_INET6;
4432
4433 log_debug(LD_EXIT, "about to try connecting");
4434 result = connection_connect(conn, conn->address,
4435 addr, port, &socket_error);
4436#ifdef HAVE_SYS_UN_H
4437 } else {
4438 /*
4439 * In the AF_UNIX case, we expect to have already had conn->port = 1,
4440 * tor_addr_make_unspec(conn->addr) (cf. the way we mark in the incoming
4441 * case in connection_handle_listener_read()), and conn->address should
4442 * have the socket path to connect to.
4443 */
4444 tor_assert(conn->address && strlen(conn->address) > 0);
4445
4446 log_debug(LD_EXIT, "about to try connecting");
4447 result = connection_connect_unix(conn, conn->address, &socket_error);
4448#endif /* defined(HAVE_SYS_UN_H) */
4449 }
4450
4451 switch (result) {
4452 case -1: {
4453 int reason = errno_to_stream_end_reason(socket_error);
4454 connection_edge_end(edge_conn, reason);
4455 circuit_detach_stream(circuit_get_by_edge_conn(edge_conn), edge_conn);
4456 connection_free(conn);
4457 return;
4458 }
4459 case 0:
4461
4463 /* writable indicates finish;
4464 * readable/error indicates broken link in windows-land. */
4465 return;
4466 /* case 1: fall through */
4467 }
4468
4470 if (connection_get_outbuf_len(conn)) {
4471 /* in case there are any queued data cells, from e.g. optimistic data */
4473 } else {
4475 }
4476
4477 /* also, deliver a 'connected' cell back through the circuit. */
4478 if (connection_edge_is_rendezvous_stream(edge_conn)) {
4479 /* don't send an address back! */
4481 RELAY_COMMAND_CONNECTED,
4482 NULL, 0);
4483 } else { /* normal stream */
4484 uint8_t connected_payload[MAX_CONNECTED_CELL_PAYLOAD_LEN];
4485 int connected_payload_len =
4486 connected_cell_format_payload(connected_payload, &conn->addr,
4487 edge_conn->address_ttl);
4488 if (connected_payload_len < 0) {
4489 connection_edge_end(edge_conn, END_STREAM_REASON_INTERNAL);
4490 circuit_detach_stream(circuit_get_by_edge_conn(edge_conn), edge_conn);
4491 connection_free(conn);
4492 return;
4493 }
4494
4496 RELAY_COMMAND_CONNECTED,
4497 (char*)connected_payload,
4498 connected_payload_len);
4499 }
4500}
4501
4502/** Given an exit conn that should attach to us as a directory server, open a
4503 * bridge connection with a linked connection pair, create a new directory
4504 * conn, and join them together. Return 0 on success (or if there was an
4505 * error we could send back an end cell for). Return -(some circuit end
4506 * reason) if the circuit needs to be torn down. Either connects
4507 * <b>exitconn</b>, frees it, or marks it, as appropriate.
4508 */
4509static int
4511{
4512 dir_connection_t *dirconn = NULL;
4513 or_circuit_t *circ = TO_OR_CIRCUIT(exitconn->on_circuit);
4514
4515 log_info(LD_EXIT, "Opening local connection for anonymized directory exit");
4516
4517 /* Note the BEGIN_DIR stream as seen. */
4518 rep_hist_note_exit_stream(RELAY_COMMAND_BEGIN_DIR);
4519
4520 exitconn->base_.state = EXIT_CONN_STATE_OPEN;
4521
4522 dirconn = dir_connection_new(tor_addr_family(&exitconn->base_.addr));
4523
4524 tor_addr_copy(&dirconn->base_.addr, &exitconn->base_.addr);
4525 dirconn->base_.port = 0;
4526 dirconn->base_.address = tor_strdup(exitconn->base_.address);
4527 dirconn->base_.type = CONN_TYPE_DIR;
4528 dirconn->base_.purpose = DIR_PURPOSE_SERVER;
4530
4531 /* Note that the new dir conn belongs to the same tunneled request as
4532 * the edge conn, so that we can measure download times. */
4533 dirconn->dirreq_id = exitconn->dirreq_id;
4534
4535 connection_link_connections(TO_CONN(dirconn), TO_CONN(exitconn));
4536
4537 if (connection_add(TO_CONN(exitconn))<0) {
4538 connection_edge_end(exitconn, END_STREAM_REASON_RESOURCELIMIT);
4539 connection_free_(TO_CONN(exitconn));
4540 connection_free_(TO_CONN(dirconn));
4541 return 0;
4542 }
4543
4544 /* link exitconn to circ, now that we know we can use it. */
4545 exitconn->next_stream = circ->n_streams;
4546 circ->n_streams = exitconn;
4547
4548 if (connection_add(TO_CONN(dirconn))<0) {
4549 connection_edge_end(exitconn, END_STREAM_REASON_RESOURCELIMIT);
4551 connection_mark_for_close(TO_CONN(exitconn));
4552 connection_free_(TO_CONN(dirconn));
4553 return 0;
4554 }
4555
4558
4559 if (connection_edge_send_command(exitconn,
4560 RELAY_COMMAND_CONNECTED, NULL, 0) < 0) {
4561 connection_mark_for_close(TO_CONN(exitconn));
4562 connection_mark_for_close(TO_CONN(dirconn));
4563 return 0;
4564 }
4565
4566 return 0;
4567}
4568
4569/** Return 1 if <b>conn</b> is a rendezvous stream, or 0 if
4570 * it is a general stream.
4571 */
4572int
4574{
4575 tor_assert(conn);
4576
4577 if (conn->hs_ident) {
4578 return 1;
4579 }
4580 return 0;
4581}
4582
4583/** Return 1 if router <b>exit_node</b> is likely to allow stream <b>conn</b>
4584 * to exit from it, or 0 if it probably will not allow it.
4585 * (We might be uncertain if conn's destination address has not yet been
4586 * resolved.)
4587 */
4588int
4590 const node_t *exit_node)
4591{
4592 const or_options_t *options = get_options();
4593
4594 tor_assert(conn);
4596 tor_assert(exit_node);
4597
4598 /* If a particular exit node has been requested for the new connection,
4599 * make sure the exit node of the existing circuit matches exactly.
4600 */
4601 if (conn->chosen_exit_name) {
4602 const node_t *chosen_exit =
4604 if (!chosen_exit || tor_memneq(chosen_exit->identity,
4605 exit_node->identity, DIGEST_LEN)) {
4606 /* doesn't match */
4607// log_debug(LD_APP,"Requested node '%s', considering node '%s'. No.",
4608// conn->chosen_exit_name, exit->nickname);
4609 return 0;
4610 }
4611 }
4612
4613 if (conn->use_begindir) {
4614 /* Internal directory fetches do not count as exiting. */
4615 return 1;
4616 }
4617
4619 tor_addr_t addr, *addrp = NULL;
4621 if (0 == tor_addr_parse(&addr, conn->socks_request->address)) {
4622 addrp = &addr;
4623 } else if (!conn->entry_cfg.ipv4_traffic && conn->entry_cfg.ipv6_traffic) {
4624 tor_addr_make_null(&addr, AF_INET6);
4625 addrp = &addr;
4626 } else if (conn->entry_cfg.ipv4_traffic && !conn->entry_cfg.ipv6_traffic) {
4627 tor_addr_make_null(&addr, AF_INET);
4628 addrp = &addr;
4629 }
4631 exit_node);
4632 if (r == ADDR_POLICY_REJECTED)
4633 return 0; /* We know the address, and the exit policy rejects it. */
4635 return 0; /* We don't know the addr, but the exit policy rejects most
4636 * addresses with this port. Since the user didn't ask for
4637 * this node, err on the side of caution. */
4638 } else if (SOCKS_COMMAND_IS_RESOLVE(conn->socks_request->command)) {
4639 /* Don't send DNS requests to non-exit servers by default. */
4640 if (!conn->chosen_exit_name && node_exit_policy_rejects_all(exit_node))
4641 return 0;
4642 }
4643 if (routerset_contains_node(options->ExcludeExitNodesUnion_, exit_node)) {
4644 /* Not a suitable exit. Refuse it. */
4645 return 0;
4646 }
4647
4648 return 1;
4649}
4650
4651/** Return true iff the (possibly NULL) <b>alen</b>-byte chunk of memory at
4652 * <b>a</b> is equal to the (possibly NULL) <b>blen</b>-byte chunk of memory
4653 * at <b>b</b>. */
4654static int
4655memeq_opt(const char *a, size_t alen, const char *b, size_t blen)
4656{
4657 if (a == NULL) {
4658 return (b == NULL);
4659 } else if (b == NULL) {
4660 return 0;
4661 } else if (alen != blen) {
4662 return 0;
4663 } else {
4664 return tor_memeq(a, b, alen);
4665 }
4666}
4667
4668/**
4669 * Return true iff none of the isolation flags and fields in <b>conn</b>
4670 * should prevent it from being attached to <b>circ</b>.
4671 */
4672int
4674 const origin_circuit_t *circ)
4675{
4676 const uint8_t iso = conn->entry_cfg.isolation_flags;
4677 const socks_request_t *sr = conn->socks_request;
4678
4679 /* If circ has never been used for an isolated connection, we can
4680 * totally use it for this one. */
4681 if (!circ->isolation_values_set)
4682 return 1;
4683
4684 /* If circ has been used for connections having more than one value
4685 * for some field f, it will have the corresponding bit set in
4686 * isolation_flags_mixed. If isolation_flags_mixed has any bits
4687 * in common with iso, then conn must be isolated from at least
4688 * one stream that has been attached to circ. */
4689 if ((iso & circ->isolation_flags_mixed) != 0) {
4690 /* For at least one field where conn is isolated, the circuit
4691 * already has mixed streams. */
4692 return 0;
4693 }
4694
4695 if (! conn->original_dest_address) {
4696 log_warn(LD_BUG, "Reached connection_edge_compatible_with_circuit without "
4697 "having set conn->original_dest_address");
4698 ((entry_connection_t*)conn)->original_dest_address =
4699 tor_strdup(conn->socks_request->address);
4700 }
4701
4702 if ((iso & ISO_STREAM) &&
4704 ENTRY_TO_CONN(conn)->global_identifier))
4705 return 0;
4706
4707 if ((iso & ISO_DESTPORT) && conn->socks_request->port != circ->dest_port)
4708 return 0;
4709 if ((iso & ISO_DESTADDR) &&
4710 strcasecmp(conn->original_dest_address, circ->dest_address))
4711 return 0;
4712 if ((iso & ISO_SOCKSAUTH) &&
4713 (! memeq_opt(sr->username, sr->usernamelen,
4714 circ->socks_username, circ->socks_username_len) ||
4715 ! memeq_opt(sr->password, sr->passwordlen,
4716 circ->socks_password, circ->socks_password_len)))
4717 return 0;
4718 if ((iso & ISO_CLIENTPROTO) &&
4719 (conn->socks_request->listener_type != circ->client_proto_type ||
4720 conn->socks_request->socks_version != circ->client_proto_socksver))
4721 return 0;
4722 if ((iso & ISO_CLIENTADDR) &&
4723 !tor_addr_eq(&ENTRY_TO_CONN(conn)->addr, &circ->client_addr))
4724 return 0;
4725 if ((iso & ISO_SESSIONGRP) &&
4726 conn->entry_cfg.session_group != circ->session_group)
4727 return 0;
4728 if ((iso & ISO_NYM_EPOCH) && conn->nym_epoch != circ->nym_epoch)
4729 return 0;
4730
4731 return 1;
4732}
4733
4734/**
4735 * If <b>dry_run</b> is false, update <b>circ</b>'s isolation flags and fields
4736 * to reflect having had <b>conn</b> attached to it, and return 0. Otherwise,
4737 * if <b>dry_run</b> is true, then make no changes to <b>circ</b>, and return
4738 * a bitfield of isolation flags that we would have to set in
4739 * isolation_flags_mixed to add <b>conn</b> to <b>circ</b>, or -1 if
4740 * <b>circ</b> has had no streams attached to it.
4741 */
4742int
4744 origin_circuit_t *circ,
4745 int dry_run)
4746{
4747 const socks_request_t *sr = conn->socks_request;
4748 if (! conn->original_dest_address) {
4749 log_warn(LD_BUG, "Reached connection_update_circuit_isolation without "
4750 "having set conn->original_dest_address");
4751 ((entry_connection_t*)conn)->original_dest_address =
4752 tor_strdup(conn->socks_request->address);
4753 }
4754
4755 if (!circ->isolation_values_set) {
4756 if (dry_run)
4757 return -1;
4759 ENTRY_TO_CONN(conn)->global_identifier;
4760 circ->dest_port = conn->socks_request->port;
4761 circ->dest_address = tor_strdup(conn->original_dest_address);
4762 circ->client_proto_type = conn->socks_request->listener_type;
4763 circ->client_proto_socksver = conn->socks_request->socks_version;
4764 tor_addr_copy(&circ->client_addr, &ENTRY_TO_CONN(conn)->addr);
4765 circ->session_group = conn->entry_cfg.session_group;
4766 circ->nym_epoch = conn->nym_epoch;
4767 circ->socks_username = sr->username ?
4768 tor_memdup(sr->username, sr->usernamelen) : NULL;
4769 circ->socks_password = sr->password ?
4770 tor_memdup(sr->password, sr->passwordlen) : NULL;
4771 circ->socks_username_len = sr->usernamelen;
4772 circ->socks_password_len = sr->passwordlen;
4773
4774 circ->isolation_values_set = 1;
4775 return 0;
4776 } else {
4777 uint8_t mixed = 0;
4778 if (conn->socks_request->port != circ->dest_port)
4779 mixed |= ISO_DESTPORT;
4780 if (strcasecmp(conn->original_dest_address, circ->dest_address))
4781 mixed |= ISO_DESTADDR;
4782 if (!memeq_opt(sr->username, sr->usernamelen,
4783 circ->socks_username, circ->socks_username_len) ||
4784 !memeq_opt(sr->password, sr->passwordlen,
4785 circ->socks_password, circ->socks_password_len))
4786 mixed |= ISO_SOCKSAUTH;
4787 if ((conn->socks_request->listener_type != circ->client_proto_type ||
4788 conn->socks_request->socks_version != circ->client_proto_socksver))
4789 mixed |= ISO_CLIENTPROTO;
4790 if (!tor_addr_eq(&ENTRY_TO_CONN(conn)->addr, &circ->client_addr))
4791 mixed |= ISO_CLIENTADDR;
4792 if (conn->entry_cfg.session_group != circ->session_group)
4793 mixed |= ISO_SESSIONGRP;
4794 if (conn->nym_epoch != circ->nym_epoch)
4795 mixed |= ISO_NYM_EPOCH;
4796
4797 if (dry_run)
4798 return mixed;
4799
4800 if ((mixed & conn->entry_cfg.isolation_flags) != 0) {
4801 log_warn(LD_BUG, "Updating a circuit with seemingly incompatible "
4802 "isolation flags.");
4803 }
4804 circ->isolation_flags_mixed |= mixed;
4805 return 0;
4806 }
4807}
4808
4809/**
4810 * Clear the isolation settings on <b>circ</b>.
4811 *
4812 * This only works on an open circuit that has never had a stream attached to
4813 * it, and whose isolation settings are hypothetical. (We set hypothetical
4814 * isolation settings on circuits as we're launching them, so that we
4815 * know whether they can handle more streams or whether we need to launch
4816 * even more circuits. Once the circuit is open, if it turns out that
4817 * we no longer have any streams to attach to it, we clear the isolation flags
4818 * and data so that other streams can have a chance.)
4819 */
4820void
4822{
4824 log_warn(LD_BUG, "Tried to clear the isolation status of a dirty circuit");
4825 return;
4826 }
4827 if (TO_CIRCUIT(circ)->state != CIRCUIT_STATE_OPEN) {
4828 log_warn(LD_BUG, "Tried to clear the isolation status of a non-open "
4829 "circuit");
4830 return;
4831 }
4832
4833 circ->isolation_values_set = 0;
4834 circ->isolation_flags_mixed = 0;
4836 circ->client_proto_type = 0;
4837 circ->client_proto_socksver = 0;
4838 circ->dest_port = 0;
4839 tor_addr_make_unspec(&circ->client_addr);
4840 tor_free(circ->dest_address);
4841 circ->session_group = -1;
4842 circ->nym_epoch = 0;
4843 if (circ->socks_username) {
4844 memwipe(circ->socks_username, 0x11, circ->socks_username_len);
4845 tor_free(circ->socks_username);
4846 }
4847 if (circ->socks_password) {
4848 memwipe(circ->socks_password, 0x05, circ->socks_password_len);
4849 tor_free(circ->socks_password);
4850 }
4851 circ->socks_username_len = circ->socks_password_len = 0;
4852}
4853
4854/** Send an END and mark for close the given edge connection conn using the
4855 * given reason that has to be a stream reason.
4856 *
4857 * Note: We don't unattached the AP connection (if applicable) because we
4858 * don't want to flush the remaining data. This function aims at ending
4859 * everything quickly regardless of the connection state.
4860 *
4861 * This function can't fail and does nothing if conn is NULL. */
4862void
4864{
4865 if (!conn) {
4866 return;
4867 }
4868
4869 connection_edge_end(conn, reason);
4870 connection_mark_for_close(TO_CONN(conn));
4871}
4872
4873/** Free all storage held in module-scoped variables for connection_edge.c */
4874void
4876{
4877 untried_pending_connections = 0;
4878 smartlist_free(pending_entry_connections);
4880 mainloop_event_free(attach_pending_entry_connections_ev);
4881}
void tor_addr_copy(tor_addr_t *dest, const tor_addr_t *src)
Definition: address.c:933
void tor_addr_from_ipv4n(tor_addr_t *dest, uint32_t v4addr)
Definition: address.c:889
void tor_addr_make_unspec(tor_addr_t *a)
Definition: address.c:225
int tor_addr_hostname_is_local(const char *name)
Definition: address.c:2090
int tor_addr_parse(tor_addr_t *addr, const char *src)
Definition: address.c:1349
void tor_addr_make_null(tor_addr_t *a, sa_family_t family)
Definition: address.c:235
int tor_addr_port_split(int severity, const char *addrport, char **address_out, uint16_t *port_out)
Definition: address.c:1916
int tor_addr_is_null(const tor_addr_t *addr)
Definition: address.c:780
char * tor_addr_to_str_dup(const tor_addr_t *addr)
Definition: address.c:1164
int tor_addr_parse_PTR_name(tor_addr_t *result, const char *address, int family, int accept_regular)
Definition: address.c:380
void tor_addr_from_in6(tor_addr_t *dest, const struct in6_addr *in6)
Definition: address.c:911
const char * tor_addr_to_str(char *dest, const tor_addr_t *addr, size_t len, int decorate)
Definition: address.c:328
int tor_addr_from_sockaddr(tor_addr_t *a, const struct sockaddr *sa, uint16_t *port_out)
Definition: address.c:165
void tor_addr_from_ipv6_bytes(tor_addr_t *dest, const uint8_t *ipv6_bytes)
Definition: address.c:900
char * tor_dup_ip(uint32_t addr)
Definition: address.c:2047
int tor_addr_to_PTR_name(char *out, size_t outlen, const tor_addr_t *addr)
Definition: address.c:470
static uint32_t tor_addr_to_ipv4n(const tor_addr_t *a)
Definition: address.h:152
#define REVERSE_LOOKUP_NAME_BUF_LEN
Definition: address.h:296
static sa_family_t tor_addr_family(const tor_addr_t *a)
Definition: address.h:187
static const struct in6_addr * tor_addr_to_in6(const tor_addr_t *a)
Definition: address.h:117
#define tor_addr_to_in6_addr8(x)
Definition: address.h:135
#define tor_addr_eq(a, b)
Definition: address.h:280
void client_dns_set_reverse_addressmap(entry_connection_t *for_conn, const char *address, const char *v, const char *exitname, int ttl)
Definition: addressmap.c:767
void clear_trackexithost_mappings(const char *exitname)
Definition: addressmap.c:174
int address_is_in_virtual_range(const char *address)
Definition: addressmap.c:860
void client_dns_set_addressmap(entry_connection_t *for_conn, const char *address, const tor_addr_t *val, const char *exitname, int ttl)
Definition: addressmap.c:728
int addressmap_rewrite(char *address, size_t maxlen, unsigned flags, time_t *expires_out, addressmap_entry_source_t *exit_source_out)
Definition: addressmap.c:383
int addressmap_address_should_automap(const char *address, const or_options_t *options)
Definition: addressmap.c:249
const char * addressmap_register_virtual_address(int type, char *new_address)
Definition: addressmap.c:1000
int addressmap_rewrite_reverse(char *address, size_t maxlen, unsigned flags, time_t *expires_out)
Definition: addressmap.c:503
Header for addressmap.c.
time_t approx_time(void)
Definition: approx_time.c:32
Header for backtrace.c.
const char * hex_str(const char *from, size_t fromlen)
Definition: binascii.c:34
void base16_encode(char *dest, size_t destlen, const char *src, size_t srclen)
Definition: binascii.c:478
size_t buf_datalen(const buf_t *buf)
Definition: buffers.c:394
int buf_set_to_copy(buf_t **output, const buf_t *input)
Definition: buffers.c:898
Header file for buffers.c.
static void set_uint16(void *cp, uint16_t v)
Definition: bytes.h:78
static void set_uint32(void *cp, uint32_t v)
Definition: bytes.h:87
static void set_uint8(void *cp, uint8_t v)
Definition: bytes.h:31
static uint32_t get_uint32(const void *cp)
Definition: bytes.h:54
Fixed-size cell structure.
int channel_is_client(const channel_t *chan)
Definition: channel.c:2918
int channel_get_addr_if_possible(const channel_t *chan, tor_addr_t *addr_out)
Definition: channel.c:2860
const char * channel_describe_peer(channel_t *chan)
Definition: channel.c:2840
Header file for channel.c.
const char * pathbias_state_to_string(path_state_t state)
Definition: circpathbias.c:265
void pathbias_mark_use_rollback(origin_circuit_t *circ)
Definition: circpathbias.c:722
void pathbias_mark_use_success(origin_circuit_t *circ)
Definition: circpathbias.c:683
Header file for circuitbuild.c.
circuit_t * circuit_get_by_edge_conn(edge_connection_t *conn)
Definition: circuitlist.c:1606
origin_circuit_t * TO_ORIGIN_CIRCUIT(circuit_t *x)
Definition: circuitlist.c:185
void assert_circuit_ok(const circuit_t *c)
Definition: circuitlist.c:2809
const char * circuit_state_to_string(int state)
Definition: circuitlist.c:781
or_circuit_t * TO_OR_CIRCUIT(circuit_t *x)
Definition: circuitlist.c:173
const char * circuit_purpose_to_string(uint8_t purpose)
Definition: circuitlist.c:929
Header file for circuitlist.c.
#define CIRCUIT_PURPOSE_IS_CLIENT(p)
Definition: circuitlist.h:150
#define CIRCUIT_PURPOSE_C_MEASURE_TIMEOUT
Definition: circuitlist.h:93
#define CIRCUIT_PURPOSE_PATH_BIAS_TESTING
Definition: circuitlist.h:123
#define CIRCUIT_STATE_OPEN
Definition: circuitlist.h:32
#define CIRCUIT_PURPOSE_C_REND_JOINED
Definition: circuitlist.h:88
#define CIRCUIT_PURPOSE_CONTROLLER
Definition: circuitlist.h:121
#define CIRCUIT_IS_ORIGIN(c)
Definition: circuitlist.h:154
#define CIRCUIT_PURPOSE_OR
Definition: circuitlist.h:39
#define CIRCUIT_PURPOSE_S_REND_JOINED
Definition: circuitlist.h:110
#define CIRCUIT_PURPOSE_S_HSDIR_POST
Definition: circuitlist.h:112
#define CIRCUIT_PURPOSE_C_HSDIR_GET
Definition: circuitlist.h:90
#define CIRCUIT_PURPOSE_C_GENERAL
Definition: circuitlist.h:70
void circpad_machine_event_circ_has_streams(origin_circuit_t *circ)
Header file for circuitpadding.c.
double get_circuit_build_timeout_ms(void)
Definition: circuitstats.c:101
Header file for circuitstats.c.
void circuit_detach_stream(circuit_t *circ, edge_connection_t *conn)
Definition: circuituse.c:1352
void circuit_read_valid_data(origin_circuit_t *circ, uint16_t relay_body_len)
Definition: circuituse.c:3197
int connection_ap_handshake_attach_circuit(entry_connection_t *conn)
Definition: circuituse.c:2835
int connection_ap_handshake_attach_chosen_circuit(entry_connection_t *conn, origin_circuit_t *circ, crypt_path_t *cpath)
Definition: circuituse.c:2750
void mark_circuit_unusable_for_new_conns(origin_circuit_t *circ)
Definition: circuituse.c:3148
Header file for circuituse.c.
#define MAX(a, b)
Definition: cmp.h:22
#define SUBTYPE_P(p, subtype, basemember)
mainloop_event_t * mainloop_event_postloop_new(void(*cb)(mainloop_event_t *, void *), void *userdata)
void mainloop_event_activate(mainloop_event_t *event)
Header for compat_libevent.c.
uint64_t monotime_absolute_usec(void)
Definition: compat_time.c:804
const char * escaped_safe_str_client(const char *address)
Definition: config.c:1136
const char * escaped_safe_str(const char *address)
Definition: config.c:1148
const or_options_t * get_options(void)
Definition: config.c:944
tor_cmdline_mode_t command
Definition: config.c:2468
Header file for config.c.
Header for confline.c.
uint64_t edge_get_max_rtt(const edge_connection_t *stream)
Definition: conflux_util.c:208
void conflux_sync_circ_fields(conflux_t *cfx, origin_circuit_t *ref_circ)
Definition: conflux_util.c:302
void conflux_update_half_streams(origin_circuit_t *circ, smartlist_t *half_streams)
Definition: conflux_util.c:355
Header file for conflux_util.c.
bool edge_uses_flow_control(const edge_connection_t *stream)
APIs for stream flow control on congestion controlled circuits.
edge_connection_t * edge_connection_new(int type, int socket_family)
Definition: connection.c:627
void connection_link_connections(connection_t *conn_a, connection_t *conn_b)
Definition: connection.c:758
int connection_buf_get_line(connection_t *conn, char *data, size_t *data_len)
Definition: connection.c:4331
void connection_mark_for_close_(connection_t *conn, int line, const char *file)
Definition: connection.c:1088
void connection_close_immediate(connection_t *conn)
Definition: connection.c:1055
int connection_state_is_open(connection_t *conn)
Definition: connection.c:5058
const char * connection_describe_peer(const connection_t *conn)
Definition: connection.c:530
entry_connection_t * entry_connection_new(int type, int socket_family)
Definition: connection.c:603
const char * connection_describe(const connection_t *conn)
Definition: connection.c:545
dir_connection_t * dir_connection_new(int socket_family)
Definition: connection.c:563
void connection_free_(connection_t *conn)
Definition: connection.c:972
int connection_connect(connection_t *conn, const char *address, const tor_addr_t *addr, uint16_t port, int *socket_error)
Definition: connection.c:2446
const char * conn_state_to_string(int type, int state)
Definition: connection.c:304
Header file for connection.c.
#define CONN_TYPE_AP_HTTP_CONNECT_LISTENER
Definition: connection.h:75
#define CONN_TYPE_DIR_LISTENER
Definition: connection.h:53
#define CONN_TYPE_AP
Definition: connection.h:51
#define connection_mark_and_flush_(c, line, file)
Definition: connection.h:179
#define CONN_TYPE_DIR
Definition: connection.h:55
#define CONN_TYPE_EXIT
Definition: connection.h:46
int connection_edge_compatible_with_circuit(const entry_connection_t *conn, const origin_circuit_t *circ)
int connection_ap_handshake_rewrite_and_attach(entry_connection_t *conn, origin_circuit_t *circ, crypt_path_t *cpath)
int connection_half_edge_is_valid_data(const smartlist_t *half_conns, streamid_t stream_id)
void connection_ap_mark_as_waiting_for_renddesc(entry_connection_t *entry_conn)
void connection_mark_unattached_ap_(entry_connection_t *conn, int endreason, int line, const char *file)
static uint32_t connection_ap_get_begincell_flags(entry_connection_t *ap_conn)
void connection_edge_free_all(void)
void connection_ap_mark_as_non_pending_circuit(entry_connection_t *entry_conn)
static int connection_half_edge_compare_bsearch(const void *key, const void **member)
static size_t n_half_conns_allocated
int connection_ap_rewrite_and_attach_if_allowed(entry_connection_t *conn, origin_circuit_t *circ, crypt_path_t *cpath)
uint32_t clip_dns_fuzzy_ttl(uint32_t ttl)
static int connection_ap_supports_optimistic_data(const entry_connection_t *)
STATIC int connection_ap_process_http_connect(entry_connection_t *conn)
const edge_connection_t * CONST_TO_EDGE_CONN(const connection_t *c)
#define MAX_CONNECTED_CELL_PAYLOAD_LEN
entry_connection_t * connection_ap_make_link(connection_t *partner, char *address, uint16_t port, const char *digest, int session_group, int isolation_flags, int use_begindir, int want_onehop)
void connection_ap_expire_beginning(void)
void connection_ap_fail_onehop(const char *failed_digest, cpath_build_state_t *build_state)
static void connection_edge_about_to_close(edge_connection_t *edge_conn)
int connection_ap_detach_retriable(entry_connection_t *conn, origin_circuit_t *circ, int reason)
STATIC int connected_cell_format_payload(uint8_t *payload_out, const tor_addr_t *addr, uint32_t ttl)
void connection_ap_rescan_and_attach_pending(void)
int connection_ap_handshake_send_begin(entry_connection_t *ap_conn)
static int connection_ap_process_natd(entry_connection_t *conn)
static int consider_plaintext_ports(entry_connection_t *conn, uint16_t port)
void connection_ap_handshake_socks_reply(entry_connection_t *conn, char *reply, size_t replylen, int endreason)
static smartlist_t * pending_entry_connections
int connection_half_edge_is_valid_end(smartlist_t *half_conns, streamid_t stream_id)
void connection_exit_connect(edge_connection_t *edge_conn)
uint32_t clip_dns_ttl(uint32_t ttl)
static bool network_reentry_is_allowed(void)
bool connection_half_edges_waiting(const origin_circuit_t *circ)
int connection_ap_process_transparent(entry_connection_t *conn)
void connection_ap_mark_as_pending_circuit_(entry_connection_t *entry_conn, const char *fname, int lineno)
#define TRACKHOSTEXITS_RETRIES
static mainloop_event_t * attach_pending_entry_connections_ev
void connection_edge_end_close(edge_connection_t *conn, uint8_t reason)
int connection_edge_finished_connecting(edge_connection_t *edge_conn)
int connection_edge_destroy(circid_t circ_id, edge_connection_t *conn)
static int connection_exit_connect_dir(edge_connection_t *exitconn)
int connection_edge_finished_flushing(edge_connection_t *conn)
static int my_exit_policy_rejects(const tor_addr_t *addr, uint16_t port, const char **why_rejected)
void circuit_clear_isolation(origin_circuit_t *circ)
int connection_exit_begin_resolve(cell_t *cell, or_circuit_t *circ)
void connection_exit_about_to_close(edge_connection_t *edge_conn)
static int connection_ap_get_original_destination(entry_connection_t *conn, socks_request_t *req)
STATIC bool parse_extended_hostname(char *address, hostname_type_t *type_out)
int connection_half_edge_is_valid_connected(const smartlist_t *half_conns, streamid_t stream_id)
int connection_edge_flushed_some(edge_connection_t *conn)
entry_connection_t * EDGE_TO_ENTRY_CONN(edge_connection_t *c)
int connection_ap_handshake_send_resolve(entry_connection_t *ap_conn)
void connection_ap_handshake_socks_resolved_addr(entry_connection_t *conn, const tor_addr_t *answer, int ttl, time_t expires)
int connection_edge_update_circuit_isolation(const entry_connection_t *conn, origin_circuit_t *circ, int dry_run)
int connection_edge_reached_eof(edge_connection_t *conn)
const entry_connection_t * CONST_TO_ENTRY_CONN(const connection_t *c)
static void tell_controller_about_resolved_result(entry_connection_t *conn, int answer_type, size_t answer_len, const char *answer, int ttl, time_t expires)
int connection_ap_can_use_exit(const entry_connection_t *conn, const node_t *exit_node)
int connection_half_edge_is_valid_resolved(smartlist_t *half_conns, streamid_t stream_id)
int connection_edge_end_errno(edge_connection_t *conn)
int connection_edge_end(edge_connection_t *conn, uint8_t reason)
void connection_ap_attach_pending(int retry)
size_t half_streams_get_total_allocation(void)
int connection_half_edge_is_valid_sendme(const smartlist_t *half_conns, streamid_t stream_id)
int connection_edge_is_rendezvous_stream(const edge_connection_t *conn)
static int connection_ap_handle_onion(entry_connection_t *conn, socks_request_t *socks, origin_circuit_t *circ)
STATIC int begin_cell_parse(const cell_t *cell, begin_cell_t *bcell, uint8_t *end_reason_out)
void connection_ap_about_to_close(entry_connection_t *entry_conn)
static int relay_send_end_cell_from_edge(streamid_t stream_id, circuit_t *circ, uint8_t reason, crypt_path_t *cpath_layer)
const entry_connection_t * CONST_EDGE_TO_ENTRY_CONN(const edge_connection_t *c)
entry_connection_t * TO_ENTRY_CONN(connection_t *c)
STATIC void connection_half_edge_add(const edge_connection_t *conn, origin_circuit_t *circ)
static int handle_hs_exit_conn(circuit_t *circ, edge_connection_t *conn)
void connection_ap_handshake_socks_resolved(entry_connection_t *conn, int answer_type, size_t answer_len, const uint8_t *answer, int ttl, time_t expires)
static int memeq_opt(const char *a, size_t alen, const char *b, size_t blen)
int connection_exit_begin_conn(cell_t *cell, circuit_t *circ)
void connection_entry_set_controller_wait(entry_connection_t *conn)
streamid_t get_unique_stream_id_by_circ(origin_circuit_t *circ)
void half_edge_free_(half_edge_t *he)
void circuit_discard_optional_exit_enclaves(extend_info_t *info)
static int connection_ap_handshake_process_socks(entry_connection_t *conn)
edge_connection_t * TO_EDGE_CONN(connection_t *c)
int connection_edge_process_inbuf(edge_connection_t *conn, int package_partial)
STATIC half_edge_t * connection_half_edge_find_stream_id(const smartlist_t *half_conns, streamid_t stream_id)
static int compute_retry_timeout(entry_connection_t *conn)
Header file for connection_edge.c.
#define AP_CONN_STATE_HTTP_CONNECT_WAIT
#define EXIT_CONN_STATE_CONNECTING
#define AP_CONN_STATE_CONTROLLER_WAIT
#define EXIT_CONN_STATE_OPEN
#define AP_CONN_STATE_SOCKS_WAIT
int address_is_invalid_destination(const char *address, int client)
Definition: addressmap.c:1082
#define BEGIN_FLAG_IPV6_PREFERRED
#define EXIT_CONN_STATE_RESOLVEFAILED
#define AP_CONN_STATE_IS_UNATTACHED(s)
#define AP_CONN_STATE_CONNECT_WAIT
hostname_type_t
#define AP_CONN_STATE_OPEN
#define EXIT_PURPOSE_CONNECT
#define AP_CONN_STATE_RESOLVE_WAIT
#define BEGIN_FLAG_IPV4_NOT_OK
#define FUZZY_DNS_TTL
#define AP_CONN_STATE_CIRCUIT_WAIT
#define EXIT_CONN_STATE_RESOLVING
#define MIN_DNS_TTL
#define AP_CONN_STATE_NATD_WAIT
#define AP_CONN_STATE_RENDDESC_WAIT
#define BEGIN_FLAG_IPV6_OK
#define EXIT_PURPOSE_RESOLVE
#define MAX_DNS_TTL
int connection_or_digest_is_known_relay(const char *id_digest)
Header file for connection_or.c.
int control_event_stream_bandwidth(edge_connection_t *edge_conn)
int control_event_client_status(int severity, const char *format,...)
int control_event_stream_status(entry_connection_t *conn, stream_status_event_t tp, int reason_code)
int control_event_address_mapped(const char *from, const char *to, time_t expires, const char *error, const int cached, uint64_t stream_id)
Header file for control_events.c.
#define REMAP_STREAM_SOURCE_CACHE
Circuit-build-stse structure.
#define HEX_DIGEST_LEN
Definition: crypto_digest.h:35
Common functions for using (pseudo-)random number generators.
unsigned crypto_rand_uint(unsigned limit)
void memwipe(void *mem, uint8_t byte, size_t sz)
Definition: crypto_util.c:55
Common functions for cryptographic routines.
const char * extend_info_describe(const extend_info_t *ei)
Definition: describe.c:224
const char * node_describe(const node_t *node)
Definition: describe.c:160
Header file for describe.c.
int tor_memeq(const void *a, const void *b, size_t sz)
Definition: di_ops.c:107
#define tor_memneq(a, b, sz)
Definition: di_ops.h:21
#define DIGEST_LEN
Definition: digest_sizes.h:20
Client/server directory connection structure.
int purpose_needs_anonymity(uint8_t dir_purpose, uint8_t router_purpose, const char *resource)
Definition: directory.c:113
dir_connection_t * TO_DIR_CONN(connection_t *c)
Definition: directory.c:88
char * http_get_header(const char *headers, const char *which)
Definition: directory.c:325
int parse_http_command(const char *headers, char **command_out, char **url_out)
Definition: directory.c:271
Header file for directory.c.
#define DIR_CONN_STATE_SERVER_COMMAND_WAIT
Definition: directory.h:28
#define DIR_PURPOSE_SERVER
Definition: directory.h:60
int directory_permits_begindir_requests(const or_options_t *options)
Definition: dirserv.c:110
Header file for dirserv.c.
void connection_dns_remove(edge_connection_t *conn)
Definition: dns.c:993
int dns_resolve(edge_connection_t *exitconn)
Definition: dns.c:632
Header file for dns.c.
void dnsserv_reject_request(entry_connection_t *conn)
Definition: dnsserv.c:292
void dnsserv_resolved(entry_connection_t *conn, int answer_type, size_t answer_len, const char *answer, int ttl)
Definition: dnsserv.c:342
Header file for dnsserv.c.
Entry connection structure.
#define ENTRY_TO_EDGE_CONN(c)
const char * escaped(const char *s)
Definition: escape.c:126
Extend-info structure.
bool extend_info_has_orport(const extend_info_t *ei, const tor_addr_t *addr, uint16_t port)
Definition: extendinfo.c:243
Header for core/or/extendinfo.c.
int tor_open_cloexec(const char *path, int flags, unsigned mode)
Definition: files.c:54
Half-open connection structure.
int we_are_hibernating(void)
Definition: hibernate.c:937
Header file for hibernate.c.
const hs_descriptor_t * hs_cache_lookup_as_client(const ed25519_public_key_t *key)
Definition: hs_cache.c:845
Header file for hs_cache.c.
Header file containing circuit data for the whole HS subsystem.
int hs_client_any_intro_points_usable(const ed25519_public_key_t *service_pk, const hs_descriptor_t *desc)
Definition: hs_client.c:2205
int hs_client_refetch_hsdesc(const ed25519_public_key_t *identity_pk)
Definition: hs_client.c:2228
Header file containing client data for the HS subsystem.
@ HS_CLIENT_FETCH_PENDING
Definition: hs_client.h:33
@ HS_CLIENT_FETCH_MISSING_INFO
Definition: hs_client.h:31
@ HS_CLIENT_FETCH_NO_HSDIRS
Definition: hs_client.h:27
@ HS_CLIENT_FETCH_HAVE_DESC
Definition: hs_client.h:25
@ HS_CLIENT_FETCH_NOT_ALLOWED
Definition: hs_client.h:29
@ HS_CLIENT_FETCH_ERROR
Definition: hs_client.h:21
@ HS_CLIENT_FETCH_LAUNCHED
Definition: hs_client.h:23
int hs_parse_address(const char *address, ed25519_public_key_t *key_out, uint8_t *checksum_out, uint8_t *version_out)
Definition: hs_common.c:840
int hs_address_is_valid(const char *address)
Definition: hs_common.c:856
void hs_inc_rdv_stream_counter(origin_circuit_t *circ)
Definition: hs_common.c:1737
Header file containing common data for the whole HS subsystem.
#define HS_SERVICE_ADDR_LEN_BASE32
Definition: hs_common.h:80
hs_ident_edge_conn_t * hs_ident_edge_conn_new(const ed25519_public_key_t *identity_pk)
Definition: hs_ident.c:84
hs_circuit_id_protocol_t hs_service_exports_circuit_id(const ed25519_public_key_t *pk)
Definition: hs_service.c:4325
int hs_service_set_conn_addr_port(const origin_circuit_t *circ, edge_connection_t *conn)
Definition: hs_service.c:4245