Split circuit_send_next_onion_skin() into its three main cases.
[tor.git] / src / or / circuitbuild.c
blob21ed0386643fef7911e579be32bf8a579cf3ad38
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-2017, 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 * On the server side, this module also handles the logic of responding to
25 * RELAY_EXTEND requests, using circuit_extend().
26 **/
28 #define CIRCUITBUILD_PRIVATE
30 #include "or.h"
31 #include "bridges.h"
32 #include "channel.h"
33 #include "circpathbias.h"
34 #define CIRCUITBUILD_PRIVATE
35 #include "circuitbuild.h"
36 #include "circuitlist.h"
37 #include "circuitstats.h"
38 #include "circuituse.h"
39 #include "command.h"
40 #include "config.h"
41 #include "confparse.h"
42 #include "connection.h"
43 #include "connection_edge.h"
44 #include "connection_or.h"
45 #include "control.h"
46 #include "crypto.h"
47 #include "directory.h"
48 #include "entrynodes.h"
49 #include "main.h"
50 #include "microdesc.h"
51 #include "networkstatus.h"
52 #include "nodelist.h"
53 #include "onion.h"
54 #include "onion_tap.h"
55 #include "onion_fast.h"
56 #include "policies.h"
57 #include "relay.h"
58 #include "rendcommon.h"
59 #include "rephist.h"
60 #include "router.h"
61 #include "routerlist.h"
62 #include "routerparse.h"
63 #include "routerset.h"
64 #include "transports.h"
66 static channel_t * channel_connect_for_circuit(const tor_addr_t *addr,
67 uint16_t port,
68 const char *id_digest,
69 const ed25519_public_key_t *ed_id);
70 static int circuit_deliver_create_cell(circuit_t *circ,
71 const create_cell_t *create_cell,
72 int relayed);
73 static int onion_pick_cpath_exit(origin_circuit_t *circ, extend_info_t *exit);
74 static crypt_path_t *onion_next_hop_in_cpath(crypt_path_t *cpath);
75 static int onion_extend_cpath(origin_circuit_t *circ);
76 static int onion_append_hop(crypt_path_t **head_ptr, extend_info_t *choice);
77 static int circuit_send_first_onion_skin(origin_circuit_t *circ);
78 static int circuit_build_no_more_hops(origin_circuit_t *circ);
79 static int circuit_send_intermediate_onion_skin(origin_circuit_t *circ,
80 crypt_path_t *hop);
82 /** This function tries to get a channel to the specified endpoint,
83 * and then calls command_setup_channel() to give it the right
84 * callbacks.
86 static channel_t *
87 channel_connect_for_circuit(const tor_addr_t *addr, uint16_t port,
88 const char *id_digest,
89 const ed25519_public_key_t *ed_id)
91 channel_t *chan;
93 chan = channel_connect(addr, port, id_digest, ed_id);
94 if (chan) command_setup_channel(chan);
96 return chan;
99 /** Search for a value for circ_id that we can use on <b>chan</b> for an
100 * outbound circuit, until we get a circ_id that is not in use by any other
101 * circuit on that conn.
103 * Return it, or 0 if can't get a unique circ_id.
105 STATIC circid_t
106 get_unique_circ_id_by_chan(channel_t *chan)
108 /* This number is chosen somewhat arbitrarily; see comment below for more
109 * info. When the space is 80% full, it gives a one-in-a-million failure
110 * chance; when the space is 90% full, it gives a one-in-850 chance; and when
111 * the space is 95% full, it gives a one-in-26 failure chance. That seems
112 * okay, though you could make a case IMO for anything between N=32 and
113 * N=256. */
114 #define MAX_CIRCID_ATTEMPTS 64
115 int in_use;
116 unsigned n_with_circ = 0, n_pending_destroy = 0, n_weird_pending_destroy = 0;
117 circid_t test_circ_id;
118 circid_t attempts=0;
119 circid_t high_bit, max_range, mask;
120 int64_t pending_destroy_time_total = 0;
121 int64_t pending_destroy_time_max = 0;
123 tor_assert(chan);
125 if (chan->circ_id_type == CIRC_ID_TYPE_NEITHER) {
126 log_warn(LD_BUG,
127 "Trying to pick a circuit ID for a connection from "
128 "a client with no identity.");
129 return 0;
131 max_range = (chan->wide_circ_ids) ? (1u<<31) : (1u<<15);
132 mask = max_range - 1;
133 high_bit = (chan->circ_id_type == CIRC_ID_TYPE_HIGHER) ? max_range : 0;
134 do {
135 if (++attempts > MAX_CIRCID_ATTEMPTS) {
136 /* Make sure we don't loop forever because all circuit IDs are used.
138 * Once, we would try until we had tried every possible circuit ID. But
139 * that's quite expensive. Instead, we try MAX_CIRCID_ATTEMPTS random
140 * circuit IDs, and then give up.
142 * This potentially causes us to give up early if our circuit ID space
143 * is nearly full. If we have N circuit IDs in use, then we will reject
144 * a new circuit with probability (N / max_range) ^ MAX_CIRCID_ATTEMPTS.
145 * This means that in practice, a few percent of our circuit ID capacity
146 * will go unused.
148 * The alternative here, though, is to do a linear search over the
149 * whole circuit ID space every time we extend a circuit, which is
150 * not so great either.
152 int64_t queued_destroys;
153 char *m = rate_limit_log(&chan->last_warned_circ_ids_exhausted,
154 approx_time());
155 if (m == NULL)
156 return 0; /* This message has been rate-limited away. */
157 if (n_pending_destroy)
158 pending_destroy_time_total /= n_pending_destroy;
159 log_warn(LD_CIRC,"No unused circIDs found on channel %s wide "
160 "circID support, with %u inbound and %u outbound circuits. "
161 "Found %u circuit IDs in use by circuits, and %u with "
162 "pending destroy cells. (%u of those were marked bogusly.) "
163 "The ones with pending destroy cells "
164 "have been marked unusable for an average of %ld seconds "
165 "and a maximum of %ld seconds. This channel is %ld seconds "
166 "old. Failing a circuit.%s",
167 chan->wide_circ_ids ? "with" : "without",
168 chan->num_p_circuits, chan->num_n_circuits,
169 n_with_circ, n_pending_destroy, n_weird_pending_destroy,
170 (long)pending_destroy_time_total,
171 (long)pending_destroy_time_max,
172 (long)(approx_time() - chan->timestamp_created),
174 tor_free(m);
176 if (!chan->cmux) {
177 /* This warning should be impossible. */
178 log_warn(LD_BUG, " This channel somehow has no cmux on it!");
179 return 0;
182 /* analysis so far on 12184 suggests that we're running out of circuit
183 IDs because it looks like we have too many pending destroy
184 cells. Let's see how many we really have pending.
186 queued_destroys = circuitmux_count_queued_destroy_cells(chan,
187 chan->cmux);
189 log_warn(LD_CIRC, " Circuitmux on this channel has %u circuits, "
190 "of which %u are active. It says it has "I64_FORMAT
191 " destroy cells queued.",
192 circuitmux_num_circuits(chan->cmux),
193 circuitmux_num_active_circuits(chan->cmux),
194 I64_PRINTF_ARG(queued_destroys));
196 /* Change this into "if (1)" in order to get more information about
197 * possible failure modes here. You'll need to know how to use gdb with
198 * Tor: this will make Tor exit with an assertion failure if the cmux is
199 * corrupt. */
200 if (0)
201 circuitmux_assert_okay(chan->cmux);
203 channel_dump_statistics(chan, LOG_WARN);
205 return 0;
208 do {
209 crypto_rand((char*) &test_circ_id, sizeof(test_circ_id));
210 test_circ_id &= mask;
211 } while (test_circ_id == 0);
213 test_circ_id |= high_bit;
215 in_use = circuit_id_in_use_on_channel(test_circ_id, chan);
216 if (in_use == 1)
217 ++n_with_circ;
218 else if (in_use == 2) {
219 time_t since_when;
220 ++n_pending_destroy;
221 since_when =
222 circuit_id_when_marked_unusable_on_channel(test_circ_id, chan);
223 if (since_when) {
224 time_t waiting = approx_time() - since_when;
225 pending_destroy_time_total += waiting;
226 if (waiting > pending_destroy_time_max)
227 pending_destroy_time_max = waiting;
228 } else {
229 ++n_weird_pending_destroy;
232 } while (in_use);
233 return test_circ_id;
236 /** If <b>verbose</b> is false, allocate and return a comma-separated list of
237 * the currently built elements of <b>circ</b>. If <b>verbose</b> is true, also
238 * list information about link status in a more verbose format using spaces.
239 * If <b>verbose_names</b> is false, give nicknames for Named routers and hex
240 * digests for others; if <b>verbose_names</b> is true, use $DIGEST=Name style
241 * names.
243 static char *
244 circuit_list_path_impl(origin_circuit_t *circ, int verbose, int verbose_names)
246 crypt_path_t *hop;
247 smartlist_t *elements;
248 const char *states[] = {"closed", "waiting for keys", "open"};
249 char *s;
251 elements = smartlist_new();
253 if (verbose) {
254 const char *nickname = build_state_get_exit_nickname(circ->build_state);
255 smartlist_add_asprintf(elements, "%s%s circ (length %d%s%s):",
256 circ->build_state->is_internal ? "internal" : "exit",
257 circ->build_state->need_uptime ? " (high-uptime)" : "",
258 circ->build_state->desired_path_len,
259 circ->base_.state == CIRCUIT_STATE_OPEN ? "" : ", last hop ",
260 circ->base_.state == CIRCUIT_STATE_OPEN ? "" :
261 (nickname?nickname:"*unnamed*"));
264 hop = circ->cpath;
265 do {
266 char *elt;
267 const char *id;
268 const node_t *node;
269 if (!hop)
270 break;
271 if (!verbose && hop->state != CPATH_STATE_OPEN)
272 break;
273 if (!hop->extend_info)
274 break;
275 id = hop->extend_info->identity_digest;
276 if (verbose_names) {
277 elt = tor_malloc(MAX_VERBOSE_NICKNAME_LEN+1);
278 if ((node = node_get_by_id(id))) {
279 node_get_verbose_nickname(node, elt);
280 } else if (is_legal_nickname(hop->extend_info->nickname)) {
281 elt[0] = '$';
282 base16_encode(elt+1, HEX_DIGEST_LEN+1, id, DIGEST_LEN);
283 elt[HEX_DIGEST_LEN+1]= '~';
284 strlcpy(elt+HEX_DIGEST_LEN+2,
285 hop->extend_info->nickname, MAX_NICKNAME_LEN+1);
286 } else {
287 elt[0] = '$';
288 base16_encode(elt+1, HEX_DIGEST_LEN+1, id, DIGEST_LEN);
290 } else { /* ! verbose_names */
291 node = node_get_by_id(id);
292 if (node && node_is_named(node)) {
293 elt = tor_strdup(node_get_nickname(node));
294 } else {
295 elt = tor_malloc(HEX_DIGEST_LEN+2);
296 elt[0] = '$';
297 base16_encode(elt+1, HEX_DIGEST_LEN+1, id, DIGEST_LEN);
300 tor_assert(elt);
301 if (verbose) {
302 tor_assert(hop->state <= 2);
303 smartlist_add_asprintf(elements,"%s(%s)",elt,states[hop->state]);
304 tor_free(elt);
305 } else {
306 smartlist_add(elements, elt);
308 hop = hop->next;
309 } while (hop != circ->cpath);
311 s = smartlist_join_strings(elements, verbose?" ":",", 0, NULL);
312 SMARTLIST_FOREACH(elements, char*, cp, tor_free(cp));
313 smartlist_free(elements);
314 return s;
317 /** If <b>verbose</b> is false, allocate and return a comma-separated
318 * list of the currently built elements of <b>circ</b>. If
319 * <b>verbose</b> is true, also list information about link status in
320 * a more verbose format using spaces.
322 char *
323 circuit_list_path(origin_circuit_t *circ, int verbose)
325 return circuit_list_path_impl(circ, verbose, 0);
328 /** Allocate and return a comma-separated list of the currently built elements
329 * of <b>circ</b>, giving each as a verbose nickname.
331 char *
332 circuit_list_path_for_controller(origin_circuit_t *circ)
334 return circuit_list_path_impl(circ, 0, 1);
337 /** Log, at severity <b>severity</b>, the nicknames of each router in
338 * <b>circ</b>'s cpath. Also log the length of the cpath, and the intended
339 * exit point.
341 void
342 circuit_log_path(int severity, unsigned int domain, origin_circuit_t *circ)
344 char *s = circuit_list_path(circ,1);
345 tor_log(severity,domain,"%s",s);
346 tor_free(s);
349 /** Tell the rep(utation)hist(ory) module about the status of the links
350 * in <b>circ</b>. Hops that have become OPEN are marked as successfully
351 * extended; the _first_ hop that isn't open (if any) is marked as
352 * unable to extend.
354 /* XXXX Someday we should learn from OR circuits too. */
355 void
356 circuit_rep_hist_note_result(origin_circuit_t *circ)
358 crypt_path_t *hop;
359 const char *prev_digest = NULL;
360 hop = circ->cpath;
361 if (!hop) /* circuit hasn't started building yet. */
362 return;
363 if (server_mode(get_options())) {
364 const routerinfo_t *me = router_get_my_routerinfo();
365 if (!me)
366 return;
367 prev_digest = me->cache_info.identity_digest;
369 do {
370 const node_t *node = node_get_by_id(hop->extend_info->identity_digest);
371 if (node) { /* Why do we check this? We know the identity. -NM XXXX */
372 if (prev_digest) {
373 if (hop->state == CPATH_STATE_OPEN)
374 rep_hist_note_extend_succeeded(prev_digest, node->identity);
375 else {
376 rep_hist_note_extend_failed(prev_digest, node->identity);
377 break;
380 prev_digest = node->identity;
381 } else {
382 prev_digest = NULL;
384 hop=hop->next;
385 } while (hop!=circ->cpath);
388 /** Return 1 iff every node in circ's cpath definitely supports ntor. */
389 static int
390 circuit_cpath_supports_ntor(const origin_circuit_t *circ)
392 crypt_path_t *head, *cpath;
394 cpath = head = circ->cpath;
395 do {
396 /* if the extend_info is missing, we can't tell if it supports ntor */
397 if (!cpath->extend_info) {
398 return 0;
401 /* if the key is blank, it definitely doesn't support ntor */
402 if (!extend_info_supports_ntor(cpath->extend_info)) {
403 return 0;
405 cpath = cpath->next;
406 } while (cpath != head);
408 return 1;
411 /** Pick all the entries in our cpath. Stop and return 0 when we're
412 * happy, or return -1 if an error occurs. */
413 static int
414 onion_populate_cpath(origin_circuit_t *circ)
416 int r = 0;
418 /* onion_extend_cpath assumes these are non-NULL */
419 tor_assert(circ);
420 tor_assert(circ->build_state);
422 while (r == 0) {
423 r = onion_extend_cpath(circ);
424 if (r < 0) {
425 log_info(LD_CIRC,"Generating cpath hop failed.");
426 return -1;
430 /* The path is complete */
431 tor_assert(r == 1);
433 /* Does every node in this path support ntor? */
434 int path_supports_ntor = circuit_cpath_supports_ntor(circ);
436 /* We would like every path to support ntor, but we have to allow for some
437 * edge cases. */
438 tor_assert(circuit_get_cpath_len(circ));
439 if (circuit_can_use_tap(circ)) {
440 /* Circuits from clients to intro points, and hidden services to
441 * rend points do not support ntor, because the hidden service protocol
442 * does not include ntor onion keys. This is also true for Tor2web clients
443 * and Single Onion Services. */
444 return 0;
447 if (circuit_get_cpath_len(circ) == 1) {
448 /* Allow for bootstrapping: when we're fetching directly from a fallback,
449 * authority, or bridge, we have no way of knowing its ntor onion key
450 * before we connect to it. So instead, we try connecting, and end up using
451 * CREATE_FAST. */
452 tor_assert(circ->cpath);
453 tor_assert(circ->cpath->extend_info);
454 const node_t *node = node_get_by_id(
455 circ->cpath->extend_info->identity_digest);
456 /* If we don't know the node and its descriptor, we must be bootstrapping.
458 if (!node || !node_has_descriptor(node)) {
459 return 0;
463 if (BUG(!path_supports_ntor)) {
464 /* If we're building a multi-hop path, and it's not one of the HS or
465 * bootstrapping exceptions, and it doesn't support ntor, something has
466 * gone wrong. */
467 return -1;
470 return 0;
473 /** Create and return a new origin circuit. Initialize its purpose and
474 * build-state based on our arguments. The <b>flags</b> argument is a
475 * bitfield of CIRCLAUNCH_* flags. */
476 origin_circuit_t *
477 origin_circuit_init(uint8_t purpose, int flags)
479 /* sets circ->p_circ_id and circ->p_chan */
480 origin_circuit_t *circ = origin_circuit_new();
481 circuit_set_state(TO_CIRCUIT(circ), CIRCUIT_STATE_CHAN_WAIT);
482 circ->build_state = tor_malloc_zero(sizeof(cpath_build_state_t));
483 circ->build_state->onehop_tunnel =
484 ((flags & CIRCLAUNCH_ONEHOP_TUNNEL) ? 1 : 0);
485 circ->build_state->need_uptime =
486 ((flags & CIRCLAUNCH_NEED_UPTIME) ? 1 : 0);
487 circ->build_state->need_capacity =
488 ((flags & CIRCLAUNCH_NEED_CAPACITY) ? 1 : 0);
489 circ->build_state->is_internal =
490 ((flags & CIRCLAUNCH_IS_INTERNAL) ? 1 : 0);
491 circ->base_.purpose = purpose;
492 return circ;
495 /** Build a new circuit for <b>purpose</b>. If <b>exit</b>
496 * is defined, then use that as your exit router, else choose a suitable
497 * exit node.
499 * Also launch a connection to the first OR in the chosen path, if
500 * it's not open already.
502 origin_circuit_t *
503 circuit_establish_circuit(uint8_t purpose, extend_info_t *exit_ei, int flags)
505 origin_circuit_t *circ;
506 int err_reason = 0;
508 circ = origin_circuit_init(purpose, flags);
510 if (onion_pick_cpath_exit(circ, exit_ei) < 0 ||
511 onion_populate_cpath(circ) < 0) {
512 circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_NOPATH);
513 return NULL;
516 control_event_circuit_status(circ, CIRC_EVENT_LAUNCHED, 0);
518 if ((err_reason = circuit_handle_first_hop(circ)) < 0) {
519 circuit_mark_for_close(TO_CIRCUIT(circ), -err_reason);
520 return NULL;
522 return circ;
525 /** Return the guard state associated with <b>circ</b>, which may be NULL. */
526 circuit_guard_state_t *
527 origin_circuit_get_guard_state(origin_circuit_t *circ)
529 return circ->guard_state;
532 /** Start establishing the first hop of our circuit. Figure out what
533 * OR we should connect to, and if necessary start the connection to
534 * it. If we're already connected, then send the 'create' cell.
535 * Return 0 for ok, -reason if circ should be marked-for-close. */
537 circuit_handle_first_hop(origin_circuit_t *circ)
539 crypt_path_t *firsthop;
540 channel_t *n_chan;
541 int err_reason = 0;
542 const char *msg = NULL;
543 int should_launch = 0;
544 const or_options_t *options = get_options();
546 firsthop = onion_next_hop_in_cpath(circ->cpath);
547 tor_assert(firsthop);
548 tor_assert(firsthop->extend_info);
550 /* Some bridges are on private addresses. Others pass a dummy private
551 * address to the pluggable transport, which ignores it.
552 * Deny the connection if:
553 * - the address is internal, and
554 * - we're not connecting to a configured bridge, and
555 * - we're not configured to allow extends to private addresses. */
556 if (tor_addr_is_internal(&firsthop->extend_info->addr, 0) &&
557 !extend_info_is_a_configured_bridge(firsthop->extend_info) &&
558 !options->ExtendAllowPrivateAddresses) {
559 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
560 "Client asked me to connect directly to a private address");
561 return -END_CIRC_REASON_TORPROTOCOL;
564 /* now see if we're already connected to the first OR in 'route' */
565 log_debug(LD_CIRC,"Looking for firsthop '%s'",
566 fmt_addrport(&firsthop->extend_info->addr,
567 firsthop->extend_info->port));
569 n_chan = channel_get_for_extend(firsthop->extend_info->identity_digest,
570 &firsthop->extend_info->ed_identity,
571 &firsthop->extend_info->addr,
572 &msg,
573 &should_launch);
575 if (!n_chan) {
576 /* not currently connected in a useful way. */
577 log_info(LD_CIRC, "Next router is %s: %s",
578 safe_str_client(extend_info_describe(firsthop->extend_info)),
579 msg?msg:"???");
580 circ->base_.n_hop = extend_info_dup(firsthop->extend_info);
582 if (should_launch) {
583 if (circ->build_state->onehop_tunnel)
584 control_event_bootstrap(BOOTSTRAP_STATUS_CONN_DIR, 0);
585 n_chan = channel_connect_for_circuit(
586 &firsthop->extend_info->addr,
587 firsthop->extend_info->port,
588 firsthop->extend_info->identity_digest,
589 &firsthop->extend_info->ed_identity);
590 if (!n_chan) { /* connect failed, forget the whole thing */
591 log_info(LD_CIRC,"connect to firsthop failed. Closing.");
592 return -END_CIRC_REASON_CONNECTFAILED;
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 log_debug(LD_CIRC,"Conn open. Delivering first onion skin.");
606 if ((err_reason = circuit_send_next_onion_skin(circ)) < 0) {
607 log_info(LD_CIRC,"circuit_send_next_onion_skin failed.");
608 circ->base_.n_chan = NULL;
609 return err_reason;
612 return 0;
615 /** Find any circuits that are waiting on <b>or_conn</b> to become
616 * open and get them to send their create cells forward.
618 * Status is 1 if connect succeeded, or 0 if connect failed.
620 * Close_origin_circuits is 1 if we should close all the origin circuits
621 * through this channel, or 0 otherwise. (This happens when we want to retry
622 * an older guard.)
624 void
625 circuit_n_chan_done(channel_t *chan, int status, int close_origin_circuits)
627 smartlist_t *pending_circs;
628 int err_reason = 0;
630 tor_assert(chan);
632 log_debug(LD_CIRC,"chan to %s/%s, status=%d",
633 chan->nickname ? chan->nickname : "NULL",
634 channel_get_canonical_remote_descr(chan), status);
636 pending_circs = smartlist_new();
637 circuit_get_all_pending_on_channel(pending_circs, chan);
639 SMARTLIST_FOREACH_BEGIN(pending_circs, circuit_t *, circ)
641 /* These checks are redundant wrt get_all_pending_on_or_conn, but I'm
642 * leaving them in in case it's possible for the status of a circuit to
643 * change as we're going down the list. */
644 if (circ->marked_for_close || circ->n_chan || !circ->n_hop ||
645 circ->state != CIRCUIT_STATE_CHAN_WAIT)
646 continue;
648 if (tor_digest_is_zero(circ->n_hop->identity_digest)) {
649 /* Look at addr/port. This is an unkeyed connection. */
650 if (!channel_matches_extend_info(chan, circ->n_hop))
651 continue;
652 } else {
653 /* We expected a key. See if it's the right one. */
654 if (tor_memneq(chan->identity_digest,
655 circ->n_hop->identity_digest, DIGEST_LEN))
656 continue;
658 if (!status) { /* chan failed; close circ */
659 log_info(LD_CIRC,"Channel failed; closing circ.");
660 circuit_mark_for_close(circ, END_CIRC_REASON_CHANNEL_CLOSED);
661 continue;
663 if (close_origin_circuits && CIRCUIT_IS_ORIGIN(circ)) {
664 log_info(LD_CIRC,"Channel deprecated for origin circs; closing circ.");
665 circuit_mark_for_close(circ, END_CIRC_REASON_CHANNEL_CLOSED);
666 continue;
668 log_debug(LD_CIRC, "Found circ, sending create cell.");
669 /* circuit_deliver_create_cell will set n_circ_id and add us to
670 * chan_circuid_circuit_map, so we don't need to call
671 * set_circid_chan here. */
672 circ->n_chan = chan;
673 extend_info_free(circ->n_hop);
674 circ->n_hop = NULL;
676 if (CIRCUIT_IS_ORIGIN(circ)) {
677 if ((err_reason =
678 circuit_send_next_onion_skin(TO_ORIGIN_CIRCUIT(circ))) < 0) {
679 log_info(LD_CIRC,
680 "send_next_onion_skin failed; circuit marked for closing.");
681 circuit_mark_for_close(circ, -err_reason);
682 continue;
683 /* XXX could this be bad, eg if next_onion_skin failed because conn
684 * died? */
686 } else {
687 /* pull the create cell out of circ->n_chan_create_cell, and send it */
688 tor_assert(circ->n_chan_create_cell);
689 if (circuit_deliver_create_cell(circ, circ->n_chan_create_cell, 1)<0) {
690 circuit_mark_for_close(circ, END_CIRC_REASON_RESOURCELIMIT);
691 continue;
693 tor_free(circ->n_chan_create_cell);
694 circuit_set_state(circ, CIRCUIT_STATE_OPEN);
697 SMARTLIST_FOREACH_END(circ);
699 smartlist_free(pending_circs);
702 /** Find a new circid that isn't currently in use on the circ->n_chan
703 * for the outgoing
704 * circuit <b>circ</b>, and deliver the cell <b>create_cell</b> to this
705 * circuit. If <b>relayed</b> is true, this is a create cell somebody
706 * gave us via an EXTEND cell, so we shouldn't worry if we don't understand
707 * it. Return -1 if we failed to find a suitable circid, else return 0.
709 static int
710 circuit_deliver_create_cell(circuit_t *circ, const create_cell_t *create_cell,
711 int relayed)
713 cell_t cell;
714 circid_t id;
715 int r;
717 tor_assert(circ);
718 tor_assert(circ->n_chan);
719 tor_assert(create_cell);
720 tor_assert(create_cell->cell_type == CELL_CREATE ||
721 create_cell->cell_type == CELL_CREATE_FAST ||
722 create_cell->cell_type == CELL_CREATE2);
724 id = get_unique_circ_id_by_chan(circ->n_chan);
725 if (!id) {
726 static ratelim_t circid_warning_limit = RATELIM_INIT(9600);
727 log_fn_ratelim(&circid_warning_limit, LOG_WARN, LD_CIRC,
728 "failed to get unique circID.");
729 goto error;
732 memset(&cell, 0, sizeof(cell_t));
733 r = relayed ? create_cell_format_relayed(&cell, create_cell)
734 : create_cell_format(&cell, create_cell);
735 if (r < 0) {
736 log_warn(LD_CIRC,"Couldn't format create cell");
737 goto error;
739 log_debug(LD_CIRC,"Chosen circID %u.", (unsigned)id);
740 circuit_set_n_circid_chan(circ, id, circ->n_chan);
741 cell.circ_id = circ->n_circ_id;
743 append_cell_to_circuit_queue(circ, circ->n_chan, &cell,
744 CELL_DIRECTION_OUT, 0);
746 if (CIRCUIT_IS_ORIGIN(circ)) {
747 /* Update began timestamp for circuits starting their first hop */
748 if (TO_ORIGIN_CIRCUIT(circ)->cpath->state == CPATH_STATE_CLOSED) {
749 if (!CHANNEL_IS_OPEN(circ->n_chan)) {
750 log_warn(LD_CIRC,
751 "Got first hop for a circuit without an opened channel. "
752 "State: %s.", channel_state_to_string(circ->n_chan->state));
753 tor_fragile_assert();
756 tor_gettimeofday(&circ->timestamp_began);
759 /* mark it so it gets better rate limiting treatment. */
760 channel_timestamp_client(circ->n_chan);
763 return 0;
764 error:
765 circ->n_chan = NULL;
766 return -1;
769 /** We've decided to start our reachability testing. If all
770 * is set, log this to the user. Return 1 if we did, or 0 if
771 * we chose not to log anything. */
773 inform_testing_reachability(void)
775 char dirbuf[128];
776 char *address;
777 const routerinfo_t *me = router_get_my_routerinfo();
778 if (!me)
779 return 0;
780 address = tor_dup_ip(me->addr);
781 control_event_server_status(LOG_NOTICE,
782 "CHECKING_REACHABILITY ORADDRESS=%s:%d",
783 address, me->or_port);
784 if (me->dir_port) {
785 tor_snprintf(dirbuf, sizeof(dirbuf), " and DirPort %s:%d",
786 address, me->dir_port);
787 control_event_server_status(LOG_NOTICE,
788 "CHECKING_REACHABILITY DIRADDRESS=%s:%d",
789 address, me->dir_port);
791 log_notice(LD_OR, "Now checking whether ORPort %s:%d%s %s reachable... "
792 "(this may take up to %d minutes -- look for log "
793 "messages indicating success)",
794 address, me->or_port,
795 me->dir_port ? dirbuf : "",
796 me->dir_port ? "are" : "is",
797 TIMEOUT_UNTIL_UNREACHABILITY_COMPLAINT/60);
799 tor_free(address);
800 return 1;
803 /** Return true iff we should send a create_fast cell to start building a given
804 * circuit */
805 static inline int
806 should_use_create_fast_for_circuit(origin_circuit_t *circ)
808 const or_options_t *options = get_options();
809 tor_assert(circ->cpath);
810 tor_assert(circ->cpath->extend_info);
812 if (!circuit_has_usable_onion_key(circ)) {
813 /* We don't have ntor, and we don't have or can't use TAP,
814 * so our hand is forced: only a create_fast will work. */
815 return 1;
817 if (public_server_mode(options)) {
818 /* We're a server, and we have a usable onion key. We can choose.
819 * Prefer to blend our circuit into the other circuits we are
820 * creating on behalf of others. */
821 return 0;
823 return networkstatus_get_param(NULL, "usecreatefast", 0, 0, 1);
826 /** Return true if <b>circ</b> is the type of circuit we want to count
827 * timeouts from. In particular, we want it to have not completed yet
828 * (already completing indicates we cannibalized it), and we want it to
829 * have exactly three hops.
832 circuit_timeout_want_to_count_circ(origin_circuit_t *circ)
834 return !circ->has_opened
835 && circ->build_state->desired_path_len == DEFAULT_ROUTE_LEN;
838 /** Decide whether to use a TAP or ntor handshake for connecting to <b>ei</b>
839 * directly, and set *<b>cell_type_out</b> and *<b>handshake_type_out</b>
840 * accordingly.
841 * Note that TAP handshakes in CREATE cells are only used for direct
842 * connections:
843 * - from Tor2web to intro points not in the client's consensus, and
844 * - from Single Onions to rend points not in the service's consensus.
845 * This is checked in onion_populate_cpath. */
846 static void
847 circuit_pick_create_handshake(uint8_t *cell_type_out,
848 uint16_t *handshake_type_out,
849 const extend_info_t *ei)
851 /* torspec says: In general, clients SHOULD use CREATE whenever they are
852 * using the TAP handshake, and CREATE2 otherwise. */
853 if (extend_info_supports_ntor(ei)) {
854 *cell_type_out = CELL_CREATE2;
855 *handshake_type_out = ONION_HANDSHAKE_TYPE_NTOR;
856 } else {
857 /* XXXX030 Remove support for deciding to use TAP and EXTEND. */
858 *cell_type_out = CELL_CREATE;
859 *handshake_type_out = ONION_HANDSHAKE_TYPE_TAP;
863 /** Decide whether to use a TAP or ntor handshake for extending to <b>ei</b>
864 * and set *<b>handshake_type_out</b> accordingly. Decide whether we should
865 * use an EXTEND2 or an EXTEND cell to do so, and set *<b>cell_type_out</b>
866 * and *<b>create_cell_type_out</b> accordingly.
867 * Note that TAP handshakes in EXTEND cells are only used:
868 * - from clients to intro points, and
869 * - from hidden services to rend points.
870 * This is checked in onion_populate_cpath.
872 static void
873 circuit_pick_extend_handshake(uint8_t *cell_type_out,
874 uint8_t *create_cell_type_out,
875 uint16_t *handshake_type_out,
876 const extend_info_t *ei)
878 uint8_t t;
879 circuit_pick_create_handshake(&t, handshake_type_out, ei);
881 /* torspec says: Clients SHOULD use the EXTEND format whenever sending a TAP
882 * handshake... In other cases, clients SHOULD use EXTEND2. */
883 if (*handshake_type_out != ONION_HANDSHAKE_TYPE_TAP) {
884 *cell_type_out = RELAY_COMMAND_EXTEND2;
885 *create_cell_type_out = CELL_CREATE2;
886 } else {
887 /* XXXX030 Remove support for deciding to use TAP and EXTEND. */
888 *cell_type_out = RELAY_COMMAND_EXTEND;
889 *create_cell_type_out = CELL_CREATE;
894 * Return true iff <b>purpose</b> is a purpose for a circuit which is
895 * allowed to have no guard configured, even if the circuit is multihop
896 * and guards are enabled.
898 static int
899 circuit_purpose_may_omit_guard(int purpose)
901 switch (purpose) {
902 case CIRCUIT_PURPOSE_TESTING:
903 case CIRCUIT_PURPOSE_C_MEASURE_TIMEOUT:
904 /* Testing circuits may omit guards because they're measuring
905 * liveness or performance, and don't want guards to interfere. */
906 return 1;
907 default:
908 /* All other multihop circuits should use guards if guards are
909 * enabled. */
910 return 0;
914 /** This is the backbone function for building circuits.
916 * If circ's first hop is closed, then we need to build a create
917 * cell and send it forward.
919 * Otherwise, we need to build a relay extend cell and send it
920 * forward.
922 * Return -reason if we want to tear down circ, else return 0.
925 circuit_send_next_onion_skin(origin_circuit_t *circ)
928 tor_assert(circ);
930 if (circ->cpath->state == CPATH_STATE_CLOSED) {
931 return circuit_send_first_onion_skin(circ);
932 } else {
933 tor_assert(circ->cpath->state == CPATH_STATE_OPEN);
934 tor_assert(circ->base_.state == CIRCUIT_STATE_BUILDING);
935 log_debug(LD_CIRC,"starting to send subsequent skin.");
936 crypt_path_t *hop = onion_next_hop_in_cpath(circ->cpath);
937 if (!hop) {
938 return circuit_build_no_more_hops(circ);
939 } else {
940 return circuit_send_intermediate_onion_skin(circ, hop);
945 static int
946 circuit_send_first_onion_skin(origin_circuit_t *circ)
948 const node_t *node;
949 /* This is the first hop. */
950 create_cell_t cc;
951 int fast;
952 int len;
953 log_debug(LD_CIRC,"First skin; sending create cell.");
954 memset(&cc, 0, sizeof(cc));
955 if (circ->build_state->onehop_tunnel)
956 control_event_bootstrap(BOOTSTRAP_STATUS_ONEHOP_CREATE, 0);
957 else {
958 control_event_bootstrap(BOOTSTRAP_STATUS_CIRCUIT_CREATE, 0);
960 /* If this is not a one-hop tunnel, the channel is being used
961 * for traffic that wants anonymity and protection from traffic
962 * analysis (such as netflow record retention). That means we want
963 * to pad it.
965 if (circ->base_.n_chan->channel_usage < CHANNEL_USED_FOR_FULL_CIRCS)
966 circ->base_.n_chan->channel_usage = CHANNEL_USED_FOR_FULL_CIRCS;
969 node = node_get_by_id(circ->base_.n_chan->identity_digest);
970 fast = should_use_create_fast_for_circuit(circ);
971 if (!fast) {
972 /* We are an OR and we know the right onion key: we should
973 * send a create cell.
975 circuit_pick_create_handshake(&cc.cell_type, &cc.handshake_type,
976 circ->cpath->extend_info);
977 } else {
978 /* We are not an OR, and we're building the first hop of a circuit to a
979 * new OR: we can be speedy and use CREATE_FAST to save an RSA operation
980 * and a DH operation. */
981 cc.cell_type = CELL_CREATE_FAST;
982 cc.handshake_type = ONION_HANDSHAKE_TYPE_FAST;
985 len = onion_skin_create(cc.handshake_type,
986 circ->cpath->extend_info,
987 &circ->cpath->handshake_state,
988 cc.onionskin);
989 if (len < 0) {
990 log_warn(LD_CIRC,"onion_skin_create (first hop) failed.");
991 return - END_CIRC_REASON_INTERNAL;
993 cc.handshake_len = len;
995 if (circuit_deliver_create_cell(TO_CIRCUIT(circ), &cc, 0) < 0)
996 return - END_CIRC_REASON_RESOURCELIMIT;
998 circ->cpath->state = CPATH_STATE_AWAITING_KEYS;
999 circuit_set_state(TO_CIRCUIT(circ), CIRCUIT_STATE_BUILDING);
1000 log_info(LD_CIRC,"First hop: finished sending %s cell to '%s'",
1001 fast ? "CREATE_FAST" : "CREATE",
1002 node ? node_describe(node) : "<unnamed>");
1003 return 0;
1006 static int
1007 circuit_build_no_more_hops(origin_circuit_t *circ)
1009 /* done building the circuit. whew. */
1010 guard_usable_t r;
1011 if (! circ->guard_state) {
1012 if (circuit_get_cpath_len(circ) != 1 &&
1013 ! circuit_purpose_may_omit_guard(circ->base_.purpose) &&
1014 get_options()->UseEntryGuards) {
1015 log_warn(LD_BUG, "%d-hop circuit %p with purpose %d has no "
1016 "guard state",
1017 circuit_get_cpath_len(circ), circ, circ->base_.purpose);
1019 r = GUARD_USABLE_NOW;
1020 } else {
1021 r = entry_guard_succeeded(&circ->guard_state);
1023 const int is_usable_for_streams = (r == GUARD_USABLE_NOW);
1024 if (r == GUARD_USABLE_NOW) {
1025 circuit_set_state(TO_CIRCUIT(circ), CIRCUIT_STATE_OPEN);
1026 } else if (r == GUARD_MAYBE_USABLE_LATER) {
1027 // Wait till either a better guard succeeds, or till
1028 // all better guards fail.
1029 circuit_set_state(TO_CIRCUIT(circ), CIRCUIT_STATE_GUARD_WAIT);
1030 } else {
1031 tor_assert_nonfatal(r == GUARD_USABLE_NEVER);
1032 return - END_CIRC_REASON_INTERNAL;
1035 /* XXXX #21422 -- the rest of this branch needs careful thought!
1036 * Some of the things here need to happen when a circuit becomes
1037 * mechanically open; some need to happen when it is actually usable.
1038 * I think I got them right, but more checking would be wise. -NM
1041 if (circuit_timeout_want_to_count_circ(circ)) {
1042 struct timeval end;
1043 long timediff;
1044 tor_gettimeofday(&end);
1045 timediff = tv_mdiff(&circ->base_.timestamp_began, &end);
1048 * If the circuit build time is much greater than we would have cut
1049 * it off at, we probably had a suspend event along this codepath,
1050 * and we should discard the value.
1052 if (timediff < 0 ||
1053 timediff > 2*get_circuit_build_close_time_ms()+1000) {
1054 log_notice(LD_CIRC, "Strange value for circuit build time: %ldmsec. "
1055 "Assuming clock jump. Purpose %d (%s)", timediff,
1056 circ->base_.purpose,
1057 circuit_purpose_to_string(circ->base_.purpose));
1058 } else if (!circuit_build_times_disabled(get_options())) {
1059 /* Only count circuit times if the network is live */
1060 if (circuit_build_times_network_check_live(
1061 get_circuit_build_times())) {
1062 circuit_build_times_add_time(get_circuit_build_times_mutable(),
1063 (build_time_t)timediff);
1064 circuit_build_times_set_timeout(get_circuit_build_times_mutable());
1067 if (circ->base_.purpose != CIRCUIT_PURPOSE_C_MEASURE_TIMEOUT) {
1068 circuit_build_times_network_circ_success(
1069 get_circuit_build_times_mutable());
1073 log_info(LD_CIRC,"circuit built!");
1074 circuit_reset_failure_count(0);
1076 if (circ->build_state->onehop_tunnel || circ->has_opened) {
1077 control_event_bootstrap(BOOTSTRAP_STATUS_REQUESTING_STATUS, 0);
1080 pathbias_count_build_success(circ);
1081 circuit_rep_hist_note_result(circ);
1082 if (is_usable_for_streams)
1083 circuit_has_opened(circ); /* do other actions as necessary */
1085 if (!have_completed_a_circuit() && !circ->build_state->onehop_tunnel) {
1086 const or_options_t *options = get_options();
1087 note_that_we_completed_a_circuit();
1088 /* FFFF Log a count of known routers here */
1089 log_notice(LD_GENERAL,
1090 "Tor has successfully opened a circuit. "
1091 "Looks like client functionality is working.");
1092 if (control_event_bootstrap(BOOTSTRAP_STATUS_DONE, 0) == 0) {
1093 log_notice(LD_GENERAL,
1094 "Tor has successfully opened a circuit. "
1095 "Looks like client functionality is working.");
1097 control_event_client_status(LOG_NOTICE, "CIRCUIT_ESTABLISHED");
1098 clear_broken_connection_map(1);
1099 if (server_mode(options) && !check_whether_orport_reachable(options)) {
1100 inform_testing_reachability();
1101 consider_testing_reachability(1, 1);
1105 /* We're done with measurement circuits here. Just close them */
1106 if (circ->base_.purpose == CIRCUIT_PURPOSE_C_MEASURE_TIMEOUT) {
1107 circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_FINISHED);
1109 return 0;
1112 static int
1113 circuit_send_intermediate_onion_skin(origin_circuit_t *circ,
1114 crypt_path_t *hop)
1116 extend_cell_t ec;
1117 int len;
1118 memset(&ec, 0, sizeof(ec));
1119 if (tor_addr_family(&hop->extend_info->addr) != AF_INET) {
1120 log_warn(LD_BUG, "Trying to extend to a non-IPv4 address.");
1121 return - END_CIRC_REASON_INTERNAL;
1124 circuit_pick_extend_handshake(&ec.cell_type,
1125 &ec.create_cell.cell_type,
1126 &ec.create_cell.handshake_type,
1127 hop->extend_info);
1129 tor_addr_copy(&ec.orport_ipv4.addr, &hop->extend_info->addr);
1130 ec.orport_ipv4.port = hop->extend_info->port;
1131 tor_addr_make_unspec(&ec.orport_ipv6.addr);
1132 memcpy(ec.node_id, hop->extend_info->identity_digest, DIGEST_LEN);
1133 /* Set the ED25519 identity too -- it will only get included
1134 * in the extend2 cell if we're configured to use it, though. */
1135 ed25519_pubkey_copy(&ec.ed_pubkey, &hop->extend_info->ed_identity);
1137 len = onion_skin_create(ec.create_cell.handshake_type,
1138 hop->extend_info,
1139 &hop->handshake_state,
1140 ec.create_cell.onionskin);
1141 if (len < 0) {
1142 log_warn(LD_CIRC,"onion_skin_create failed.");
1143 return - END_CIRC_REASON_INTERNAL;
1145 ec.create_cell.handshake_len = len;
1147 log_info(LD_CIRC,"Sending extend relay cell.");
1149 uint8_t command = 0;
1150 uint16_t payload_len=0;
1151 uint8_t payload[RELAY_PAYLOAD_SIZE];
1152 if (extend_cell_format(&command, &payload_len, payload, &ec)<0) {
1153 log_warn(LD_CIRC,"Couldn't format extend cell");
1154 return -END_CIRC_REASON_INTERNAL;
1157 /* send it to hop->prev, because it will transfer
1158 * it to a create cell and then send to hop */
1159 if (relay_send_command_from_edge(0, TO_CIRCUIT(circ),
1160 command,
1161 (char*)payload, payload_len,
1162 hop->prev) < 0)
1163 return 0; /* circuit is closed */
1165 hop->state = CPATH_STATE_AWAITING_KEYS;
1166 return 0;
1169 /** Our clock just jumped by <b>seconds_elapsed</b>. Assume
1170 * something has also gone wrong with our network: notify the user,
1171 * and abandon all not-yet-used circuits. */
1172 void
1173 circuit_note_clock_jumped(int seconds_elapsed)
1175 int severity = server_mode(get_options()) ? LOG_WARN : LOG_NOTICE;
1176 tor_log(severity, LD_GENERAL, "Your system clock just jumped %d seconds %s; "
1177 "assuming established circuits no longer work.",
1178 seconds_elapsed >=0 ? seconds_elapsed : -seconds_elapsed,
1179 seconds_elapsed >=0 ? "forward" : "backward");
1180 control_event_general_status(LOG_WARN, "CLOCK_JUMPED TIME=%d",
1181 seconds_elapsed);
1182 /* so we log when it works again */
1183 note_that_we_maybe_cant_complete_circuits();
1184 control_event_client_status(severity, "CIRCUIT_NOT_ESTABLISHED REASON=%s",
1185 "CLOCK_JUMPED");
1186 circuit_mark_all_unused_circs();
1187 circuit_mark_all_dirty_circs_as_unusable();
1188 if (seconds_elapsed < 0) {
1189 /* Restart all the timers in case we jumped a long way into the past. */
1190 reset_all_main_loop_timers();
1194 /** Take the 'extend' <b>cell</b>, pull out addr/port plus the onion
1195 * skin and identity digest for the next hop. If we're already connected,
1196 * pass the onion skin to the next hop using a create cell; otherwise
1197 * launch a new OR connection, and <b>circ</b> will notice when the
1198 * connection succeeds or fails.
1200 * Return -1 if we want to warn and tear down the circuit, else return 0.
1203 circuit_extend(cell_t *cell, circuit_t *circ)
1205 channel_t *n_chan;
1206 relay_header_t rh;
1207 extend_cell_t ec;
1208 const char *msg = NULL;
1209 int should_launch = 0;
1211 if (circ->n_chan) {
1212 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
1213 "n_chan already set. Bug/attack. Closing.");
1214 return -1;
1216 if (circ->n_hop) {
1217 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
1218 "conn to next hop already launched. Bug/attack. Closing.");
1219 return -1;
1222 if (!server_mode(get_options())) {
1223 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
1224 "Got an extend cell, but running as a client. Closing.");
1225 return -1;
1228 relay_header_unpack(&rh, cell->payload);
1230 if (extend_cell_parse(&ec, rh.command,
1231 cell->payload+RELAY_HEADER_SIZE,
1232 rh.length) < 0) {
1233 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
1234 "Can't parse extend cell. Closing circuit.");
1235 return -1;
1238 if (!ec.orport_ipv4.port || tor_addr_is_null(&ec.orport_ipv4.addr)) {
1239 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
1240 "Client asked me to extend to zero destination port or addr.");
1241 return -1;
1244 if (tor_addr_is_internal(&ec.orport_ipv4.addr, 0) &&
1245 !get_options()->ExtendAllowPrivateAddresses) {
1246 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
1247 "Client asked me to extend to a private address");
1248 return -1;
1251 /* Check if they asked us for 0000..0000. We support using
1252 * an empty fingerprint for the first hop (e.g. for a bridge relay),
1253 * but we don't want to let clients send us extend cells for empty
1254 * fingerprints -- a) because it opens the user up to a mitm attack,
1255 * and b) because it lets an attacker force the relay to hold open a
1256 * new TLS connection for each extend request. */
1257 if (tor_digest_is_zero((const char*)ec.node_id)) {
1258 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
1259 "Client asked me to extend without specifying an id_digest.");
1260 return -1;
1263 /* Fill in ed_pubkey if it was not provided and we can infer it from
1264 * our networkstatus */
1265 if (ed25519_public_key_is_zero(&ec.ed_pubkey)) {
1266 const node_t *node = node_get_by_id((const char*)ec.node_id);
1267 const ed25519_public_key_t *node_ed_id = NULL;
1268 if (node &&
1269 node_supports_ed25519_link_authentication(node) &&
1270 (node_ed_id = node_get_ed25519_id(node))) {
1271 ed25519_pubkey_copy(&ec.ed_pubkey, node_ed_id);
1275 /* Next, check if we're being asked to connect to the hop that the
1276 * extend cell came from. There isn't any reason for that, and it can
1277 * assist circular-path attacks. */
1278 if (tor_memeq(ec.node_id,
1279 TO_OR_CIRCUIT(circ)->p_chan->identity_digest,
1280 DIGEST_LEN)) {
1281 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
1282 "Client asked me to extend back to the previous hop.");
1283 return -1;
1286 /* Check the previous hop Ed25519 ID too */
1287 if (! ed25519_public_key_is_zero(&ec.ed_pubkey) &&
1288 ed25519_pubkey_eq(&ec.ed_pubkey,
1289 &TO_OR_CIRCUIT(circ)->p_chan->ed25519_identity)) {
1290 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
1291 "Client asked me to extend back to the previous hop "
1292 "(by Ed25519 ID).");
1295 n_chan = channel_get_for_extend((const char*)ec.node_id,
1296 &ec.ed_pubkey,
1297 &ec.orport_ipv4.addr,
1298 &msg,
1299 &should_launch);
1301 if (!n_chan) {
1302 log_debug(LD_CIRC|LD_OR,"Next router (%s): %s",
1303 fmt_addrport(&ec.orport_ipv4.addr,ec.orport_ipv4.port),
1304 msg?msg:"????");
1306 circ->n_hop = extend_info_new(NULL /*nickname*/,
1307 (const char*)ec.node_id,
1308 &ec.ed_pubkey,
1309 NULL, /*onion_key*/
1310 NULL, /*curve25519_key*/
1311 &ec.orport_ipv4.addr,
1312 ec.orport_ipv4.port);
1314 circ->n_chan_create_cell = tor_memdup(&ec.create_cell,
1315 sizeof(ec.create_cell));
1317 circuit_set_state(circ, CIRCUIT_STATE_CHAN_WAIT);
1319 if (should_launch) {
1320 /* we should try to open a connection */
1321 n_chan = channel_connect_for_circuit(&ec.orport_ipv4.addr,
1322 ec.orport_ipv4.port,
1323 (const char*)ec.node_id,
1324 &ec.ed_pubkey);
1325 if (!n_chan) {
1326 log_info(LD_CIRC,"Launching n_chan failed. Closing circuit.");
1327 circuit_mark_for_close(circ, END_CIRC_REASON_CONNECTFAILED);
1328 return 0;
1330 log_debug(LD_CIRC,"connecting in progress (or finished). Good.");
1332 /* return success. The onion/circuit/etc will be taken care of
1333 * automatically (may already have been) whenever n_chan reaches
1334 * OR_CONN_STATE_OPEN.
1336 return 0;
1339 tor_assert(!circ->n_hop); /* Connection is already established. */
1340 circ->n_chan = n_chan;
1341 log_debug(LD_CIRC,
1342 "n_chan is %s",
1343 channel_get_canonical_remote_descr(n_chan));
1345 if (circuit_deliver_create_cell(circ, &ec.create_cell, 1) < 0)
1346 return -1;
1348 return 0;
1351 /** Initialize cpath-\>{f|b}_{crypto|digest} from the key material in
1352 * key_data. key_data must contain CPATH_KEY_MATERIAL bytes, which are
1353 * used as follows:
1354 * - 20 to initialize f_digest
1355 * - 20 to initialize b_digest
1356 * - 16 to key f_crypto
1357 * - 16 to key b_crypto
1359 * (If 'reverse' is true, then f_XX and b_XX are swapped.)
1362 circuit_init_cpath_crypto(crypt_path_t *cpath, const char *key_data,
1363 int reverse)
1365 crypto_digest_t *tmp_digest;
1366 crypto_cipher_t *tmp_crypto;
1368 tor_assert(cpath);
1369 tor_assert(key_data);
1370 tor_assert(!(cpath->f_crypto || cpath->b_crypto ||
1371 cpath->f_digest || cpath->b_digest));
1373 cpath->f_digest = crypto_digest_new();
1374 crypto_digest_add_bytes(cpath->f_digest, key_data, DIGEST_LEN);
1375 cpath->b_digest = crypto_digest_new();
1376 crypto_digest_add_bytes(cpath->b_digest, key_data+DIGEST_LEN, DIGEST_LEN);
1378 if (!(cpath->f_crypto =
1379 crypto_cipher_new(key_data+(2*DIGEST_LEN)))) {
1380 log_warn(LD_BUG,"Forward cipher initialization failed.");
1381 return -1;
1383 if (!(cpath->b_crypto =
1384 crypto_cipher_new(key_data+(2*DIGEST_LEN)+CIPHER_KEY_LEN))) {
1385 log_warn(LD_BUG,"Backward cipher initialization failed.");
1386 return -1;
1389 if (reverse) {
1390 tmp_digest = cpath->f_digest;
1391 cpath->f_digest = cpath->b_digest;
1392 cpath->b_digest = tmp_digest;
1393 tmp_crypto = cpath->f_crypto;
1394 cpath->f_crypto = cpath->b_crypto;
1395 cpath->b_crypto = tmp_crypto;
1398 return 0;
1401 /** A "created" cell <b>reply</b> came back to us on circuit <b>circ</b>.
1402 * (The body of <b>reply</b> varies depending on what sort of handshake
1403 * this is.)
1405 * Calculate the appropriate keys and digests, make sure KH is
1406 * correct, and initialize this hop of the cpath.
1408 * Return - reason if we want to mark circ for close, else return 0.
1411 circuit_finish_handshake(origin_circuit_t *circ,
1412 const created_cell_t *reply)
1414 char keys[CPATH_KEY_MATERIAL_LEN];
1415 crypt_path_t *hop;
1416 int rv;
1418 if ((rv = pathbias_count_build_attempt(circ)) < 0) {
1419 log_warn(LD_CIRC, "pathbias_count_build_attempt failed: %d", rv);
1420 return rv;
1423 if (circ->cpath->state == CPATH_STATE_AWAITING_KEYS) {
1424 hop = circ->cpath;
1425 } else {
1426 hop = onion_next_hop_in_cpath(circ->cpath);
1427 if (!hop) { /* got an extended when we're all done? */
1428 log_warn(LD_PROTOCOL,"got extended when circ already built? Closing.");
1429 return - END_CIRC_REASON_TORPROTOCOL;
1432 tor_assert(hop->state == CPATH_STATE_AWAITING_KEYS);
1435 const char *msg = NULL;
1436 if (onion_skin_client_handshake(hop->handshake_state.tag,
1437 &hop->handshake_state,
1438 reply->reply, reply->handshake_len,
1439 (uint8_t*)keys, sizeof(keys),
1440 (uint8_t*)hop->rend_circ_nonce,
1441 &msg) < 0) {
1442 if (msg)
1443 log_warn(LD_CIRC,"onion_skin_client_handshake failed: %s", msg);
1444 return -END_CIRC_REASON_TORPROTOCOL;
1448 onion_handshake_state_release(&hop->handshake_state);
1450 if (circuit_init_cpath_crypto(hop, keys, 0)<0) {
1451 return -END_CIRC_REASON_TORPROTOCOL;
1454 hop->state = CPATH_STATE_OPEN;
1455 log_info(LD_CIRC,"Finished building circuit hop:");
1456 circuit_log_path(LOG_INFO,LD_CIRC,circ);
1457 control_event_circuit_status(circ, CIRC_EVENT_EXTENDED, 0);
1459 return 0;
1462 /** We received a relay truncated cell on circ.
1464 * Since we don't send truncates currently, getting a truncated
1465 * means that a connection broke or an extend failed. For now,
1466 * just give up: force circ to close, and return 0.
1469 circuit_truncated(origin_circuit_t *circ, crypt_path_t *layer, int reason)
1471 // crypt_path_t *victim;
1472 // connection_t *stream;
1474 tor_assert(circ);
1475 tor_assert(layer);
1477 /* XXX Since we don't send truncates currently, getting a truncated
1478 * means that a connection broke or an extend failed. For now,
1479 * just give up.
1481 circuit_mark_for_close(TO_CIRCUIT(circ),
1482 END_CIRC_REASON_FLAG_REMOTE|reason);
1483 return 0;
1485 #if 0
1486 while (layer->next != circ->cpath) {
1487 /* we need to clear out layer->next */
1488 victim = layer->next;
1489 log_debug(LD_CIRC, "Killing a layer of the cpath.");
1491 for (stream = circ->p_streams; stream; stream=stream->next_stream) {
1492 if (stream->cpath_layer == victim) {
1493 log_info(LD_APP, "Marking stream %d for close because of truncate.",
1494 stream->stream_id);
1495 /* no need to send 'end' relay cells,
1496 * because the other side's already dead
1498 connection_mark_unattached_ap(stream, END_STREAM_REASON_DESTROY);
1502 layer->next = victim->next;
1503 circuit_free_cpath_node(victim);
1506 log_info(LD_CIRC, "finished");
1507 return 0;
1508 #endif
1511 /** Given a response payload and keys, initialize, then send a created
1512 * cell back.
1515 onionskin_answer(or_circuit_t *circ,
1516 const created_cell_t *created_cell,
1517 const char *keys,
1518 const uint8_t *rend_circ_nonce)
1520 cell_t cell;
1521 crypt_path_t *tmp_cpath;
1523 if (created_cell_format(&cell, created_cell) < 0) {
1524 log_warn(LD_BUG,"couldn't format created cell (type=%d, len=%d)",
1525 (int)created_cell->cell_type, (int)created_cell->handshake_len);
1526 return -1;
1528 cell.circ_id = circ->p_circ_id;
1530 tmp_cpath = tor_malloc_zero(sizeof(crypt_path_t));
1531 tmp_cpath->magic = CRYPT_PATH_MAGIC;
1533 circuit_set_state(TO_CIRCUIT(circ), CIRCUIT_STATE_OPEN);
1535 log_debug(LD_CIRC,"init digest forward 0x%.8x, backward 0x%.8x.",
1536 (unsigned int)get_uint32(keys),
1537 (unsigned int)get_uint32(keys+20));
1538 if (circuit_init_cpath_crypto(tmp_cpath, keys, 0)<0) {
1539 log_warn(LD_BUG,"Circuit initialization failed");
1540 tor_free(tmp_cpath);
1541 return -1;
1543 circ->n_digest = tmp_cpath->f_digest;
1544 circ->n_crypto = tmp_cpath->f_crypto;
1545 circ->p_digest = tmp_cpath->b_digest;
1546 circ->p_crypto = tmp_cpath->b_crypto;
1547 tmp_cpath->magic = 0;
1548 tor_free(tmp_cpath);
1550 memcpy(circ->rend_circ_nonce, rend_circ_nonce, DIGEST_LEN);
1552 circ->is_first_hop = (created_cell->cell_type == CELL_CREATED_FAST);
1554 append_cell_to_circuit_queue(TO_CIRCUIT(circ),
1555 circ->p_chan, &cell, CELL_DIRECTION_IN, 0);
1556 log_debug(LD_CIRC,"Finished sending '%s' cell.",
1557 circ->is_first_hop ? "created_fast" : "created");
1559 /* Ignore the local bit when ExtendAllowPrivateAddresses is set:
1560 * it violates the assumption that private addresses are local.
1561 * Also, many test networks run on local addresses, and
1562 * TestingTorNetwork sets ExtendAllowPrivateAddresses. */
1563 if ((!channel_is_local(circ->p_chan)
1564 || get_options()->ExtendAllowPrivateAddresses)
1565 && !channel_is_outgoing(circ->p_chan)) {
1566 /* record that we could process create cells from a non-local conn
1567 * that we didn't initiate; presumably this means that create cells
1568 * can reach us too. */
1569 router_orport_found_reachable();
1572 return 0;
1575 /** Helper for new_route_len(). Choose a circuit length for purpose
1576 * <b>purpose</b>: DEFAULT_ROUTE_LEN (+ 1 if someone else chose the
1577 * exit). If someone else chose the exit, they could be colluding
1578 * with the exit, so add a randomly selected node to preserve
1579 * anonymity.
1581 * Here, "exit node" sometimes means an OR acting as an internal
1582 * endpoint, rather than as a relay to an external endpoint. This
1583 * means there need to be at least DEFAULT_ROUTE_LEN routers between
1584 * us and the internal endpoint to preserve the same anonymity
1585 * properties that we would get when connecting to an external
1586 * endpoint. These internal endpoints can include:
1588 * - Connections to a directory of hidden services
1589 * (CIRCUIT_PURPOSE_C_GENERAL)
1591 * - A client connecting to an introduction point, which the hidden
1592 * service picked (CIRCUIT_PURPOSE_C_INTRODUCING, via
1593 * circuit_get_open_circ_or_launch() which rewrites it from
1594 * CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT)
1596 * - A hidden service connecting to a rendezvous point, which the
1597 * client picked (CIRCUIT_PURPOSE_S_CONNECT_REND, via
1598 * rend_service_receive_introduction() and
1599 * rend_service_relaunch_rendezvous)
1601 * There are currently two situations where we picked the exit node
1602 * ourselves, making DEFAULT_ROUTE_LEN a safe circuit length:
1604 * - We are a hidden service connecting to an introduction point
1605 * (CIRCUIT_PURPOSE_S_ESTABLISH_INTRO, via
1606 * rend_service_launch_establish_intro())
1608 * - We are a router testing its own reachabiity
1609 * (CIRCUIT_PURPOSE_TESTING, via consider_testing_reachability())
1611 * onion_pick_cpath_exit() bypasses us (by not calling
1612 * new_route_len()) in the one-hop tunnel case, so we don't need to
1613 * handle that.
1615 static int
1616 route_len_for_purpose(uint8_t purpose, extend_info_t *exit_ei)
1618 int routelen = DEFAULT_ROUTE_LEN;
1619 int known_purpose = 0;
1621 if (!exit_ei)
1622 return routelen;
1624 switch (purpose) {
1625 /* These two purposes connect to a router that we chose, so
1626 * DEFAULT_ROUTE_LEN is safe. */
1627 case CIRCUIT_PURPOSE_S_ESTABLISH_INTRO:
1628 /* hidden service connecting to introduction point */
1629 case CIRCUIT_PURPOSE_TESTING:
1630 /* router reachability testing */
1631 known_purpose = 1;
1632 break;
1634 /* These three purposes connect to a router that someone else
1635 * might have chosen, so add an extra hop to protect anonymity. */
1636 case CIRCUIT_PURPOSE_C_GENERAL:
1637 /* connecting to hidden service directory */
1638 case CIRCUIT_PURPOSE_C_INTRODUCING:
1639 /* client connecting to introduction point */
1640 case CIRCUIT_PURPOSE_S_CONNECT_REND:
1641 /* hidden service connecting to rendezvous point */
1642 known_purpose = 1;
1643 routelen++;
1644 break;
1646 default:
1647 /* Got a purpose not listed above along with a chosen exit.
1648 * Increase the circuit length by one anyway for safety. */
1649 routelen++;
1650 break;
1653 if (BUG(exit_ei && !known_purpose)) {
1654 log_warn(LD_BUG, "Unhandled purpose %d with a chosen exit; "
1655 "assuming routelen %d.", purpose, routelen);
1657 return routelen;
1660 /** Choose a length for a circuit of purpose <b>purpose</b> and check
1661 * if enough routers are available.
1663 * If the routerlist <b>nodes</b> doesn't have enough routers
1664 * to handle the desired path length, return -1.
1666 STATIC int
1667 new_route_len(uint8_t purpose, extend_info_t *exit_ei, smartlist_t *nodes)
1669 int num_acceptable_routers;
1670 int routelen;
1672 tor_assert(nodes);
1674 routelen = route_len_for_purpose(purpose, exit_ei);
1676 num_acceptable_routers = count_acceptable_nodes(nodes);
1678 log_debug(LD_CIRC,"Chosen route length %d (%d/%d routers suitable).",
1679 routelen, num_acceptable_routers, smartlist_len(nodes));
1681 if (num_acceptable_routers < routelen) {
1682 log_info(LD_CIRC,
1683 "Not enough acceptable routers (%d/%d). Discarding this circuit.",
1684 num_acceptable_routers, routelen);
1685 return -1;
1688 return routelen;
1691 /** Return a newly allocated list of uint16_t * for each predicted port not
1692 * handled by a current circuit. */
1693 static smartlist_t *
1694 circuit_get_unhandled_ports(time_t now)
1696 smartlist_t *dest = rep_hist_get_predicted_ports(now);
1697 circuit_remove_handled_ports(dest);
1698 return dest;
1701 /** Return 1 if we already have circuits present or on the way for
1702 * all anticipated ports. Return 0 if we should make more.
1704 * If we're returning 0, set need_uptime and need_capacity to
1705 * indicate any requirements that the unhandled ports have.
1707 MOCK_IMPL(int,
1708 circuit_all_predicted_ports_handled, (time_t now, int *need_uptime,
1709 int *need_capacity))
1711 int i, enough;
1712 uint16_t *port;
1713 smartlist_t *sl = circuit_get_unhandled_ports(now);
1714 smartlist_t *LongLivedServices = get_options()->LongLivedPorts;
1715 tor_assert(need_uptime);
1716 tor_assert(need_capacity);
1717 // Always predict need_capacity
1718 *need_capacity = 1;
1719 enough = (smartlist_len(sl) == 0);
1720 for (i = 0; i < smartlist_len(sl); ++i) {
1721 port = smartlist_get(sl, i);
1722 if (smartlist_contains_int_as_string(LongLivedServices, *port))
1723 *need_uptime = 1;
1724 tor_free(port);
1726 smartlist_free(sl);
1727 return enough;
1730 /** Return 1 if <b>node</b> can handle one or more of the ports in
1731 * <b>needed_ports</b>, else return 0.
1733 static int
1734 node_handles_some_port(const node_t *node, smartlist_t *needed_ports)
1735 { /* XXXX MOVE */
1736 int i;
1737 uint16_t port;
1739 for (i = 0; i < smartlist_len(needed_ports); ++i) {
1740 addr_policy_result_t r;
1741 /* alignment issues aren't a worry for this dereference, since
1742 needed_ports is explicitly a smartlist of uint16_t's */
1743 port = *(uint16_t *)smartlist_get(needed_ports, i);
1744 tor_assert(port);
1745 if (node)
1746 r = compare_tor_addr_to_node_policy(NULL, port, node);
1747 else
1748 continue;
1749 if (r != ADDR_POLICY_REJECTED && r != ADDR_POLICY_PROBABLY_REJECTED)
1750 return 1;
1752 return 0;
1755 /** Return true iff <b>conn</b> needs another general circuit to be
1756 * built. */
1757 static int
1758 ap_stream_wants_exit_attention(connection_t *conn)
1760 entry_connection_t *entry;
1761 if (conn->type != CONN_TYPE_AP)
1762 return 0;
1763 entry = TO_ENTRY_CONN(conn);
1765 if (conn->state == AP_CONN_STATE_CIRCUIT_WAIT &&
1766 !conn->marked_for_close &&
1767 !(entry->want_onehop) && /* ignore one-hop streams */
1768 !(entry->use_begindir) && /* ignore targeted dir fetches */
1769 !(entry->chosen_exit_name) && /* ignore defined streams */
1770 !connection_edge_is_rendezvous_stream(TO_EDGE_CONN(conn)) &&
1771 !circuit_stream_is_being_handled(TO_ENTRY_CONN(conn), 0,
1772 MIN_CIRCUITS_HANDLING_STREAM))
1773 return 1;
1774 return 0;
1777 /** Return a pointer to a suitable router to be the exit node for the
1778 * general-purpose circuit we're about to build.
1780 * Look through the connection array, and choose a router that maximizes
1781 * the number of pending streams that can exit from this router.
1783 * Return NULL if we can't find any suitable routers.
1785 static const node_t *
1786 choose_good_exit_server_general(int need_uptime, int need_capacity)
1788 int *n_supported;
1789 int n_pending_connections = 0;
1790 smartlist_t *connections;
1791 int best_support = -1;
1792 int n_best_support=0;
1793 const or_options_t *options = get_options();
1794 const smartlist_t *the_nodes;
1795 const node_t *selected_node=NULL;
1797 connections = get_connection_array();
1799 /* Count how many connections are waiting for a circuit to be built.
1800 * We use this for log messages now, but in the future we may depend on it.
1802 SMARTLIST_FOREACH(connections, connection_t *, conn,
1804 if (ap_stream_wants_exit_attention(conn))
1805 ++n_pending_connections;
1807 // log_fn(LOG_DEBUG, "Choosing exit node; %d connections are pending",
1808 // n_pending_connections);
1809 /* Now we count, for each of the routers in the directory, how many
1810 * of the pending connections could possibly exit from that
1811 * router (n_supported[i]). (We can't be sure about cases where we
1812 * don't know the IP address of the pending connection.)
1814 * -1 means "Don't use this router at all."
1816 the_nodes = nodelist_get_list();
1817 n_supported = tor_calloc(smartlist_len(the_nodes), sizeof(int));
1818 SMARTLIST_FOREACH_BEGIN(the_nodes, const node_t *, node) {
1819 const int i = node_sl_idx;
1820 if (router_digest_is_me(node->identity)) {
1821 n_supported[i] = -1;
1822 // log_fn(LOG_DEBUG,"Skipping node %s -- it's me.", router->nickname);
1823 /* XXX there's probably a reverse predecessor attack here, but
1824 * it's slow. should we take this out? -RD
1826 continue;
1828 if (!node_has_descriptor(node)) {
1829 n_supported[i] = -1;
1830 continue;
1832 if (!node->is_running || node->is_bad_exit) {
1833 n_supported[i] = -1;
1834 continue; /* skip routers that are known to be down or bad exits */
1836 if (node_get_purpose(node) != ROUTER_PURPOSE_GENERAL) {
1837 /* never pick a non-general node as a random exit. */
1838 n_supported[i] = -1;
1839 continue;
1841 if (routerset_contains_node(options->ExcludeExitNodesUnion_, node)) {
1842 n_supported[i] = -1;
1843 continue; /* user asked us not to use it, no matter what */
1845 if (options->ExitNodes &&
1846 !routerset_contains_node(options->ExitNodes, node)) {
1847 n_supported[i] = -1;
1848 continue; /* not one of our chosen exit nodes */
1851 if (node_is_unreliable(node, need_uptime, need_capacity, 0)) {
1852 n_supported[i] = -1;
1853 continue; /* skip routers that are not suitable. Don't worry if
1854 * this makes us reject all the possible routers: if so,
1855 * we'll retry later in this function with need_update and
1856 * need_capacity set to 0. */
1858 if (!(node->is_valid)) {
1859 /* if it's invalid and we don't want it */
1860 n_supported[i] = -1;
1861 // log_fn(LOG_DEBUG,"Skipping node %s (index %d) -- invalid router.",
1862 // router->nickname, i);
1863 continue; /* skip invalid routers */
1865 /* We do not allow relays that allow single hop exits by default. Option
1866 * was deprecated in 0.2.9.2-alpha and removed in 0.3.1.0-alpha. */
1867 if (node_allows_single_hop_exits(node)) {
1868 n_supported[i] = -1;
1869 continue;
1871 if (node_exit_policy_rejects_all(node)) {
1872 n_supported[i] = -1;
1873 // log_fn(LOG_DEBUG,"Skipping node %s (index %d) -- it rejects all.",
1874 // router->nickname, i);
1875 continue; /* skip routers that reject all */
1877 n_supported[i] = 0;
1878 /* iterate over connections */
1879 SMARTLIST_FOREACH_BEGIN(connections, connection_t *, conn) {
1880 if (!ap_stream_wants_exit_attention(conn))
1881 continue; /* Skip everything but APs in CIRCUIT_WAIT */
1882 if (connection_ap_can_use_exit(TO_ENTRY_CONN(conn), node)) {
1883 ++n_supported[i];
1884 // log_fn(LOG_DEBUG,"%s is supported. n_supported[%d] now %d.",
1885 // router->nickname, i, n_supported[i]);
1886 } else {
1887 // log_fn(LOG_DEBUG,"%s (index %d) would reject this stream.",
1888 // router->nickname, i);
1890 } SMARTLIST_FOREACH_END(conn);
1891 if (n_pending_connections > 0 && n_supported[i] == 0) {
1892 /* Leave best_support at -1 if that's where it is, so we can
1893 * distinguish it later. */
1894 continue;
1896 if (n_supported[i] > best_support) {
1897 /* If this router is better than previous ones, remember its index
1898 * and goodness, and start counting how many routers are this good. */
1899 best_support = n_supported[i]; n_best_support=1;
1900 // log_fn(LOG_DEBUG,"%s is new best supported option so far.",
1901 // router->nickname);
1902 } else if (n_supported[i] == best_support) {
1903 /* If this router is _as good_ as the best one, just increment the
1904 * count of equally good routers.*/
1905 ++n_best_support;
1907 } SMARTLIST_FOREACH_END(node);
1908 log_info(LD_CIRC,
1909 "Found %d servers that might support %d/%d pending connections.",
1910 n_best_support, best_support >= 0 ? best_support : 0,
1911 n_pending_connections);
1913 /* If any routers definitely support any pending connections, choose one
1914 * at random. */
1915 if (best_support > 0) {
1916 smartlist_t *supporting = smartlist_new();
1918 SMARTLIST_FOREACH(the_nodes, const node_t *, node, {
1919 if (n_supported[node_sl_idx] == best_support)
1920 smartlist_add(supporting, (void*)node);
1923 selected_node = node_sl_choose_by_bandwidth(supporting, WEIGHT_FOR_EXIT);
1924 smartlist_free(supporting);
1925 } else {
1926 /* Either there are no pending connections, or no routers even seem to
1927 * possibly support any of them. Choose a router at random that satisfies
1928 * at least one predicted exit port. */
1930 int attempt;
1931 smartlist_t *needed_ports, *supporting;
1933 if (best_support == -1) {
1934 if (need_uptime || need_capacity) {
1935 log_info(LD_CIRC,
1936 "We couldn't find any live%s%s routers; falling back "
1937 "to list of all routers.",
1938 need_capacity?", fast":"",
1939 need_uptime?", stable":"");
1940 tor_free(n_supported);
1941 return choose_good_exit_server_general(0, 0);
1943 log_notice(LD_CIRC, "All routers are down or won't exit%s -- "
1944 "choosing a doomed exit at random.",
1945 options->ExcludeExitNodesUnion_ ? " or are Excluded" : "");
1947 supporting = smartlist_new();
1948 needed_ports = circuit_get_unhandled_ports(time(NULL));
1949 for (attempt = 0; attempt < 2; attempt++) {
1950 /* try once to pick only from routers that satisfy a needed port,
1951 * then if there are none, pick from any that support exiting. */
1952 SMARTLIST_FOREACH_BEGIN(the_nodes, const node_t *, node) {
1953 if (n_supported[node_sl_idx] != -1 &&
1954 (attempt || node_handles_some_port(node, needed_ports))) {
1955 // log_fn(LOG_DEBUG,"Try %d: '%s' is a possibility.",
1956 // try, router->nickname);
1957 smartlist_add(supporting, (void*)node);
1959 } SMARTLIST_FOREACH_END(node);
1961 selected_node = node_sl_choose_by_bandwidth(supporting, WEIGHT_FOR_EXIT);
1962 if (selected_node)
1963 break;
1964 smartlist_clear(supporting);
1965 /* If we reach this point, we can't actually support any unhandled
1966 * predicted ports, so clear all the remaining ones. */
1967 if (smartlist_len(needed_ports))
1968 rep_hist_remove_predicted_ports(needed_ports);
1970 SMARTLIST_FOREACH(needed_ports, uint16_t *, cp, tor_free(cp));
1971 smartlist_free(needed_ports);
1972 smartlist_free(supporting);
1975 tor_free(n_supported);
1976 if (selected_node) {
1977 log_info(LD_CIRC, "Chose exit server '%s'", node_describe(selected_node));
1978 return selected_node;
1980 if (options->ExitNodes) {
1981 log_warn(LD_CIRC,
1982 "No exits in ExitNodes%s seem to be running: "
1983 "can't choose an exit.",
1984 options->ExcludeExitNodesUnion_ ?
1985 ", except possibly those excluded by your configuration, " : "");
1987 return NULL;
1990 #if defined(ENABLE_TOR2WEB_MODE) || defined(TOR_UNIT_TESTS)
1991 /* The config option Tor2webRendezvousPoints has been set and we need
1992 * to pick an RP out of that set. Make sure that the RP we choose is
1993 * alive, and return it. Return NULL if no usable RP could be found in
1994 * Tor2webRendezvousPoints. */
1995 STATIC const node_t *
1996 pick_tor2web_rendezvous_node(router_crn_flags_t flags,
1997 const or_options_t *options)
1999 const node_t *rp_node = NULL;
2000 const int need_desc = (flags & CRN_NEED_DESC) != 0;
2001 const int pref_addr = (flags & CRN_PREF_ADDR) != 0;
2002 const int direct_conn = (flags & CRN_DIRECT_CONN) != 0;
2004 smartlist_t *whitelisted_live_rps = smartlist_new();
2005 smartlist_t *all_live_nodes = smartlist_new();
2007 tor_assert(options->Tor2webRendezvousPoints);
2009 /* Add all running nodes to all_live_nodes */
2010 router_add_running_nodes_to_smartlist(all_live_nodes,
2011 0, 0, 0,
2012 need_desc,
2013 pref_addr,
2014 direct_conn);
2016 /* Filter all_live_nodes to only add live *and* whitelisted RPs to
2017 * the list whitelisted_live_rps. */
2018 SMARTLIST_FOREACH_BEGIN(all_live_nodes, node_t *, live_node) {
2019 if (routerset_contains_node(options->Tor2webRendezvousPoints, live_node)) {
2020 smartlist_add(whitelisted_live_rps, live_node);
2022 } SMARTLIST_FOREACH_END(live_node);
2024 /* Honor ExcludeNodes */
2025 if (options->ExcludeNodes) {
2026 routerset_subtract_nodes(whitelisted_live_rps, options->ExcludeNodes);
2029 /* Now pick randomly amongst the whitelisted RPs. No need to waste time
2030 doing bandwidth load balancing, for most use cases
2031 'whitelisted_live_rps' contains a single OR anyway. */
2032 rp_node = smartlist_choose(whitelisted_live_rps);
2034 if (!rp_node) {
2035 log_warn(LD_REND, "Could not find a Rendezvous Point that suits "
2036 "the purposes of Tor2webRendezvousPoints. Choosing random one.");
2039 smartlist_free(whitelisted_live_rps);
2040 smartlist_free(all_live_nodes);
2042 return rp_node;
2044 #endif
2046 /* Pick a Rendezvous Point for our HS circuits according to <b>flags</b>. */
2047 static const node_t *
2048 pick_rendezvous_node(router_crn_flags_t flags)
2050 const or_options_t *options = get_options();
2052 #ifdef ENABLE_TOR2WEB_MODE
2053 /* We want to connect directly to the node if we can */
2054 router_crn_flags_t direct_flags = flags;
2055 direct_flags |= CRN_PREF_ADDR;
2056 direct_flags |= CRN_DIRECT_CONN;
2058 /* The user wants us to pick specific RPs. */
2059 if (options->Tor2webRendezvousPoints) {
2060 const node_t *tor2web_rp = pick_tor2web_rendezvous_node(direct_flags,
2061 options);
2062 if (tor2web_rp) {
2063 return tor2web_rp;
2067 /* Else, if no direct, preferred tor2web RP was found, fall back to choosing
2068 * a random direct node */
2069 const node_t *node = router_choose_random_node(NULL, options->ExcludeNodes,
2070 direct_flags);
2071 /* Return the direct node (if found), or log a message and fall back to an
2072 * indirect connection. */
2073 if (node) {
2074 return node;
2075 } else {
2076 log_info(LD_REND,
2077 "Unable to find a random rendezvous point that is reachable via "
2078 "a direct connection, falling back to a 3-hop path.");
2080 #endif
2082 return router_choose_random_node(NULL, options->ExcludeNodes, flags);
2085 /** Return a pointer to a suitable router to be the exit node for the
2086 * circuit of purpose <b>purpose</b> that we're about to build (or NULL
2087 * if no router is suitable).
2089 * For general-purpose circuits, pass it off to
2090 * choose_good_exit_server_general()
2092 * For client-side rendezvous circuits, choose a random node, weighted
2093 * toward the preferences in 'options'.
2095 static const node_t *
2096 choose_good_exit_server(uint8_t purpose,
2097 int need_uptime, int need_capacity, int is_internal)
2099 const or_options_t *options = get_options();
2100 router_crn_flags_t flags = CRN_NEED_DESC;
2101 if (need_uptime)
2102 flags |= CRN_NEED_UPTIME;
2103 if (need_capacity)
2104 flags |= CRN_NEED_CAPACITY;
2106 switch (purpose) {
2107 case CIRCUIT_PURPOSE_C_GENERAL:
2108 if (is_internal) /* pick it like a middle hop */
2109 return router_choose_random_node(NULL, options->ExcludeNodes, flags);
2110 else
2111 return choose_good_exit_server_general(need_uptime,need_capacity);
2112 case CIRCUIT_PURPOSE_C_ESTABLISH_REND:
2114 /* Pick a new RP */
2115 const node_t *rendezvous_node = pick_rendezvous_node(flags);
2116 log_info(LD_REND, "Picked new RP: %s",
2117 safe_str_client(node_describe(rendezvous_node)));
2118 return rendezvous_node;
2121 log_warn(LD_BUG,"Unhandled purpose %d", purpose);
2122 tor_fragile_assert();
2123 return NULL;
2126 /** Log a warning if the user specified an exit for the circuit that
2127 * has been excluded from use by ExcludeNodes or ExcludeExitNodes. */
2128 static void
2129 warn_if_last_router_excluded(origin_circuit_t *circ,
2130 const extend_info_t *exit_ei)
2132 const or_options_t *options = get_options();
2133 routerset_t *rs = options->ExcludeNodes;
2134 const char *description;
2135 uint8_t purpose = circ->base_.purpose;
2137 if (circ->build_state->onehop_tunnel)
2138 return;
2140 switch (purpose)
2142 default:
2143 case CIRCUIT_PURPOSE_OR:
2144 case CIRCUIT_PURPOSE_INTRO_POINT:
2145 case CIRCUIT_PURPOSE_REND_POINT_WAITING:
2146 case CIRCUIT_PURPOSE_REND_ESTABLISHED:
2147 log_warn(LD_BUG, "Called on non-origin circuit (purpose %d, %s)",
2148 (int)purpose,
2149 circuit_purpose_to_string(purpose));
2150 return;
2151 case CIRCUIT_PURPOSE_C_GENERAL:
2152 if (circ->build_state->is_internal)
2153 return;
2154 description = "requested exit node";
2155 rs = options->ExcludeExitNodesUnion_;
2156 break;
2157 case CIRCUIT_PURPOSE_C_INTRODUCING:
2158 case CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT:
2159 case CIRCUIT_PURPOSE_C_INTRODUCE_ACKED:
2160 case CIRCUIT_PURPOSE_S_ESTABLISH_INTRO:
2161 case CIRCUIT_PURPOSE_S_CONNECT_REND:
2162 case CIRCUIT_PURPOSE_S_REND_JOINED:
2163 case CIRCUIT_PURPOSE_TESTING:
2164 return;
2165 case CIRCUIT_PURPOSE_C_ESTABLISH_REND:
2166 case CIRCUIT_PURPOSE_C_REND_READY:
2167 case CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED:
2168 case CIRCUIT_PURPOSE_C_REND_JOINED:
2169 description = "chosen rendezvous point";
2170 break;
2171 case CIRCUIT_PURPOSE_CONTROLLER:
2172 rs = options->ExcludeExitNodesUnion_;
2173 description = "controller-selected circuit target";
2174 break;
2177 if (routerset_contains_extendinfo(rs, exit_ei)) {
2178 /* We should never get here if StrictNodes is set to 1. */
2179 if (options->StrictNodes) {
2180 log_warn(LD_BUG, "Using %s '%s' which is listed in ExcludeNodes%s, "
2181 "even though StrictNodes is set. Please report. "
2182 "(Circuit purpose: %s)",
2183 description, extend_info_describe(exit_ei),
2184 rs==options->ExcludeNodes?"":" or ExcludeExitNodes",
2185 circuit_purpose_to_string(purpose));
2186 } else {
2187 log_warn(LD_CIRC, "Using %s '%s' which is listed in "
2188 "ExcludeNodes%s, because no better options were available. To "
2189 "prevent this (and possibly break your Tor functionality), "
2190 "set the StrictNodes configuration option. "
2191 "(Circuit purpose: %s)",
2192 description, extend_info_describe(exit_ei),
2193 rs==options->ExcludeNodes?"":" or ExcludeExitNodes",
2194 circuit_purpose_to_string(purpose));
2196 circuit_log_path(LOG_WARN, LD_CIRC, circ);
2199 return;
2202 /** Decide a suitable length for circ's cpath, and pick an exit
2203 * router (or use <b>exit</b> if provided). Store these in the
2204 * cpath. Return 0 if ok, -1 if circuit should be closed. */
2205 static int
2206 onion_pick_cpath_exit(origin_circuit_t *circ, extend_info_t *exit_ei)
2208 cpath_build_state_t *state = circ->build_state;
2210 if (state->onehop_tunnel) {
2211 log_debug(LD_CIRC, "Launching a one-hop circuit for dir tunnel%s.",
2212 (rend_allow_non_anonymous_connection(get_options()) ?
2213 ", or intro or rendezvous connection" : ""));
2214 state->desired_path_len = 1;
2215 } else {
2216 int r = new_route_len(circ->base_.purpose, exit_ei, nodelist_get_list());
2217 if (r < 1) /* must be at least 1 */
2218 return -1;
2219 state->desired_path_len = r;
2222 if (exit_ei) { /* the circuit-builder pre-requested one */
2223 warn_if_last_router_excluded(circ, exit_ei);
2224 log_info(LD_CIRC,"Using requested exit node '%s'",
2225 extend_info_describe(exit_ei));
2226 exit_ei = extend_info_dup(exit_ei);
2227 } else { /* we have to decide one */
2228 const node_t *node =
2229 choose_good_exit_server(circ->base_.purpose, state->need_uptime,
2230 state->need_capacity, state->is_internal);
2231 if (!node) {
2232 log_warn(LD_CIRC,"Failed to choose an exit server");
2233 return -1;
2235 exit_ei = extend_info_from_node(node, 0);
2236 if (BUG(exit_ei == NULL))
2237 return -1;
2239 state->chosen_exit = exit_ei;
2240 return 0;
2243 /** Give <b>circ</b> a new exit destination to <b>exit</b>, and add a
2244 * hop to the cpath reflecting this. Don't send the next extend cell --
2245 * the caller will do this if it wants to.
2248 circuit_append_new_exit(origin_circuit_t *circ, extend_info_t *exit_ei)
2250 cpath_build_state_t *state;
2251 tor_assert(exit_ei);
2252 tor_assert(circ);
2254 state = circ->build_state;
2255 tor_assert(state);
2256 extend_info_free(state->chosen_exit);
2257 state->chosen_exit = extend_info_dup(exit_ei);
2259 ++circ->build_state->desired_path_len;
2260 onion_append_hop(&circ->cpath, exit_ei);
2261 return 0;
2264 /** Take an open <b>circ</b>, and add a new hop at the end, based on
2265 * <b>info</b>. Set its state back to CIRCUIT_STATE_BUILDING, and then
2266 * send the next extend cell to begin connecting to that hop.
2269 circuit_extend_to_new_exit(origin_circuit_t *circ, extend_info_t *exit_ei)
2271 int err_reason = 0;
2272 warn_if_last_router_excluded(circ, exit_ei);
2274 tor_gettimeofday(&circ->base_.timestamp_began);
2276 circuit_append_new_exit(circ, exit_ei);
2277 circuit_set_state(TO_CIRCUIT(circ), CIRCUIT_STATE_BUILDING);
2278 if ((err_reason = circuit_send_next_onion_skin(circ))<0) {
2279 log_warn(LD_CIRC, "Couldn't extend circuit to new point %s.",
2280 extend_info_describe(exit_ei));
2281 circuit_mark_for_close(TO_CIRCUIT(circ), -err_reason);
2282 return -1;
2285 // XXX: Should cannibalized circuits be dirty or not? Not easy to say..
2287 return 0;
2290 /** Return the number of routers in <b>routers</b> that are currently up
2291 * and available for building circuits through.
2293 MOCK_IMPL(STATIC int,
2294 count_acceptable_nodes, (smartlist_t *nodes))
2296 int num=0;
2298 SMARTLIST_FOREACH_BEGIN(nodes, const node_t *, node) {
2299 // log_debug(LD_CIRC,
2300 // "Contemplating whether router %d (%s) is a new option.",
2301 // i, r->nickname);
2302 if (! node->is_running)
2303 // log_debug(LD_CIRC,"Nope, the directory says %d is not running.",i);
2304 continue;
2305 if (! node->is_valid)
2306 // log_debug(LD_CIRC,"Nope, the directory says %d is not valid.",i);
2307 continue;
2308 if (! node_has_descriptor(node))
2309 continue;
2310 /* The node has a descriptor, so we can just check the ntor key directly */
2311 if (!node_has_curve25519_onion_key(node))
2312 continue;
2313 ++num;
2314 } SMARTLIST_FOREACH_END(node);
2316 // log_debug(LD_CIRC,"I like %d. num_acceptable_routers now %d.",i, num);
2318 return num;
2321 /** Add <b>new_hop</b> to the end of the doubly-linked-list <b>head_ptr</b>.
2322 * This function is used to extend cpath by another hop.
2324 void
2325 onion_append_to_cpath(crypt_path_t **head_ptr, crypt_path_t *new_hop)
2327 if (*head_ptr) {
2328 new_hop->next = (*head_ptr);
2329 new_hop->prev = (*head_ptr)->prev;
2330 (*head_ptr)->prev->next = new_hop;
2331 (*head_ptr)->prev = new_hop;
2332 } else {
2333 *head_ptr = new_hop;
2334 new_hop->prev = new_hop->next = new_hop;
2338 /** A helper function used by onion_extend_cpath(). Use <b>purpose</b>
2339 * and <b>state</b> and the cpath <b>head</b> (currently populated only
2340 * to length <b>cur_len</b> to decide a suitable middle hop for a
2341 * circuit. In particular, make sure we don't pick the exit node or its
2342 * family, and make sure we don't duplicate any previous nodes or their
2343 * families. */
2344 static const node_t *
2345 choose_good_middle_server(uint8_t purpose,
2346 cpath_build_state_t *state,
2347 crypt_path_t *head,
2348 int cur_len)
2350 int i;
2351 const node_t *r, *choice;
2352 crypt_path_t *cpath;
2353 smartlist_t *excluded;
2354 const or_options_t *options = get_options();
2355 router_crn_flags_t flags = CRN_NEED_DESC;
2356 tor_assert(CIRCUIT_PURPOSE_MIN_ <= purpose &&
2357 purpose <= CIRCUIT_PURPOSE_MAX_);
2359 log_debug(LD_CIRC, "Contemplating intermediate hop %d: random choice.",
2360 cur_len);
2361 excluded = smartlist_new();
2362 if ((r = build_state_get_exit_node(state))) {
2363 nodelist_add_node_and_family(excluded, r);
2365 for (i = 0, cpath = head; i < cur_len; ++i, cpath=cpath->next) {
2366 if ((r = node_get_by_id(cpath->extend_info->identity_digest))) {
2367 nodelist_add_node_and_family(excluded, r);
2371 if (state->need_uptime)
2372 flags |= CRN_NEED_UPTIME;
2373 if (state->need_capacity)
2374 flags |= CRN_NEED_CAPACITY;
2375 choice = router_choose_random_node(excluded, options->ExcludeNodes, flags);
2376 smartlist_free(excluded);
2377 return choice;
2380 /** Pick a good entry server for the circuit to be built according to
2381 * <b>state</b>. Don't reuse a chosen exit (if any), don't use this
2382 * router (if we're an OR), and respect firewall settings; if we're
2383 * configured to use entry guards, return one.
2385 * If <b>state</b> is NULL, we're choosing a router to serve as an entry
2386 * guard, not for any particular circuit.
2388 * Set *<b>guard_state_out</b> to information about the guard that
2389 * we're selecting, which we'll use later to remember whether the
2390 * guard worked or not.
2392 const node_t *
2393 choose_good_entry_server(uint8_t purpose, cpath_build_state_t *state,
2394 circuit_guard_state_t **guard_state_out)
2396 const node_t *choice;
2397 smartlist_t *excluded;
2398 const or_options_t *options = get_options();
2399 /* If possible, choose an entry server with a preferred address,
2400 * otherwise, choose one with an allowed address */
2401 router_crn_flags_t flags = (CRN_NEED_GUARD|CRN_NEED_DESC|CRN_PREF_ADDR|
2402 CRN_DIRECT_CONN);
2403 const node_t *node;
2405 if (state && options->UseEntryGuards &&
2406 (purpose != CIRCUIT_PURPOSE_TESTING || options->BridgeRelay)) {
2407 /* This request is for an entry server to use for a regular circuit,
2408 * and we use entry guard nodes. Just return one of the guard nodes. */
2409 tor_assert(guard_state_out);
2410 return guards_choose_guard(state, guard_state_out);
2413 excluded = smartlist_new();
2415 if (state && (node = build_state_get_exit_node(state))) {
2416 /* Exclude the exit node from the state, if we have one. Also exclude its
2417 * family. */
2418 nodelist_add_node_and_family(excluded, node);
2421 if (state) {
2422 if (state->need_uptime)
2423 flags |= CRN_NEED_UPTIME;
2424 if (state->need_capacity)
2425 flags |= CRN_NEED_CAPACITY;
2428 choice = router_choose_random_node(excluded, options->ExcludeNodes, flags);
2429 smartlist_free(excluded);
2430 return choice;
2433 /** Return the first non-open hop in cpath, or return NULL if all
2434 * hops are open. */
2435 static crypt_path_t *
2436 onion_next_hop_in_cpath(crypt_path_t *cpath)
2438 crypt_path_t *hop = cpath;
2439 do {
2440 if (hop->state != CPATH_STATE_OPEN)
2441 return hop;
2442 hop = hop->next;
2443 } while (hop != cpath);
2444 return NULL;
2447 /** Choose a suitable next hop in the cpath <b>head_ptr</b>,
2448 * based on <b>state</b>. Append the hop info to head_ptr.
2450 * Return 1 if the path is complete, 0 if we successfully added a hop,
2451 * and -1 on error.
2453 static int
2454 onion_extend_cpath(origin_circuit_t *circ)
2456 uint8_t purpose = circ->base_.purpose;
2457 cpath_build_state_t *state = circ->build_state;
2458 int cur_len = circuit_get_cpath_len(circ);
2459 extend_info_t *info = NULL;
2461 if (cur_len >= state->desired_path_len) {
2462 log_debug(LD_CIRC, "Path is complete: %d steps long",
2463 state->desired_path_len);
2464 return 1;
2467 log_debug(LD_CIRC, "Path is %d long; we want %d", cur_len,
2468 state->desired_path_len);
2470 if (cur_len == state->desired_path_len - 1) { /* Picking last node */
2471 info = extend_info_dup(state->chosen_exit);
2472 } else if (cur_len == 0) { /* picking first node */
2473 const node_t *r = choose_good_entry_server(purpose, state,
2474 &circ->guard_state);
2475 if (r) {
2476 /* If we're a client, use the preferred address rather than the
2477 primary address, for potentially connecting to an IPv6 OR
2478 port. Servers always want the primary (IPv4) address. */
2479 int client = (server_mode(get_options()) == 0);
2480 info = extend_info_from_node(r, client);
2481 /* Clients can fail to find an allowed address */
2482 tor_assert_nonfatal(info || client);
2484 } else {
2485 const node_t *r =
2486 choose_good_middle_server(purpose, state, circ->cpath, cur_len);
2487 if (r) {
2488 info = extend_info_from_node(r, 0);
2489 tor_assert_nonfatal(info);
2493 if (!info) {
2494 log_warn(LD_CIRC,"Failed to find node for hop %d of our path. Discarding "
2495 "this circuit.", cur_len);
2496 return -1;
2499 log_debug(LD_CIRC,"Chose router %s for hop %d (exit is %s)",
2500 extend_info_describe(info),
2501 cur_len+1, build_state_get_exit_nickname(state));
2503 onion_append_hop(&circ->cpath, info);
2504 extend_info_free(info);
2505 return 0;
2508 /** Create a new hop, annotate it with information about its
2509 * corresponding router <b>choice</b>, and append it to the
2510 * end of the cpath <b>head_ptr</b>. */
2511 static int
2512 onion_append_hop(crypt_path_t **head_ptr, extend_info_t *choice)
2514 crypt_path_t *hop = tor_malloc_zero(sizeof(crypt_path_t));
2516 /* link hop into the cpath, at the end. */
2517 onion_append_to_cpath(head_ptr, hop);
2519 hop->magic = CRYPT_PATH_MAGIC;
2520 hop->state = CPATH_STATE_CLOSED;
2522 hop->extend_info = extend_info_dup(choice);
2524 hop->package_window = circuit_initial_package_window();
2525 hop->deliver_window = CIRCWINDOW_START;
2527 return 0;
2530 /** Allocate a new extend_info object based on the various arguments. */
2531 extend_info_t *
2532 extend_info_new(const char *nickname,
2533 const char *rsa_id_digest,
2534 const ed25519_public_key_t *ed_id,
2535 crypto_pk_t *onion_key,
2536 const curve25519_public_key_t *ntor_key,
2537 const tor_addr_t *addr, uint16_t port)
2539 extend_info_t *info = tor_malloc_zero(sizeof(extend_info_t));
2540 memcpy(info->identity_digest, rsa_id_digest, DIGEST_LEN);
2541 if (ed_id && !ed25519_public_key_is_zero(ed_id))
2542 memcpy(&info->ed_identity, ed_id, sizeof(ed25519_public_key_t));
2543 if (nickname)
2544 strlcpy(info->nickname, nickname, sizeof(info->nickname));
2545 if (onion_key)
2546 info->onion_key = crypto_pk_dup_key(onion_key);
2547 if (ntor_key)
2548 memcpy(&info->curve25519_onion_key, ntor_key,
2549 sizeof(curve25519_public_key_t));
2550 tor_addr_copy(&info->addr, addr);
2551 info->port = port;
2552 return info;
2555 /** Allocate and return a new extend_info that can be used to build a
2556 * circuit to or through the node <b>node</b>. Use the primary address
2557 * of the node (i.e. its IPv4 address) unless
2558 * <b>for_direct_connect</b> is true, in which case the preferred
2559 * address is used instead. May return NULL if there is not enough
2560 * info about <b>node</b> to extend to it--for example, if there is no
2561 * routerinfo_t or microdesc_t, or if for_direct_connect is true and none of
2562 * the node's addresses are allowed by tor's firewall and IP version config.
2564 extend_info_t *
2565 extend_info_from_node(const node_t *node, int for_direct_connect)
2567 tor_addr_port_t ap;
2568 int valid_addr = 0;
2570 if (node->ri == NULL && (node->rs == NULL || node->md == NULL))
2571 return NULL;
2573 /* Choose a preferred address first, but fall back to an allowed address.
2574 * choose_address returns 1 on success, but get_prim_orport returns 0. */
2575 if (for_direct_connect)
2576 valid_addr = fascist_firewall_choose_address_node(node,
2577 FIREWALL_OR_CONNECTION,
2578 0, &ap);
2579 else
2580 valid_addr = !node_get_prim_orport(node, &ap);
2582 if (valid_addr)
2583 log_debug(LD_CIRC, "using %s for %s",
2584 fmt_addrport(&ap.addr, ap.port),
2585 node->ri ? node->ri->nickname : node->rs->nickname);
2586 else
2587 log_warn(LD_CIRC, "Could not choose valid address for %s",
2588 node->ri ? node->ri->nickname : node->rs->nickname);
2590 /* Every node we connect or extend to must support ntor */
2591 if (!node_has_curve25519_onion_key(node)) {
2592 log_fn(LOG_PROTOCOL_WARN, LD_CIRC,
2593 "Attempted to create extend_info for a node that does not support "
2594 "ntor: %s", node_describe(node));
2595 return NULL;
2598 const ed25519_public_key_t *ed_pubkey = NULL;
2600 /* Don't send the ed25519 pubkey unless the target node actually supports
2601 * authenticating with it. */
2602 if (node_supports_ed25519_link_authentication(node)) {
2603 log_info(LD_CIRC, "Including Ed25519 ID for %s", node_describe(node));
2604 ed_pubkey = node_get_ed25519_id(node);
2605 } else if (node_get_ed25519_id(node)) {
2606 log_info(LD_CIRC, "Not including the ed25519 ID for %s, since it won't "
2607 "be able to authenticate it.",
2608 node_describe(node));
2611 if (valid_addr && node->ri)
2612 return extend_info_new(node->ri->nickname,
2613 node->identity,
2614 ed_pubkey,
2615 node->ri->onion_pkey,
2616 node->ri->onion_curve25519_pkey,
2617 &ap.addr,
2618 ap.port);
2619 else if (valid_addr && node->rs && node->md)
2620 return extend_info_new(node->rs->nickname,
2621 node->identity,
2622 ed_pubkey,
2623 node->md->onion_pkey,
2624 node->md->onion_curve25519_pkey,
2625 &ap.addr,
2626 ap.port);
2627 else
2628 return NULL;
2631 /** Release storage held by an extend_info_t struct. */
2632 void
2633 extend_info_free(extend_info_t *info)
2635 if (!info)
2636 return;
2637 crypto_pk_free(info->onion_key);
2638 tor_free(info);
2641 /** Allocate and return a new extend_info_t with the same contents as
2642 * <b>info</b>. */
2643 extend_info_t *
2644 extend_info_dup(extend_info_t *info)
2646 extend_info_t *newinfo;
2647 tor_assert(info);
2648 newinfo = tor_malloc(sizeof(extend_info_t));
2649 memcpy(newinfo, info, sizeof(extend_info_t));
2650 if (info->onion_key)
2651 newinfo->onion_key = crypto_pk_dup_key(info->onion_key);
2652 else
2653 newinfo->onion_key = NULL;
2654 return newinfo;
2657 /** Return the node_t for the chosen exit router in <b>state</b>.
2658 * If there is no chosen exit, or if we don't know the node_t for
2659 * the chosen exit, return NULL.
2661 const node_t *
2662 build_state_get_exit_node(cpath_build_state_t *state)
2664 if (!state || !state->chosen_exit)
2665 return NULL;
2666 return node_get_by_id(state->chosen_exit->identity_digest);
2669 /** Return the RSA ID digest for the chosen exit router in <b>state</b>.
2670 * If there is no chosen exit, return NULL.
2672 const uint8_t *
2673 build_state_get_exit_rsa_id(cpath_build_state_t *state)
2675 if (!state || !state->chosen_exit)
2676 return NULL;
2677 return (const uint8_t *) state->chosen_exit->identity_digest;
2680 /** Return the nickname for the chosen exit router in <b>state</b>. If
2681 * there is no chosen exit, or if we don't know the routerinfo_t for the
2682 * chosen exit, return NULL.
2684 const char *
2685 build_state_get_exit_nickname(cpath_build_state_t *state)
2687 if (!state || !state->chosen_exit)
2688 return NULL;
2689 return state->chosen_exit->nickname;
2692 /** Return true iff the given address can be used to extend to. */
2694 extend_info_addr_is_allowed(const tor_addr_t *addr)
2696 tor_assert(addr);
2698 /* Check if we have a private address and if we can extend to it. */
2699 if ((tor_addr_is_internal(addr, 0) || tor_addr_is_multicast(addr)) &&
2700 !get_options()->ExtendAllowPrivateAddresses) {
2701 goto disallow;
2703 /* Allowed! */
2704 return 1;
2705 disallow:
2706 return 0;
2709 /* Does ei have a valid TAP key? */
2711 extend_info_supports_tap(const extend_info_t* ei)
2713 tor_assert(ei);
2714 /* Valid TAP keys are not NULL */
2715 return ei->onion_key != NULL;
2718 /* Does ei have a valid ntor key? */
2720 extend_info_supports_ntor(const extend_info_t* ei)
2722 tor_assert(ei);
2723 /* Valid ntor keys have at least one non-zero byte */
2724 return !tor_mem_is_zero(
2725 (const char*)ei->curve25519_onion_key.public_key,
2726 CURVE25519_PUBKEY_LEN);
2729 /* Is circuit purpose allowed to use the deprecated TAP encryption protocol?
2730 * The hidden service protocol still uses TAP for some connections, because
2731 * ntor onion keys aren't included in HS descriptors or INTRODUCE cells. */
2732 static int
2733 circuit_purpose_can_use_tap_impl(uint8_t purpose)
2735 return (purpose == CIRCUIT_PURPOSE_S_CONNECT_REND ||
2736 purpose == CIRCUIT_PURPOSE_C_INTRODUCING);
2739 /* Is circ allowed to use the deprecated TAP encryption protocol?
2740 * The hidden service protocol still uses TAP for some connections, because
2741 * ntor onion keys aren't included in HS descriptors or INTRODUCE cells. */
2743 circuit_can_use_tap(const origin_circuit_t *circ)
2745 tor_assert(circ);
2746 tor_assert(circ->cpath);
2747 tor_assert(circ->cpath->extend_info);
2748 return (circuit_purpose_can_use_tap_impl(circ->base_.purpose) &&
2749 extend_info_supports_tap(circ->cpath->extend_info));
2752 /* Does circ have an onion key which it's allowed to use? */
2754 circuit_has_usable_onion_key(const origin_circuit_t *circ)
2756 tor_assert(circ);
2757 tor_assert(circ->cpath);
2758 tor_assert(circ->cpath->extend_info);
2759 return (extend_info_supports_ntor(circ->cpath->extend_info) ||
2760 circuit_can_use_tap(circ));
2763 /* Does ei have an onion key which it would prefer to use?
2764 * Currently, we prefer ntor keys*/
2766 extend_info_has_preferred_onion_key(const extend_info_t* ei)
2768 tor_assert(ei);
2769 return extend_info_supports_ntor(ei);
2772 /** Find the circuits that are waiting to find out whether their guards are
2773 * usable, and if any are ready to become usable, mark them open and try
2774 * attaching streams as appropriate. */
2775 void
2776 circuit_upgrade_circuits_from_guard_wait(void)
2778 smartlist_t *to_upgrade =
2779 circuit_find_circuits_to_upgrade_from_guard_wait();
2781 if (to_upgrade == NULL)
2782 return;
2784 log_info(LD_GUARD, "Upgrading %d circuits from 'waiting for better guard' "
2785 "to 'open'.", smartlist_len(to_upgrade));
2787 SMARTLIST_FOREACH_BEGIN(to_upgrade, origin_circuit_t *, circ) {
2788 circuit_set_state(TO_CIRCUIT(circ), CIRCUIT_STATE_OPEN);
2789 circuit_has_opened(circ);
2790 } SMARTLIST_FOREACH_END(circ);
2792 smartlist_free(to_upgrade);