trace: Add two origin circuit specific tracepoints
[tor.git] / src / core / or / circuitbuild.c
blob034a0dc77891b9591c3114d47996fd69dd92448d
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/extendinfo.h"
49 #include "core/or/onion.h"
50 #include "core/or/ocirc_event.h"
51 #include "core/or/policies.h"
52 #include "core/or/relay.h"
53 #include "core/or/trace_probes_circuit.h"
54 #include "core/or/crypt_path.h"
55 #include "feature/client/bridges.h"
56 #include "feature/client/circpathbias.h"
57 #include "feature/client/entrynodes.h"
58 #include "feature/client/transports.h"
59 #include "feature/control/control_events.h"
60 #include "feature/dircommon/directory.h"
61 #include "feature/nodelist/describe.h"
62 #include "feature/nodelist/microdesc.h"
63 #include "feature/nodelist/networkstatus.h"
64 #include "feature/nodelist/nickname.h"
65 #include "feature/nodelist/node_select.h"
66 #include "feature/nodelist/nodelist.h"
67 #include "feature/nodelist/routerlist.h"
68 #include "feature/nodelist/routerset.h"
69 #include "feature/relay/router.h"
70 #include "feature/relay/routermode.h"
71 #include "feature/relay/selftest.h"
72 #include "feature/rend/rendcommon.h"
73 #include "feature/stats/predict_ports.h"
74 #include "lib/crypt_ops/crypto_rand.h"
75 #include "lib/trace/events.h"
77 #include "core/or/cell_st.h"
78 #include "core/or/cpath_build_state_st.h"
79 #include "core/or/entry_connection_st.h"
80 #include "core/or/extend_info_st.h"
81 #include "feature/nodelist/node_st.h"
82 #include "core/or/or_circuit_st.h"
83 #include "core/or/origin_circuit_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 extend_info_t *ei))
101 channel_t *chan;
103 const tor_addr_port_t *orport = extend_info_pick_orport(ei);
104 if (!orport)
105 return NULL;
106 const char *id_digest = ei->identity_digest;
107 const ed25519_public_key_t *ed_id = &ei->ed_identity;
109 chan = channel_connect(&orport->addr, orport->port, id_digest, ed_id);
110 if (chan) command_setup_channel(chan);
112 return chan;
115 /** Search for a value for circ_id that we can use on <b>chan</b> for an
116 * outbound circuit, until we get a circ_id that is not in use by any other
117 * circuit on that conn.
119 * Return it, or 0 if can't get a unique circ_id.
121 STATIC circid_t
122 get_unique_circ_id_by_chan(channel_t *chan)
124 /* This number is chosen somewhat arbitrarily; see comment below for more
125 * info. When the space is 80% full, it gives a one-in-a-million failure
126 * chance; when the space is 90% full, it gives a one-in-850 chance; and when
127 * the space is 95% full, it gives a one-in-26 failure chance. That seems
128 * okay, though you could make a case IMO for anything between N=32 and
129 * N=256. */
130 #define MAX_CIRCID_ATTEMPTS 64
131 int in_use;
132 unsigned n_with_circ = 0, n_pending_destroy = 0, n_weird_pending_destroy = 0;
133 circid_t test_circ_id;
134 circid_t attempts=0;
135 circid_t high_bit, max_range, mask;
136 int64_t pending_destroy_time_total = 0;
137 int64_t pending_destroy_time_max = 0;
139 tor_assert(chan);
141 if (chan->circ_id_type == CIRC_ID_TYPE_NEITHER) {
142 log_warn(LD_BUG,
143 "Trying to pick a circuit ID for a connection from "
144 "a client with no identity.");
145 return 0;
147 max_range = (chan->wide_circ_ids) ? (1u<<31) : (1u<<15);
148 mask = max_range - 1;
149 high_bit = (chan->circ_id_type == CIRC_ID_TYPE_HIGHER) ? max_range : 0;
150 do {
151 if (++attempts > MAX_CIRCID_ATTEMPTS) {
152 /* Make sure we don't loop forever because all circuit IDs are used.
154 * Once, we would try until we had tried every possible circuit ID. But
155 * that's quite expensive. Instead, we try MAX_CIRCID_ATTEMPTS random
156 * circuit IDs, and then give up.
158 * This potentially causes us to give up early if our circuit ID space
159 * is nearly full. If we have N circuit IDs in use, then we will reject
160 * a new circuit with probability (N / max_range) ^ MAX_CIRCID_ATTEMPTS.
161 * This means that in practice, a few percent of our circuit ID capacity
162 * will go unused.
164 * The alternative here, though, is to do a linear search over the
165 * whole circuit ID space every time we extend a circuit, which is
166 * not so great either.
168 int64_t queued_destroys;
169 char *m = rate_limit_log(&chan->last_warned_circ_ids_exhausted,
170 approx_time());
171 if (m == NULL)
172 return 0; /* This message has been rate-limited away. */
173 if (n_pending_destroy)
174 pending_destroy_time_total /= n_pending_destroy;
175 log_warn(LD_CIRC,"No unused circIDs found on channel %s wide "
176 "circID support, with %u inbound and %u outbound circuits. "
177 "Found %u circuit IDs in use by circuits, and %u with "
178 "pending destroy cells. (%u of those were marked bogusly.) "
179 "The ones with pending destroy cells "
180 "have been marked unusable for an average of %ld seconds "
181 "and a maximum of %ld seconds. This channel is %ld seconds "
182 "old. Failing a circuit.%s",
183 chan->wide_circ_ids ? "with" : "without",
184 chan->num_p_circuits, chan->num_n_circuits,
185 n_with_circ, n_pending_destroy, n_weird_pending_destroy,
186 (long)pending_destroy_time_total,
187 (long)pending_destroy_time_max,
188 (long)(approx_time() - chan->timestamp_created),
190 tor_free(m);
192 if (!chan->cmux) {
193 /* This warning should be impossible. */
194 log_warn(LD_BUG, " This channel somehow has no cmux on it!");
195 return 0;
198 /* analysis so far on 12184 suggests that we're running out of circuit
199 IDs because it looks like we have too many pending destroy
200 cells. Let's see how many we really have pending.
202 queued_destroys = circuitmux_count_queued_destroy_cells(chan,
203 chan->cmux);
205 log_warn(LD_CIRC, " Circuitmux on this channel has %u circuits, "
206 "of which %u are active. It says it has %"PRId64
207 " destroy cells queued.",
208 circuitmux_num_circuits(chan->cmux),
209 circuitmux_num_active_circuits(chan->cmux),
210 (queued_destroys));
212 /* Change this into "if (1)" in order to get more information about
213 * possible failure modes here. You'll need to know how to use gdb with
214 * Tor: this will make Tor exit with an assertion failure if the cmux is
215 * corrupt. */
216 if (0)
217 circuitmux_assert_okay(chan->cmux);
219 channel_dump_statistics(chan, LOG_WARN);
221 return 0;
224 do {
225 crypto_rand((char*) &test_circ_id, sizeof(test_circ_id));
226 test_circ_id &= mask;
227 } while (test_circ_id == 0);
229 test_circ_id |= high_bit;
231 in_use = circuit_id_in_use_on_channel(test_circ_id, chan);
232 if (in_use == 1)
233 ++n_with_circ;
234 else if (in_use == 2) {
235 time_t since_when;
236 ++n_pending_destroy;
237 since_when =
238 circuit_id_when_marked_unusable_on_channel(test_circ_id, chan);
239 if (since_when) {
240 time_t waiting = approx_time() - since_when;
241 pending_destroy_time_total += waiting;
242 if (waiting > pending_destroy_time_max)
243 pending_destroy_time_max = waiting;
244 } else {
245 ++n_weird_pending_destroy;
248 } while (in_use);
249 return test_circ_id;
252 /** If <b>verbose</b> is false, allocate and return a comma-separated list of
253 * the currently built elements of <b>circ</b>. If <b>verbose</b> is true, also
254 * list information about link status in a more verbose format using spaces.
255 * If <b>verbose_names</b> is false, give hex digests; if <b>verbose_names</b>
256 * is true, use $DIGEST=Name style names.
258 static char *
259 circuit_list_path_impl(origin_circuit_t *circ, int verbose, int verbose_names)
261 crypt_path_t *hop;
262 smartlist_t *elements;
263 const char *states[] = {"closed", "waiting for keys", "open"};
264 char *s;
266 elements = smartlist_new();
268 if (verbose) {
269 const char *nickname = build_state_get_exit_nickname(circ->build_state);
270 smartlist_add_asprintf(elements, "%s%s circ (length %d%s%s):",
271 circ->build_state->is_internal ? "internal" : "exit",
272 circ->build_state->need_uptime ? " (high-uptime)" : "",
273 circ->build_state->desired_path_len,
274 circ->base_.state == CIRCUIT_STATE_OPEN ? "" : ", last hop ",
275 circ->base_.state == CIRCUIT_STATE_OPEN ? "" :
276 (nickname?nickname:"*unnamed*"));
279 hop = circ->cpath;
280 do {
281 char *elt;
282 const char *id;
283 const node_t *node;
284 if (!hop)
285 break;
286 if (!verbose && hop->state != CPATH_STATE_OPEN)
287 break;
288 if (!hop->extend_info)
289 break;
290 id = hop->extend_info->identity_digest;
291 if (verbose_names) {
292 elt = tor_malloc(MAX_VERBOSE_NICKNAME_LEN+1);
293 if ((node = node_get_by_id(id))) {
294 node_get_verbose_nickname(node, elt);
295 } else if (is_legal_nickname(hop->extend_info->nickname)) {
296 elt[0] = '$';
297 base16_encode(elt+1, HEX_DIGEST_LEN+1, id, DIGEST_LEN);
298 elt[HEX_DIGEST_LEN+1]= '~';
299 strlcpy(elt+HEX_DIGEST_LEN+2,
300 hop->extend_info->nickname, MAX_NICKNAME_LEN+1);
301 } else {
302 elt[0] = '$';
303 base16_encode(elt+1, HEX_DIGEST_LEN+1, id, DIGEST_LEN);
305 } else { /* ! verbose_names */
306 elt = tor_malloc(HEX_DIGEST_LEN+2);
307 elt[0] = '$';
308 base16_encode(elt+1, HEX_DIGEST_LEN+1, id, DIGEST_LEN);
310 tor_assert(elt);
311 if (verbose) {
312 tor_assert(hop->state <= 2);
313 smartlist_add_asprintf(elements,"%s(%s)",elt,states[hop->state]);
314 tor_free(elt);
315 } else {
316 smartlist_add(elements, elt);
318 hop = hop->next;
319 } while (hop != circ->cpath);
321 s = smartlist_join_strings(elements, verbose?" ":",", 0, NULL);
322 SMARTLIST_FOREACH(elements, char*, cp, tor_free(cp));
323 smartlist_free(elements);
324 return s;
327 /** If <b>verbose</b> is false, allocate and return a comma-separated
328 * list of the currently built elements of <b>circ</b>. If
329 * <b>verbose</b> is true, also list information about link status in
330 * a more verbose format using spaces.
332 char *
333 circuit_list_path(origin_circuit_t *circ, int verbose)
335 return circuit_list_path_impl(circ, verbose, 0);
338 /** Allocate and return a comma-separated list of the currently built elements
339 * of <b>circ</b>, giving each as a verbose nickname.
341 char *
342 circuit_list_path_for_controller(origin_circuit_t *circ)
344 return circuit_list_path_impl(circ, 0, 1);
347 /** Log, at severity <b>severity</b>, the nicknames of each router in
348 * <b>circ</b>'s cpath. Also log the length of the cpath, and the intended
349 * exit point.
351 void
352 circuit_log_path(int severity, unsigned int domain, origin_circuit_t *circ)
354 char *s = circuit_list_path(circ,1);
355 tor_log(severity,domain,"%s",s);
356 tor_free(s);
359 /** Return 1 iff every node in circ's cpath definitely supports ntor. */
360 static int
361 circuit_cpath_supports_ntor(const origin_circuit_t *circ)
363 crypt_path_t *head, *cpath;
365 cpath = head = circ->cpath;
366 do {
367 /* if the extend_info is missing, we can't tell if it supports ntor */
368 if (!cpath->extend_info) {
369 return 0;
372 /* if the key is blank, it definitely doesn't support ntor */
373 if (!extend_info_supports_ntor(cpath->extend_info)) {
374 return 0;
376 cpath = cpath->next;
377 } while (cpath != head);
379 return 1;
382 /** Pick all the entries in our cpath. Stop and return 0 when we're
383 * happy, or return -1 if an error occurs. */
384 static int
385 onion_populate_cpath(origin_circuit_t *circ)
387 int r = 0;
389 /* onion_extend_cpath assumes these are non-NULL */
390 tor_assert(circ);
391 tor_assert(circ->build_state);
393 while (r == 0) {
394 r = onion_extend_cpath(circ);
395 if (r < 0) {
396 log_info(LD_CIRC,"Generating cpath hop failed.");
397 return -1;
401 /* The path is complete */
402 tor_assert(r == 1);
404 /* Does every node in this path support ntor? */
405 int path_supports_ntor = circuit_cpath_supports_ntor(circ);
407 /* We would like every path to support ntor, but we have to allow for some
408 * edge cases. */
409 tor_assert(circuit_get_cpath_len(circ));
410 if (circuit_can_use_tap(circ)) {
411 /* Circuits from clients to intro points, and hidden services to rend
412 * points do not support ntor, because the hidden service protocol does
413 * not include ntor onion keys. This is also true for Single Onion
414 * Services. */
415 return 0;
418 if (circuit_get_cpath_len(circ) == 1) {
419 /* Allow for bootstrapping: when we're fetching directly from a fallback,
420 * authority, or bridge, we have no way of knowing its ntor onion key
421 * before we connect to it. So instead, we try connecting, and end up using
422 * CREATE_FAST. */
423 tor_assert(circ->cpath);
424 tor_assert(circ->cpath->extend_info);
425 const node_t *node = node_get_by_id(
426 circ->cpath->extend_info->identity_digest);
427 /* If we don't know the node and its descriptor, we must be bootstrapping.
429 if (!node || !node_has_preferred_descriptor(node, 1)) {
430 return 0;
434 if (BUG(!path_supports_ntor)) {
435 /* If we're building a multi-hop path, and it's not one of the HS or
436 * bootstrapping exceptions, and it doesn't support ntor, something has
437 * gone wrong. */
438 return -1;
441 return 0;
444 /** Create and return a new origin circuit. Initialize its purpose and
445 * build-state based on our arguments. The <b>flags</b> argument is a
446 * bitfield of CIRCLAUNCH_* flags, see circuit_launch_by_extend_info() for
447 * more details. */
448 origin_circuit_t *
449 origin_circuit_init(uint8_t purpose, int flags)
451 /* sets circ->p_circ_id and circ->p_chan */
452 origin_circuit_t *circ = origin_circuit_new();
453 circuit_set_state(TO_CIRCUIT(circ), CIRCUIT_STATE_CHAN_WAIT);
454 circ->build_state = tor_malloc_zero(sizeof(cpath_build_state_t));
455 circ->build_state->onehop_tunnel =
456 ((flags & CIRCLAUNCH_ONEHOP_TUNNEL) ? 1 : 0);
457 circ->build_state->need_uptime =
458 ((flags & CIRCLAUNCH_NEED_UPTIME) ? 1 : 0);
459 circ->build_state->need_capacity =
460 ((flags & CIRCLAUNCH_NEED_CAPACITY) ? 1 : 0);
461 circ->build_state->is_internal =
462 ((flags & CIRCLAUNCH_IS_INTERNAL) ? 1 : 0);
463 circ->build_state->is_ipv6_selftest =
464 ((flags & CIRCLAUNCH_IS_IPV6_SELFTEST) ? 1 : 0);
465 circ->base_.purpose = purpose;
466 return circ;
469 /** Build a new circuit for <b>purpose</b>. If <b>exit</b> is defined, then use
470 * that as your exit router, else choose a suitable exit node. The <b>flags</b>
471 * argument is a bitfield of CIRCLAUNCH_* flags, see
472 * circuit_launch_by_extend_info() for more details.
474 * Also launch a connection to the first OR in the chosen path, if
475 * it's not open already.
477 origin_circuit_t *
478 circuit_establish_circuit(uint8_t purpose, extend_info_t *exit_ei, int flags)
480 origin_circuit_t *circ;
481 int err_reason = 0;
482 int is_hs_v3_rp_circuit = 0;
484 if (flags & CIRCLAUNCH_IS_V3_RP) {
485 is_hs_v3_rp_circuit = 1;
488 circ = origin_circuit_init(purpose, flags);
490 if (onion_pick_cpath_exit(circ, exit_ei, is_hs_v3_rp_circuit) < 0 ||
491 onion_populate_cpath(circ) < 0) {
492 circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_NOPATH);
493 return NULL;
496 circuit_event_status(circ, CIRC_EVENT_LAUNCHED, 0);
498 if ((err_reason = circuit_handle_first_hop(circ)) < 0) {
499 circuit_mark_for_close(TO_CIRCUIT(circ), -err_reason);
500 return NULL;
503 tor_trace(circuit, establish, circ);
504 return circ;
507 /** Return the guard state associated with <b>circ</b>, which may be NULL. */
508 circuit_guard_state_t *
509 origin_circuit_get_guard_state(origin_circuit_t *circ)
511 return circ->guard_state;
515 * Helper function to publish a channel association message
517 * circuit_handle_first_hop() calls this to notify subscribers about a
518 * channel launch event, which associates a circuit with a channel.
519 * This doesn't always correspond to an assignment of the circuit's
520 * n_chan field, because that seems to be only for fully-open
521 * channels.
523 static void
524 circuit_chan_publish(const origin_circuit_t *circ, const channel_t *chan)
526 ocirc_chan_msg_t *msg = tor_malloc(sizeof(*msg));
528 msg->gid = circ->global_identifier;
529 msg->chan = chan->global_identifier;
530 msg->onehop = circ->build_state->onehop_tunnel;
532 ocirc_chan_publish(msg);
535 /** Start establishing the first hop of our circuit. Figure out what
536 * OR we should connect to, and if necessary start the connection to
537 * it. If we're already connected, then send the 'create' cell.
538 * Return 0 for ok, -reason if circ should be marked-for-close. */
540 circuit_handle_first_hop(origin_circuit_t *circ)
542 crypt_path_t *firsthop;
543 channel_t *n_chan;
544 int err_reason = 0;
545 const char *msg = NULL;
546 int should_launch = 0;
547 const or_options_t *options = get_options();
549 firsthop = cpath_get_next_non_open_hop(circ->cpath);
550 tor_assert(firsthop);
551 tor_assert(firsthop->extend_info);
553 /* Some bridges are on private addresses. Others pass a dummy private
554 * address to the pluggable transport, which ignores it.
555 * Deny the connection if:
556 * - the address is internal, and
557 * - we're not connecting to a configured bridge, and
558 * - we're not configured to allow extends to private addresses. */
559 if (extend_info_any_orport_addr_is_internal(firsthop->extend_info) &&
560 !extend_info_is_a_configured_bridge(firsthop->extend_info) &&
561 !options->ExtendAllowPrivateAddresses) {
562 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
563 "Client asked me to connect directly to a private address");
564 return -END_CIRC_REASON_TORPROTOCOL;
567 /* now see if we're already connected to the first OR in 'route' */
568 const tor_addr_port_t *orport4 =
569 extend_info_get_orport(firsthop->extend_info, AF_INET);
570 const tor_addr_port_t *orport6 =
571 extend_info_get_orport(firsthop->extend_info, AF_INET6);
572 n_chan = channel_get_for_extend(
573 firsthop->extend_info->identity_digest,
574 &firsthop->extend_info->ed_identity,
575 orport4 ? &orport4->addr : NULL,
576 orport6 ? &orport6->addr : NULL,
577 &msg,
578 &should_launch);
580 if (!n_chan) {
581 /* not currently connected in a useful way. */
582 log_info(LD_CIRC, "Next router is %s: %s",
583 safe_str_client(extend_info_describe(firsthop->extend_info)),
584 msg?msg:"???");
585 circ->base_.n_hop = extend_info_dup(firsthop->extend_info);
587 if (should_launch) {
588 n_chan = channel_connect_for_circuit(firsthop->extend_info);
589 if (!n_chan) { /* connect failed, forget the whole thing */
590 log_info(LD_CIRC,"connect to firsthop failed. Closing.");
591 return -END_CIRC_REASON_CONNECTFAILED;
593 circuit_chan_publish(circ, n_chan);
596 log_debug(LD_CIRC,"connecting in progress (or finished). Good.");
597 /* return success. The onion/circuit/etc will be taken care of
598 * automatically (may already have been) whenever n_chan reaches
599 * OR_CONN_STATE_OPEN.
601 return 0;
602 } else { /* it's already open. use it. */
603 tor_assert(!circ->base_.n_hop);
604 circ->base_.n_chan = n_chan;
605 circuit_chan_publish(circ, n_chan);
606 log_debug(LD_CIRC,"Conn open for %s. Delivering first onion skin.",
607 safe_str_client(extend_info_describe(firsthop->extend_info)));
608 if ((err_reason = circuit_send_next_onion_skin(circ)) < 0) {
609 log_info(LD_CIRC,"circuit_send_next_onion_skin failed.");
610 circ->base_.n_chan = NULL;
611 return err_reason;
614 return 0;
617 /** Find any circuits that are waiting on <b>or_conn</b> to become
618 * open and get them to send their create cells forward.
620 * Status is 1 if connect succeeded, or 0 if connect failed.
622 * Close_origin_circuits is 1 if we should close all the origin circuits
623 * through this channel, or 0 otherwise. (This happens when we want to retry
624 * an older guard.)
626 void
627 circuit_n_chan_done(channel_t *chan, int status, int close_origin_circuits)
629 smartlist_t *pending_circs;
630 int err_reason = 0;
632 tor_assert(chan);
634 log_debug(LD_CIRC,"chan to %s, status=%d",
635 channel_get_canonical_remote_descr(chan), status);
637 pending_circs = smartlist_new();
638 circuit_get_all_pending_on_channel(pending_circs, chan);
640 SMARTLIST_FOREACH_BEGIN(pending_circs, circuit_t *, circ)
642 /* These checks are redundant wrt get_all_pending_on_or_conn, but I'm
643 * leaving them in in case it's possible for the status of a circuit to
644 * change as we're going down the list. */
645 if (circ->marked_for_close || circ->n_chan || !circ->n_hop ||
646 circ->state != CIRCUIT_STATE_CHAN_WAIT)
647 continue;
649 if (tor_digest_is_zero(circ->n_hop->identity_digest)) {
650 /* Look at addr/port. This is an unkeyed connection. */
651 if (!channel_matches_extend_info(chan, circ->n_hop))
652 continue;
653 } else {
654 /* We expected a key. See if it's the right one. */
655 if (tor_memneq(chan->identity_digest,
656 circ->n_hop->identity_digest, DIGEST_LEN))
657 continue;
659 if (!status) { /* chan failed; close circ */
660 log_info(LD_CIRC,"Channel failed; closing circ.");
661 circuit_mark_for_close(circ, END_CIRC_REASON_CHANNEL_CLOSED);
662 continue;
664 if (close_origin_circuits && CIRCUIT_IS_ORIGIN(circ)) {
665 log_info(LD_CIRC,"Channel deprecated for origin circs; closing circ.");
666 circuit_mark_for_close(circ, END_CIRC_REASON_CHANNEL_CLOSED);
667 continue;
669 log_debug(LD_CIRC, "Found circ, sending create cell.");
670 /* circuit_deliver_create_cell will set n_circ_id and add us to
671 * chan_circuid_circuit_map, so we don't need to call
672 * set_circid_chan here. */
673 circ->n_chan = chan;
674 extend_info_free(circ->n_hop);
675 circ->n_hop = NULL;
677 if (CIRCUIT_IS_ORIGIN(circ)) {
678 if ((err_reason =
679 circuit_send_next_onion_skin(TO_ORIGIN_CIRCUIT(circ))) < 0) {
680 log_info(LD_CIRC,
681 "send_next_onion_skin failed; circuit marked for closing.");
682 circuit_mark_for_close(circ, -err_reason);
683 continue;
684 /* XXX could this be bad, eg if next_onion_skin failed because conn
685 * died? */
687 } else {
688 /* pull the create cell out of circ->n_chan_create_cell, and send it */
689 tor_assert(circ->n_chan_create_cell);
690 if (circuit_deliver_create_cell(circ, circ->n_chan_create_cell, 1)<0) {
691 circuit_mark_for_close(circ, END_CIRC_REASON_RESOURCELIMIT);
692 continue;
694 tor_free(circ->n_chan_create_cell);
695 circuit_set_state(circ, CIRCUIT_STATE_OPEN);
698 SMARTLIST_FOREACH_END(circ);
700 smartlist_free(pending_circs);
703 /** Find a new circid that isn't currently in use on the circ->n_chan
704 * for the outgoing
705 * circuit <b>circ</b>, and deliver the cell <b>create_cell</b> to this
706 * circuit. If <b>relayed</b> is true, this is a create cell somebody
707 * gave us via an EXTEND cell, so we shouldn't worry if we don't understand
708 * it. Return -1 if we failed to find a suitable circid, else return 0.
710 MOCK_IMPL(int,
711 circuit_deliver_create_cell,(circuit_t *circ,
712 const struct create_cell_t *create_cell,
713 int relayed))
715 cell_t cell;
716 circid_t id;
717 int r;
719 tor_assert(circ);
720 tor_assert(circ->n_chan);
721 tor_assert(create_cell);
722 tor_assert(create_cell->cell_type == CELL_CREATE ||
723 create_cell->cell_type == CELL_CREATE_FAST ||
724 create_cell->cell_type == CELL_CREATE2);
726 id = get_unique_circ_id_by_chan(circ->n_chan);
727 if (!id) {
728 static ratelim_t circid_warning_limit = RATELIM_INIT(9600);
729 log_fn_ratelim(&circid_warning_limit, LOG_WARN, LD_CIRC,
730 "failed to get unique circID.");
731 goto error;
734 memset(&cell, 0, sizeof(cell_t));
735 r = relayed ? create_cell_format_relayed(&cell, create_cell)
736 : create_cell_format(&cell, create_cell);
737 if (r < 0) {
738 log_warn(LD_CIRC,"Couldn't format create cell");
739 goto error;
741 log_debug(LD_CIRC,"Chosen circID %u.", (unsigned)id);
742 circuit_set_n_circid_chan(circ, id, circ->n_chan);
743 cell.circ_id = circ->n_circ_id;
745 append_cell_to_circuit_queue(circ, circ->n_chan, &cell,
746 CELL_DIRECTION_OUT, 0);
748 if (CIRCUIT_IS_ORIGIN(circ)) {
749 /* Update began timestamp for circuits starting their first hop */
750 if (TO_ORIGIN_CIRCUIT(circ)->cpath->state == CPATH_STATE_CLOSED) {
751 if (!CHANNEL_IS_OPEN(circ->n_chan)) {
752 log_warn(LD_CIRC,
753 "Got first hop for a circuit without an opened channel. "
754 "State: %s.", channel_state_to_string(circ->n_chan->state));
755 tor_fragile_assert();
758 tor_gettimeofday(&circ->timestamp_began);
761 /* mark it so it gets better rate limiting treatment. */
762 channel_timestamp_client(circ->n_chan);
765 return 0;
766 error:
767 circ->n_chan = NULL;
768 return -1;
771 /** Return true iff we should send a create_fast cell to start building a given
772 * circuit */
773 static inline int
774 should_use_create_fast_for_circuit(origin_circuit_t *circ)
776 const or_options_t *options = get_options();
777 tor_assert(circ->cpath);
778 tor_assert(circ->cpath->extend_info);
780 if (!circuit_has_usable_onion_key(circ)) {
781 /* We don't have ntor, and we don't have or can't use TAP,
782 * so our hand is forced: only a create_fast will work. */
783 return 1;
785 if (public_server_mode(options)) {
786 /* We're a server, and we have a usable onion key. We can choose.
787 * Prefer to blend our circuit into the other circuits we are
788 * creating on behalf of others. */
789 return 0;
791 return networkstatus_get_param(NULL, "usecreatefast", 0, 0, 1);
795 * Return true if <b>circ</b> is the type of circuit we want to count
796 * timeouts from.
798 * In particular, we want to consider any circuit that plans to build
799 * at least 3 hops (but maybe more), but has 3 or fewer hops built
800 * so far.
802 * We still want to consider circuits before 3 hops, because we need
803 * to decide if we should convert them to a measurement circuit in
804 * circuit_build_times_handle_completed_hop(), rather than letting
805 * slow circuits get killed right away.
808 circuit_timeout_want_to_count_circ(const origin_circuit_t *circ)
810 return !circ->has_opened
811 && circ->build_state->desired_path_len >= DEFAULT_ROUTE_LEN
812 && circuit_get_cpath_opened_len(circ) <= DEFAULT_ROUTE_LEN;
815 /** Decide whether to use a TAP or ntor handshake for connecting to <b>ei</b>
816 * directly, and set *<b>cell_type_out</b> and *<b>handshake_type_out</b>
817 * accordingly.
818 * Note that TAP handshakes in CREATE cells are only used for direct
819 * connections:
820 * - from Single Onions to rend points not in the service's consensus.
821 * This is checked in onion_populate_cpath. */
822 static void
823 circuit_pick_create_handshake(uint8_t *cell_type_out,
824 uint16_t *handshake_type_out,
825 const extend_info_t *ei)
827 /* torspec says: In general, clients SHOULD use CREATE whenever they are
828 * using the TAP handshake, and CREATE2 otherwise. */
829 if (extend_info_supports_ntor(ei)) {
830 *cell_type_out = CELL_CREATE2;
831 *handshake_type_out = ONION_HANDSHAKE_TYPE_NTOR;
832 } else {
833 /* XXXX030 Remove support for deciding to use TAP and EXTEND. */
834 *cell_type_out = CELL_CREATE;
835 *handshake_type_out = ONION_HANDSHAKE_TYPE_TAP;
839 /** Decide whether to use a TAP or ntor handshake for extending to <b>ei</b>
840 * and set *<b>handshake_type_out</b> accordingly. Decide whether we should
841 * use an EXTEND2 or an EXTEND cell to do so, and set *<b>cell_type_out</b>
842 * and *<b>create_cell_type_out</b> accordingly.
843 * Note that TAP handshakes in EXTEND cells are only used:
844 * - from clients to intro points, and
845 * - from hidden services to rend points.
846 * This is checked in onion_populate_cpath.
848 static void
849 circuit_pick_extend_handshake(uint8_t *cell_type_out,
850 uint8_t *create_cell_type_out,
851 uint16_t *handshake_type_out,
852 const extend_info_t *ei)
854 uint8_t t;
855 circuit_pick_create_handshake(&t, handshake_type_out, ei);
857 /* torspec says: Clients SHOULD use the EXTEND format whenever sending a TAP
858 * handshake... In other cases, clients SHOULD use EXTEND2. */
859 if (*handshake_type_out != ONION_HANDSHAKE_TYPE_TAP) {
860 *cell_type_out = RELAY_COMMAND_EXTEND2;
861 *create_cell_type_out = CELL_CREATE2;
862 } else {
863 /* XXXX030 Remove support for deciding to use TAP and EXTEND. */
864 *cell_type_out = RELAY_COMMAND_EXTEND;
865 *create_cell_type_out = CELL_CREATE;
870 * Return true iff <b>purpose</b> is a purpose for a circuit which is
871 * allowed to have no guard configured, even if the circuit is multihop
872 * and guards are enabled.
874 static int
875 circuit_purpose_may_omit_guard(int purpose)
877 switch (purpose) {
878 case CIRCUIT_PURPOSE_TESTING:
879 case CIRCUIT_PURPOSE_C_MEASURE_TIMEOUT:
880 /* Testing circuits may omit guards because they're measuring
881 * liveness or performance, and don't want guards to interfere. */
882 return 1;
883 default:
884 /* All other multihop circuits should use guards if guards are
885 * enabled. */
886 return 0;
890 /** This is the backbone function for building circuits.
892 * If circ's first hop is closed, then we need to build a create
893 * cell and send it forward.
895 * Otherwise, if circ's cpath still has any non-open hops, we need to
896 * build a relay extend cell and send it forward to the next non-open hop.
898 * If all hops on the cpath are open, we're done building the circuit
899 * and we should do housekeeping for the newly opened circuit.
901 * Return -reason if we want to tear down circ, else return 0.
904 circuit_send_next_onion_skin(origin_circuit_t *circ)
906 tor_assert(circ);
908 if (circ->cpath->state == CPATH_STATE_CLOSED) {
909 /* Case one: we're on the first hop. */
910 return circuit_send_first_onion_skin(circ);
913 tor_assert(circ->cpath->state == CPATH_STATE_OPEN);
914 tor_assert(circ->base_.state == CIRCUIT_STATE_BUILDING);
916 crypt_path_t *hop = cpath_get_next_non_open_hop(circ->cpath);
917 circuit_build_times_handle_completed_hop(circ);
919 circpad_machine_event_circ_added_hop(circ);
921 if (hop) {
922 /* Case two: we're on a hop after the first. */
923 return circuit_send_intermediate_onion_skin(circ, hop);
926 /* Case three: the circuit is finished. Do housekeeping tasks on it. */
927 circpad_machine_event_circ_built(circ);
928 return circuit_build_no_more_hops(circ);
932 * Called from circuit_send_next_onion_skin() when we find ourselves connected
933 * to the first hop in <b>circ</b>: Send a CREATE or CREATE2 or CREATE_FAST
934 * cell to that hop. Return 0 on success; -reason on failure (if the circuit
935 * should be torn down).
937 static int
938 circuit_send_first_onion_skin(origin_circuit_t *circ)
940 int fast;
941 int len;
942 const node_t *node;
943 create_cell_t cc;
944 memset(&cc, 0, sizeof(cc));
946 log_debug(LD_CIRC,"First skin; sending create cell.");
948 if (circ->build_state->onehop_tunnel) {
949 control_event_bootstrap(BOOTSTRAP_STATUS_ONEHOP_CREATE, 0);
950 } else {
951 control_event_bootstrap(BOOTSTRAP_STATUS_CIRCUIT_CREATE, 0);
953 /* If this is not a one-hop tunnel, the channel is being used
954 * for traffic that wants anonymity and protection from traffic
955 * analysis (such as netflow record retention). That means we want
956 * to pad it.
958 if (circ->base_.n_chan->channel_usage < CHANNEL_USED_FOR_FULL_CIRCS)
959 circ->base_.n_chan->channel_usage = CHANNEL_USED_FOR_FULL_CIRCS;
962 node = node_get_by_id(circ->base_.n_chan->identity_digest);
963 fast = should_use_create_fast_for_circuit(circ);
964 if (!fast) {
965 /* We know the right onion key: we should send a create cell. */
966 circuit_pick_create_handshake(&cc.cell_type, &cc.handshake_type,
967 circ->cpath->extend_info);
968 } else {
969 /* We don't know an onion key, so we need to fall back to CREATE_FAST. */
970 cc.cell_type = CELL_CREATE_FAST;
971 cc.handshake_type = ONION_HANDSHAKE_TYPE_FAST;
974 len = onion_skin_create(cc.handshake_type,
975 circ->cpath->extend_info,
976 &circ->cpath->handshake_state,
977 cc.onionskin);
978 if (len < 0) {
979 log_warn(LD_CIRC,"onion_skin_create (first hop) failed.");
980 return - END_CIRC_REASON_INTERNAL;
982 cc.handshake_len = len;
984 if (circuit_deliver_create_cell(TO_CIRCUIT(circ), &cc, 0) < 0)
985 return - END_CIRC_REASON_RESOURCELIMIT;
986 tor_trace(circuit, first_onion_skin, circ, circ->cpath);
988 circ->cpath->state = CPATH_STATE_AWAITING_KEYS;
989 circuit_set_state(TO_CIRCUIT(circ), CIRCUIT_STATE_BUILDING);
990 log_info(LD_CIRC,"First hop: finished sending %s cell to '%s'",
991 fast ? "CREATE_FAST" : "CREATE",
992 node ? node_describe(node) : "<unnamed>");
993 return 0;
997 * Called from circuit_send_next_onion_skin() when we find that we have no
998 * more hops: mark the circuit as finished, and perform the necessary
999 * bookkeeping. Return 0 on success; -reason on failure (if the circuit
1000 * should be torn down).
1002 static int
1003 circuit_build_no_more_hops(origin_circuit_t *circ)
1005 guard_usable_t r;
1006 if (! circ->guard_state) {
1007 if (circuit_get_cpath_len(circ) != 1 &&
1008 ! circuit_purpose_may_omit_guard(circ->base_.purpose) &&
1009 get_options()->UseEntryGuards) {
1010 log_warn(LD_BUG, "%d-hop circuit %p with purpose %d has no "
1011 "guard state",
1012 circuit_get_cpath_len(circ), circ, circ->base_.purpose);
1014 r = GUARD_USABLE_NOW;
1015 } else {
1016 r = entry_guard_succeeded(&circ->guard_state);
1018 const int is_usable_for_streams = (r == GUARD_USABLE_NOW);
1019 if (r == GUARD_USABLE_NOW) {
1020 circuit_set_state(TO_CIRCUIT(circ), CIRCUIT_STATE_OPEN);
1021 } else if (r == GUARD_MAYBE_USABLE_LATER) {
1022 // Wait till either a better guard succeeds, or till
1023 // all better guards fail.
1024 circuit_set_state(TO_CIRCUIT(circ), CIRCUIT_STATE_GUARD_WAIT);
1025 } else {
1026 tor_assert_nonfatal(r == GUARD_USABLE_NEVER);
1027 return - END_CIRC_REASON_INTERNAL;
1030 /* XXXX #21422 -- the rest of this branch needs careful thought!
1031 * Some of the things here need to happen when a circuit becomes
1032 * mechanically open; some need to happen when it is actually usable.
1033 * I think I got them right, but more checking would be wise. -NM
1036 log_info(LD_CIRC,"circuit built!");
1037 circuit_reset_failure_count(0);
1039 if (circ->build_state->onehop_tunnel || circ->has_opened) {
1040 control_event_bootstrap(BOOTSTRAP_STATUS_REQUESTING_STATUS, 0);
1043 pathbias_count_build_success(circ);
1044 if (is_usable_for_streams)
1045 circuit_has_opened(circ); /* do other actions as necessary */
1047 if (!have_completed_a_circuit() && !circ->build_state->onehop_tunnel) {
1048 const or_options_t *options = get_options();
1049 note_that_we_completed_a_circuit();
1050 /* FFFF Log a count of known routers here */
1051 log_info(LD_GENERAL,
1052 "Tor has successfully opened a circuit. "
1053 "Looks like client functionality is working.");
1054 control_event_bootstrap(BOOTSTRAP_STATUS_DONE, 0);
1055 control_event_client_status(LOG_NOTICE, "CIRCUIT_ESTABLISHED");
1056 clear_broken_connection_map(1);
1057 if (server_mode(options) &&
1058 !router_all_orports_seem_reachable(options)) {
1059 router_do_reachability_checks(1, 1);
1063 /* We're done with measurement circuits here. Just close them */
1064 if (circ->base_.purpose == CIRCUIT_PURPOSE_C_MEASURE_TIMEOUT) {
1065 circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_FINISHED);
1067 return 0;
1071 * Called from circuit_send_next_onion_skin() when we find that we have a hop
1072 * other than the first that we need to extend to: use <b>hop</b>'s
1073 * information to extend the circuit another step. Return 0 on success;
1074 * -reason on failure (if the circuit should be torn down).
1076 static int
1077 circuit_send_intermediate_onion_skin(origin_circuit_t *circ,
1078 crypt_path_t *hop)
1080 int len;
1081 extend_cell_t ec;
1082 /* Relays and bridges can send IPv6 extends. But for clients, it's an
1083 * obvious version distinguisher. */
1084 const bool include_ipv6 = server_mode(get_options());
1085 memset(&ec, 0, sizeof(ec));
1086 tor_addr_make_unspec(&ec.orport_ipv4.addr);
1087 tor_addr_make_unspec(&ec.orport_ipv6.addr);
1089 log_debug(LD_CIRC,"starting to send subsequent skin.");
1091 circuit_pick_extend_handshake(&ec.cell_type,
1092 &ec.create_cell.cell_type,
1093 &ec.create_cell.handshake_type,
1094 hop->extend_info);
1096 const tor_addr_port_t *orport4 =
1097 extend_info_get_orport(hop->extend_info, AF_INET);
1098 const tor_addr_port_t *orport6 =
1099 extend_info_get_orport(hop->extend_info, AF_INET6);
1100 int n_addrs_set = 0;
1101 if (orport4) {
1102 tor_addr_copy(&ec.orport_ipv4.addr, &orport4->addr);
1103 ec.orport_ipv4.port = orport4->port;
1104 ++n_addrs_set;
1106 if (orport6 && include_ipv6) {
1107 tor_addr_copy(&ec.orport_ipv6.addr, &orport6->addr);
1108 ec.orport_ipv6.port = orport6->port;
1109 ++n_addrs_set;
1112 if (n_addrs_set == 0) {
1113 log_warn(LD_BUG, "No supported address family found in extend_info.");
1114 return - END_CIRC_REASON_INTERNAL;
1116 memcpy(ec.node_id, hop->extend_info->identity_digest, DIGEST_LEN);
1117 /* Set the ED25519 identity too -- it will only get included
1118 * in the extend2 cell if we're configured to use it, though. */
1119 ed25519_pubkey_copy(&ec.ed_pubkey, &hop->extend_info->ed_identity);
1121 len = onion_skin_create(ec.create_cell.handshake_type,
1122 hop->extend_info,
1123 &hop->handshake_state,
1124 ec.create_cell.onionskin);
1125 if (len < 0) {
1126 log_warn(LD_CIRC,"onion_skin_create failed.");
1127 return - END_CIRC_REASON_INTERNAL;
1129 ec.create_cell.handshake_len = len;
1131 log_info(LD_CIRC,"Sending extend relay cell.");
1133 uint8_t command = 0;
1134 uint16_t payload_len=0;
1135 uint8_t payload[RELAY_PAYLOAD_SIZE];
1136 if (extend_cell_format(&command, &payload_len, payload, &ec)<0) {
1137 log_warn(LD_CIRC,"Couldn't format extend cell");
1138 return -END_CIRC_REASON_INTERNAL;
1141 /* send it to hop->prev, because that relay will transfer
1142 * it to a create cell and then send to hop */
1143 if (relay_send_command_from_edge(0, TO_CIRCUIT(circ),
1144 command,
1145 (char*)payload, payload_len,
1146 hop->prev) < 0)
1147 return 0; /* circuit is closed */
1149 hop->state = CPATH_STATE_AWAITING_KEYS;
1150 tor_trace(circuit, intermediate_onion_skin, circ, hop);
1151 return 0;
1154 /** Our clock just jumped by <b>seconds_elapsed</b>. If <b>was_idle</b> is
1155 * true, then the monotonic time matches; otherwise it doesn't. Assume
1156 * something has also gone wrong with our network: notify the user, and
1157 * abandon all not-yet-used circuits. */
1158 void
1159 circuit_note_clock_jumped(int64_t seconds_elapsed, bool was_idle)
1161 int severity = server_mode(get_options()) ? LOG_WARN : LOG_NOTICE;
1162 if (was_idle) {
1163 tor_log(severity, LD_GENERAL, "Tor has been idle for %"PRId64
1164 " seconds; assuming established circuits no longer work.",
1165 (seconds_elapsed));
1166 } else {
1167 tor_log(severity, LD_GENERAL,
1168 "Your system clock just jumped %"PRId64" seconds %s; "
1169 "assuming established circuits no longer work.",
1171 seconds_elapsed >=0 ? seconds_elapsed : -seconds_elapsed),
1172 seconds_elapsed >=0 ? "forward" : "backward");
1174 control_event_general_status(LOG_WARN, "CLOCK_JUMPED TIME=%"PRId64
1175 " IDLE=%d",
1176 (seconds_elapsed), was_idle?1:0);
1177 /* so we log when it works again */
1178 note_that_we_maybe_cant_complete_circuits();
1179 control_event_client_status(severity, "CIRCUIT_NOT_ESTABLISHED REASON=%s",
1180 "CLOCK_JUMPED");
1181 circuit_mark_all_unused_circs();
1182 circuit_mark_all_dirty_circs_as_unusable();
1183 if (seconds_elapsed < 0) {
1184 /* Restart all the timers in case we jumped a long way into the past. */
1185 reset_all_main_loop_timers();
1189 /** A "created" cell <b>reply</b> came back to us on circuit <b>circ</b>.
1190 * (The body of <b>reply</b> varies depending on what sort of handshake
1191 * this is.)
1193 * Calculate the appropriate keys and digests, make sure KH is
1194 * correct, and initialize this hop of the cpath.
1196 * Return - reason if we want to mark circ for close, else return 0.
1199 circuit_finish_handshake(origin_circuit_t *circ,
1200 const created_cell_t *reply)
1202 char keys[CPATH_KEY_MATERIAL_LEN];
1203 crypt_path_t *hop;
1204 int rv;
1206 if ((rv = pathbias_count_build_attempt(circ)) < 0) {
1207 log_warn(LD_CIRC, "pathbias_count_build_attempt failed: %d", rv);
1208 return rv;
1211 if (circ->cpath->state == CPATH_STATE_AWAITING_KEYS) {
1212 hop = circ->cpath;
1213 } else {
1214 hop = cpath_get_next_non_open_hop(circ->cpath);
1215 if (!hop) { /* got an extended when we're all done? */
1216 log_warn(LD_PROTOCOL,"got extended when circ already built? Closing.");
1217 return - END_CIRC_REASON_TORPROTOCOL;
1220 tor_assert(hop->state == CPATH_STATE_AWAITING_KEYS);
1223 const char *msg = NULL;
1224 if (onion_skin_client_handshake(hop->handshake_state.tag,
1225 &hop->handshake_state,
1226 reply->reply, reply->handshake_len,
1227 (uint8_t*)keys, sizeof(keys),
1228 (uint8_t*)hop->rend_circ_nonce,
1229 &msg) < 0) {
1230 if (msg)
1231 log_warn(LD_CIRC,"onion_skin_client_handshake failed: %s", msg);
1232 return -END_CIRC_REASON_TORPROTOCOL;
1236 onion_handshake_state_release(&hop->handshake_state);
1238 if (cpath_init_circuit_crypto(hop, keys, sizeof(keys), 0, 0)<0) {
1239 return -END_CIRC_REASON_TORPROTOCOL;
1242 hop->state = CPATH_STATE_OPEN;
1243 log_info(LD_CIRC,"Finished building circuit hop:");
1244 circuit_log_path(LOG_INFO,LD_CIRC,circ);
1245 circuit_event_status(circ, CIRC_EVENT_EXTENDED, 0);
1247 return 0;
1250 /** We received a relay truncated cell on circ.
1252 * Since we don't send truncates currently, getting a truncated
1253 * means that a connection broke or an extend failed. For now,
1254 * just give up: force circ to close, and return 0.
1257 circuit_truncated(origin_circuit_t *circ, int reason)
1259 // crypt_path_t *victim;
1260 // connection_t *stream;
1262 tor_assert(circ);
1264 /* XXX Since we don't send truncates currently, getting a truncated
1265 * means that a connection broke or an extend failed. For now,
1266 * just give up.
1268 circuit_mark_for_close(TO_CIRCUIT(circ),
1269 END_CIRC_REASON_FLAG_REMOTE|reason);
1270 return 0;
1272 #if 0
1273 while (layer->next != circ->cpath) {
1274 /* we need to clear out layer->next */
1275 victim = layer->next;
1276 log_debug(LD_CIRC, "Killing a layer of the cpath.");
1278 for (stream = circ->p_streams; stream; stream=stream->next_stream) {
1279 if (stream->cpath_layer == victim) {
1280 log_info(LD_APP, "Marking stream %d for close because of truncate.",
1281 stream->stream_id);
1282 /* no need to send 'end' relay cells,
1283 * because the other side's already dead
1285 connection_mark_unattached_ap(stream, END_STREAM_REASON_DESTROY);
1289 layer->next = victim->next;
1290 cpath_free(victim);
1293 log_info(LD_CIRC, "finished");
1294 return 0;
1295 #endif /* 0 */
1298 /** Helper for new_route_len(). Choose a circuit length for purpose
1299 * <b>purpose</b>: DEFAULT_ROUTE_LEN (+ 1 if someone else chose the
1300 * exit). If someone else chose the exit, they could be colluding
1301 * with the exit, so add a randomly selected node to preserve
1302 * anonymity.
1304 * Here, "exit node" sometimes means an OR acting as an internal
1305 * endpoint, rather than as a relay to an external endpoint. This
1306 * means there need to be at least DEFAULT_ROUTE_LEN routers between
1307 * us and the internal endpoint to preserve the same anonymity
1308 * properties that we would get when connecting to an external
1309 * endpoint. These internal endpoints can include:
1311 * - Connections to a directory of hidden services
1312 * (CIRCUIT_PURPOSE_C_GENERAL)
1314 * - A client connecting to an introduction point, which the hidden
1315 * service picked (CIRCUIT_PURPOSE_C_INTRODUCING, via
1316 * circuit_get_open_circ_or_launch() which rewrites it from
1317 * CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT)
1319 * - A hidden service connecting to a rendezvous point, which the
1320 * client picked (CIRCUIT_PURPOSE_S_CONNECT_REND, via
1321 * rend_service_receive_introduction() and
1322 * rend_service_relaunch_rendezvous)
1324 * There are currently two situations where we picked the exit node
1325 * ourselves, making DEFAULT_ROUTE_LEN a safe circuit length:
1327 * - We are a hidden service connecting to an introduction point
1328 * (CIRCUIT_PURPOSE_S_ESTABLISH_INTRO, via
1329 * rend_service_launch_establish_intro())
1331 * - We are a router testing its own reachabiity
1332 * (CIRCUIT_PURPOSE_TESTING, via router_do_reachability_checks())
1334 * onion_pick_cpath_exit() bypasses us (by not calling
1335 * new_route_len()) in the one-hop tunnel case, so we don't need to
1336 * handle that.
1339 route_len_for_purpose(uint8_t purpose, extend_info_t *exit_ei)
1341 int routelen = DEFAULT_ROUTE_LEN;
1342 int known_purpose = 0;
1344 if (circuit_should_use_vanguards(purpose)) {
1345 /* Clients want an extra hop for rends to avoid linkability.
1346 * Services want it for intro points to avoid publishing their
1347 * layer3 guards. They want it for hsdir posts to use
1348 * their full layer3 guard set for those connections.
1349 * Ex: C - G - L2 - L3 - R
1350 * S - G - L2 - L3 - HSDIR
1351 * S - G - L2 - L3 - I
1353 if (purpose == CIRCUIT_PURPOSE_C_ESTABLISH_REND ||
1354 purpose == CIRCUIT_PURPOSE_S_HSDIR_POST ||
1355 purpose == CIRCUIT_PURPOSE_HS_VANGUARDS ||
1356 purpose == CIRCUIT_PURPOSE_S_ESTABLISH_INTRO)
1357 return routelen+1;
1359 /* If we only have Layer2 vanguards, then we do not need
1360 * the extra hop for linkabilty reasons (see below).
1361 * This means all hops can be of the form:
1362 * S/C - G - L2 - M - R/HSDir/I
1364 if (get_options()->HSLayer2Nodes && !get_options()->HSLayer3Nodes)
1365 return routelen+1;
1367 /* For connections to hsdirs, clients want two extra hops
1368 * when using layer3 guards, to avoid linkability.
1369 * Same goes for intro points. Note that the route len
1370 * includes the intro point or hsdir, hence the +2.
1371 * Ex: C - G - L2 - L3 - M - I
1372 * C - G - L2 - L3 - M - HSDIR
1373 * S - G - L2 - L3 - M - R
1375 if (purpose == CIRCUIT_PURPOSE_S_CONNECT_REND ||
1376 purpose == CIRCUIT_PURPOSE_C_HSDIR_GET ||
1377 purpose == CIRCUIT_PURPOSE_C_INTRODUCING)
1378 return routelen+2;
1381 if (!exit_ei)
1382 return routelen;
1384 switch (purpose) {
1385 /* These two purposes connect to a router that we chose, so
1386 * DEFAULT_ROUTE_LEN is safe. */
1387 case CIRCUIT_PURPOSE_S_ESTABLISH_INTRO:
1388 /* hidden service connecting to introduction point */
1389 case CIRCUIT_PURPOSE_TESTING:
1390 /* router reachability testing */
1391 known_purpose = 1;
1392 break;
1394 /* These three purposes connect to a router that someone else
1395 * might have chosen, so add an extra hop to protect anonymity. */
1396 case CIRCUIT_PURPOSE_C_GENERAL:
1397 case CIRCUIT_PURPOSE_C_HSDIR_GET:
1398 case CIRCUIT_PURPOSE_S_HSDIR_POST:
1399 /* connecting to hidden service directory */
1400 case CIRCUIT_PURPOSE_C_INTRODUCING:
1401 /* client connecting to introduction point */
1402 case CIRCUIT_PURPOSE_S_CONNECT_REND:
1403 /* hidden service connecting to rendezvous point */
1404 known_purpose = 1;
1405 routelen++;
1406 break;
1408 default:
1409 /* Got a purpose not listed above along with a chosen exit.
1410 * Increase the circuit length by one anyway for safety. */
1411 routelen++;
1412 break;
1415 if (BUG(exit_ei && !known_purpose)) {
1416 log_warn(LD_BUG, "Unhandled purpose %d with a chosen exit; "
1417 "assuming routelen %d.", purpose, routelen);
1419 return routelen;
1422 /** Choose a length for a circuit of purpose <b>purpose</b> and check
1423 * if enough routers are available.
1425 * If the routerlist <b>nodes</b> doesn't have enough routers
1426 * to handle the desired path length, return -1.
1428 STATIC int
1429 new_route_len(uint8_t purpose, extend_info_t *exit_ei,
1430 const smartlist_t *nodes)
1432 int routelen;
1434 tor_assert(nodes);
1436 routelen = route_len_for_purpose(purpose, exit_ei);
1438 int num_acceptable_direct = count_acceptable_nodes(nodes, 1);
1439 int num_acceptable_indirect = count_acceptable_nodes(nodes, 0);
1441 log_debug(LD_CIRC,"Chosen route length %d (%d direct and %d indirect "
1442 "routers suitable).", routelen, num_acceptable_direct,
1443 num_acceptable_indirect);
1445 if (num_acceptable_direct < 1 || num_acceptable_indirect < routelen - 1) {
1446 log_info(LD_CIRC,
1447 "Not enough acceptable routers (%d/%d direct and %d/%d "
1448 "indirect routers suitable). Discarding this circuit.",
1449 num_acceptable_direct, routelen,
1450 num_acceptable_indirect, routelen);
1451 return -1;
1454 return routelen;
1457 /** Return a newly allocated list of uint16_t * for each predicted port not
1458 * handled by a current circuit. */
1459 static smartlist_t *
1460 circuit_get_unhandled_ports(time_t now)
1462 smartlist_t *dest = rep_hist_get_predicted_ports(now);
1463 circuit_remove_handled_ports(dest);
1464 return dest;
1467 /** Return 1 if we already have circuits present or on the way for
1468 * all anticipated ports. Return 0 if we should make more.
1470 * If we're returning 0, set need_uptime and need_capacity to
1471 * indicate any requirements that the unhandled ports have.
1473 MOCK_IMPL(int,
1474 circuit_all_predicted_ports_handled, (time_t now, int *need_uptime,
1475 int *need_capacity))
1477 int i, enough;
1478 uint16_t *port;
1479 smartlist_t *sl = circuit_get_unhandled_ports(now);
1480 smartlist_t *LongLivedServices = get_options()->LongLivedPorts;
1481 tor_assert(need_uptime);
1482 tor_assert(need_capacity);
1483 // Always predict need_capacity
1484 *need_capacity = 1;
1485 enough = (smartlist_len(sl) == 0);
1486 for (i = 0; i < smartlist_len(sl); ++i) {
1487 port = smartlist_get(sl, i);
1488 if (smartlist_contains_int_as_string(LongLivedServices, *port))
1489 *need_uptime = 1;
1490 tor_free(port);
1492 smartlist_free(sl);
1493 return enough;
1496 /** Return 1 if <b>node</b> can handle one or more of the ports in
1497 * <b>needed_ports</b>, else return 0.
1499 static int
1500 node_handles_some_port(const node_t *node, smartlist_t *needed_ports)
1501 { /* XXXX MOVE */
1502 int i;
1503 uint16_t port;
1505 for (i = 0; i < smartlist_len(needed_ports); ++i) {
1506 addr_policy_result_t r;
1507 /* alignment issues aren't a worry for this dereference, since
1508 needed_ports is explicitly a smartlist of uint16_t's */
1509 port = *(uint16_t *)smartlist_get(needed_ports, i);
1510 tor_assert(port);
1511 if (node)
1512 r = compare_tor_addr_to_node_policy(NULL, port, node);
1513 else
1514 continue;
1515 if (r != ADDR_POLICY_REJECTED && r != ADDR_POLICY_PROBABLY_REJECTED)
1516 return 1;
1518 return 0;
1521 /** Return true iff <b>conn</b> needs another general circuit to be
1522 * built. */
1523 static int
1524 ap_stream_wants_exit_attention(connection_t *conn)
1526 entry_connection_t *entry;
1527 if (conn->type != CONN_TYPE_AP)
1528 return 0;
1529 entry = TO_ENTRY_CONN(conn);
1531 if (conn->state == AP_CONN_STATE_CIRCUIT_WAIT &&
1532 !conn->marked_for_close &&
1533 !(entry->want_onehop) && /* ignore one-hop streams */
1534 !(entry->use_begindir) && /* ignore targeted dir fetches */
1535 !(entry->chosen_exit_name) && /* ignore defined streams */
1536 !connection_edge_is_rendezvous_stream(TO_EDGE_CONN(conn)) &&
1537 !circuit_stream_is_being_handled(TO_ENTRY_CONN(conn), 0,
1538 MIN_CIRCUITS_HANDLING_STREAM))
1539 return 1;
1540 return 0;
1543 /** Return a pointer to a suitable router to be the exit node for the
1544 * general-purpose circuit we're about to build.
1546 * Look through the connection array, and choose a router that maximizes
1547 * the number of pending streams that can exit from this router.
1549 * Return NULL if we can't find any suitable routers.
1551 static const node_t *
1552 choose_good_exit_server_general(router_crn_flags_t flags)
1554 int *n_supported;
1555 int n_pending_connections = 0;
1556 smartlist_t *connections;
1557 int best_support = -1;
1558 int n_best_support=0;
1559 const or_options_t *options = get_options();
1560 const smartlist_t *the_nodes;
1561 const node_t *selected_node=NULL;
1562 const int need_uptime = (flags & CRN_NEED_UPTIME) != 0;
1563 const int need_capacity = (flags & CRN_NEED_CAPACITY) != 0;
1565 /* We should not require guard flags on exits. */
1566 IF_BUG_ONCE(flags & CRN_NEED_GUARD)
1567 return NULL;
1569 /* We reject single-hop exits for all node positions. */
1570 IF_BUG_ONCE(flags & CRN_DIRECT_CONN)
1571 return NULL;
1573 /* This isn't the function for picking rendezvous nodes. */
1574 IF_BUG_ONCE(flags & CRN_RENDEZVOUS_V3)
1575 return NULL;
1577 /* We only want exits to extend if we cannibalize the circuit.
1578 * But we don't require IPv6 extends yet. */
1579 IF_BUG_ONCE(flags & CRN_INITIATE_IPV6_EXTEND)
1580 return NULL;
1582 connections = get_connection_array();
1584 /* Count how many connections are waiting for a circuit to be built.
1585 * We use this for log messages now, but in the future we may depend on it.
1587 SMARTLIST_FOREACH(connections, connection_t *, conn,
1589 if (ap_stream_wants_exit_attention(conn))
1590 ++n_pending_connections;
1592 // log_fn(LOG_DEBUG, "Choosing exit node; %d connections are pending",
1593 // n_pending_connections);
1594 /* Now we count, for each of the routers in the directory, how many
1595 * of the pending connections could possibly exit from that
1596 * router (n_supported[i]). (We can't be sure about cases where we
1597 * don't know the IP address of the pending connection.)
1599 * -1 means "Don't use this router at all."
1601 the_nodes = nodelist_get_list();
1602 n_supported = tor_calloc(smartlist_len(the_nodes), sizeof(int));
1603 SMARTLIST_FOREACH_BEGIN(the_nodes, const node_t *, node) {
1604 const int i = node_sl_idx;
1605 if (router_digest_is_me(node->identity)) {
1606 n_supported[i] = -1;
1607 // log_fn(LOG_DEBUG,"Skipping node %s -- it's me.", router->nickname);
1608 /* XXX there's probably a reverse predecessor attack here, but
1609 * it's slow. should we take this out? -RD
1611 continue;
1613 if (!router_can_choose_node(node, flags)) {
1614 n_supported[i] = -1;
1615 continue;
1617 if (node->is_bad_exit) {
1618 n_supported[i] = -1;
1619 continue; /* skip routers that are known to be down or bad exits */
1621 if (routerset_contains_node(options->ExcludeExitNodesUnion_, node)) {
1622 n_supported[i] = -1;
1623 continue; /* user asked us not to use it, no matter what */
1625 if (options->ExitNodes &&
1626 !routerset_contains_node(options->ExitNodes, node)) {
1627 n_supported[i] = -1;
1628 continue; /* not one of our chosen exit nodes */
1630 if (node_exit_policy_rejects_all(node)) {
1631 n_supported[i] = -1;
1632 // log_fn(LOG_DEBUG,"Skipping node %s (index %d) -- it rejects all.",
1633 // router->nickname, i);
1634 continue; /* skip routers that reject all */
1636 n_supported[i] = 0;
1637 /* iterate over connections */
1638 SMARTLIST_FOREACH_BEGIN(connections, connection_t *, conn) {
1639 if (!ap_stream_wants_exit_attention(conn))
1640 continue; /* Skip everything but APs in CIRCUIT_WAIT */
1641 if (connection_ap_can_use_exit(TO_ENTRY_CONN(conn), node)) {
1642 ++n_supported[i];
1643 // log_fn(LOG_DEBUG,"%s is supported. n_supported[%d] now %d.",
1644 // router->nickname, i, n_supported[i]);
1645 } else {
1646 // log_fn(LOG_DEBUG,"%s (index %d) would reject this stream.",
1647 // router->nickname, i);
1649 } SMARTLIST_FOREACH_END(conn);
1650 if (n_pending_connections > 0 && n_supported[i] == 0) {
1651 /* Leave best_support at -1 if that's where it is, so we can
1652 * distinguish it later. */
1653 continue;
1655 if (n_supported[i] > best_support) {
1656 /* If this router is better than previous ones, remember its index
1657 * and goodness, and start counting how many routers are this good. */
1658 best_support = n_supported[i]; n_best_support=1;
1659 // log_fn(LOG_DEBUG,"%s is new best supported option so far.",
1660 // router->nickname);
1661 } else if (n_supported[i] == best_support) {
1662 /* If this router is _as good_ as the best one, just increment the
1663 * count of equally good routers.*/
1664 ++n_best_support;
1666 } SMARTLIST_FOREACH_END(node);
1667 log_info(LD_CIRC,
1668 "Found %d servers that might support %d/%d pending connections.",
1669 n_best_support, best_support >= 0 ? best_support : 0,
1670 n_pending_connections);
1672 /* If any routers definitely support any pending connections, choose one
1673 * at random. */
1674 if (best_support > 0) {
1675 smartlist_t *supporting = smartlist_new();
1677 SMARTLIST_FOREACH(the_nodes, const node_t *, node, {
1678 if (n_supported[node_sl_idx] == best_support)
1679 smartlist_add(supporting, (void*)node);
1682 selected_node = node_sl_choose_by_bandwidth(supporting, WEIGHT_FOR_EXIT);
1683 smartlist_free(supporting);
1684 } else {
1685 /* Either there are no pending connections, or no routers even seem to
1686 * possibly support any of them. Choose a router at random that satisfies
1687 * at least one predicted exit port. */
1689 int attempt;
1690 smartlist_t *needed_ports, *supporting;
1692 if (best_support == -1) {
1693 if (need_uptime || need_capacity) {
1694 log_info(LD_CIRC,
1695 "We couldn't find any live%s%s routers; falling back "
1696 "to list of all routers.",
1697 need_capacity?", fast":"",
1698 need_uptime?", stable":"");
1699 tor_free(n_supported);
1700 flags &= ~(CRN_NEED_UPTIME|CRN_NEED_CAPACITY);
1701 return choose_good_exit_server_general(flags);
1703 log_notice(LD_CIRC, "All routers are down or won't exit%s -- "
1704 "choosing a doomed exit at random.",
1705 options->ExcludeExitNodesUnion_ ? " or are Excluded" : "");
1707 supporting = smartlist_new();
1708 needed_ports = circuit_get_unhandled_ports(time(NULL));
1709 for (attempt = 0; attempt < 2; attempt++) {
1710 /* try once to pick only from routers that satisfy a needed port,
1711 * then if there are none, pick from any that support exiting. */
1712 SMARTLIST_FOREACH_BEGIN(the_nodes, const node_t *, node) {
1713 if (n_supported[node_sl_idx] != -1 &&
1714 (attempt || node_handles_some_port(node, needed_ports))) {
1715 // log_fn(LOG_DEBUG,"Try %d: '%s' is a possibility.",
1716 // try, router->nickname);
1717 smartlist_add(supporting, (void*)node);
1719 } SMARTLIST_FOREACH_END(node);
1721 selected_node = node_sl_choose_by_bandwidth(supporting, WEIGHT_FOR_EXIT);
1722 if (selected_node)
1723 break;
1724 smartlist_clear(supporting);
1725 /* If we reach this point, we can't actually support any unhandled
1726 * predicted ports, so clear all the remaining ones. */
1727 if (smartlist_len(needed_ports))
1728 rep_hist_remove_predicted_ports(needed_ports);
1730 SMARTLIST_FOREACH(needed_ports, uint16_t *, cp, tor_free(cp));
1731 smartlist_free(needed_ports);
1732 smartlist_free(supporting);
1735 tor_free(n_supported);
1736 if (selected_node) {
1737 log_info(LD_CIRC, "Chose exit server '%s'", node_describe(selected_node));
1738 return selected_node;
1740 if (options->ExitNodes) {
1741 log_warn(LD_CIRC,
1742 "No exits in ExitNodes%s seem to be running: "
1743 "can't choose an exit.",
1744 options->ExcludeExitNodesUnion_ ?
1745 ", except possibly those excluded by your configuration, " : "");
1747 return NULL;
1750 /* Pick a Rendezvous Point for our HS circuits according to <b>flags</b>. */
1751 static const node_t *
1752 pick_rendezvous_node(router_crn_flags_t flags)
1754 const or_options_t *options = get_options();
1755 return router_choose_random_node(NULL, options->ExcludeNodes, flags);
1759 * Helper function to pick a configured restricted middle node
1760 * (either HSLayer2Nodes or HSLayer3Nodes).
1762 * Make sure that the node we chose is alive, and not excluded,
1763 * and return it.
1765 * The exclude_set is a routerset of nodes that the selected node
1766 * must not match, and the exclude_list is a simple list of nodes
1767 * that the selected node must not be in. Either or both may be
1768 * NULL.
1770 * Return NULL if no usable nodes could be found. */
1771 static const node_t *
1772 pick_restricted_middle_node(router_crn_flags_t flags,
1773 const routerset_t *pick_from,
1774 const routerset_t *exclude_set,
1775 const smartlist_t *exclude_list,
1776 int position_hint)
1778 const node_t *middle_node = NULL;
1780 smartlist_t *whitelisted_live_middles = smartlist_new();
1781 smartlist_t *all_live_nodes = smartlist_new();
1783 tor_assert(pick_from);
1785 /* Add all running nodes to all_live_nodes */
1786 router_add_running_nodes_to_smartlist(all_live_nodes, flags);
1788 /* Filter all_live_nodes to only add live *and* whitelisted middles
1789 * to the list whitelisted_live_middles. */
1790 SMARTLIST_FOREACH_BEGIN(all_live_nodes, node_t *, live_node) {
1791 if (routerset_contains_node(pick_from, live_node)) {
1792 smartlist_add(whitelisted_live_middles, live_node);
1794 } SMARTLIST_FOREACH_END(live_node);
1796 /* Honor ExcludeNodes */
1797 if (exclude_set) {
1798 routerset_subtract_nodes(whitelisted_live_middles, exclude_set);
1801 if (exclude_list) {
1802 smartlist_subtract(whitelisted_live_middles, exclude_list);
1806 * Max number of restricted nodes before we alert the user and try
1807 * to load balance for them.
1809 * The most aggressive vanguard design had 16 nodes at layer3.
1810 * Let's give a small ceiling above that. */
1811 #define MAX_SANE_RESTRICTED_NODES 20
1812 /* If the user (or associated tor controller) selected only a few nodes,
1813 * assume they took load balancing into account and don't do it for them.
1815 * If there are a lot of nodes in here, assume they did not load balance
1816 * and do it for them, but also warn them that they may be Doing It Wrong.
1818 if (smartlist_len(whitelisted_live_middles) <=
1819 MAX_SANE_RESTRICTED_NODES) {
1820 middle_node = smartlist_choose(whitelisted_live_middles);
1821 } else {
1822 static ratelim_t pinned_notice_limit = RATELIM_INIT(24*3600);
1823 log_fn_ratelim(&pinned_notice_limit, LOG_NOTICE, LD_CIRC,
1824 "Your _HSLayer%dNodes setting has resulted "
1825 "in %d total nodes. This is a lot of nodes. "
1826 "You may want to consider using a Tor controller "
1827 "to select and update a smaller set of nodes instead.",
1828 position_hint, smartlist_len(whitelisted_live_middles));
1830 /* NO_WEIGHTING here just means don't take node flags into account
1831 * (ie: use consensus measurement only). This is done so that
1832 * we don't further surprise the user by not using Exits that they
1833 * specified at all */
1834 middle_node = node_sl_choose_by_bandwidth(whitelisted_live_middles,
1835 NO_WEIGHTING);
1838 smartlist_free(whitelisted_live_middles);
1839 smartlist_free(all_live_nodes);
1841 return middle_node;
1844 /** Return a pointer to a suitable router to be the exit node for the
1845 * circuit of purpose <b>purpose</b> that we're about to build (or NULL
1846 * if no router is suitable).
1848 * For general-purpose circuits, pass it off to
1849 * choose_good_exit_server_general()
1851 * For client-side rendezvous circuits, choose a random node, weighted
1852 * toward the preferences in 'options'.
1854 static const node_t *
1855 choose_good_exit_server(origin_circuit_t *circ,
1856 router_crn_flags_t flags, int is_internal)
1858 const or_options_t *options = get_options();
1859 flags |= CRN_NEED_DESC;
1861 switch (TO_CIRCUIT(circ)->purpose) {
1862 case CIRCUIT_PURPOSE_C_HSDIR_GET:
1863 case CIRCUIT_PURPOSE_S_HSDIR_POST:
1864 case CIRCUIT_PURPOSE_HS_VANGUARDS:
1865 /* For these three, we want to pick the exit like a middle hop,
1866 * since it should be random. */
1867 tor_assert_nonfatal(is_internal);
1868 FALLTHROUGH;
1869 case CIRCUIT_PURPOSE_C_GENERAL:
1870 if (is_internal) /* pick it like a middle hop */
1871 return router_choose_random_node(NULL, options->ExcludeNodes, flags);
1872 else
1873 return choose_good_exit_server_general(flags);
1874 case CIRCUIT_PURPOSE_C_ESTABLISH_REND:
1876 /* Pick a new RP */
1877 const node_t *rendezvous_node = pick_rendezvous_node(flags);
1878 log_info(LD_REND, "Picked new RP: %s",
1879 safe_str_client(node_describe(rendezvous_node)));
1880 return rendezvous_node;
1883 log_warn(LD_BUG,"Unhandled purpose %d", TO_CIRCUIT(circ)->purpose);
1884 tor_fragile_assert();
1885 return NULL;
1888 /** Log a warning if the user specified an exit for the circuit that
1889 * has been excluded from use by ExcludeNodes or ExcludeExitNodes. */
1890 static void
1891 warn_if_last_router_excluded(origin_circuit_t *circ,
1892 const extend_info_t *exit_ei)
1894 const or_options_t *options = get_options();
1895 routerset_t *rs = options->ExcludeNodes;
1896 const char *description;
1897 uint8_t purpose = circ->base_.purpose;
1899 if (circ->build_state->onehop_tunnel)
1900 return;
1902 switch (purpose)
1904 default:
1905 case CIRCUIT_PURPOSE_OR:
1906 case CIRCUIT_PURPOSE_INTRO_POINT:
1907 case CIRCUIT_PURPOSE_REND_POINT_WAITING:
1908 case CIRCUIT_PURPOSE_REND_ESTABLISHED:
1909 log_warn(LD_BUG, "Called on non-origin circuit (purpose %d, %s)",
1910 (int)purpose,
1911 circuit_purpose_to_string(purpose));
1912 return;
1913 case CIRCUIT_PURPOSE_S_HSDIR_POST:
1914 case CIRCUIT_PURPOSE_C_HSDIR_GET:
1915 case CIRCUIT_PURPOSE_C_GENERAL:
1916 if (circ->build_state->is_internal)
1917 return;
1918 description = "requested exit node";
1919 rs = options->ExcludeExitNodesUnion_;
1920 break;
1921 case CIRCUIT_PURPOSE_C_INTRODUCING:
1922 case CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT:
1923 case CIRCUIT_PURPOSE_C_INTRODUCE_ACKED:
1924 case CIRCUIT_PURPOSE_S_ESTABLISH_INTRO:
1925 case CIRCUIT_PURPOSE_S_CONNECT_REND:
1926 case CIRCUIT_PURPOSE_S_REND_JOINED:
1927 case CIRCUIT_PURPOSE_TESTING:
1928 return;
1929 case CIRCUIT_PURPOSE_C_ESTABLISH_REND:
1930 case CIRCUIT_PURPOSE_C_REND_READY:
1931 case CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED:
1932 case CIRCUIT_PURPOSE_C_REND_JOINED:
1933 description = "chosen rendezvous point";
1934 break;
1935 case CIRCUIT_PURPOSE_CONTROLLER:
1936 rs = options->ExcludeExitNodesUnion_;
1937 description = "controller-selected circuit target";
1938 break;
1941 if (routerset_contains_extendinfo(rs, exit_ei)) {
1942 /* We should never get here if StrictNodes is set to 1. */
1943 if (options->StrictNodes) {
1944 log_warn(LD_BUG, "Using %s '%s' which is listed in ExcludeNodes%s, "
1945 "even though StrictNodes is set. Please report. "
1946 "(Circuit purpose: %s)",
1947 description, extend_info_describe(exit_ei),
1948 rs==options->ExcludeNodes?"":" or ExcludeExitNodes",
1949 circuit_purpose_to_string(purpose));
1950 } else {
1951 log_warn(LD_CIRC, "Using %s '%s' which is listed in "
1952 "ExcludeNodes%s, because no better options were available. To "
1953 "prevent this (and possibly break your Tor functionality), "
1954 "set the StrictNodes configuration option. "
1955 "(Circuit purpose: %s)",
1956 description, extend_info_describe(exit_ei),
1957 rs==options->ExcludeNodes?"":" or ExcludeExitNodes",
1958 circuit_purpose_to_string(purpose));
1960 circuit_log_path(LOG_WARN, LD_CIRC, circ);
1963 return;
1966 /* Return a set of generic CRN_* flags based on <b>state</b>.
1968 * Called for every position in the circuit. */
1969 STATIC int
1970 cpath_build_state_to_crn_flags(const cpath_build_state_t *state)
1972 router_crn_flags_t flags = 0;
1973 /* These flags apply to entry, middle, and exit nodes.
1974 * If a flag only applies to a specific position, it should be checked in
1975 * that function. */
1976 if (state->need_uptime)
1977 flags |= CRN_NEED_UPTIME;
1978 if (state->need_capacity)
1979 flags |= CRN_NEED_CAPACITY;
1980 return flags;
1983 /* Return the CRN_INITIATE_IPV6_EXTEND flag, based on <b>state</b> and
1984 * <b>cur_len</b>.
1986 * Only called for middle nodes (for now). Must not be called on single-hop
1987 * circuits. */
1988 STATIC int
1989 cpath_build_state_to_crn_ipv6_extend_flag(const cpath_build_state_t *state,
1990 int cur_len)
1992 IF_BUG_ONCE(state->desired_path_len < 2)
1993 return 0;
1995 /* The last node is the relay doing the self-test. So we want to extend over
1996 * IPv6 from the second-last node. */
1997 if (state->is_ipv6_selftest && cur_len == state->desired_path_len - 2)
1998 return CRN_INITIATE_IPV6_EXTEND;
1999 else
2000 return 0;
2003 /** Decide a suitable length for circ's cpath, and pick an exit
2004 * router (or use <b>exit</b> if provided). Store these in the
2005 * cpath.
2007 * If <b>is_hs_v3_rp_circuit</b> is set, then this exit should be suitable to
2008 * be used as an HS v3 rendezvous point.
2010 * Return 0 if ok, -1 if circuit should be closed. */
2011 STATIC int
2012 onion_pick_cpath_exit(origin_circuit_t *circ, extend_info_t *exit_ei,
2013 int is_hs_v3_rp_circuit)
2015 cpath_build_state_t *state = circ->build_state;
2017 if (state->onehop_tunnel) {
2018 log_debug(LD_CIRC, "Launching a one-hop circuit for dir tunnel%s.",
2019 (rend_allow_non_anonymous_connection(get_options()) ?
2020 ", or intro or rendezvous connection" : ""));
2021 state->desired_path_len = 1;
2022 } else {
2023 int r = new_route_len(circ->base_.purpose, exit_ei, nodelist_get_list());
2024 if (r < 1) /* must be at least 1 */
2025 return -1;
2026 state->desired_path_len = r;
2029 if (exit_ei) { /* the circuit-builder pre-requested one */
2030 warn_if_last_router_excluded(circ, exit_ei);
2031 log_info(LD_CIRC,"Using requested exit node '%s'",
2032 extend_info_describe(exit_ei));
2033 exit_ei = extend_info_dup(exit_ei);
2034 } else { /* we have to decide one */
2035 router_crn_flags_t flags = CRN_NEED_DESC;
2036 flags |= cpath_build_state_to_crn_flags(state);
2037 /* Some internal exits are one hop, for example directory connections.
2038 * (Guards are always direct, middles are never direct.) */
2039 if (state->onehop_tunnel)
2040 flags |= CRN_DIRECT_CONN;
2041 if (is_hs_v3_rp_circuit)
2042 flags |= CRN_RENDEZVOUS_V3;
2043 const node_t *node =
2044 choose_good_exit_server(circ, flags, state->is_internal);
2045 if (!node) {
2046 log_warn(LD_CIRC,"Failed to choose an exit server");
2047 return -1;
2049 exit_ei = extend_info_from_node(node, state->onehop_tunnel);
2050 if (BUG(exit_ei == NULL))
2051 return -1;
2053 state->chosen_exit = exit_ei;
2054 return 0;
2057 /** Give <b>circ</b> a new exit destination to <b>exit</b>, and add a
2058 * hop to the cpath reflecting this. Don't send the next extend cell --
2059 * the caller will do this if it wants to.
2062 circuit_append_new_exit(origin_circuit_t *circ, extend_info_t *exit_ei)
2064 cpath_build_state_t *state;
2065 tor_assert(exit_ei);
2066 tor_assert(circ);
2068 state = circ->build_state;
2069 tor_assert(state);
2070 extend_info_free(state->chosen_exit);
2071 state->chosen_exit = extend_info_dup(exit_ei);
2073 ++circ->build_state->desired_path_len;
2074 cpath_append_hop(&circ->cpath, exit_ei);
2075 return 0;
2078 /** Take an open <b>circ</b>, and add a new hop at the end, based on
2079 * <b>info</b>. Set its state back to CIRCUIT_STATE_BUILDING, and then
2080 * send the next extend cell to begin connecting to that hop.
2083 circuit_extend_to_new_exit(origin_circuit_t *circ, extend_info_t *exit_ei)
2085 int err_reason = 0;
2086 warn_if_last_router_excluded(circ, exit_ei);
2088 tor_gettimeofday(&circ->base_.timestamp_began);
2090 circuit_append_new_exit(circ, exit_ei);
2091 circuit_set_state(TO_CIRCUIT(circ), CIRCUIT_STATE_BUILDING);
2092 if ((err_reason = circuit_send_next_onion_skin(circ))<0) {
2093 log_warn(LD_CIRC, "Couldn't extend circuit to new point %s.",
2094 extend_info_describe(exit_ei));
2095 circuit_mark_for_close(TO_CIRCUIT(circ), -err_reason);
2096 return -1;
2099 // XXX: Should cannibalized circuits be dirty or not? Not easy to say..
2101 return 0;
2104 /** Return the number of routers in <b>nodes</b> that are currently up and
2105 * available for building circuits through.
2107 * If <b>direct</b> is true, only count nodes that are suitable for direct
2108 * connections. Counts nodes regardless of whether their addresses are
2109 * preferred.
2111 MOCK_IMPL(STATIC int,
2112 count_acceptable_nodes, (const smartlist_t *nodes, int direct))
2114 int num=0;
2115 int flags = CRN_NEED_DESC;
2117 if (direct)
2118 flags |= CRN_DIRECT_CONN;
2120 SMARTLIST_FOREACH_BEGIN(nodes, const node_t *, node) {
2121 // log_debug(LD_CIRC,
2122 // "Contemplating whether router %d (%s) is a new option.",
2123 // i, r->nickname);
2124 if (!router_can_choose_node(node, flags))
2125 continue;
2126 ++num;
2127 } SMARTLIST_FOREACH_END(node);
2129 // log_debug(LD_CIRC,"I like %d. num_acceptable_routers now %d.",i, num);
2131 return num;
2135 * Build the exclude list for vanguard circuits.
2137 * For vanguard circuits we exclude all the already chosen nodes (including the
2138 * exit) from being middle hops to prevent the creation of A - B - A subpaths.
2139 * We also allow the 4th hop to be the same as the guard node so as to not leak
2140 * guard information to RP/IP/HSDirs.
2142 * For vanguard circuits, we don't apply any subnet or family restrictions.
2143 * This is to avoid impossible-to-build circuit paths, or just situations where
2144 * our earlier guards prevent us from using most of our later ones.
2146 * The alternative is building the circuit in reverse. Reverse calls to
2147 * onion_extend_cpath() (ie: select outer hops first) would then have the
2148 * property that you don't gain information about inner hops by observing
2149 * outer ones. See https://trac.torproject.org/projects/tor/ticket/24487
2150 * for this.
2152 * (Note further that we still exclude the exit to prevent A - B - A
2153 * at the end of the path. */
2154 static smartlist_t *
2155 build_vanguard_middle_exclude_list(uint8_t purpose,
2156 cpath_build_state_t *state,
2157 crypt_path_t *head,
2158 int cur_len)
2160 smartlist_t *excluded;
2161 const node_t *r;
2162 crypt_path_t *cpath;
2163 int i;
2165 (void) purpose;
2167 excluded = smartlist_new();
2169 /* Add the exit to the exclude list (note that the exit/last hop is always
2170 * chosen first in circuit_establish_circuit()). */
2171 if ((r = build_state_get_exit_node(state))) {
2172 smartlist_add(excluded, (node_t*)r);
2175 /* If we are picking the 4th hop, allow that node to be the guard too.
2176 * This prevents us from avoiding the Guard for those hops, which
2177 * gives the adversary information about our guard if they control
2178 * the RP, IP, or HSDIR. We don't do this check based on purpose
2179 * because we also want to allow HS_VANGUARDS pre-build circuits
2180 * to use the guard for that last hop.
2182 if (cur_len == DEFAULT_ROUTE_LEN+1) {
2183 /* Skip the first hop for the exclude list below */
2184 head = head->next;
2185 cur_len--;
2188 for (i = 0, cpath = head; cpath && i < cur_len; ++i, cpath=cpath->next) {
2189 if ((r = node_get_by_id(cpath->extend_info->identity_digest))) {
2190 smartlist_add(excluded, (node_t*)r);
2194 return excluded;
2198 * Build a list of nodes to exclude from the choice of this middle
2199 * hop, based on already chosen nodes.
2201 static smartlist_t *
2202 build_middle_exclude_list(uint8_t purpose,
2203 cpath_build_state_t *state,
2204 crypt_path_t *head,
2205 int cur_len)
2207 smartlist_t *excluded;
2208 const node_t *r;
2209 crypt_path_t *cpath;
2210 int i;
2212 /** Vanguard circuits have their own path selection rules */
2213 if (circuit_should_use_vanguards(purpose)) {
2214 return build_vanguard_middle_exclude_list(purpose, state, head, cur_len);
2217 excluded = smartlist_new();
2219 /* For non-vanguard circuits, add the exit and its family to the exclude list
2220 * (note that the exit/last hop is always chosen first in
2221 * circuit_establish_circuit()). */
2222 if ((r = build_state_get_exit_node(state))) {
2223 nodelist_add_node_and_family(excluded, r);
2226 /* also exclude all other already chosen nodes and their family */
2227 for (i = 0, cpath = head; cpath && i < cur_len; ++i, cpath=cpath->next) {
2228 if ((r = node_get_by_id(cpath->extend_info->identity_digest))) {
2229 nodelist_add_node_and_family(excluded, r);
2233 return excluded;
2236 /** Return true if we MUST use vanguards for picking this middle node. */
2237 static int
2238 middle_node_must_be_vanguard(const or_options_t *options,
2239 uint8_t purpose, int cur_len)
2241 /* If this is not a hidden service circuit, don't use vanguards */
2242 if (!circuit_purpose_is_hidden_service(purpose)) {
2243 return 0;
2246 /* If we have sticky L2 nodes, and this is an L2 pick, use vanguards */
2247 if (options->HSLayer2Nodes && cur_len == 1) {
2248 return 1;
2251 /* If we have sticky L3 nodes, and this is an L3 pick, use vanguards */
2252 if (options->HSLayer3Nodes && cur_len == 2) {
2253 return 1;
2256 return 0;
2259 /** Pick a sticky vanguard middle node or return NULL if not found.
2260 * See doc of pick_restricted_middle_node() for argument details. */
2261 static const node_t *
2262 pick_vanguard_middle_node(const or_options_t *options,
2263 router_crn_flags_t flags, int cur_len,
2264 const smartlist_t *excluded)
2266 const routerset_t *vanguard_routerset = NULL;
2267 const node_t *node = NULL;
2269 /* Pick the right routerset based on the current hop */
2270 if (cur_len == 1) {
2271 vanguard_routerset = options->HSLayer2Nodes;
2272 } else if (cur_len == 2) {
2273 vanguard_routerset = options->HSLayer3Nodes;
2274 } else {
2275 /* guaranteed by middle_node_should_be_vanguard() */
2276 tor_assert_nonfatal_unreached();
2277 return NULL;
2280 node = pick_restricted_middle_node(flags, vanguard_routerset,
2281 options->ExcludeNodes, excluded,
2282 cur_len+1);
2284 if (!node) {
2285 static ratelim_t pinned_warning_limit = RATELIM_INIT(300);
2286 log_fn_ratelim(&pinned_warning_limit, LOG_WARN, LD_CIRC,
2287 "Could not find a node that matches the configured "
2288 "_HSLayer%dNodes set", cur_len+1);
2291 return node;
2294 /** A helper function used by onion_extend_cpath(). Use <b>purpose</b>
2295 * and <b>state</b> and the cpath <b>head</b> (currently populated only
2296 * to length <b>cur_len</b> to decide a suitable middle hop for a
2297 * circuit. In particular, make sure we don't pick the exit node or its
2298 * family, and make sure we don't duplicate any previous nodes or their
2299 * families. */
2300 static const node_t *
2301 choose_good_middle_server(uint8_t purpose,
2302 cpath_build_state_t *state,
2303 crypt_path_t *head,
2304 int cur_len)
2306 const node_t *choice;
2307 smartlist_t *excluded;
2308 const or_options_t *options = get_options();
2309 router_crn_flags_t flags = CRN_NEED_DESC;
2310 tor_assert(CIRCUIT_PURPOSE_MIN_ <= purpose &&
2311 purpose <= CIRCUIT_PURPOSE_MAX_);
2313 log_debug(LD_CIRC, "Contemplating intermediate hop #%d: random choice.",
2314 cur_len+1);
2316 excluded = build_middle_exclude_list(purpose, state, head, cur_len);
2318 flags |= cpath_build_state_to_crn_flags(state);
2319 flags |= cpath_build_state_to_crn_ipv6_extend_flag(state, cur_len);
2321 /** If a hidden service circuit wants a specific middle node, pin it. */
2322 if (middle_node_must_be_vanguard(options, purpose, cur_len)) {
2323 log_debug(LD_GENERAL, "Picking a sticky node (cur_len = %d)", cur_len);
2324 choice = pick_vanguard_middle_node(options, flags, cur_len, excluded);
2325 smartlist_free(excluded);
2326 return choice;
2329 if (options->MiddleNodes) {
2330 smartlist_t *sl = smartlist_new();
2331 routerset_get_all_nodes(sl, options->MiddleNodes,
2332 options->ExcludeNodes, 1);
2334 smartlist_subtract(sl, excluded);
2336 choice = node_sl_choose_by_bandwidth(sl, WEIGHT_FOR_MID);
2337 smartlist_free(sl);
2338 if (choice) {
2339 log_fn(LOG_INFO, LD_CIRC, "Chose fixed middle node: %s",
2340 hex_str(choice->identity, DIGEST_LEN));
2341 } else {
2342 log_fn(LOG_NOTICE, LD_CIRC, "Restricted middle not available");
2344 } else {
2345 choice = router_choose_random_node(excluded, options->ExcludeNodes, flags);
2347 smartlist_free(excluded);
2348 return choice;
2351 /** Pick a good entry server for the circuit to be built according to
2352 * <b>state</b>. Don't reuse a chosen exit (if any), don't use this
2353 * router (if we're an OR), and respect firewall settings; if we're
2354 * configured to use entry guards, return one.
2356 * Set *<b>guard_state_out</b> to information about the guard that
2357 * we're selecting, which we'll use later to remember whether the
2358 * guard worked or not.
2360 const node_t *
2361 choose_good_entry_server(uint8_t purpose, cpath_build_state_t *state,
2362 circuit_guard_state_t **guard_state_out)
2364 const node_t *choice;
2365 smartlist_t *excluded;
2366 const or_options_t *options = get_options();
2367 /* If possible, choose an entry server with a preferred address,
2368 * otherwise, choose one with an allowed address */
2369 router_crn_flags_t flags = (CRN_NEED_GUARD|CRN_NEED_DESC|CRN_PREF_ADDR|
2370 CRN_DIRECT_CONN);
2371 const node_t *node;
2373 /* Once we used this function to select a node to be a guard. We had
2374 * 'state == NULL' be the signal for that. But we don't do that any more.
2376 tor_assert_nonfatal(state);
2378 if (state && options->UseEntryGuards &&
2379 (purpose != CIRCUIT_PURPOSE_TESTING || options->BridgeRelay)) {
2380 /* This request is for an entry server to use for a regular circuit,
2381 * and we use entry guard nodes. Just return one of the guard nodes. */
2382 tor_assert(guard_state_out);
2383 return guards_choose_guard(state, purpose, guard_state_out);
2386 excluded = smartlist_new();
2388 if (state && (node = build_state_get_exit_node(state))) {
2389 /* Exclude the exit node from the state, if we have one. Also exclude its
2390 * family. */
2391 nodelist_add_node_and_family(excluded, node);
2394 if (state) {
2395 flags |= cpath_build_state_to_crn_flags(state);
2398 choice = router_choose_random_node(excluded, options->ExcludeNodes, flags);
2399 smartlist_free(excluded);
2400 return choice;
2403 /** Choose a suitable next hop for the circuit <b>circ</b>.
2404 * Append the hop info to circ->cpath.
2406 * Return 1 if the path is complete, 0 if we successfully added a hop,
2407 * and -1 on error.
2409 STATIC int
2410 onion_extend_cpath(origin_circuit_t *circ)
2412 uint8_t purpose = circ->base_.purpose;
2413 cpath_build_state_t *state = circ->build_state;
2414 int cur_len = circuit_get_cpath_len(circ);
2415 extend_info_t *info = NULL;
2417 if (cur_len >= state->desired_path_len) {
2418 log_debug(LD_CIRC, "Path is complete: %d steps long",
2419 state->desired_path_len);
2420 return 1;
2423 log_debug(LD_CIRC, "Path is %d long; we want %d", cur_len,
2424 state->desired_path_len);
2426 if (cur_len == state->desired_path_len - 1) { /* Picking last node */
2427 info = extend_info_dup(state->chosen_exit);
2428 } else if (cur_len == 0) { /* picking first node */
2429 const node_t *r = choose_good_entry_server(purpose, state,
2430 &circ->guard_state);
2431 if (r) {
2432 /* If we're a client, use the preferred address rather than the
2433 primary address, for potentially connecting to an IPv6 OR
2434 port. Servers always want the primary (IPv4) address. */
2435 int client = (server_mode(get_options()) == 0);
2436 info = extend_info_from_node(r, client);
2437 /* Clients can fail to find an allowed address */
2438 tor_assert_nonfatal(info || client);
2440 } else {
2441 const node_t *r =
2442 choose_good_middle_server(purpose, state, circ->cpath, cur_len);
2443 if (r) {
2444 info = extend_info_from_node(r, 0);
2445 tor_assert_nonfatal(info);
2449 if (!info) {
2450 log_warn(LD_CIRC,"Failed to find node for hop #%d of our path. Discarding "
2451 "this circuit.", cur_len+1);
2452 return -1;
2455 log_debug(LD_CIRC,"Chose router %s for hop #%d (exit is %s)",
2456 extend_info_describe(info),
2457 cur_len+1, build_state_get_exit_nickname(state));
2459 cpath_append_hop(&circ->cpath, info);
2460 extend_info_free(info);
2461 return 0;
2464 /** Return the node_t for the chosen exit router in <b>state</b>.
2465 * If there is no chosen exit, or if we don't know the node_t for
2466 * the chosen exit, return NULL.
2468 MOCK_IMPL(const node_t *,
2469 build_state_get_exit_node,(cpath_build_state_t *state))
2471 if (!state || !state->chosen_exit)
2472 return NULL;
2473 return node_get_by_id(state->chosen_exit->identity_digest);
2476 /** Return the RSA ID digest for the chosen exit router in <b>state</b>.
2477 * If there is no chosen exit, return NULL.
2479 const uint8_t *
2480 build_state_get_exit_rsa_id(cpath_build_state_t *state)
2482 if (!state || !state->chosen_exit)
2483 return NULL;
2484 return (const uint8_t *) state->chosen_exit->identity_digest;
2487 /** Return the nickname for the chosen exit router in <b>state</b>. If
2488 * there is no chosen exit, or if we don't know the routerinfo_t for the
2489 * chosen exit, return NULL.
2491 const char *
2492 build_state_get_exit_nickname(cpath_build_state_t *state)
2494 if (!state || !state->chosen_exit)
2495 return NULL;
2496 return state->chosen_exit->nickname;
2499 /* Is circuit purpose allowed to use the deprecated TAP encryption protocol?
2500 * The hidden service protocol still uses TAP for some connections, because
2501 * ntor onion keys aren't included in HS descriptors or INTRODUCE cells. */
2502 static int
2503 circuit_purpose_can_use_tap_impl(uint8_t purpose)
2505 return (purpose == CIRCUIT_PURPOSE_S_CONNECT_REND ||
2506 purpose == CIRCUIT_PURPOSE_C_INTRODUCING);
2509 /* Is circ allowed to use the deprecated TAP encryption protocol?
2510 * The hidden service protocol still uses TAP for some connections, because
2511 * ntor onion keys aren't included in HS descriptors or INTRODUCE cells. */
2513 circuit_can_use_tap(const origin_circuit_t *circ)
2515 tor_assert(circ);
2516 tor_assert(circ->cpath);
2517 tor_assert(circ->cpath->extend_info);
2518 return (circuit_purpose_can_use_tap_impl(circ->base_.purpose) &&
2519 extend_info_supports_tap(circ->cpath->extend_info));
2522 /* Does circ have an onion key which it's allowed to use? */
2524 circuit_has_usable_onion_key(const origin_circuit_t *circ)
2526 tor_assert(circ);
2527 tor_assert(circ->cpath);
2528 tor_assert(circ->cpath->extend_info);
2529 return (extend_info_supports_ntor(circ->cpath->extend_info) ||
2530 circuit_can_use_tap(circ));
2533 /** Find the circuits that are waiting to find out whether their guards are
2534 * usable, and if any are ready to become usable, mark them open and try
2535 * attaching streams as appropriate. */
2536 void
2537 circuit_upgrade_circuits_from_guard_wait(void)
2539 smartlist_t *to_upgrade =
2540 circuit_find_circuits_to_upgrade_from_guard_wait();
2542 if (to_upgrade == NULL)
2543 return;
2545 log_info(LD_GUARD, "Upgrading %d circuits from 'waiting for better guard' "
2546 "to 'open'.", smartlist_len(to_upgrade));
2548 SMARTLIST_FOREACH_BEGIN(to_upgrade, origin_circuit_t *, circ) {
2549 circuit_set_state(TO_CIRCUIT(circ), CIRCUIT_STATE_OPEN);
2550 circuit_has_opened(circ);
2551 } SMARTLIST_FOREACH_END(circ);
2553 smartlist_free(to_upgrade);