Merge branch 'ticket40081_035' into ticket40081_044
[tor.git] / src / core / or / circuitbuild.c
bloba1b8ba78ab2e12aa5ff62371461cab6333b40232
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-2020, The Tor Project, Inc. */
5 /* See LICENSE for licensing information */
7 /**
8 * \file circuitbuild.c
10 * \brief Implements the details of building circuits (by chosing paths,
11 * constructing/sending create/extend cells, and so on).
13 * On the client side, this module handles launching circuits. Circuit
14 * launches are srtarted from circuit_establish_circuit(), called from
15 * circuit_launch_by_extend_info()). To choose the path the circuit will
16 * take, onion_extend_cpath() calls into a maze of node selection functions.
18 * Once the circuit is ready to be launched, the first hop is treated as a
19 * special case with circuit_handle_first_hop(), since it might need to open a
20 * channel. As the channel opens, and later as CREATED and RELAY_EXTENDED
21 * cells arrive, the client will invoke circuit_send_next_onion_skin() to send
22 * CREATE or RELAY_EXTEND cells.
24 * The server side is handled in feature/relay/circuitbuild_relay.c.
25 **/
27 #define CIRCUITBUILD_PRIVATE
28 #define OCIRC_EVENT_PRIVATE
30 #include "core/or/or.h"
31 #include "app/config/config.h"
32 #include "lib/confmgt/confmgt.h"
33 #include "core/crypto/hs_ntor.h"
34 #include "core/crypto/onion_crypto.h"
35 #include "core/crypto/onion_fast.h"
36 #include "core/crypto/onion_tap.h"
37 #include "core/mainloop/connection.h"
38 #include "core/mainloop/mainloop.h"
39 #include "core/or/channel.h"
40 #include "core/or/circuitbuild.h"
41 #include "core/or/circuitlist.h"
42 #include "core/or/circuitstats.h"
43 #include "core/or/circuituse.h"
44 #include "core/or/circuitpadding.h"
45 #include "core/or/command.h"
46 #include "core/or/connection_edge.h"
47 #include "core/or/connection_or.h"
48 #include "core/or/onion.h"
49 #include "core/or/ocirc_event.h"
50 #include "core/or/policies.h"
51 #include "core/or/relay.h"
52 #include "core/or/crypt_path.h"
53 #include "feature/client/bridges.h"
54 #include "feature/client/circpathbias.h"
55 #include "feature/client/entrynodes.h"
56 #include "feature/client/transports.h"
57 #include "feature/control/control_events.h"
58 #include "feature/dircommon/directory.h"
59 #include "feature/nodelist/describe.h"
60 #include "feature/nodelist/microdesc.h"
61 #include "feature/nodelist/networkstatus.h"
62 #include "feature/nodelist/nickname.h"
63 #include "feature/nodelist/node_select.h"
64 #include "feature/nodelist/nodelist.h"
65 #include "feature/nodelist/routerlist.h"
66 #include "feature/nodelist/routerset.h"
67 #include "feature/relay/router.h"
68 #include "feature/relay/routermode.h"
69 #include "feature/relay/selftest.h"
70 #include "feature/rend/rendcommon.h"
71 #include "feature/stats/predict_ports.h"
72 #include "lib/crypt_ops/crypto_rand.h"
74 #include "core/or/cell_st.h"
75 #include "core/or/cpath_build_state_st.h"
76 #include "core/or/entry_connection_st.h"
77 #include "core/or/extend_info_st.h"
78 #include "feature/nodelist/node_st.h"
79 #include "core/or/or_circuit_st.h"
80 #include "core/or/origin_circuit_st.h"
81 #include "feature/nodelist/microdesc_st.h"
82 #include "feature/nodelist/routerinfo_st.h"
83 #include "feature/nodelist/routerstatus_st.h"
85 static int circuit_send_first_onion_skin(origin_circuit_t *circ);
86 static int circuit_build_no_more_hops(origin_circuit_t *circ);
87 static int circuit_send_intermediate_onion_skin(origin_circuit_t *circ,
88 crypt_path_t *hop);
89 static const node_t *choose_good_middle_server(uint8_t purpose,
90 cpath_build_state_t *state,
91 crypt_path_t *head,
92 int cur_len);
94 /** This function tries to get a channel to the specified endpoint,
95 * and then calls command_setup_channel() to give it the right
96 * callbacks.
98 MOCK_IMPL(channel_t *,
99 channel_connect_for_circuit,(const tor_addr_t *addr, uint16_t port,
100 const char *id_digest,
101 const struct ed25519_public_key_t *ed_id))
103 channel_t *chan;
105 chan = channel_connect(addr, port, id_digest, ed_id);
106 if (chan) command_setup_channel(chan);
108 return chan;
111 /** Search for a value for circ_id that we can use on <b>chan</b> for an
112 * outbound circuit, until we get a circ_id that is not in use by any other
113 * circuit on that conn.
115 * Return it, or 0 if can't get a unique circ_id.
117 STATIC circid_t
118 get_unique_circ_id_by_chan(channel_t *chan)
120 /* This number is chosen somewhat arbitrarily; see comment below for more
121 * info. When the space is 80% full, it gives a one-in-a-million failure
122 * chance; when the space is 90% full, it gives a one-in-850 chance; and when
123 * the space is 95% full, it gives a one-in-26 failure chance. That seems
124 * okay, though you could make a case IMO for anything between N=32 and
125 * N=256. */
126 #define MAX_CIRCID_ATTEMPTS 64
127 int in_use;
128 unsigned n_with_circ = 0, n_pending_destroy = 0, n_weird_pending_destroy = 0;
129 circid_t test_circ_id;
130 circid_t attempts=0;
131 circid_t high_bit, max_range, mask;
132 int64_t pending_destroy_time_total = 0;
133 int64_t pending_destroy_time_max = 0;
135 tor_assert(chan);
137 if (chan->circ_id_type == CIRC_ID_TYPE_NEITHER) {
138 log_warn(LD_BUG,
139 "Trying to pick a circuit ID for a connection from "
140 "a client with no identity.");
141 return 0;
143 max_range = (chan->wide_circ_ids) ? (1u<<31) : (1u<<15);
144 mask = max_range - 1;
145 high_bit = (chan->circ_id_type == CIRC_ID_TYPE_HIGHER) ? max_range : 0;
146 do {
147 if (++attempts > MAX_CIRCID_ATTEMPTS) {
148 /* Make sure we don't loop forever because all circuit IDs are used.
150 * Once, we would try until we had tried every possible circuit ID. But
151 * that's quite expensive. Instead, we try MAX_CIRCID_ATTEMPTS random
152 * circuit IDs, and then give up.
154 * This potentially causes us to give up early if our circuit ID space
155 * is nearly full. If we have N circuit IDs in use, then we will reject
156 * a new circuit with probability (N / max_range) ^ MAX_CIRCID_ATTEMPTS.
157 * This means that in practice, a few percent of our circuit ID capacity
158 * will go unused.
160 * The alternative here, though, is to do a linear search over the
161 * whole circuit ID space every time we extend a circuit, which is
162 * not so great either.
164 int64_t queued_destroys;
165 char *m = rate_limit_log(&chan->last_warned_circ_ids_exhausted,
166 approx_time());
167 if (m == NULL)
168 return 0; /* This message has been rate-limited away. */
169 if (n_pending_destroy)
170 pending_destroy_time_total /= n_pending_destroy;
171 log_warn(LD_CIRC,"No unused circIDs found on channel %s wide "
172 "circID support, with %u inbound and %u outbound circuits. "
173 "Found %u circuit IDs in use by circuits, and %u with "
174 "pending destroy cells. (%u of those were marked bogusly.) "
175 "The ones with pending destroy cells "
176 "have been marked unusable for an average of %ld seconds "
177 "and a maximum of %ld seconds. This channel is %ld seconds "
178 "old. Failing a circuit.%s",
179 chan->wide_circ_ids ? "with" : "without",
180 chan->num_p_circuits, chan->num_n_circuits,
181 n_with_circ, n_pending_destroy, n_weird_pending_destroy,
182 (long)pending_destroy_time_total,
183 (long)pending_destroy_time_max,
184 (long)(approx_time() - chan->timestamp_created),
186 tor_free(m);
188 if (!chan->cmux) {
189 /* This warning should be impossible. */
190 log_warn(LD_BUG, " This channel somehow has no cmux on it!");
191 return 0;
194 /* analysis so far on 12184 suggests that we're running out of circuit
195 IDs because it looks like we have too many pending destroy
196 cells. Let's see how many we really have pending.
198 queued_destroys = circuitmux_count_queued_destroy_cells(chan,
199 chan->cmux);
201 log_warn(LD_CIRC, " Circuitmux on this channel has %u circuits, "
202 "of which %u are active. It says it has %"PRId64
203 " destroy cells queued.",
204 circuitmux_num_circuits(chan->cmux),
205 circuitmux_num_active_circuits(chan->cmux),
206 (queued_destroys));
208 /* Change this into "if (1)" in order to get more information about
209 * possible failure modes here. You'll need to know how to use gdb with
210 * Tor: this will make Tor exit with an assertion failure if the cmux is
211 * corrupt. */
212 if (0)
213 circuitmux_assert_okay(chan->cmux);
215 channel_dump_statistics(chan, LOG_WARN);
217 return 0;
220 do {
221 crypto_rand((char*) &test_circ_id, sizeof(test_circ_id));
222 test_circ_id &= mask;
223 } while (test_circ_id == 0);
225 test_circ_id |= high_bit;
227 in_use = circuit_id_in_use_on_channel(test_circ_id, chan);
228 if (in_use == 1)
229 ++n_with_circ;
230 else if (in_use == 2) {
231 time_t since_when;
232 ++n_pending_destroy;
233 since_when =
234 circuit_id_when_marked_unusable_on_channel(test_circ_id, chan);
235 if (since_when) {
236 time_t waiting = approx_time() - since_when;
237 pending_destroy_time_total += waiting;
238 if (waiting > pending_destroy_time_max)
239 pending_destroy_time_max = waiting;
240 } else {
241 ++n_weird_pending_destroy;
244 } while (in_use);
245 return test_circ_id;
248 /** If <b>verbose</b> is false, allocate and return a comma-separated list of
249 * the currently built elements of <b>circ</b>. If <b>verbose</b> is true, also
250 * list information about link status in a more verbose format using spaces.
251 * If <b>verbose_names</b> is false, give hex digests; if <b>verbose_names</b>
252 * is true, use $DIGEST=Name style names.
254 static char *
255 circuit_list_path_impl(origin_circuit_t *circ, int verbose, int verbose_names)
257 crypt_path_t *hop;
258 smartlist_t *elements;
259 const char *states[] = {"closed", "waiting for keys", "open"};
260 char *s;
262 elements = smartlist_new();
264 if (verbose) {
265 const char *nickname = build_state_get_exit_nickname(circ->build_state);
266 smartlist_add_asprintf(elements, "%s%s circ (length %d%s%s):",
267 circ->build_state->is_internal ? "internal" : "exit",
268 circ->build_state->need_uptime ? " (high-uptime)" : "",
269 circ->build_state->desired_path_len,
270 circ->base_.state == CIRCUIT_STATE_OPEN ? "" : ", last hop ",
271 circ->base_.state == CIRCUIT_STATE_OPEN ? "" :
272 (nickname?nickname:"*unnamed*"));
275 hop = circ->cpath;
276 do {
277 char *elt;
278 const char *id;
279 const node_t *node;
280 if (!hop)
281 break;
282 if (!verbose && hop->state != CPATH_STATE_OPEN)
283 break;
284 if (!hop->extend_info)
285 break;
286 id = hop->extend_info->identity_digest;
287 if (verbose_names) {
288 elt = tor_malloc(MAX_VERBOSE_NICKNAME_LEN+1);
289 if ((node = node_get_by_id(id))) {
290 node_get_verbose_nickname(node, elt);
291 } else if (is_legal_nickname(hop->extend_info->nickname)) {
292 elt[0] = '$';
293 base16_encode(elt+1, HEX_DIGEST_LEN+1, id, DIGEST_LEN);
294 elt[HEX_DIGEST_LEN+1]= '~';
295 strlcpy(elt+HEX_DIGEST_LEN+2,
296 hop->extend_info->nickname, MAX_NICKNAME_LEN+1);
297 } else {
298 elt[0] = '$';
299 base16_encode(elt+1, HEX_DIGEST_LEN+1, id, DIGEST_LEN);
301 } else { /* ! verbose_names */
302 elt = tor_malloc(HEX_DIGEST_LEN+2);
303 elt[0] = '$';
304 base16_encode(elt+1, HEX_DIGEST_LEN+1, id, DIGEST_LEN);
306 tor_assert(elt);
307 if (verbose) {
308 tor_assert(hop->state <= 2);
309 smartlist_add_asprintf(elements,"%s(%s)",elt,states[hop->state]);
310 tor_free(elt);
311 } else {
312 smartlist_add(elements, elt);
314 hop = hop->next;
315 } while (hop != circ->cpath);
317 s = smartlist_join_strings(elements, verbose?" ":",", 0, NULL);
318 SMARTLIST_FOREACH(elements, char*, cp, tor_free(cp));
319 smartlist_free(elements);
320 return s;
323 /** If <b>verbose</b> is false, allocate and return a comma-separated
324 * list of the currently built elements of <b>circ</b>. If
325 * <b>verbose</b> is true, also list information about link status in
326 * a more verbose format using spaces.
328 char *
329 circuit_list_path(origin_circuit_t *circ, int verbose)
331 return circuit_list_path_impl(circ, verbose, 0);
334 /** Allocate and return a comma-separated list of the currently built elements
335 * of <b>circ</b>, giving each as a verbose nickname.
337 char *
338 circuit_list_path_for_controller(origin_circuit_t *circ)
340 return circuit_list_path_impl(circ, 0, 1);
343 /** Log, at severity <b>severity</b>, the nicknames of each router in
344 * <b>circ</b>'s cpath. Also log the length of the cpath, and the intended
345 * exit point.
347 void
348 circuit_log_path(int severity, unsigned int domain, origin_circuit_t *circ)
350 char *s = circuit_list_path(circ,1);
351 tor_log(severity,domain,"%s",s);
352 tor_free(s);
355 /** Return 1 iff every node in circ's cpath definitely supports ntor. */
356 static int
357 circuit_cpath_supports_ntor(const origin_circuit_t *circ)
359 crypt_path_t *head, *cpath;
361 cpath = head = circ->cpath;
362 do {
363 /* if the extend_info is missing, we can't tell if it supports ntor */
364 if (!cpath->extend_info) {
365 return 0;
368 /* if the key is blank, it definitely doesn't support ntor */
369 if (!extend_info_supports_ntor(cpath->extend_info)) {
370 return 0;
372 cpath = cpath->next;
373 } while (cpath != head);
375 return 1;
378 /** Pick all the entries in our cpath. Stop and return 0 when we're
379 * happy, or return -1 if an error occurs. */
380 static int
381 onion_populate_cpath(origin_circuit_t *circ)
383 int r = 0;
385 /* onion_extend_cpath assumes these are non-NULL */
386 tor_assert(circ);
387 tor_assert(circ->build_state);
389 while (r == 0) {
390 r = onion_extend_cpath(circ);
391 if (r < 0) {
392 log_info(LD_CIRC,"Generating cpath hop failed.");
393 return -1;
397 /* The path is complete */
398 tor_assert(r == 1);
400 /* Does every node in this path support ntor? */
401 int path_supports_ntor = circuit_cpath_supports_ntor(circ);
403 /* We would like every path to support ntor, but we have to allow for some
404 * edge cases. */
405 tor_assert(circuit_get_cpath_len(circ));
406 if (circuit_can_use_tap(circ)) {
407 /* Circuits from clients to intro points, and hidden services to rend
408 * points do not support ntor, because the hidden service protocol does
409 * not include ntor onion keys. This is also true for Single Onion
410 * Services. */
411 return 0;
414 if (circuit_get_cpath_len(circ) == 1) {
415 /* Allow for bootstrapping: when we're fetching directly from a fallback,
416 * authority, or bridge, we have no way of knowing its ntor onion key
417 * before we connect to it. So instead, we try connecting, and end up using
418 * CREATE_FAST. */
419 tor_assert(circ->cpath);
420 tor_assert(circ->cpath->extend_info);
421 const node_t *node = node_get_by_id(
422 circ->cpath->extend_info->identity_digest);
423 /* If we don't know the node and its descriptor, we must be bootstrapping.
425 if (!node || !node_has_preferred_descriptor(node, 1)) {
426 return 0;
430 if (BUG(!path_supports_ntor)) {
431 /* If we're building a multi-hop path, and it's not one of the HS or
432 * bootstrapping exceptions, and it doesn't support ntor, something has
433 * gone wrong. */
434 return -1;
437 return 0;
440 /** Create and return a new origin circuit. Initialize its purpose and
441 * build-state based on our arguments. The <b>flags</b> argument is a
442 * bitfield of CIRCLAUNCH_* flags. */
443 origin_circuit_t *
444 origin_circuit_init(uint8_t purpose, int flags)
446 /* sets circ->p_circ_id and circ->p_chan */
447 origin_circuit_t *circ = origin_circuit_new();
448 circuit_set_state(TO_CIRCUIT(circ), CIRCUIT_STATE_CHAN_WAIT);
449 circ->build_state = tor_malloc_zero(sizeof(cpath_build_state_t));
450 circ->build_state->onehop_tunnel =
451 ((flags & CIRCLAUNCH_ONEHOP_TUNNEL) ? 1 : 0);
452 circ->build_state->need_uptime =
453 ((flags & CIRCLAUNCH_NEED_UPTIME) ? 1 : 0);
454 circ->build_state->need_capacity =
455 ((flags & CIRCLAUNCH_NEED_CAPACITY) ? 1 : 0);
456 circ->build_state->is_internal =
457 ((flags & CIRCLAUNCH_IS_INTERNAL) ? 1 : 0);
458 circ->base_.purpose = purpose;
459 return circ;
462 /** Build a new circuit for <b>purpose</b>. If <b>exit</b>
463 * is defined, then use that as your exit router, else choose a suitable
464 * exit node.
466 * Also launch a connection to the first OR in the chosen path, if
467 * it's not open already.
469 origin_circuit_t *
470 circuit_establish_circuit(uint8_t purpose, extend_info_t *exit_ei, int flags)
472 origin_circuit_t *circ;
473 int err_reason = 0;
474 int is_hs_v3_rp_circuit = 0;
476 if (flags & CIRCLAUNCH_IS_V3_RP) {
477 is_hs_v3_rp_circuit = 1;
480 circ = origin_circuit_init(purpose, flags);
482 if (onion_pick_cpath_exit(circ, exit_ei, is_hs_v3_rp_circuit) < 0 ||
483 onion_populate_cpath(circ) < 0) {
484 circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_NOPATH);
485 return NULL;
488 circuit_event_status(circ, CIRC_EVENT_LAUNCHED, 0);
490 if ((err_reason = circuit_handle_first_hop(circ)) < 0) {
491 circuit_mark_for_close(TO_CIRCUIT(circ), -err_reason);
492 return NULL;
494 return circ;
497 /** Return the guard state associated with <b>circ</b>, which may be NULL. */
498 circuit_guard_state_t *
499 origin_circuit_get_guard_state(origin_circuit_t *circ)
501 return circ->guard_state;
505 * Helper function to publish a channel association message
507 * circuit_handle_first_hop() calls this to notify subscribers about a
508 * channel launch event, which associates a circuit with a channel.
509 * This doesn't always correspond to an assignment of the circuit's
510 * n_chan field, because that seems to be only for fully-open
511 * channels.
513 static void
514 circuit_chan_publish(const origin_circuit_t *circ, const channel_t *chan)
516 ocirc_chan_msg_t *msg = tor_malloc(sizeof(*msg));
518 msg->gid = circ->global_identifier;
519 msg->chan = chan->global_identifier;
520 msg->onehop = circ->build_state->onehop_tunnel;
522 ocirc_chan_publish(msg);
525 /** Start establishing the first hop of our circuit. Figure out what
526 * OR we should connect to, and if necessary start the connection to
527 * it. If we're already connected, then send the 'create' cell.
528 * Return 0 for ok, -reason if circ should be marked-for-close. */
530 circuit_handle_first_hop(origin_circuit_t *circ)
532 crypt_path_t *firsthop;
533 channel_t *n_chan;
534 int err_reason = 0;
535 const char *msg = NULL;
536 int should_launch = 0;
537 const or_options_t *options = get_options();
539 firsthop = cpath_get_next_non_open_hop(circ->cpath);
540 tor_assert(firsthop);
541 tor_assert(firsthop->extend_info);
543 /* Some bridges are on private addresses. Others pass a dummy private
544 * address to the pluggable transport, which ignores it.
545 * Deny the connection if:
546 * - the address is internal, and
547 * - we're not connecting to a configured bridge, and
548 * - we're not configured to allow extends to private addresses. */
549 if (tor_addr_is_internal(&firsthop->extend_info->addr, 0) &&
550 !extend_info_is_a_configured_bridge(firsthop->extend_info) &&
551 !options->ExtendAllowPrivateAddresses) {
552 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
553 "Client asked me to connect directly to a private address");
554 return -END_CIRC_REASON_TORPROTOCOL;
557 /* now see if we're already connected to the first OR in 'route' */
558 log_debug(LD_CIRC,"Looking for firsthop '%s'",
559 fmt_addrport(&firsthop->extend_info->addr,
560 firsthop->extend_info->port));
562 /* We'll cleanup this code in #33220, when we add an IPv6 address to
563 * extend_info_t. */
564 const bool addr_is_ipv4 =
565 (tor_addr_family(&firsthop->extend_info->addr) == AF_INET);
566 n_chan = channel_get_for_extend(
567 firsthop->extend_info->identity_digest,
568 &firsthop->extend_info->ed_identity,
569 addr_is_ipv4 ? &firsthop->extend_info->addr : NULL,
570 addr_is_ipv4 ? NULL : &firsthop->extend_info->addr,
571 &msg,
572 &should_launch);
574 if (!n_chan) {
575 /* not currently connected in a useful way. */
576 log_info(LD_CIRC, "Next router is %s: %s",
577 safe_str_client(extend_info_describe(firsthop->extend_info)),
578 msg?msg:"???");
579 circ->base_.n_hop = extend_info_dup(firsthop->extend_info);
581 if (should_launch) {
582 n_chan = channel_connect_for_circuit(
583 &firsthop->extend_info->addr,
584 firsthop->extend_info->port,
585 firsthop->extend_info->identity_digest,
586 &firsthop->extend_info->ed_identity);
587 if (!n_chan) { /* connect failed, forget the whole thing */
588 log_info(LD_CIRC,"connect to firsthop failed. Closing.");
589 return -END_CIRC_REASON_CONNECTFAILED;
591 circuit_chan_publish(circ, n_chan);
594 log_debug(LD_CIRC,"connecting in progress (or finished). Good.");
595 /* return success. The onion/circuit/etc will be taken care of
596 * automatically (may already have been) whenever n_chan reaches
597 * OR_CONN_STATE_OPEN.
599 return 0;
600 } else { /* it's already open. use it. */
601 tor_assert(!circ->base_.n_hop);
602 circ->base_.n_chan = n_chan;
603 circuit_chan_publish(circ, n_chan);
604 log_debug(LD_CIRC,"Conn open. Delivering first onion skin.");
605 if ((err_reason = circuit_send_next_onion_skin(circ)) < 0) {
606 log_info(LD_CIRC,"circuit_send_next_onion_skin failed.");
607 circ->base_.n_chan = NULL;
608 return err_reason;
611 return 0;
614 /** Find any circuits that are waiting on <b>or_conn</b> to become
615 * open and get them to send their create cells forward.
617 * Status is 1 if connect succeeded, or 0 if connect failed.
619 * Close_origin_circuits is 1 if we should close all the origin circuits
620 * through this channel, or 0 otherwise. (This happens when we want to retry
621 * an older guard.)
623 void
624 circuit_n_chan_done(channel_t *chan, int status, int close_origin_circuits)
626 smartlist_t *pending_circs;
627 int err_reason = 0;
629 tor_assert(chan);
631 log_debug(LD_CIRC,"chan to %s, status=%d",
632 channel_get_canonical_remote_descr(chan), status);
634 pending_circs = smartlist_new();
635 circuit_get_all_pending_on_channel(pending_circs, chan);
637 SMARTLIST_FOREACH_BEGIN(pending_circs, circuit_t *, circ)
639 /* These checks are redundant wrt get_all_pending_on_or_conn, but I'm
640 * leaving them in in case it's possible for the status of a circuit to
641 * change as we're going down the list. */
642 if (circ->marked_for_close || circ->n_chan || !circ->n_hop ||
643 circ->state != CIRCUIT_STATE_CHAN_WAIT)
644 continue;
646 if (tor_digest_is_zero(circ->n_hop->identity_digest)) {
647 /* Look at addr/port. This is an unkeyed connection. */
648 if (!channel_matches_extend_info(chan, circ->n_hop))
649 continue;
650 } else {
651 /* We expected a key. See if it's the right one. */
652 if (tor_memneq(chan->identity_digest,
653 circ->n_hop->identity_digest, DIGEST_LEN))
654 continue;
656 if (!status) { /* chan failed; close circ */
657 log_info(LD_CIRC,"Channel failed; closing circ.");
658 circuit_mark_for_close(circ, END_CIRC_REASON_CHANNEL_CLOSED);
659 continue;
661 if (close_origin_circuits && CIRCUIT_IS_ORIGIN(circ)) {
662 log_info(LD_CIRC,"Channel deprecated for origin circs; closing circ.");
663 circuit_mark_for_close(circ, END_CIRC_REASON_CHANNEL_CLOSED);
664 continue;
666 log_debug(LD_CIRC, "Found circ, sending create cell.");
667 /* circuit_deliver_create_cell will set n_circ_id and add us to
668 * chan_circuid_circuit_map, so we don't need to call
669 * set_circid_chan here. */
670 circ->n_chan = chan;
671 extend_info_free(circ->n_hop);
672 circ->n_hop = NULL;
674 if (CIRCUIT_IS_ORIGIN(circ)) {
675 if ((err_reason =
676 circuit_send_next_onion_skin(TO_ORIGIN_CIRCUIT(circ))) < 0) {
677 log_info(LD_CIRC,
678 "send_next_onion_skin failed; circuit marked for closing.");
679 circuit_mark_for_close(circ, -err_reason);
680 continue;
681 /* XXX could this be bad, eg if next_onion_skin failed because conn
682 * died? */
684 } else {
685 /* pull the create cell out of circ->n_chan_create_cell, and send it */
686 tor_assert(circ->n_chan_create_cell);
687 if (circuit_deliver_create_cell(circ, circ->n_chan_create_cell, 1)<0) {
688 circuit_mark_for_close(circ, END_CIRC_REASON_RESOURCELIMIT);
689 continue;
691 tor_free(circ->n_chan_create_cell);
692 circuit_set_state(circ, CIRCUIT_STATE_OPEN);
695 SMARTLIST_FOREACH_END(circ);
697 smartlist_free(pending_circs);
700 /** Find a new circid that isn't currently in use on the circ->n_chan
701 * for the outgoing
702 * circuit <b>circ</b>, and deliver the cell <b>create_cell</b> to this
703 * circuit. If <b>relayed</b> is true, this is a create cell somebody
704 * gave us via an EXTEND cell, so we shouldn't worry if we don't understand
705 * it. Return -1 if we failed to find a suitable circid, else return 0.
707 MOCK_IMPL(int,
708 circuit_deliver_create_cell,(circuit_t *circ,
709 const struct create_cell_t *create_cell,
710 int relayed))
712 cell_t cell;
713 circid_t id;
714 int r;
716 tor_assert(circ);
717 tor_assert(circ->n_chan);
718 tor_assert(create_cell);
719 tor_assert(create_cell->cell_type == CELL_CREATE ||
720 create_cell->cell_type == CELL_CREATE_FAST ||
721 create_cell->cell_type == CELL_CREATE2);
723 id = get_unique_circ_id_by_chan(circ->n_chan);
724 if (!id) {
725 static ratelim_t circid_warning_limit = RATELIM_INIT(9600);
726 log_fn_ratelim(&circid_warning_limit, LOG_WARN, LD_CIRC,
727 "failed to get unique circID.");
728 goto error;
731 tor_assert_nonfatal_once(circ->n_chan->is_canonical);
733 memset(&cell, 0, sizeof(cell_t));
734 r = relayed ? create_cell_format_relayed(&cell, create_cell)
735 : create_cell_format(&cell, create_cell);
736 if (r < 0) {
737 log_warn(LD_CIRC,"Couldn't format create cell");
738 goto error;
740 log_debug(LD_CIRC,"Chosen circID %u.", (unsigned)id);
741 circuit_set_n_circid_chan(circ, id, circ->n_chan);
742 cell.circ_id = circ->n_circ_id;
744 append_cell_to_circuit_queue(circ, circ->n_chan, &cell,
745 CELL_DIRECTION_OUT, 0);
747 if (CIRCUIT_IS_ORIGIN(circ)) {
748 /* Update began timestamp for circuits starting their first hop */
749 if (TO_ORIGIN_CIRCUIT(circ)->cpath->state == CPATH_STATE_CLOSED) {
750 if (!CHANNEL_IS_OPEN(circ->n_chan)) {
751 log_warn(LD_CIRC,
752 "Got first hop for a circuit without an opened channel. "
753 "State: %s.", channel_state_to_string(circ->n_chan->state));
754 tor_fragile_assert();
757 tor_gettimeofday(&circ->timestamp_began);
760 /* mark it so it gets better rate limiting treatment. */
761 channel_timestamp_client(circ->n_chan);
764 return 0;
765 error:
766 circ->n_chan = NULL;
767 return -1;
770 /** Return true iff we should send a create_fast cell to start building a given
771 * circuit */
772 static inline int
773 should_use_create_fast_for_circuit(origin_circuit_t *circ)
775 const or_options_t *options = get_options();
776 tor_assert(circ->cpath);
777 tor_assert(circ->cpath->extend_info);
779 if (!circuit_has_usable_onion_key(circ)) {
780 /* We don't have ntor, and we don't have or can't use TAP,
781 * so our hand is forced: only a create_fast will work. */
782 return 1;
784 if (public_server_mode(options)) {
785 /* We're a server, and we have a usable onion key. We can choose.
786 * Prefer to blend our circuit into the other circuits we are
787 * creating on behalf of others. */
788 return 0;
790 return networkstatus_get_param(NULL, "usecreatefast", 0, 0, 1);
794 * Return true if <b>circ</b> is the type of circuit we want to count
795 * timeouts from.
797 * In particular, we want to consider any circuit that plans to build
798 * at least 3 hops (but maybe more), but has 3 or fewer hops built
799 * so far.
801 * We still want to consider circuits before 3 hops, because we need
802 * to decide if we should convert them to a measurement circuit in
803 * circuit_build_times_handle_completed_hop(), rather than letting
804 * slow circuits get killed right away.
807 circuit_timeout_want_to_count_circ(const origin_circuit_t *circ)
809 return !circ->has_opened
810 && circ->build_state->desired_path_len >= DEFAULT_ROUTE_LEN
811 && circuit_get_cpath_opened_len(circ) <= DEFAULT_ROUTE_LEN;
814 /** Decide whether to use a TAP or ntor handshake for connecting to <b>ei</b>
815 * directly, and set *<b>cell_type_out</b> and *<b>handshake_type_out</b>
816 * accordingly.
817 * Note that TAP handshakes in CREATE cells are only used for direct
818 * connections:
819 * - from Single Onions to rend points not in the service's consensus.
820 * This is checked in onion_populate_cpath. */
821 static void
822 circuit_pick_create_handshake(uint8_t *cell_type_out,
823 uint16_t *handshake_type_out,
824 const extend_info_t *ei)
826 /* torspec says: In general, clients SHOULD use CREATE whenever they are
827 * using the TAP handshake, and CREATE2 otherwise. */
828 if (extend_info_supports_ntor(ei)) {
829 *cell_type_out = CELL_CREATE2;
830 *handshake_type_out = ONION_HANDSHAKE_TYPE_NTOR;
831 } else {
832 /* XXXX030 Remove support for deciding to use TAP and EXTEND. */
833 *cell_type_out = CELL_CREATE;
834 *handshake_type_out = ONION_HANDSHAKE_TYPE_TAP;
838 /** Decide whether to use a TAP or ntor handshake for extending to <b>ei</b>
839 * and set *<b>handshake_type_out</b> accordingly. Decide whether we should
840 * use an EXTEND2 or an EXTEND cell to do so, and set *<b>cell_type_out</b>
841 * and *<b>create_cell_type_out</b> accordingly.
842 * Note that TAP handshakes in EXTEND cells are only used:
843 * - from clients to intro points, and
844 * - from hidden services to rend points.
845 * This is checked in onion_populate_cpath.
847 static void
848 circuit_pick_extend_handshake(uint8_t *cell_type_out,
849 uint8_t *create_cell_type_out,
850 uint16_t *handshake_type_out,
851 const extend_info_t *ei)
853 uint8_t t;
854 circuit_pick_create_handshake(&t, handshake_type_out, ei);
856 /* torspec says: Clients SHOULD use the EXTEND format whenever sending a TAP
857 * handshake... In other cases, clients SHOULD use EXTEND2. */
858 if (*handshake_type_out != ONION_HANDSHAKE_TYPE_TAP) {
859 *cell_type_out = RELAY_COMMAND_EXTEND2;
860 *create_cell_type_out = CELL_CREATE2;
861 } else {
862 /* XXXX030 Remove support for deciding to use TAP and EXTEND. */
863 *cell_type_out = RELAY_COMMAND_EXTEND;
864 *create_cell_type_out = CELL_CREATE;
869 * Return true iff <b>purpose</b> is a purpose for a circuit which is
870 * allowed to have no guard configured, even if the circuit is multihop
871 * and guards are enabled.
873 static int
874 circuit_purpose_may_omit_guard(int purpose)
876 switch (purpose) {
877 case CIRCUIT_PURPOSE_TESTING:
878 case CIRCUIT_PURPOSE_C_MEASURE_TIMEOUT:
879 /* Testing circuits may omit guards because they're measuring
880 * liveness or performance, and don't want guards to interfere. */
881 return 1;
882 default:
883 /* All other multihop circuits should use guards if guards are
884 * enabled. */
885 return 0;
889 /** This is the backbone function for building circuits.
891 * If circ's first hop is closed, then we need to build a create
892 * cell and send it forward.
894 * Otherwise, if circ's cpath still has any non-open hops, we need to
895 * build a relay extend cell and send it forward to the next non-open hop.
897 * If all hops on the cpath are open, we're done building the circuit
898 * and we should do housekeeping for the newly opened circuit.
900 * Return -reason if we want to tear down circ, else return 0.
903 circuit_send_next_onion_skin(origin_circuit_t *circ)
905 tor_assert(circ);
907 if (circ->cpath->state == CPATH_STATE_CLOSED) {
908 /* Case one: we're on the first hop. */
909 return circuit_send_first_onion_skin(circ);
912 tor_assert(circ->cpath->state == CPATH_STATE_OPEN);
913 tor_assert(circ->base_.state == CIRCUIT_STATE_BUILDING);
915 crypt_path_t *hop = cpath_get_next_non_open_hop(circ->cpath);
916 circuit_build_times_handle_completed_hop(circ);
918 circpad_machine_event_circ_added_hop(circ);
920 if (hop) {
921 /* Case two: we're on a hop after the first. */
922 return circuit_send_intermediate_onion_skin(circ, hop);
925 /* Case three: the circuit is finished. Do housekeeping tasks on it. */
926 circpad_machine_event_circ_built(circ);
927 return circuit_build_no_more_hops(circ);
931 * Called from circuit_send_next_onion_skin() when we find ourselves connected
932 * to the first hop in <b>circ</b>: Send a CREATE or CREATE2 or CREATE_FAST
933 * cell to that hop. Return 0 on success; -reason on failure (if the circuit
934 * should be torn down).
936 static int
937 circuit_send_first_onion_skin(origin_circuit_t *circ)
939 int fast;
940 int len;
941 const node_t *node;
942 create_cell_t cc;
943 memset(&cc, 0, sizeof(cc));
945 log_debug(LD_CIRC,"First skin; sending create cell.");
947 if (circ->build_state->onehop_tunnel) {
948 control_event_bootstrap(BOOTSTRAP_STATUS_ONEHOP_CREATE, 0);
949 } else {
950 control_event_bootstrap(BOOTSTRAP_STATUS_CIRCUIT_CREATE, 0);
952 /* If this is not a one-hop tunnel, the channel is being used
953 * for traffic that wants anonymity and protection from traffic
954 * analysis (such as netflow record retention). That means we want
955 * to pad it.
957 if (circ->base_.n_chan->channel_usage < CHANNEL_USED_FOR_FULL_CIRCS)
958 circ->base_.n_chan->channel_usage = CHANNEL_USED_FOR_FULL_CIRCS;
961 node = node_get_by_id(circ->base_.n_chan->identity_digest);
962 fast = should_use_create_fast_for_circuit(circ);
963 if (!fast) {
964 /* We know the right onion key: we should send a create cell. */
965 circuit_pick_create_handshake(&cc.cell_type, &cc.handshake_type,
966 circ->cpath->extend_info);
967 } else {
968 /* We don't know an onion key, so we need to fall back to CREATE_FAST. */
969 cc.cell_type = CELL_CREATE_FAST;
970 cc.handshake_type = ONION_HANDSHAKE_TYPE_FAST;
973 len = onion_skin_create(cc.handshake_type,
974 circ->cpath->extend_info,
975 &circ->cpath->handshake_state,
976 cc.onionskin);
977 if (len < 0) {
978 log_warn(LD_CIRC,"onion_skin_create (first hop) failed.");
979 return - END_CIRC_REASON_INTERNAL;
981 cc.handshake_len = len;
983 if (circuit_deliver_create_cell(TO_CIRCUIT(circ), &cc, 0) < 0)
984 return - END_CIRC_REASON_RESOURCELIMIT;
986 circ->cpath->state = CPATH_STATE_AWAITING_KEYS;
987 circuit_set_state(TO_CIRCUIT(circ), CIRCUIT_STATE_BUILDING);
988 log_info(LD_CIRC,"First hop: finished sending %s cell to '%s'",
989 fast ? "CREATE_FAST" : "CREATE",
990 node ? node_describe(node) : "<unnamed>");
991 return 0;
995 * Called from circuit_send_next_onion_skin() when we find that we have no
996 * more hops: mark the circuit as finished, and perform the necessary
997 * bookkeeping. Return 0 on success; -reason on failure (if the circuit
998 * should be torn down).
1000 static int
1001 circuit_build_no_more_hops(origin_circuit_t *circ)
1003 guard_usable_t r;
1004 if (! circ->guard_state) {
1005 if (circuit_get_cpath_len(circ) != 1 &&
1006 ! circuit_purpose_may_omit_guard(circ->base_.purpose) &&
1007 get_options()->UseEntryGuards) {
1008 log_warn(LD_BUG, "%d-hop circuit %p with purpose %d has no "
1009 "guard state",
1010 circuit_get_cpath_len(circ), circ, circ->base_.purpose);
1012 r = GUARD_USABLE_NOW;
1013 } else {
1014 r = entry_guard_succeeded(&circ->guard_state);
1016 const int is_usable_for_streams = (r == GUARD_USABLE_NOW);
1017 if (r == GUARD_USABLE_NOW) {
1018 circuit_set_state(TO_CIRCUIT(circ), CIRCUIT_STATE_OPEN);
1019 } else if (r == GUARD_MAYBE_USABLE_LATER) {
1020 // Wait till either a better guard succeeds, or till
1021 // all better guards fail.
1022 circuit_set_state(TO_CIRCUIT(circ), CIRCUIT_STATE_GUARD_WAIT);
1023 } else {
1024 tor_assert_nonfatal(r == GUARD_USABLE_NEVER);
1025 return - END_CIRC_REASON_INTERNAL;
1028 /* XXXX #21422 -- the rest of this branch needs careful thought!
1029 * Some of the things here need to happen when a circuit becomes
1030 * mechanically open; some need to happen when it is actually usable.
1031 * I think I got them right, but more checking would be wise. -NM
1034 log_info(LD_CIRC,"circuit built!");
1035 circuit_reset_failure_count(0);
1037 if (circ->build_state->onehop_tunnel || circ->has_opened) {
1038 control_event_bootstrap(BOOTSTRAP_STATUS_REQUESTING_STATUS, 0);
1041 pathbias_count_build_success(circ);
1042 if (is_usable_for_streams)
1043 circuit_has_opened(circ); /* do other actions as necessary */
1045 if (!have_completed_a_circuit() && !circ->build_state->onehop_tunnel) {
1046 const or_options_t *options = get_options();
1047 note_that_we_completed_a_circuit();
1048 /* FFFF Log a count of known routers here */
1049 log_info(LD_GENERAL,
1050 "Tor has successfully opened a circuit. "
1051 "Looks like client functionality is working.");
1052 control_event_bootstrap(BOOTSTRAP_STATUS_DONE, 0);
1053 control_event_client_status(LOG_NOTICE, "CIRCUIT_ESTABLISHED");
1054 clear_broken_connection_map(1);
1055 if (server_mode(options) && !check_whether_orport_reachable(options)) {
1056 inform_testing_reachability();
1057 router_do_reachability_checks(1, 1);
1061 /* We're done with measurement circuits here. Just close them */
1062 if (circ->base_.purpose == CIRCUIT_PURPOSE_C_MEASURE_TIMEOUT) {
1063 circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_FINISHED);
1065 return 0;
1069 * Called from circuit_send_next_onion_skin() when we find that we have a hop
1070 * other than the first that we need to extend to: use <b>hop</b>'s
1071 * information to extend the circuit another step. Return 0 on success;
1072 * -reason on failure (if the circuit should be torn down).
1074 static int
1075 circuit_send_intermediate_onion_skin(origin_circuit_t *circ,
1076 crypt_path_t *hop)
1078 int len;
1079 extend_cell_t ec;
1080 memset(&ec, 0, sizeof(ec));
1082 log_debug(LD_CIRC,"starting to send subsequent skin.");
1084 if (tor_addr_family(&hop->extend_info->addr) != AF_INET) {
1085 log_warn(LD_BUG, "Trying to extend to a non-IPv4 address.");
1086 return - END_CIRC_REASON_INTERNAL;
1089 circuit_pick_extend_handshake(&ec.cell_type,
1090 &ec.create_cell.cell_type,
1091 &ec.create_cell.handshake_type,
1092 hop->extend_info);
1094 tor_addr_copy(&ec.orport_ipv4.addr, &hop->extend_info->addr);
1095 ec.orport_ipv4.port = hop->extend_info->port;
1096 tor_addr_make_unspec(&ec.orport_ipv6.addr);
1097 memcpy(ec.node_id, hop->extend_info->identity_digest, DIGEST_LEN);
1098 /* Set the ED25519 identity too -- it will only get included
1099 * in the extend2 cell if we're configured to use it, though. */
1100 ed25519_pubkey_copy(&ec.ed_pubkey, &hop->extend_info->ed_identity);
1102 len = onion_skin_create(ec.create_cell.handshake_type,
1103 hop->extend_info,
1104 &hop->handshake_state,
1105 ec.create_cell.onionskin);
1106 if (len < 0) {
1107 log_warn(LD_CIRC,"onion_skin_create failed.");
1108 return - END_CIRC_REASON_INTERNAL;
1110 ec.create_cell.handshake_len = len;
1112 log_info(LD_CIRC,"Sending extend relay cell.");
1114 uint8_t command = 0;
1115 uint16_t payload_len=0;
1116 uint8_t payload[RELAY_PAYLOAD_SIZE];
1117 if (extend_cell_format(&command, &payload_len, payload, &ec)<0) {
1118 log_warn(LD_CIRC,"Couldn't format extend cell");
1119 return -END_CIRC_REASON_INTERNAL;
1122 /* send it to hop->prev, because that relay will transfer
1123 * it to a create cell and then send to hop */
1124 if (relay_send_command_from_edge(0, TO_CIRCUIT(circ),
1125 command,
1126 (char*)payload, payload_len,
1127 hop->prev) < 0)
1128 return 0; /* circuit is closed */
1130 hop->state = CPATH_STATE_AWAITING_KEYS;
1131 return 0;
1134 /** Our clock just jumped by <b>seconds_elapsed</b>. If <b>was_idle</b> is
1135 * true, then the monotonic time matches; otherwise it doesn't. Assume
1136 * something has also gone wrong with our network: notify the user, and
1137 * abandon all not-yet-used circuits. */
1138 void
1139 circuit_note_clock_jumped(int64_t seconds_elapsed, bool was_idle)
1141 int severity = server_mode(get_options()) ? LOG_WARN : LOG_NOTICE;
1142 if (was_idle) {
1143 tor_log(severity, LD_GENERAL, "Tor has been idle for %"PRId64
1144 " seconds; assuming established circuits no longer work.",
1145 (seconds_elapsed));
1146 } else {
1147 tor_log(severity, LD_GENERAL,
1148 "Your system clock just jumped %"PRId64" seconds %s; "
1149 "assuming established circuits no longer work.",
1151 seconds_elapsed >=0 ? seconds_elapsed : -seconds_elapsed),
1152 seconds_elapsed >=0 ? "forward" : "backward");
1154 control_event_general_status(LOG_WARN, "CLOCK_JUMPED TIME=%"PRId64
1155 " IDLE=%d",
1156 (seconds_elapsed), was_idle?1:0);
1157 /* so we log when it works again */
1158 note_that_we_maybe_cant_complete_circuits();
1159 control_event_client_status(severity, "CIRCUIT_NOT_ESTABLISHED REASON=%s",
1160 "CLOCK_JUMPED");
1161 circuit_mark_all_unused_circs();
1162 circuit_mark_all_dirty_circs_as_unusable();
1163 if (seconds_elapsed < 0) {
1164 /* Restart all the timers in case we jumped a long way into the past. */
1165 reset_all_main_loop_timers();
1169 /** A "created" cell <b>reply</b> came back to us on circuit <b>circ</b>.
1170 * (The body of <b>reply</b> varies depending on what sort of handshake
1171 * this is.)
1173 * Calculate the appropriate keys and digests, make sure KH is
1174 * correct, and initialize this hop of the cpath.
1176 * Return - reason if we want to mark circ for close, else return 0.
1179 circuit_finish_handshake(origin_circuit_t *circ,
1180 const created_cell_t *reply)
1182 char keys[CPATH_KEY_MATERIAL_LEN];
1183 crypt_path_t *hop;
1184 int rv;
1186 if ((rv = pathbias_count_build_attempt(circ)) < 0) {
1187 log_warn(LD_CIRC, "pathbias_count_build_attempt failed: %d", rv);
1188 return rv;
1191 if (circ->cpath->state == CPATH_STATE_AWAITING_KEYS) {
1192 hop = circ->cpath;
1193 } else {
1194 hop = cpath_get_next_non_open_hop(circ->cpath);
1195 if (!hop) { /* got an extended when we're all done? */
1196 log_warn(LD_PROTOCOL,"got extended when circ already built? Closing.");
1197 return - END_CIRC_REASON_TORPROTOCOL;
1200 tor_assert(hop->state == CPATH_STATE_AWAITING_KEYS);
1203 const char *msg = NULL;
1204 if (onion_skin_client_handshake(hop->handshake_state.tag,
1205 &hop->handshake_state,
1206 reply->reply, reply->handshake_len,
1207 (uint8_t*)keys, sizeof(keys),
1208 (uint8_t*)hop->rend_circ_nonce,
1209 &msg) < 0) {
1210 if (msg)
1211 log_warn(LD_CIRC,"onion_skin_client_handshake failed: %s", msg);
1212 return -END_CIRC_REASON_TORPROTOCOL;
1216 onion_handshake_state_release(&hop->handshake_state);
1218 if (cpath_init_circuit_crypto(hop, keys, sizeof(keys), 0, 0)<0) {
1219 return -END_CIRC_REASON_TORPROTOCOL;
1222 hop->state = CPATH_STATE_OPEN;
1223 log_info(LD_CIRC,"Finished building circuit hop:");
1224 circuit_log_path(LOG_INFO,LD_CIRC,circ);
1225 circuit_event_status(circ, CIRC_EVENT_EXTENDED, 0);
1227 return 0;
1230 /** We received a relay truncated cell on circ.
1232 * Since we don't send truncates currently, getting a truncated
1233 * means that a connection broke or an extend failed. For now,
1234 * just give up: force circ to close, and return 0.
1237 circuit_truncated(origin_circuit_t *circ, int reason)
1239 // crypt_path_t *victim;
1240 // connection_t *stream;
1242 tor_assert(circ);
1244 /* XXX Since we don't send truncates currently, getting a truncated
1245 * means that a connection broke or an extend failed. For now,
1246 * just give up.
1248 circuit_mark_for_close(TO_CIRCUIT(circ),
1249 END_CIRC_REASON_FLAG_REMOTE|reason);
1250 return 0;
1252 #if 0
1253 while (layer->next != circ->cpath) {
1254 /* we need to clear out layer->next */
1255 victim = layer->next;
1256 log_debug(LD_CIRC, "Killing a layer of the cpath.");
1258 for (stream = circ->p_streams; stream; stream=stream->next_stream) {
1259 if (stream->cpath_layer == victim) {
1260 log_info(LD_APP, "Marking stream %d for close because of truncate.",
1261 stream->stream_id);
1262 /* no need to send 'end' relay cells,
1263 * because the other side's already dead
1265 connection_mark_unattached_ap(stream, END_STREAM_REASON_DESTROY);
1269 layer->next = victim->next;
1270 cpath_free(victim);
1273 log_info(LD_CIRC, "finished");
1274 return 0;
1275 #endif /* 0 */
1278 /** Helper for new_route_len(). Choose a circuit length for purpose
1279 * <b>purpose</b>: DEFAULT_ROUTE_LEN (+ 1 if someone else chose the
1280 * exit). If someone else chose the exit, they could be colluding
1281 * with the exit, so add a randomly selected node to preserve
1282 * anonymity.
1284 * Here, "exit node" sometimes means an OR acting as an internal
1285 * endpoint, rather than as a relay to an external endpoint. This
1286 * means there need to be at least DEFAULT_ROUTE_LEN routers between
1287 * us and the internal endpoint to preserve the same anonymity
1288 * properties that we would get when connecting to an external
1289 * endpoint. These internal endpoints can include:
1291 * - Connections to a directory of hidden services
1292 * (CIRCUIT_PURPOSE_C_GENERAL)
1294 * - A client connecting to an introduction point, which the hidden
1295 * service picked (CIRCUIT_PURPOSE_C_INTRODUCING, via
1296 * circuit_get_open_circ_or_launch() which rewrites it from
1297 * CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT)
1299 * - A hidden service connecting to a rendezvous point, which the
1300 * client picked (CIRCUIT_PURPOSE_S_CONNECT_REND, via
1301 * rend_service_receive_introduction() and
1302 * rend_service_relaunch_rendezvous)
1304 * There are currently two situations where we picked the exit node
1305 * ourselves, making DEFAULT_ROUTE_LEN a safe circuit length:
1307 * - We are a hidden service connecting to an introduction point
1308 * (CIRCUIT_PURPOSE_S_ESTABLISH_INTRO, via
1309 * rend_service_launch_establish_intro())
1311 * - We are a router testing its own reachabiity
1312 * (CIRCUIT_PURPOSE_TESTING, via router_do_reachability_checks())
1314 * onion_pick_cpath_exit() bypasses us (by not calling
1315 * new_route_len()) in the one-hop tunnel case, so we don't need to
1316 * handle that.
1319 route_len_for_purpose(uint8_t purpose, extend_info_t *exit_ei)
1321 int routelen = DEFAULT_ROUTE_LEN;
1322 int known_purpose = 0;
1324 if (circuit_should_use_vanguards(purpose)) {
1325 /* Clients want an extra hop for rends to avoid linkability.
1326 * Services want it for intro points to avoid publishing their
1327 * layer3 guards. They want it for hsdir posts to use
1328 * their full layer3 guard set for those connections.
1329 * Ex: C - G - L2 - L3 - R
1330 * S - G - L2 - L3 - HSDIR
1331 * S - G - L2 - L3 - I
1333 if (purpose == CIRCUIT_PURPOSE_C_ESTABLISH_REND ||
1334 purpose == CIRCUIT_PURPOSE_S_HSDIR_POST ||
1335 purpose == CIRCUIT_PURPOSE_HS_VANGUARDS ||
1336 purpose == CIRCUIT_PURPOSE_S_ESTABLISH_INTRO)
1337 return routelen+1;
1339 /* If we only have Layer2 vanguards, then we do not need
1340 * the extra hop for linkabilty reasons (see below).
1341 * This means all hops can be of the form:
1342 * S/C - G - L2 - M - R/HSDir/I
1344 if (get_options()->HSLayer2Nodes && !get_options()->HSLayer3Nodes)
1345 return routelen+1;
1347 /* For connections to hsdirs, clients want two extra hops
1348 * when using layer3 guards, to avoid linkability.
1349 * Same goes for intro points. Note that the route len
1350 * includes the intro point or hsdir, hence the +2.
1351 * Ex: C - G - L2 - L3 - M - I
1352 * C - G - L2 - L3 - M - HSDIR
1353 * S - G - L2 - L3 - M - R
1355 if (purpose == CIRCUIT_PURPOSE_S_CONNECT_REND ||
1356 purpose == CIRCUIT_PURPOSE_C_HSDIR_GET ||
1357 purpose == CIRCUIT_PURPOSE_C_INTRODUCING)
1358 return routelen+2;
1361 if (!exit_ei)
1362 return routelen;
1364 switch (purpose) {
1365 /* These two purposes connect to a router that we chose, so
1366 * DEFAULT_ROUTE_LEN is safe. */
1367 case CIRCUIT_PURPOSE_S_ESTABLISH_INTRO:
1368 /* hidden service connecting to introduction point */
1369 case CIRCUIT_PURPOSE_TESTING:
1370 /* router reachability testing */
1371 known_purpose = 1;
1372 break;
1374 /* These three purposes connect to a router that someone else
1375 * might have chosen, so add an extra hop to protect anonymity. */
1376 case CIRCUIT_PURPOSE_C_GENERAL:
1377 case CIRCUIT_PURPOSE_C_HSDIR_GET:
1378 case CIRCUIT_PURPOSE_S_HSDIR_POST:
1379 /* connecting to hidden service directory */
1380 case CIRCUIT_PURPOSE_C_INTRODUCING:
1381 /* client connecting to introduction point */
1382 case CIRCUIT_PURPOSE_S_CONNECT_REND:
1383 /* hidden service connecting to rendezvous point */
1384 known_purpose = 1;
1385 routelen++;
1386 break;
1388 default:
1389 /* Got a purpose not listed above along with a chosen exit.
1390 * Increase the circuit length by one anyway for safety. */
1391 routelen++;
1392 break;
1395 if (BUG(exit_ei && !known_purpose)) {
1396 log_warn(LD_BUG, "Unhandled purpose %d with a chosen exit; "
1397 "assuming routelen %d.", purpose, routelen);
1399 return routelen;
1402 /** Choose a length for a circuit of purpose <b>purpose</b> and check
1403 * if enough routers are available.
1405 * If the routerlist <b>nodes</b> doesn't have enough routers
1406 * to handle the desired path length, return -1.
1408 STATIC int
1409 new_route_len(uint8_t purpose, extend_info_t *exit_ei,
1410 const smartlist_t *nodes)
1412 int routelen;
1414 tor_assert(nodes);
1416 routelen = route_len_for_purpose(purpose, exit_ei);
1418 int num_acceptable_direct = count_acceptable_nodes(nodes, 1);
1419 int num_acceptable_indirect = count_acceptable_nodes(nodes, 0);
1421 log_debug(LD_CIRC,"Chosen route length %d (%d direct and %d indirect "
1422 "routers suitable).", routelen, num_acceptable_direct,
1423 num_acceptable_indirect);
1425 if (num_acceptable_direct < 1 || num_acceptable_indirect < routelen - 1) {
1426 log_info(LD_CIRC,
1427 "Not enough acceptable routers (%d/%d direct and %d/%d "
1428 "indirect routers suitable). Discarding this circuit.",
1429 num_acceptable_direct, routelen,
1430 num_acceptable_indirect, routelen);
1431 return -1;
1434 return routelen;
1437 /** Return a newly allocated list of uint16_t * for each predicted port not
1438 * handled by a current circuit. */
1439 static smartlist_t *
1440 circuit_get_unhandled_ports(time_t now)
1442 smartlist_t *dest = rep_hist_get_predicted_ports(now);
1443 circuit_remove_handled_ports(dest);
1444 return dest;
1447 /** Return 1 if we already have circuits present or on the way for
1448 * all anticipated ports. Return 0 if we should make more.
1450 * If we're returning 0, set need_uptime and need_capacity to
1451 * indicate any requirements that the unhandled ports have.
1453 MOCK_IMPL(int,
1454 circuit_all_predicted_ports_handled, (time_t now, int *need_uptime,
1455 int *need_capacity))
1457 int i, enough;
1458 uint16_t *port;
1459 smartlist_t *sl = circuit_get_unhandled_ports(now);
1460 smartlist_t *LongLivedServices = get_options()->LongLivedPorts;
1461 tor_assert(need_uptime);
1462 tor_assert(need_capacity);
1463 // Always predict need_capacity
1464 *need_capacity = 1;
1465 enough = (smartlist_len(sl) == 0);
1466 for (i = 0; i < smartlist_len(sl); ++i) {
1467 port = smartlist_get(sl, i);
1468 if (smartlist_contains_int_as_string(LongLivedServices, *port))
1469 *need_uptime = 1;
1470 tor_free(port);
1472 smartlist_free(sl);
1473 return enough;
1476 /** Return 1 if <b>node</b> can handle one or more of the ports in
1477 * <b>needed_ports</b>, else return 0.
1479 static int
1480 node_handles_some_port(const node_t *node, smartlist_t *needed_ports)
1481 { /* XXXX MOVE */
1482 int i;
1483 uint16_t port;
1485 for (i = 0; i < smartlist_len(needed_ports); ++i) {
1486 addr_policy_result_t r;
1487 /* alignment issues aren't a worry for this dereference, since
1488 needed_ports is explicitly a smartlist of uint16_t's */
1489 port = *(uint16_t *)smartlist_get(needed_ports, i);
1490 tor_assert(port);
1491 if (node)
1492 r = compare_tor_addr_to_node_policy(NULL, port, node);
1493 else
1494 continue;
1495 if (r != ADDR_POLICY_REJECTED && r != ADDR_POLICY_PROBABLY_REJECTED)
1496 return 1;
1498 return 0;
1501 /** Return true iff <b>conn</b> needs another general circuit to be
1502 * built. */
1503 static int
1504 ap_stream_wants_exit_attention(connection_t *conn)
1506 entry_connection_t *entry;
1507 if (conn->type != CONN_TYPE_AP)
1508 return 0;
1509 entry = TO_ENTRY_CONN(conn);
1511 if (conn->state == AP_CONN_STATE_CIRCUIT_WAIT &&
1512 !conn->marked_for_close &&
1513 !(entry->want_onehop) && /* ignore one-hop streams */
1514 !(entry->use_begindir) && /* ignore targeted dir fetches */
1515 !(entry->chosen_exit_name) && /* ignore defined streams */
1516 !connection_edge_is_rendezvous_stream(TO_EDGE_CONN(conn)) &&
1517 !circuit_stream_is_being_handled(TO_ENTRY_CONN(conn), 0,
1518 MIN_CIRCUITS_HANDLING_STREAM))
1519 return 1;
1520 return 0;
1523 /** Return a pointer to a suitable router to be the exit node for the
1524 * general-purpose circuit we're about to build.
1526 * Look through the connection array, and choose a router that maximizes
1527 * the number of pending streams that can exit from this router.
1529 * Return NULL if we can't find any suitable routers.
1531 static const node_t *
1532 choose_good_exit_server_general(router_crn_flags_t flags)
1534 int *n_supported;
1535 int n_pending_connections = 0;
1536 smartlist_t *connections;
1537 int best_support = -1;
1538 int n_best_support=0;
1539 const or_options_t *options = get_options();
1540 const smartlist_t *the_nodes;
1541 const node_t *selected_node=NULL;
1542 const int need_uptime = (flags & CRN_NEED_UPTIME) != 0;
1543 const int need_capacity = (flags & CRN_NEED_CAPACITY) != 0;
1544 const int direct_conn = (flags & CRN_DIRECT_CONN) != 0;
1546 connections = get_connection_array();
1548 /* Count how many connections are waiting for a circuit to be built.
1549 * We use this for log messages now, but in the future we may depend on it.
1551 SMARTLIST_FOREACH(connections, connection_t *, conn,
1553 if (ap_stream_wants_exit_attention(conn))
1554 ++n_pending_connections;
1556 // log_fn(LOG_DEBUG, "Choosing exit node; %d connections are pending",
1557 // n_pending_connections);
1558 /* Now we count, for each of the routers in the directory, how many
1559 * of the pending connections could possibly exit from that
1560 * router (n_supported[i]). (We can't be sure about cases where we
1561 * don't know the IP address of the pending connection.)
1563 * -1 means "Don't use this router at all."
1565 the_nodes = nodelist_get_list();
1566 n_supported = tor_calloc(smartlist_len(the_nodes), sizeof(int));
1567 SMARTLIST_FOREACH_BEGIN(the_nodes, const node_t *, node) {
1568 const int i = node_sl_idx;
1569 if (router_digest_is_me(node->identity)) {
1570 n_supported[i] = -1;
1571 // log_fn(LOG_DEBUG,"Skipping node %s -- it's me.", router->nickname);
1572 /* XXX there's probably a reverse predecessor attack here, but
1573 * it's slow. should we take this out? -RD
1575 continue;
1577 if (!node_has_preferred_descriptor(node, direct_conn)) {
1578 n_supported[i] = -1;
1579 continue;
1581 if (!node->is_running || node->is_bad_exit) {
1582 n_supported[i] = -1;
1583 continue; /* skip routers that are known to be down or bad exits */
1585 if (node_get_purpose(node) != ROUTER_PURPOSE_GENERAL) {
1586 /* never pick a non-general node as a random exit. */
1587 n_supported[i] = -1;
1588 continue;
1590 if (routerset_contains_node(options->ExcludeExitNodesUnion_, node)) {
1591 n_supported[i] = -1;
1592 continue; /* user asked us not to use it, no matter what */
1594 if (options->ExitNodes &&
1595 !routerset_contains_node(options->ExitNodes, node)) {
1596 n_supported[i] = -1;
1597 continue; /* not one of our chosen exit nodes */
1600 if (node_is_unreliable(node, need_uptime, need_capacity, 0)) {
1601 n_supported[i] = -1;
1602 continue; /* skip routers that are not suitable. Don't worry if
1603 * this makes us reject all the possible routers: if so,
1604 * we'll retry later in this function with need_update and
1605 * need_capacity set to 0. */
1607 if (!(node->is_valid)) {
1608 /* if it's invalid and we don't want it */
1609 n_supported[i] = -1;
1610 // log_fn(LOG_DEBUG,"Skipping node %s (index %d) -- invalid router.",
1611 // router->nickname, i);
1612 continue; /* skip invalid routers */
1614 /* We do not allow relays that allow single hop exits by default. Option
1615 * was deprecated in 0.2.9.2-alpha and removed in 0.3.1.0-alpha. */
1616 if (node_allows_single_hop_exits(node)) {
1617 n_supported[i] = -1;
1618 continue;
1620 if (node_exit_policy_rejects_all(node)) {
1621 n_supported[i] = -1;
1622 // log_fn(LOG_DEBUG,"Skipping node %s (index %d) -- it rejects all.",
1623 // router->nickname, i);
1624 continue; /* skip routers that reject all */
1626 n_supported[i] = 0;
1627 /* iterate over connections */
1628 SMARTLIST_FOREACH_BEGIN(connections, connection_t *, conn) {
1629 if (!ap_stream_wants_exit_attention(conn))
1630 continue; /* Skip everything but APs in CIRCUIT_WAIT */
1631 if (connection_ap_can_use_exit(TO_ENTRY_CONN(conn), node)) {
1632 ++n_supported[i];
1633 // log_fn(LOG_DEBUG,"%s is supported. n_supported[%d] now %d.",
1634 // router->nickname, i, n_supported[i]);
1635 } else {
1636 // log_fn(LOG_DEBUG,"%s (index %d) would reject this stream.",
1637 // router->nickname, i);
1639 } SMARTLIST_FOREACH_END(conn);
1640 if (n_pending_connections > 0 && n_supported[i] == 0) {
1641 /* Leave best_support at -1 if that's where it is, so we can
1642 * distinguish it later. */
1643 continue;
1645 if (n_supported[i] > best_support) {
1646 /* If this router is better than previous ones, remember its index
1647 * and goodness, and start counting how many routers are this good. */
1648 best_support = n_supported[i]; n_best_support=1;
1649 // log_fn(LOG_DEBUG,"%s is new best supported option so far.",
1650 // router->nickname);
1651 } else if (n_supported[i] == best_support) {
1652 /* If this router is _as good_ as the best one, just increment the
1653 * count of equally good routers.*/
1654 ++n_best_support;
1656 } SMARTLIST_FOREACH_END(node);
1657 log_info(LD_CIRC,
1658 "Found %d servers that might support %d/%d pending connections.",
1659 n_best_support, best_support >= 0 ? best_support : 0,
1660 n_pending_connections);
1662 /* If any routers definitely support any pending connections, choose one
1663 * at random. */
1664 if (best_support > 0) {
1665 smartlist_t *supporting = smartlist_new();
1667 SMARTLIST_FOREACH(the_nodes, const node_t *, node, {
1668 if (n_supported[node_sl_idx] == best_support)
1669 smartlist_add(supporting, (void*)node);
1672 selected_node = node_sl_choose_by_bandwidth(supporting, WEIGHT_FOR_EXIT);
1673 smartlist_free(supporting);
1674 } else {
1675 /* Either there are no pending connections, or no routers even seem to
1676 * possibly support any of them. Choose a router at random that satisfies
1677 * at least one predicted exit port. */
1679 int attempt;
1680 smartlist_t *needed_ports, *supporting;
1682 if (best_support == -1) {
1683 if (need_uptime || need_capacity) {
1684 log_info(LD_CIRC,
1685 "We couldn't find any live%s%s routers; falling back "
1686 "to list of all routers.",
1687 need_capacity?", fast":"",
1688 need_uptime?", stable":"");
1689 tor_free(n_supported);
1690 flags &= ~(CRN_NEED_UPTIME|CRN_NEED_CAPACITY);
1691 return choose_good_exit_server_general(flags);
1693 log_notice(LD_CIRC, "All routers are down or won't exit%s -- "
1694 "choosing a doomed exit at random.",
1695 options->ExcludeExitNodesUnion_ ? " or are Excluded" : "");
1697 supporting = smartlist_new();
1698 needed_ports = circuit_get_unhandled_ports(time(NULL));
1699 for (attempt = 0; attempt < 2; attempt++) {
1700 /* try once to pick only from routers that satisfy a needed port,
1701 * then if there are none, pick from any that support exiting. */
1702 SMARTLIST_FOREACH_BEGIN(the_nodes, const node_t *, node) {
1703 if (n_supported[node_sl_idx] != -1 &&
1704 (attempt || node_handles_some_port(node, needed_ports))) {
1705 // log_fn(LOG_DEBUG,"Try %d: '%s' is a possibility.",
1706 // try, router->nickname);
1707 smartlist_add(supporting, (void*)node);
1709 } SMARTLIST_FOREACH_END(node);
1711 selected_node = node_sl_choose_by_bandwidth(supporting, WEIGHT_FOR_EXIT);
1712 if (selected_node)
1713 break;
1714 smartlist_clear(supporting);
1715 /* If we reach this point, we can't actually support any unhandled
1716 * predicted ports, so clear all the remaining ones. */
1717 if (smartlist_len(needed_ports))
1718 rep_hist_remove_predicted_ports(needed_ports);
1720 SMARTLIST_FOREACH(needed_ports, uint16_t *, cp, tor_free(cp));
1721 smartlist_free(needed_ports);
1722 smartlist_free(supporting);
1725 tor_free(n_supported);
1726 if (selected_node) {
1727 log_info(LD_CIRC, "Chose exit server '%s'", node_describe(selected_node));
1728 return selected_node;
1730 if (options->ExitNodes) {
1731 log_warn(LD_CIRC,
1732 "No exits in ExitNodes%s seem to be running: "
1733 "can't choose an exit.",
1734 options->ExcludeExitNodesUnion_ ?
1735 ", except possibly those excluded by your configuration, " : "");
1737 return NULL;
1740 /* Pick a Rendezvous Point for our HS circuits according to <b>flags</b>. */
1741 static const node_t *
1742 pick_rendezvous_node(router_crn_flags_t flags)
1744 const or_options_t *options = get_options();
1745 return router_choose_random_node(NULL, options->ExcludeNodes, flags);
1749 * Helper function to pick a configured restricted middle node
1750 * (either HSLayer2Nodes or HSLayer3Nodes).
1752 * Make sure that the node we chose is alive, and not excluded,
1753 * and return it.
1755 * The exclude_set is a routerset of nodes that the selected node
1756 * must not match, and the exclude_list is a simple list of nodes
1757 * that the selected node must not be in. Either or both may be
1758 * NULL.
1760 * Return NULL if no usable nodes could be found. */
1761 static const node_t *
1762 pick_restricted_middle_node(router_crn_flags_t flags,
1763 const routerset_t *pick_from,
1764 const routerset_t *exclude_set,
1765 const smartlist_t *exclude_list,
1766 int position_hint)
1768 const node_t *middle_node = NULL;
1770 smartlist_t *whitelisted_live_middles = smartlist_new();
1771 smartlist_t *all_live_nodes = smartlist_new();
1773 tor_assert(pick_from);
1775 /* Add all running nodes to all_live_nodes */
1776 router_add_running_nodes_to_smartlist(all_live_nodes,
1777 (flags & CRN_NEED_UPTIME) != 0,
1778 (flags & CRN_NEED_CAPACITY) != 0,
1779 (flags & CRN_NEED_GUARD) != 0,
1780 (flags & CRN_NEED_DESC) != 0,
1781 (flags & CRN_PREF_ADDR) != 0,
1782 (flags & CRN_DIRECT_CONN) != 0);
1784 /* Filter all_live_nodes to only add live *and* whitelisted middles
1785 * to the list whitelisted_live_middles. */
1786 SMARTLIST_FOREACH_BEGIN(all_live_nodes, node_t *, live_node) {
1787 if (routerset_contains_node(pick_from, live_node)) {
1788 smartlist_add(whitelisted_live_middles, live_node);
1790 } SMARTLIST_FOREACH_END(live_node);
1792 /* Honor ExcludeNodes */
1793 if (exclude_set) {
1794 routerset_subtract_nodes(whitelisted_live_middles, exclude_set);
1797 if (exclude_list) {
1798 smartlist_subtract(whitelisted_live_middles, exclude_list);
1802 * Max number of restricted nodes before we alert the user and try
1803 * to load balance for them.
1805 * The most aggressive vanguard design had 16 nodes at layer3.
1806 * Let's give a small ceiling above that. */
1807 #define MAX_SANE_RESTRICTED_NODES 20
1808 /* If the user (or associated tor controller) selected only a few nodes,
1809 * assume they took load balancing into account and don't do it for them.
1811 * If there are a lot of nodes in here, assume they did not load balance
1812 * and do it for them, but also warn them that they may be Doing It Wrong.
1814 if (smartlist_len(whitelisted_live_middles) <=
1815 MAX_SANE_RESTRICTED_NODES) {
1816 middle_node = smartlist_choose(whitelisted_live_middles);
1817 } else {
1818 static ratelim_t pinned_notice_limit = RATELIM_INIT(24*3600);
1819 log_fn_ratelim(&pinned_notice_limit, LOG_NOTICE, LD_CIRC,
1820 "Your _HSLayer%dNodes setting has resulted "
1821 "in %d total nodes. This is a lot of nodes. "
1822 "You may want to consider using a Tor controller "
1823 "to select and update a smaller set of nodes instead.",
1824 position_hint, smartlist_len(whitelisted_live_middles));
1826 /* NO_WEIGHTING here just means don't take node flags into account
1827 * (ie: use consensus measurement only). This is done so that
1828 * we don't further surprise the user by not using Exits that they
1829 * specified at all */
1830 middle_node = node_sl_choose_by_bandwidth(whitelisted_live_middles,
1831 NO_WEIGHTING);
1834 smartlist_free(whitelisted_live_middles);
1835 smartlist_free(all_live_nodes);
1837 return middle_node;
1840 /** Return a pointer to a suitable router to be the exit node for the
1841 * circuit of purpose <b>purpose</b> that we're about to build (or NULL
1842 * if no router is suitable).
1844 * For general-purpose circuits, pass it off to
1845 * choose_good_exit_server_general()
1847 * For client-side rendezvous circuits, choose a random node, weighted
1848 * toward the preferences in 'options'.
1850 static const node_t *
1851 choose_good_exit_server(origin_circuit_t *circ,
1852 router_crn_flags_t flags, int is_internal)
1854 const or_options_t *options = get_options();
1855 flags |= CRN_NEED_DESC;
1857 switch (TO_CIRCUIT(circ)->purpose) {
1858 case CIRCUIT_PURPOSE_C_HSDIR_GET:
1859 case CIRCUIT_PURPOSE_S_HSDIR_POST:
1860 case CIRCUIT_PURPOSE_HS_VANGUARDS:
1861 /* For these three, we want to pick the exit like a middle hop,
1862 * since it should be random. */
1863 tor_assert_nonfatal(is_internal);
1864 FALLTHROUGH;
1865 case CIRCUIT_PURPOSE_C_GENERAL:
1866 if (is_internal) /* pick it like a middle hop */
1867 return router_choose_random_node(NULL, options->ExcludeNodes, flags);
1868 else
1869 return choose_good_exit_server_general(flags);
1870 case CIRCUIT_PURPOSE_C_ESTABLISH_REND:
1872 /* Pick a new RP */
1873 const node_t *rendezvous_node = pick_rendezvous_node(flags);
1874 log_info(LD_REND, "Picked new RP: %s",
1875 safe_str_client(node_describe(rendezvous_node)));
1876 return rendezvous_node;
1879 log_warn(LD_BUG,"Unhandled purpose %d", TO_CIRCUIT(circ)->purpose);
1880 tor_fragile_assert();
1881 return NULL;
1884 /** Log a warning if the user specified an exit for the circuit that
1885 * has been excluded from use by ExcludeNodes or ExcludeExitNodes. */
1886 static void
1887 warn_if_last_router_excluded(origin_circuit_t *circ,
1888 const extend_info_t *exit_ei)
1890 const or_options_t *options = get_options();
1891 routerset_t *rs = options->ExcludeNodes;
1892 const char *description;
1893 uint8_t purpose = circ->base_.purpose;
1895 if (circ->build_state->onehop_tunnel)
1896 return;
1898 switch (purpose)
1900 default:
1901 case CIRCUIT_PURPOSE_OR:
1902 case CIRCUIT_PURPOSE_INTRO_POINT:
1903 case CIRCUIT_PURPOSE_REND_POINT_WAITING:
1904 case CIRCUIT_PURPOSE_REND_ESTABLISHED:
1905 log_warn(LD_BUG, "Called on non-origin circuit (purpose %d, %s)",
1906 (int)purpose,
1907 circuit_purpose_to_string(purpose));
1908 return;
1909 case CIRCUIT_PURPOSE_S_HSDIR_POST:
1910 case CIRCUIT_PURPOSE_C_HSDIR_GET:
1911 case CIRCUIT_PURPOSE_C_GENERAL:
1912 if (circ->build_state->is_internal)
1913 return;
1914 description = "requested exit node";
1915 rs = options->ExcludeExitNodesUnion_;
1916 break;
1917 case CIRCUIT_PURPOSE_C_INTRODUCING:
1918 case CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT:
1919 case CIRCUIT_PURPOSE_C_INTRODUCE_ACKED:
1920 case CIRCUIT_PURPOSE_S_ESTABLISH_INTRO:
1921 case CIRCUIT_PURPOSE_S_CONNECT_REND:
1922 case CIRCUIT_PURPOSE_S_REND_JOINED:
1923 case CIRCUIT_PURPOSE_TESTING:
1924 return;
1925 case CIRCUIT_PURPOSE_C_ESTABLISH_REND:
1926 case CIRCUIT_PURPOSE_C_REND_READY:
1927 case CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED:
1928 case CIRCUIT_PURPOSE_C_REND_JOINED:
1929 description = "chosen rendezvous point";
1930 break;
1931 case CIRCUIT_PURPOSE_CONTROLLER:
1932 rs = options->ExcludeExitNodesUnion_;
1933 description = "controller-selected circuit target";
1934 break;
1937 if (routerset_contains_extendinfo(rs, exit_ei)) {
1938 /* We should never get here if StrictNodes is set to 1. */
1939 if (options->StrictNodes) {
1940 log_warn(LD_BUG, "Using %s '%s' which is listed in ExcludeNodes%s, "
1941 "even though StrictNodes is set. Please report. "
1942 "(Circuit purpose: %s)",
1943 description, extend_info_describe(exit_ei),
1944 rs==options->ExcludeNodes?"":" or ExcludeExitNodes",
1945 circuit_purpose_to_string(purpose));
1946 } else {
1947 log_warn(LD_CIRC, "Using %s '%s' which is listed in "
1948 "ExcludeNodes%s, because no better options were available. To "
1949 "prevent this (and possibly break your Tor functionality), "
1950 "set the StrictNodes configuration option. "
1951 "(Circuit purpose: %s)",
1952 description, extend_info_describe(exit_ei),
1953 rs==options->ExcludeNodes?"":" or ExcludeExitNodes",
1954 circuit_purpose_to_string(purpose));
1956 circuit_log_path(LOG_WARN, LD_CIRC, circ);
1959 return;
1962 /** Decide a suitable length for circ's cpath, and pick an exit
1963 * router (or use <b>exit</b> if provided). Store these in the
1964 * cpath.
1966 * If <b>is_hs_v3_rp_circuit</b> is set, then this exit should be suitable to
1967 * be used as an HS v3 rendezvous point.
1969 * Return 0 if ok, -1 if circuit should be closed. */
1970 STATIC int
1971 onion_pick_cpath_exit(origin_circuit_t *circ, extend_info_t *exit_ei,
1972 int is_hs_v3_rp_circuit)
1974 cpath_build_state_t *state = circ->build_state;
1976 if (state->onehop_tunnel) {
1977 log_debug(LD_CIRC, "Launching a one-hop circuit for dir tunnel%s.",
1978 (rend_allow_non_anonymous_connection(get_options()) ?
1979 ", or intro or rendezvous connection" : ""));
1980 state->desired_path_len = 1;
1981 } else {
1982 int r = new_route_len(circ->base_.purpose, exit_ei, nodelist_get_list());
1983 if (r < 1) /* must be at least 1 */
1984 return -1;
1985 state->desired_path_len = r;
1988 if (exit_ei) { /* the circuit-builder pre-requested one */
1989 warn_if_last_router_excluded(circ, exit_ei);
1990 log_info(LD_CIRC,"Using requested exit node '%s'",
1991 extend_info_describe(exit_ei));
1992 exit_ei = extend_info_dup(exit_ei);
1993 } else { /* we have to decide one */
1994 router_crn_flags_t flags = CRN_NEED_DESC;
1995 if (state->need_uptime)
1996 flags |= CRN_NEED_UPTIME;
1997 if (state->need_capacity)
1998 flags |= CRN_NEED_CAPACITY;
1999 if (is_hs_v3_rp_circuit)
2000 flags |= CRN_RENDEZVOUS_V3;
2001 if (state->onehop_tunnel)
2002 flags |= CRN_DIRECT_CONN;
2003 const node_t *node =
2004 choose_good_exit_server(circ, flags, state->is_internal);
2005 if (!node) {
2006 log_warn(LD_CIRC,"Failed to choose an exit server");
2007 return -1;
2009 exit_ei = extend_info_from_node(node, state->onehop_tunnel);
2010 if (BUG(exit_ei == NULL))
2011 return -1;
2013 state->chosen_exit = exit_ei;
2014 return 0;
2017 /** Give <b>circ</b> a new exit destination to <b>exit</b>, and add a
2018 * hop to the cpath reflecting this. Don't send the next extend cell --
2019 * the caller will do this if it wants to.
2022 circuit_append_new_exit(origin_circuit_t *circ, extend_info_t *exit_ei)
2024 cpath_build_state_t *state;
2025 tor_assert(exit_ei);
2026 tor_assert(circ);
2028 state = circ->build_state;
2029 tor_assert(state);
2030 extend_info_free(state->chosen_exit);
2031 state->chosen_exit = extend_info_dup(exit_ei);
2033 ++circ->build_state->desired_path_len;
2034 cpath_append_hop(&circ->cpath, exit_ei);
2035 return 0;
2038 /** Take an open <b>circ</b>, and add a new hop at the end, based on
2039 * <b>info</b>. Set its state back to CIRCUIT_STATE_BUILDING, and then
2040 * send the next extend cell to begin connecting to that hop.
2043 circuit_extend_to_new_exit(origin_circuit_t *circ, extend_info_t *exit_ei)
2045 int err_reason = 0;
2046 warn_if_last_router_excluded(circ, exit_ei);
2048 tor_gettimeofday(&circ->base_.timestamp_began);
2050 circuit_append_new_exit(circ, exit_ei);
2051 circuit_set_state(TO_CIRCUIT(circ), CIRCUIT_STATE_BUILDING);
2052 if ((err_reason = circuit_send_next_onion_skin(circ))<0) {
2053 log_warn(LD_CIRC, "Couldn't extend circuit to new point %s.",
2054 extend_info_describe(exit_ei));
2055 circuit_mark_for_close(TO_CIRCUIT(circ), -err_reason);
2056 return -1;
2059 // XXX: Should cannibalized circuits be dirty or not? Not easy to say..
2061 return 0;
2064 /** Return the number of routers in <b>routers</b> that are currently up
2065 * and available for building circuits through.
2067 * (Note that this function may overcount or undercount, if we have
2068 * descriptors that are not the type we would prefer to use for some
2069 * particular router. See bug #25885.)
2071 MOCK_IMPL(STATIC int,
2072 count_acceptable_nodes, (const smartlist_t *nodes, int direct))
2074 int num=0;
2076 SMARTLIST_FOREACH_BEGIN(nodes, const node_t *, node) {
2077 // log_debug(LD_CIRC,
2078 // "Contemplating whether router %d (%s) is a new option.",
2079 // i, r->nickname);
2080 if (! node->is_running)
2081 // log_debug(LD_CIRC,"Nope, the directory says %d is not running.",i);
2082 continue;
2083 if (! node->is_valid)
2084 // log_debug(LD_CIRC,"Nope, the directory says %d is not valid.",i);
2085 continue;
2086 if (! node_has_preferred_descriptor(node, direct))
2087 continue;
2088 /* The node has a descriptor, so we can just check the ntor key directly */
2089 if (!node_has_curve25519_onion_key(node))
2090 continue;
2091 ++num;
2092 } SMARTLIST_FOREACH_END(node);
2094 // log_debug(LD_CIRC,"I like %d. num_acceptable_routers now %d.",i, num);
2096 return num;
2100 * Build the exclude list for vanguard circuits.
2102 * For vanguard circuits we exclude all the already chosen nodes (including the
2103 * exit) from being middle hops to prevent the creation of A - B - A subpaths.
2104 * We also allow the 4th hop to be the same as the guard node so as to not leak
2105 * guard information to RP/IP/HSDirs.
2107 * For vanguard circuits, we don't apply any subnet or family restrictions.
2108 * This is to avoid impossible-to-build circuit paths, or just situations where
2109 * our earlier guards prevent us from using most of our later ones.
2111 * The alternative is building the circuit in reverse. Reverse calls to
2112 * onion_extend_cpath() (ie: select outer hops first) would then have the
2113 * property that you don't gain information about inner hops by observing
2114 * outer ones. See https://trac.torproject.org/projects/tor/ticket/24487
2115 * for this.
2117 * (Note further that we still exclude the exit to prevent A - B - A
2118 * at the end of the path. */
2119 static smartlist_t *
2120 build_vanguard_middle_exclude_list(uint8_t purpose,
2121 cpath_build_state_t *state,
2122 crypt_path_t *head,
2123 int cur_len)
2125 smartlist_t *excluded;
2126 const node_t *r;
2127 crypt_path_t *cpath;
2128 int i;
2130 (void) purpose;
2132 excluded = smartlist_new();
2134 /* Add the exit to the exclude list (note that the exit/last hop is always
2135 * chosen first in circuit_establish_circuit()). */
2136 if ((r = build_state_get_exit_node(state))) {
2137 smartlist_add(excluded, (node_t*)r);
2140 /* If we are picking the 4th hop, allow that node to be the guard too.
2141 * This prevents us from avoiding the Guard for those hops, which
2142 * gives the adversary information about our guard if they control
2143 * the RP, IP, or HSDIR. We don't do this check based on purpose
2144 * because we also want to allow HS_VANGUARDS pre-build circuits
2145 * to use the guard for that last hop.
2147 if (cur_len == DEFAULT_ROUTE_LEN+1) {
2148 /* Skip the first hop for the exclude list below */
2149 head = head->next;
2150 cur_len--;
2153 for (i = 0, cpath = head; cpath && i < cur_len; ++i, cpath=cpath->next) {
2154 if ((r = node_get_by_id(cpath->extend_info->identity_digest))) {
2155 smartlist_add(excluded, (node_t*)r);
2159 return excluded;
2163 * Build a list of nodes to exclude from the choice of this middle
2164 * hop, based on already chosen nodes.
2166 static smartlist_t *
2167 build_middle_exclude_list(uint8_t purpose,
2168 cpath_build_state_t *state,
2169 crypt_path_t *head,
2170 int cur_len)
2172 smartlist_t *excluded;
2173 const node_t *r;
2174 crypt_path_t *cpath;
2175 int i;
2177 /** Vanguard circuits have their own path selection rules */
2178 if (circuit_should_use_vanguards(purpose)) {
2179 return build_vanguard_middle_exclude_list(purpose, state, head, cur_len);
2182 excluded = smartlist_new();
2184 /* For non-vanguard circuits, add the exit and its family to the exclude list
2185 * (note that the exit/last hop is always chosen first in
2186 * circuit_establish_circuit()). */
2187 if ((r = build_state_get_exit_node(state))) {
2188 nodelist_add_node_and_family(excluded, r);
2191 /* also exclude all other already chosen nodes and their family */
2192 for (i = 0, cpath = head; cpath && i < cur_len; ++i, cpath=cpath->next) {
2193 if ((r = node_get_by_id(cpath->extend_info->identity_digest))) {
2194 nodelist_add_node_and_family(excluded, r);
2198 return excluded;
2201 /** Return true if we MUST use vanguards for picking this middle node. */
2202 static int
2203 middle_node_must_be_vanguard(const or_options_t *options,
2204 uint8_t purpose, int cur_len)
2206 /* If this is not a hidden service circuit, don't use vanguards */
2207 if (!circuit_purpose_is_hidden_service(purpose)) {
2208 return 0;
2211 /* If we have sticky L2 nodes, and this is an L2 pick, use vanguards */
2212 if (options->HSLayer2Nodes && cur_len == 1) {
2213 return 1;
2216 /* If we have sticky L3 nodes, and this is an L3 pick, use vanguards */
2217 if (options->HSLayer3Nodes && cur_len == 2) {
2218 return 1;
2221 return 0;
2224 /** Pick a sticky vanguard middle node or return NULL if not found.
2225 * See doc of pick_restricted_middle_node() for argument details. */
2226 static const node_t *
2227 pick_vanguard_middle_node(const or_options_t *options,
2228 router_crn_flags_t flags, int cur_len,
2229 const smartlist_t *excluded)
2231 const routerset_t *vanguard_routerset = NULL;
2232 const node_t *node = NULL;
2234 /* Pick the right routerset based on the current hop */
2235 if (cur_len == 1) {
2236 vanguard_routerset = options->HSLayer2Nodes;
2237 } else if (cur_len == 2) {
2238 vanguard_routerset = options->HSLayer3Nodes;
2239 } else {
2240 /* guaranteed by middle_node_should_be_vanguard() */
2241 tor_assert_nonfatal_unreached();
2242 return NULL;
2245 node = pick_restricted_middle_node(flags, vanguard_routerset,
2246 options->ExcludeNodes, excluded,
2247 cur_len+1);
2249 if (!node) {
2250 static ratelim_t pinned_warning_limit = RATELIM_INIT(300);
2251 log_fn_ratelim(&pinned_warning_limit, LOG_WARN, LD_CIRC,
2252 "Could not find a node that matches the configured "
2253 "_HSLayer%dNodes set", cur_len+1);
2256 return node;
2259 /** A helper function used by onion_extend_cpath(). Use <b>purpose</b>
2260 * and <b>state</b> and the cpath <b>head</b> (currently populated only
2261 * to length <b>cur_len</b> to decide a suitable middle hop for a
2262 * circuit. In particular, make sure we don't pick the exit node or its
2263 * family, and make sure we don't duplicate any previous nodes or their
2264 * families. */
2265 static const node_t *
2266 choose_good_middle_server(uint8_t purpose,
2267 cpath_build_state_t *state,
2268 crypt_path_t *head,
2269 int cur_len)
2271 const node_t *choice;
2272 smartlist_t *excluded;
2273 const or_options_t *options = get_options();
2274 router_crn_flags_t flags = CRN_NEED_DESC;
2275 tor_assert(CIRCUIT_PURPOSE_MIN_ <= purpose &&
2276 purpose <= CIRCUIT_PURPOSE_MAX_);
2278 log_debug(LD_CIRC, "Contemplating intermediate hop #%d: random choice.",
2279 cur_len+1);
2281 excluded = build_middle_exclude_list(purpose, state, head, cur_len);
2283 if (state->need_uptime)
2284 flags |= CRN_NEED_UPTIME;
2285 if (state->need_capacity)
2286 flags |= CRN_NEED_CAPACITY;
2288 /** If a hidden service circuit wants a specific middle node, pin it. */
2289 if (middle_node_must_be_vanguard(options, purpose, cur_len)) {
2290 log_debug(LD_GENERAL, "Picking a sticky node (cur_len = %d)", cur_len);
2291 choice = pick_vanguard_middle_node(options, flags, cur_len, excluded);
2292 smartlist_free(excluded);
2293 return choice;
2296 if (options->MiddleNodes) {
2297 smartlist_t *sl = smartlist_new();
2298 routerset_get_all_nodes(sl, options->MiddleNodes,
2299 options->ExcludeNodes, 1);
2301 smartlist_subtract(sl, excluded);
2303 choice = node_sl_choose_by_bandwidth(sl, WEIGHT_FOR_MID);
2304 smartlist_free(sl);
2305 if (choice) {
2306 log_fn(LOG_INFO, LD_CIRC, "Chose fixed middle node: %s",
2307 hex_str(choice->identity, DIGEST_LEN));
2308 } else {
2309 log_fn(LOG_NOTICE, LD_CIRC, "Restricted middle not available");
2311 } else {
2312 choice = router_choose_random_node(excluded, options->ExcludeNodes, flags);
2314 smartlist_free(excluded);
2315 return choice;
2318 /** Pick a good entry server for the circuit to be built according to
2319 * <b>state</b>. Don't reuse a chosen exit (if any), don't use this
2320 * router (if we're an OR), and respect firewall settings; if we're
2321 * configured to use entry guards, return one.
2323 * Set *<b>guard_state_out</b> to information about the guard that
2324 * we're selecting, which we'll use later to remember whether the
2325 * guard worked or not.
2327 const node_t *
2328 choose_good_entry_server(uint8_t purpose, cpath_build_state_t *state,
2329 circuit_guard_state_t **guard_state_out)
2331 const node_t *choice;
2332 smartlist_t *excluded;
2333 const or_options_t *options = get_options();
2334 /* If possible, choose an entry server with a preferred address,
2335 * otherwise, choose one with an allowed address */
2336 router_crn_flags_t flags = (CRN_NEED_GUARD|CRN_NEED_DESC|CRN_PREF_ADDR|
2337 CRN_DIRECT_CONN);
2338 const node_t *node;
2340 /* Once we used this function to select a node to be a guard. We had
2341 * 'state == NULL' be the signal for that. But we don't do that any more.
2343 tor_assert_nonfatal(state);
2345 if (state && options->UseEntryGuards &&
2346 (purpose != CIRCUIT_PURPOSE_TESTING || options->BridgeRelay)) {
2347 /* This request is for an entry server to use for a regular circuit,
2348 * and we use entry guard nodes. Just return one of the guard nodes. */
2349 tor_assert(guard_state_out);
2350 return guards_choose_guard(state, purpose, guard_state_out);
2353 excluded = smartlist_new();
2355 if (state && (node = build_state_get_exit_node(state))) {
2356 /* Exclude the exit node from the state, if we have one. Also exclude its
2357 * family. */
2358 nodelist_add_node_and_family(excluded, node);
2361 if (state) {
2362 if (state->need_uptime)
2363 flags |= CRN_NEED_UPTIME;
2364 if (state->need_capacity)
2365 flags |= CRN_NEED_CAPACITY;
2368 choice = router_choose_random_node(excluded, options->ExcludeNodes, flags);
2369 smartlist_free(excluded);
2370 return choice;
2373 /** Choose a suitable next hop for the circuit <b>circ</b>.
2374 * Append the hop info to circ->cpath.
2376 * Return 1 if the path is complete, 0 if we successfully added a hop,
2377 * and -1 on error.
2379 STATIC int
2380 onion_extend_cpath(origin_circuit_t *circ)
2382 uint8_t purpose = circ->base_.purpose;
2383 cpath_build_state_t *state = circ->build_state;
2384 int cur_len = circuit_get_cpath_len(circ);
2385 extend_info_t *info = NULL;
2387 if (cur_len >= state->desired_path_len) {
2388 log_debug(LD_CIRC, "Path is complete: %d steps long",
2389 state->desired_path_len);
2390 return 1;
2393 log_debug(LD_CIRC, "Path is %d long; we want %d", cur_len,
2394 state->desired_path_len);
2396 if (cur_len == state->desired_path_len - 1) { /* Picking last node */
2397 info = extend_info_dup(state->chosen_exit);
2398 } else if (cur_len == 0) { /* picking first node */
2399 const node_t *r = choose_good_entry_server(purpose, state,
2400 &circ->guard_state);
2401 if (r) {
2402 /* If we're a client, use the preferred address rather than the
2403 primary address, for potentially connecting to an IPv6 OR
2404 port. Servers always want the primary (IPv4) address. */
2405 int client = (server_mode(get_options()) == 0);
2406 info = extend_info_from_node(r, client);
2407 /* Clients can fail to find an allowed address */
2408 tor_assert_nonfatal(info || client);
2410 } else {
2411 const node_t *r =
2412 choose_good_middle_server(purpose, state, circ->cpath, cur_len);
2413 if (r) {
2414 info = extend_info_from_node(r, 0);
2415 tor_assert_nonfatal(info);
2419 if (!info) {
2420 log_warn(LD_CIRC,"Failed to find node for hop #%d of our path. Discarding "
2421 "this circuit.", cur_len+1);
2422 return -1;
2425 log_debug(LD_CIRC,"Chose router %s for hop #%d (exit is %s)",
2426 extend_info_describe(info),
2427 cur_len+1, build_state_get_exit_nickname(state));
2429 cpath_append_hop(&circ->cpath, info);
2430 extend_info_free(info);
2431 return 0;
2434 /** Allocate a new extend_info object based on the various arguments. */
2435 extend_info_t *
2436 extend_info_new(const char *nickname,
2437 const char *rsa_id_digest,
2438 const ed25519_public_key_t *ed_id,
2439 crypto_pk_t *onion_key,
2440 const curve25519_public_key_t *ntor_key,
2441 const tor_addr_t *addr, uint16_t port)
2443 extend_info_t *info = tor_malloc_zero(sizeof(extend_info_t));
2444 memcpy(info->identity_digest, rsa_id_digest, DIGEST_LEN);
2445 if (ed_id && !ed25519_public_key_is_zero(ed_id))
2446 memcpy(&info->ed_identity, ed_id, sizeof(ed25519_public_key_t));
2447 if (nickname)
2448 strlcpy(info->nickname, nickname, sizeof(info->nickname));
2449 if (onion_key)
2450 info->onion_key = crypto_pk_dup_key(onion_key);
2451 if (ntor_key)
2452 memcpy(&info->curve25519_onion_key, ntor_key,
2453 sizeof(curve25519_public_key_t));
2454 tor_addr_copy(&info->addr, addr);
2455 info->port = port;
2456 return info;
2459 /** Allocate and return a new extend_info that can be used to build a
2460 * circuit to or through the node <b>node</b>. Use the primary address
2461 * of the node (i.e. its IPv4 address) unless
2462 * <b>for_direct_connect</b> is true, in which case the preferred
2463 * address is used instead. May return NULL if there is not enough
2464 * info about <b>node</b> to extend to it--for example, if the preferred
2465 * routerinfo_t or microdesc_t is missing, or if for_direct_connect is
2466 * true and none of the node's addresses is allowed by tor's firewall
2467 * and IP version config.
2469 extend_info_t *
2470 extend_info_from_node(const node_t *node, int for_direct_connect)
2472 crypto_pk_t *rsa_pubkey = NULL;
2473 extend_info_t *info = NULL;
2474 tor_addr_port_t ap;
2475 int valid_addr = 0;
2477 if (!node_has_preferred_descriptor(node, for_direct_connect)) {
2478 return NULL;
2481 /* Choose a preferred address first, but fall back to an allowed address. */
2482 if (for_direct_connect)
2483 fascist_firewall_choose_address_node(node, FIREWALL_OR_CONNECTION, 0, &ap);
2484 else {
2485 node_get_prim_orport(node, &ap);
2487 valid_addr = tor_addr_port_is_valid_ap(&ap, 0);
2489 if (valid_addr)
2490 log_debug(LD_CIRC, "using %s for %s",
2491 fmt_addrport(&ap.addr, ap.port),
2492 node->ri ? node->ri->nickname : node->rs->nickname);
2493 else
2494 log_warn(LD_CIRC, "Could not choose valid address for %s",
2495 node->ri ? node->ri->nickname : node->rs->nickname);
2497 /* Every node we connect or extend to must support ntor */
2498 if (!node_has_curve25519_onion_key(node)) {
2499 log_fn(LOG_PROTOCOL_WARN, LD_CIRC,
2500 "Attempted to create extend_info for a node that does not support "
2501 "ntor: %s", node_describe(node));
2502 return NULL;
2505 const ed25519_public_key_t *ed_pubkey = NULL;
2507 /* Don't send the ed25519 pubkey unless the target node actually supports
2508 * authenticating with it. */
2509 if (node_supports_ed25519_link_authentication(node, 0)) {
2510 log_info(LD_CIRC, "Including Ed25519 ID for %s", node_describe(node));
2511 ed_pubkey = node_get_ed25519_id(node);
2512 } else if (node_get_ed25519_id(node)) {
2513 log_info(LD_CIRC, "Not including the ed25519 ID for %s, since it won't "
2514 "be able to authenticate it.",
2515 node_describe(node));
2518 /* Retrieve the curve25519 pubkey. */
2519 const curve25519_public_key_t *curve_pubkey =
2520 node_get_curve25519_onion_key(node);
2521 rsa_pubkey = node_get_rsa_onion_key(node);
2523 if (valid_addr && node->ri) {
2524 info = extend_info_new(node->ri->nickname,
2525 node->identity,
2526 ed_pubkey,
2527 rsa_pubkey,
2528 curve_pubkey,
2529 &ap.addr,
2530 ap.port);
2531 } else if (valid_addr && node->rs && node->md) {
2532 info = extend_info_new(node->rs->nickname,
2533 node->identity,
2534 ed_pubkey,
2535 rsa_pubkey,
2536 curve_pubkey,
2537 &ap.addr,
2538 ap.port);
2541 crypto_pk_free(rsa_pubkey);
2542 return info;
2545 /** Release storage held by an extend_info_t struct. */
2546 void
2547 extend_info_free_(extend_info_t *info)
2549 if (!info)
2550 return;
2551 crypto_pk_free(info->onion_key);
2552 tor_free(info);
2555 /** Allocate and return a new extend_info_t with the same contents as
2556 * <b>info</b>. */
2557 extend_info_t *
2558 extend_info_dup(extend_info_t *info)
2560 extend_info_t *newinfo;
2561 tor_assert(info);
2562 newinfo = tor_malloc(sizeof(extend_info_t));
2563 memcpy(newinfo, info, sizeof(extend_info_t));
2564 if (info->onion_key)
2565 newinfo->onion_key = crypto_pk_dup_key(info->onion_key);
2566 else
2567 newinfo->onion_key = NULL;
2568 return newinfo;
2571 /** Return the node_t for the chosen exit router in <b>state</b>.
2572 * If there is no chosen exit, or if we don't know the node_t for
2573 * the chosen exit, return NULL.
2575 MOCK_IMPL(const node_t *,
2576 build_state_get_exit_node,(cpath_build_state_t *state))
2578 if (!state || !state->chosen_exit)
2579 return NULL;
2580 return node_get_by_id(state->chosen_exit->identity_digest);
2583 /** Return the RSA ID digest for the chosen exit router in <b>state</b>.
2584 * If there is no chosen exit, return NULL.
2586 const uint8_t *
2587 build_state_get_exit_rsa_id(cpath_build_state_t *state)
2589 if (!state || !state->chosen_exit)
2590 return NULL;
2591 return (const uint8_t *) state->chosen_exit->identity_digest;
2594 /** Return the nickname for the chosen exit router in <b>state</b>. If
2595 * there is no chosen exit, or if we don't know the routerinfo_t for the
2596 * chosen exit, return NULL.
2598 const char *
2599 build_state_get_exit_nickname(cpath_build_state_t *state)
2601 if (!state || !state->chosen_exit)
2602 return NULL;
2603 return state->chosen_exit->nickname;
2606 /** Return true iff the given address can be used to extend to. */
2608 extend_info_addr_is_allowed(const tor_addr_t *addr)
2610 tor_assert(addr);
2612 /* Check if we have a private address and if we can extend to it. */
2613 if ((tor_addr_is_internal(addr, 0) || tor_addr_is_multicast(addr)) &&
2614 !get_options()->ExtendAllowPrivateAddresses) {
2615 goto disallow;
2617 /* Allowed! */
2618 return 1;
2619 disallow:
2620 return 0;
2623 /* Does ei have a valid TAP key? */
2625 extend_info_supports_tap(const extend_info_t* ei)
2627 tor_assert(ei);
2628 /* Valid TAP keys are not NULL */
2629 return ei->onion_key != NULL;
2632 /* Does ei have a valid ntor key? */
2634 extend_info_supports_ntor(const extend_info_t* ei)
2636 tor_assert(ei);
2637 /* Valid ntor keys have at least one non-zero byte */
2638 return !fast_mem_is_zero(
2639 (const char*)ei->curve25519_onion_key.public_key,
2640 CURVE25519_PUBKEY_LEN);
2643 /* Is circuit purpose allowed to use the deprecated TAP encryption protocol?
2644 * The hidden service protocol still uses TAP for some connections, because
2645 * ntor onion keys aren't included in HS descriptors or INTRODUCE cells. */
2646 static int
2647 circuit_purpose_can_use_tap_impl(uint8_t purpose)
2649 return (purpose == CIRCUIT_PURPOSE_S_CONNECT_REND ||
2650 purpose == CIRCUIT_PURPOSE_C_INTRODUCING);
2653 /* Is circ allowed to use the deprecated TAP encryption protocol?
2654 * The hidden service protocol still uses TAP for some connections, because
2655 * ntor onion keys aren't included in HS descriptors or INTRODUCE cells. */
2657 circuit_can_use_tap(const origin_circuit_t *circ)
2659 tor_assert(circ);
2660 tor_assert(circ->cpath);
2661 tor_assert(circ->cpath->extend_info);
2662 return (circuit_purpose_can_use_tap_impl(circ->base_.purpose) &&
2663 extend_info_supports_tap(circ->cpath->extend_info));
2666 /* Does circ have an onion key which it's allowed to use? */
2668 circuit_has_usable_onion_key(const origin_circuit_t *circ)
2670 tor_assert(circ);
2671 tor_assert(circ->cpath);
2672 tor_assert(circ->cpath->extend_info);
2673 return (extend_info_supports_ntor(circ->cpath->extend_info) ||
2674 circuit_can_use_tap(circ));
2677 /* Does ei have an onion key which it would prefer to use?
2678 * Currently, we prefer ntor keys*/
2680 extend_info_has_preferred_onion_key(const extend_info_t* ei)
2682 tor_assert(ei);
2683 return extend_info_supports_ntor(ei);
2686 /** Find the circuits that are waiting to find out whether their guards are
2687 * usable, and if any are ready to become usable, mark them open and try
2688 * attaching streams as appropriate. */
2689 void
2690 circuit_upgrade_circuits_from_guard_wait(void)
2692 smartlist_t *to_upgrade =
2693 circuit_find_circuits_to_upgrade_from_guard_wait();
2695 if (to_upgrade == NULL)
2696 return;
2698 log_info(LD_GUARD, "Upgrading %d circuits from 'waiting for better guard' "
2699 "to 'open'.", smartlist_len(to_upgrade));
2701 SMARTLIST_FOREACH_BEGIN(to_upgrade, origin_circuit_t *, circ) {
2702 circuit_set_state(TO_CIRCUIT(circ), CIRCUIT_STATE_OPEN);
2703 circuit_has_opened(circ);
2704 } SMARTLIST_FOREACH_END(circ);
2706 smartlist_free(to_upgrade);