Merge remote-tracking branch 'public/bug12848_024' into maint-0.2.5
[tor.git] / src / or / circuitbuild.c
blob897f90fe4c7160abab96f5af74d6d5310709baba
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-2013, The Tor Project, Inc. */
5 /* See LICENSE for licensing information */
7 /**
8 * \file circuitbuild.c
9 * \brief The actual details of building circuits.
10 **/
12 #define CIRCUITBUILD_PRIVATE
14 #include "or.h"
15 #include "channel.h"
16 #include "circpathbias.h"
17 #include "circuitbuild.h"
18 #include "circuitlist.h"
19 #include "circuitstats.h"
20 #include "circuituse.h"
21 #include "command.h"
22 #include "config.h"
23 #include "confparse.h"
24 #include "connection.h"
25 #include "connection_edge.h"
26 #include "connection_or.h"
27 #include "control.h"
28 #include "directory.h"
29 #include "entrynodes.h"
30 #include "main.h"
31 #include "microdesc.h"
32 #include "networkstatus.h"
33 #include "nodelist.h"
34 #include "onion.h"
35 #include "onion_tap.h"
36 #include "onion_fast.h"
37 #include "policies.h"
38 #include "transports.h"
39 #include "relay.h"
40 #include "rephist.h"
41 #include "router.h"
42 #include "routerlist.h"
43 #include "routerparse.h"
44 #include "routerset.h"
45 #include "crypto.h"
47 #ifndef MIN
48 #define MIN(a,b) ((a)<(b)?(a):(b))
49 #endif
51 static channel_t * channel_connect_for_circuit(const tor_addr_t *addr,
52 uint16_t port,
53 const char *id_digest);
54 static int circuit_deliver_create_cell(circuit_t *circ,
55 const create_cell_t *create_cell,
56 int relayed);
57 static int onion_pick_cpath_exit(origin_circuit_t *circ, extend_info_t *exit);
58 static crypt_path_t *onion_next_hop_in_cpath(crypt_path_t *cpath);
59 static int onion_extend_cpath(origin_circuit_t *circ);
60 static int count_acceptable_nodes(smartlist_t *routers);
61 static int onion_append_hop(crypt_path_t **head_ptr, extend_info_t *choice);
62 #ifdef CURVE25519_ENABLED
63 static int circuits_can_use_ntor(void);
64 #endif
66 /** This function tries to get a channel to the specified endpoint,
67 * and then calls command_setup_channel() to give it the right
68 * callbacks.
70 static channel_t *
71 channel_connect_for_circuit(const tor_addr_t *addr, uint16_t port,
72 const char *id_digest)
74 channel_t *chan;
76 chan = channel_connect(addr, port, id_digest);
77 if (chan) command_setup_channel(chan);
79 return chan;
82 /** Search for a value for circ_id that we can use on <b>chan</b> for an
83 * outbound circuit, until we get a circ_id that is not in use by any other
84 * circuit on that conn.
86 * Return it, or 0 if can't get a unique circ_id.
88 STATIC circid_t
89 get_unique_circ_id_by_chan(channel_t *chan)
91 /* This number is chosen somewhat arbitrarily; see comment below for more
92 * info. When the space is 80% full, it gives a one-in-a-million failure
93 * chance; when the space is 90% full, it gives a one-in-850 chance; and when
94 * the space is 95% full, it gives a one-in-26 failure chance. That seems
95 * okay, though you could make a case IMO for anything between N=32 and
96 * N=256. */
97 #define MAX_CIRCID_ATTEMPTS 64
98 int in_use;
99 unsigned n_with_circ = 0, n_pending_destroy = 0, n_weird_pending_destroy = 0;
100 circid_t test_circ_id;
101 circid_t attempts=0;
102 circid_t high_bit, max_range, mask;
103 int64_t pending_destroy_time_total = 0;
104 int64_t pending_destroy_time_max = 0;
106 tor_assert(chan);
108 if (chan->circ_id_type == CIRC_ID_TYPE_NEITHER) {
109 log_warn(LD_BUG,
110 "Trying to pick a circuit ID for a connection from "
111 "a client with no identity.");
112 return 0;
114 max_range = (chan->wide_circ_ids) ? (1u<<31) : (1u<<15);
115 mask = max_range - 1;
116 high_bit = (chan->circ_id_type == CIRC_ID_TYPE_HIGHER) ? max_range : 0;
117 do {
118 if (++attempts > MAX_CIRCID_ATTEMPTS) {
119 /* Make sure we don't loop forever because all circuit IDs are used.
121 * Once, we would try until we had tried every possible circuit ID. But
122 * that's quite expensive. Instead, we try MAX_CIRCID_ATTEMPTS random
123 * circuit IDs, and then give up.
125 * This potentially causes us to give up early if our circuit ID space
126 * is nearly full. If we have N circuit IDs in use, then we will reject
127 * a new circuit with probability (N / max_range) ^ MAX_CIRCID_ATTEMPTS.
128 * This means that in practice, a few percent of our circuit ID capacity
129 * will go unused.
131 * The alternative here, though, is to do a linear search over the
132 * whole circuit ID space every time we extend a circuit, which is
133 * not so great either.
135 int64_t queued_destroys;
136 char *m = rate_limit_log(&chan->last_warned_circ_ids_exhausted,
137 approx_time());
138 if (m == NULL)
139 return 0; /* This message has been rate-limited away. */
140 if (n_pending_destroy)
141 pending_destroy_time_total /= n_pending_destroy;
142 log_warn(LD_CIRC,"No unused circIDs found on channel %s wide "
143 "circID support, with %u inbound and %u outbound circuits. "
144 "Found %u circuit IDs in use by circuits, and %u with "
145 "pending destroy cells. (%u of those were marked bogusly.) "
146 "The ones with pending destroy cells "
147 "have been marked unusable for an average of %ld seconds "
148 "and a maximum of %ld seconds. This channel is %ld seconds "
149 "old. Failing a circuit.%s",
150 chan->wide_circ_ids ? "with" : "without",
151 chan->num_p_circuits, chan->num_n_circuits,
152 n_with_circ, n_pending_destroy, n_weird_pending_destroy,
153 (long)pending_destroy_time_total,
154 (long)pending_destroy_time_max,
155 (long)(approx_time() - chan->timestamp_created),
157 tor_free(m);
159 if (!chan->cmux) {
160 /* This warning should be impossible. */
161 log_warn(LD_BUG, " This channel somehow has no cmux on it!");
162 return 0;
165 /* analysis so far on 12184 suggests that we're running out of circuit
166 IDs because it looks like we have too many pending destroy
167 cells. Let's see how many we really have pending.
169 queued_destroys = circuitmux_count_queued_destroy_cells(chan,
170 chan->cmux);
172 log_warn(LD_CIRC, " Circuitmux on this channel has %u circuits, "
173 "of which %u are active. It says it has "I64_FORMAT
174 " destroy cells queued.",
175 circuitmux_num_circuits(chan->cmux),
176 circuitmux_num_active_circuits(chan->cmux),
177 I64_PRINTF_ARG(queued_destroys));
179 /* Change this into "if (1)" in order to get more information about
180 * possible failure modes here. You'll need to know how to use gdb with
181 * Tor: this will make Tor exit with an assertion failure if the cmux is
182 * corrupt. */
183 if (0)
184 circuitmux_assert_okay(chan->cmux);
186 channel_dump_statistics(chan, LOG_WARN);
188 return 0;
191 do {
192 crypto_rand((char*) &test_circ_id, sizeof(test_circ_id));
193 test_circ_id &= mask;
194 } while (test_circ_id == 0);
196 test_circ_id |= high_bit;
198 in_use = circuit_id_in_use_on_channel(test_circ_id, chan);
199 if (in_use == 1)
200 ++n_with_circ;
201 else if (in_use == 2) {
202 time_t since_when;
203 ++n_pending_destroy;
204 since_when =
205 circuit_id_when_marked_unusable_on_channel(test_circ_id, chan);
206 if (since_when) {
207 time_t waiting = approx_time() - since_when;
208 pending_destroy_time_total += waiting;
209 if (waiting > pending_destroy_time_max)
210 pending_destroy_time_max = waiting;
211 } else {
212 ++n_weird_pending_destroy;
215 } while (in_use);
216 return test_circ_id;
219 /** If <b>verbose</b> is false, allocate and return a comma-separated list of
220 * the currently built elements of <b>circ</b>. If <b>verbose</b> is true, also
221 * list information about link status in a more verbose format using spaces.
222 * If <b>verbose_names</b> is false, give nicknames for Named routers and hex
223 * digests for others; if <b>verbose_names</b> is true, use $DIGEST=Name style
224 * names.
226 static char *
227 circuit_list_path_impl(origin_circuit_t *circ, int verbose, int verbose_names)
229 crypt_path_t *hop;
230 smartlist_t *elements;
231 const char *states[] = {"closed", "waiting for keys", "open"};
232 char *s;
234 elements = smartlist_new();
236 if (verbose) {
237 const char *nickname = build_state_get_exit_nickname(circ->build_state);
238 smartlist_add_asprintf(elements, "%s%s circ (length %d%s%s):",
239 circ->build_state->is_internal ? "internal" : "exit",
240 circ->build_state->need_uptime ? " (high-uptime)" : "",
241 circ->build_state->desired_path_len,
242 circ->base_.state == CIRCUIT_STATE_OPEN ? "" : ", last hop ",
243 circ->base_.state == CIRCUIT_STATE_OPEN ? "" :
244 (nickname?nickname:"*unnamed*"));
247 hop = circ->cpath;
248 do {
249 char *elt;
250 const char *id;
251 const node_t *node;
252 if (!hop)
253 break;
254 if (!verbose && hop->state != CPATH_STATE_OPEN)
255 break;
256 if (!hop->extend_info)
257 break;
258 id = hop->extend_info->identity_digest;
259 if (verbose_names) {
260 elt = tor_malloc(MAX_VERBOSE_NICKNAME_LEN+1);
261 if ((node = node_get_by_id(id))) {
262 node_get_verbose_nickname(node, elt);
263 } else if (is_legal_nickname(hop->extend_info->nickname)) {
264 elt[0] = '$';
265 base16_encode(elt+1, HEX_DIGEST_LEN+1, id, DIGEST_LEN);
266 elt[HEX_DIGEST_LEN+1]= '~';
267 strlcpy(elt+HEX_DIGEST_LEN+2,
268 hop->extend_info->nickname, MAX_NICKNAME_LEN+1);
269 } else {
270 elt[0] = '$';
271 base16_encode(elt+1, HEX_DIGEST_LEN+1, id, DIGEST_LEN);
273 } else { /* ! verbose_names */
274 node = node_get_by_id(id);
275 if (node && node_is_named(node)) {
276 elt = tor_strdup(node_get_nickname(node));
277 } else {
278 elt = tor_malloc(HEX_DIGEST_LEN+2);
279 elt[0] = '$';
280 base16_encode(elt+1, HEX_DIGEST_LEN+1, id, DIGEST_LEN);
283 tor_assert(elt);
284 if (verbose) {
285 tor_assert(hop->state <= 2);
286 smartlist_add_asprintf(elements,"%s(%s)",elt,states[hop->state]);
287 tor_free(elt);
288 } else {
289 smartlist_add(elements, elt);
291 hop = hop->next;
292 } while (hop != circ->cpath);
294 s = smartlist_join_strings(elements, verbose?" ":",", 0, NULL);
295 SMARTLIST_FOREACH(elements, char*, cp, tor_free(cp));
296 smartlist_free(elements);
297 return s;
300 /** If <b>verbose</b> is false, allocate and return a comma-separated
301 * list of the currently built elements of <b>circ</b>. If
302 * <b>verbose</b> is true, also list information about link status in
303 * a more verbose format using spaces.
305 char *
306 circuit_list_path(origin_circuit_t *circ, int verbose)
308 return circuit_list_path_impl(circ, verbose, 0);
311 /** Allocate and return a comma-separated list of the currently built elements
312 * of <b>circ</b>, giving each as a verbose nickname.
314 char *
315 circuit_list_path_for_controller(origin_circuit_t *circ)
317 return circuit_list_path_impl(circ, 0, 1);
320 /** Log, at severity <b>severity</b>, the nicknames of each router in
321 * <b>circ</b>'s cpath. Also log the length of the cpath, and the intended
322 * exit point.
324 void
325 circuit_log_path(int severity, unsigned int domain, origin_circuit_t *circ)
327 char *s = circuit_list_path(circ,1);
328 tor_log(severity,domain,"%s",s);
329 tor_free(s);
332 /** Tell the rep(utation)hist(ory) module about the status of the links
333 * in <b>circ</b>. Hops that have become OPEN are marked as successfully
334 * extended; the _first_ hop that isn't open (if any) is marked as
335 * unable to extend.
337 /* XXXX Someday we should learn from OR circuits too. */
338 void
339 circuit_rep_hist_note_result(origin_circuit_t *circ)
341 crypt_path_t *hop;
342 const char *prev_digest = NULL;
343 hop = circ->cpath;
344 if (!hop) /* circuit hasn't started building yet. */
345 return;
346 if (server_mode(get_options())) {
347 const routerinfo_t *me = router_get_my_routerinfo();
348 if (!me)
349 return;
350 prev_digest = me->cache_info.identity_digest;
352 do {
353 const node_t *node = node_get_by_id(hop->extend_info->identity_digest);
354 if (node) { /* Why do we check this? We know the identity. -NM XXXX */
355 if (prev_digest) {
356 if (hop->state == CPATH_STATE_OPEN)
357 rep_hist_note_extend_succeeded(prev_digest, node->identity);
358 else {
359 rep_hist_note_extend_failed(prev_digest, node->identity);
360 break;
363 prev_digest = node->identity;
364 } else {
365 prev_digest = NULL;
367 hop=hop->next;
368 } while (hop!=circ->cpath);
371 #ifdef CURVE25519_ENABLED
372 /** Return 1 iff at least one node in circ's cpath supports ntor. */
373 static int
374 circuit_cpath_supports_ntor(const origin_circuit_t *circ)
376 crypt_path_t *head, *cpath;
378 cpath = head = circ->cpath;
379 do {
380 if (cpath->extend_info &&
381 !tor_mem_is_zero(
382 (const char*)cpath->extend_info->curve25519_onion_key.public_key,
383 CURVE25519_PUBKEY_LEN))
384 return 1;
386 cpath = cpath->next;
387 } while (cpath != head);
389 return 0;
391 #else
392 #define circuit_cpath_supports_ntor(circ) 0
393 #endif
395 /** Pick all the entries in our cpath. Stop and return 0 when we're
396 * happy, or return -1 if an error occurs. */
397 static int
398 onion_populate_cpath(origin_circuit_t *circ)
400 int n_tries = 0;
401 #ifdef CURVE25519_ENABLED
402 const int using_ntor = circuits_can_use_ntor();
403 #else
404 const int using_ntor = 0;
405 #endif
407 #define MAX_POPULATE_ATTEMPTS 32
409 while (1) {
410 int r = onion_extend_cpath(circ);
411 if (r < 0) {
412 log_info(LD_CIRC,"Generating cpath hop failed.");
413 return -1;
415 if (r == 1) {
416 /* This circuit doesn't need/shouldn't be forced to have an ntor hop */
417 if (circ->build_state->desired_path_len <= 1 || ! using_ntor)
418 return 0;
420 /* This circuit has an ntor hop. great! */
421 if (circuit_cpath_supports_ntor(circ))
422 return 0;
424 /* No node in the circuit supports ntor. Have we already tried too many
425 * times? */
426 if (++n_tries >= MAX_POPULATE_ATTEMPTS)
427 break;
429 /* Clear the path and retry */
430 circuit_clear_cpath(circ);
433 log_warn(LD_CIRC, "I tried for %d times, but I couldn't build a %d-hop "
434 "circuit with at least one node that supports ntor.",
435 MAX_POPULATE_ATTEMPTS,
436 circ->build_state->desired_path_len);
438 return -1;
441 /** Create and return a new origin circuit. Initialize its purpose and
442 * build-state based on our arguments. The <b>flags</b> argument is a
443 * bitfield of CIRCLAUNCH_* flags. */
444 origin_circuit_t *
445 origin_circuit_init(uint8_t purpose, int flags)
447 /* sets circ->p_circ_id and circ->p_chan */
448 origin_circuit_t *circ = origin_circuit_new();
449 circuit_set_state(TO_CIRCUIT(circ), CIRCUIT_STATE_CHAN_WAIT);
450 circ->build_state = tor_malloc_zero(sizeof(cpath_build_state_t));
451 circ->build_state->onehop_tunnel =
452 ((flags & CIRCLAUNCH_ONEHOP_TUNNEL) ? 1 : 0);
453 circ->build_state->need_uptime =
454 ((flags & CIRCLAUNCH_NEED_UPTIME) ? 1 : 0);
455 circ->build_state->need_capacity =
456 ((flags & CIRCLAUNCH_NEED_CAPACITY) ? 1 : 0);
457 circ->build_state->is_internal =
458 ((flags & CIRCLAUNCH_IS_INTERNAL) ? 1 : 0);
459 circ->base_.purpose = purpose;
460 return circ;
463 /** Build a new circuit for <b>purpose</b>. If <b>exit</b>
464 * is defined, then use that as your exit router, else choose a suitable
465 * exit node.
467 * Also launch a connection to the first OR in the chosen path, if
468 * it's not open already.
470 origin_circuit_t *
471 circuit_establish_circuit(uint8_t purpose, extend_info_t *exit, int flags)
473 origin_circuit_t *circ;
474 int err_reason = 0;
476 circ = origin_circuit_init(purpose, flags);
478 if (onion_pick_cpath_exit(circ, exit) < 0 ||
479 onion_populate_cpath(circ) < 0) {
480 circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_NOPATH);
481 return NULL;
484 control_event_circuit_status(circ, CIRC_EVENT_LAUNCHED, 0);
486 if ((err_reason = circuit_handle_first_hop(circ)) < 0) {
487 circuit_mark_for_close(TO_CIRCUIT(circ), -err_reason);
488 return NULL;
490 return circ;
493 /** Start establishing the first hop of our circuit. Figure out what
494 * OR we should connect to, and if necessary start the connection to
495 * it. If we're already connected, then send the 'create' cell.
496 * Return 0 for ok, -reason if circ should be marked-for-close. */
498 circuit_handle_first_hop(origin_circuit_t *circ)
500 crypt_path_t *firsthop;
501 channel_t *n_chan;
502 int err_reason = 0;
503 const char *msg = NULL;
504 int should_launch = 0;
506 firsthop = onion_next_hop_in_cpath(circ->cpath);
507 tor_assert(firsthop);
508 tor_assert(firsthop->extend_info);
510 /* now see if we're already connected to the first OR in 'route' */
511 log_debug(LD_CIRC,"Looking for firsthop '%s'",
512 fmt_addrport(&firsthop->extend_info->addr,
513 firsthop->extend_info->port));
515 n_chan = channel_get_for_extend(firsthop->extend_info->identity_digest,
516 &firsthop->extend_info->addr,
517 &msg,
518 &should_launch);
520 if (!n_chan) {
521 /* not currently connected in a useful way. */
522 log_info(LD_CIRC, "Next router is %s: %s",
523 safe_str_client(extend_info_describe(firsthop->extend_info)),
524 msg?msg:"???");
525 circ->base_.n_hop = extend_info_dup(firsthop->extend_info);
527 if (should_launch) {
528 if (circ->build_state->onehop_tunnel)
529 control_event_bootstrap(BOOTSTRAP_STATUS_CONN_DIR, 0);
530 n_chan = channel_connect_for_circuit(
531 &firsthop->extend_info->addr,
532 firsthop->extend_info->port,
533 firsthop->extend_info->identity_digest);
534 if (!n_chan) { /* connect failed, forget the whole thing */
535 log_info(LD_CIRC,"connect to firsthop failed. Closing.");
536 return -END_CIRC_REASON_CONNECTFAILED;
540 log_debug(LD_CIRC,"connecting in progress (or finished). Good.");
541 /* return success. The onion/circuit/etc will be taken care of
542 * automatically (may already have been) whenever n_chan reaches
543 * OR_CONN_STATE_OPEN.
545 return 0;
546 } else { /* it's already open. use it. */
547 tor_assert(!circ->base_.n_hop);
548 circ->base_.n_chan = n_chan;
549 log_debug(LD_CIRC,"Conn open. Delivering first onion skin.");
550 if ((err_reason = circuit_send_next_onion_skin(circ)) < 0) {
551 log_info(LD_CIRC,"circuit_send_next_onion_skin failed.");
552 circ->base_.n_chan = NULL;
553 return err_reason;
556 return 0;
559 /** Find any circuits that are waiting on <b>or_conn</b> to become
560 * open and get them to send their create cells forward.
562 * Status is 1 if connect succeeded, or 0 if connect failed.
564 void
565 circuit_n_chan_done(channel_t *chan, int status)
567 smartlist_t *pending_circs;
568 int err_reason = 0;
570 tor_assert(chan);
572 log_debug(LD_CIRC,"chan to %s/%s, status=%d",
573 chan->nickname ? chan->nickname : "NULL",
574 channel_get_canonical_remote_descr(chan), status);
576 pending_circs = smartlist_new();
577 circuit_get_all_pending_on_channel(pending_circs, chan);
579 SMARTLIST_FOREACH_BEGIN(pending_circs, circuit_t *, circ)
581 /* These checks are redundant wrt get_all_pending_on_or_conn, but I'm
582 * leaving them in in case it's possible for the status of a circuit to
583 * change as we're going down the list. */
584 if (circ->marked_for_close || circ->n_chan || !circ->n_hop ||
585 circ->state != CIRCUIT_STATE_CHAN_WAIT)
586 continue;
588 if (tor_digest_is_zero(circ->n_hop->identity_digest)) {
589 /* Look at addr/port. This is an unkeyed connection. */
590 if (!channel_matches_extend_info(chan, circ->n_hop))
591 continue;
592 } else {
593 /* We expected a key. See if it's the right one. */
594 if (tor_memneq(chan->identity_digest,
595 circ->n_hop->identity_digest, DIGEST_LEN))
596 continue;
598 if (!status) { /* chan failed; close circ */
599 log_info(LD_CIRC,"Channel failed; closing circ.");
600 circuit_mark_for_close(circ, END_CIRC_REASON_CHANNEL_CLOSED);
601 continue;
603 log_debug(LD_CIRC, "Found circ, sending create cell.");
604 /* circuit_deliver_create_cell will set n_circ_id and add us to
605 * chan_circuid_circuit_map, so we don't need to call
606 * set_circid_chan here. */
607 circ->n_chan = chan;
608 extend_info_free(circ->n_hop);
609 circ->n_hop = NULL;
611 if (CIRCUIT_IS_ORIGIN(circ)) {
612 if ((err_reason =
613 circuit_send_next_onion_skin(TO_ORIGIN_CIRCUIT(circ))) < 0) {
614 log_info(LD_CIRC,
615 "send_next_onion_skin failed; circuit marked for closing.");
616 circuit_mark_for_close(circ, -err_reason);
617 continue;
618 /* XXX could this be bad, eg if next_onion_skin failed because conn
619 * died? */
621 } else {
622 /* pull the create cell out of circ->n_chan_create_cell, and send it */
623 tor_assert(circ->n_chan_create_cell);
624 if (circuit_deliver_create_cell(circ, circ->n_chan_create_cell, 1)<0) {
625 circuit_mark_for_close(circ, END_CIRC_REASON_RESOURCELIMIT);
626 continue;
628 tor_free(circ->n_chan_create_cell);
629 circuit_set_state(circ, CIRCUIT_STATE_OPEN);
632 SMARTLIST_FOREACH_END(circ);
634 smartlist_free(pending_circs);
637 /** Find a new circid that isn't currently in use on the circ->n_chan
638 * for the outgoing
639 * circuit <b>circ</b>, and deliver the cell <b>create_cell</b> to this
640 * circuit. If <b>relayed</b> is true, this is a create cell somebody
641 * gave us via an EXTEND cell, so we shouldn't worry if we don't understand
642 * it. Return -1 if we failed to find a suitable circid, else return 0.
644 static int
645 circuit_deliver_create_cell(circuit_t *circ, const create_cell_t *create_cell,
646 int relayed)
648 cell_t cell;
649 circid_t id;
650 int r;
652 tor_assert(circ);
653 tor_assert(circ->n_chan);
654 tor_assert(create_cell);
655 tor_assert(create_cell->cell_type == CELL_CREATE ||
656 create_cell->cell_type == CELL_CREATE_FAST ||
657 create_cell->cell_type == CELL_CREATE2);
659 id = get_unique_circ_id_by_chan(circ->n_chan);
660 if (!id) {
661 static ratelim_t circid_warning_limit = RATELIM_INIT(9600);
662 log_fn_ratelim(&circid_warning_limit, LOG_WARN, LD_CIRC,
663 "failed to get unique circID.");
664 goto error;
667 memset(&cell, 0, sizeof(cell_t));
668 r = relayed ? create_cell_format_relayed(&cell, create_cell)
669 : create_cell_format(&cell, create_cell);
670 if (r < 0) {
671 log_warn(LD_CIRC,"Couldn't format create cell");
672 goto error;
674 log_debug(LD_CIRC,"Chosen circID %u.", (unsigned)id);
675 circuit_set_n_circid_chan(circ, id, circ->n_chan);
676 cell.circ_id = circ->n_circ_id;
678 append_cell_to_circuit_queue(circ, circ->n_chan, &cell,
679 CELL_DIRECTION_OUT, 0);
681 if (CIRCUIT_IS_ORIGIN(circ)) {
682 /* Update began timestamp for circuits starting their first hop */
683 if (TO_ORIGIN_CIRCUIT(circ)->cpath->state == CPATH_STATE_CLOSED) {
684 if (circ->n_chan->state != CHANNEL_STATE_OPEN) {
685 log_warn(LD_CIRC,
686 "Got first hop for a circuit without an opened channel. "
687 "State: %s.", channel_state_to_string(circ->n_chan->state));
688 tor_fragile_assert();
691 tor_gettimeofday(&circ->timestamp_began);
694 /* mark it so it gets better rate limiting treatment. */
695 channel_timestamp_client(circ->n_chan);
698 return 0;
699 error:
700 circ->n_chan = NULL;
701 return -1;
704 /** We've decided to start our reachability testing. If all
705 * is set, log this to the user. Return 1 if we did, or 0 if
706 * we chose not to log anything. */
708 inform_testing_reachability(void)
710 char dirbuf[128];
711 char *address;
712 const routerinfo_t *me = router_get_my_routerinfo();
713 if (!me)
714 return 0;
715 address = tor_dup_ip(me->addr);
716 control_event_server_status(LOG_NOTICE,
717 "CHECKING_REACHABILITY ORADDRESS=%s:%d",
718 address, me->or_port);
719 if (me->dir_port) {
720 tor_snprintf(dirbuf, sizeof(dirbuf), " and DirPort %s:%d",
721 address, me->dir_port);
722 control_event_server_status(LOG_NOTICE,
723 "CHECKING_REACHABILITY DIRADDRESS=%s:%d",
724 address, me->dir_port);
726 log_notice(LD_OR, "Now checking whether ORPort %s:%d%s %s reachable... "
727 "(this may take up to %d minutes -- look for log "
728 "messages indicating success)",
729 address, me->or_port,
730 me->dir_port ? dirbuf : "",
731 me->dir_port ? "are" : "is",
732 TIMEOUT_UNTIL_UNREACHABILITY_COMPLAINT/60);
734 tor_free(address);
735 return 1;
738 /** Return true iff we should send a create_fast cell to start building a given
739 * circuit */
740 static INLINE int
741 should_use_create_fast_for_circuit(origin_circuit_t *circ)
743 const or_options_t *options = get_options();
744 tor_assert(circ->cpath);
745 tor_assert(circ->cpath->extend_info);
747 if (!circ->cpath->extend_info->onion_key)
748 return 1; /* our hand is forced: only a create_fast will work. */
749 if (public_server_mode(options)) {
750 /* We're a server, and we know an onion key. We can choose.
751 * Prefer to blend our circuit into the other circuits we are
752 * creating on behalf of others. */
753 return 0;
755 if (options->FastFirstHopPK == -1) {
756 /* option is "auto", so look at the consensus. */
757 return networkstatus_get_param(NULL, "usecreatefast", 1, 0, 1);
760 return options->FastFirstHopPK;
763 /** Return true if <b>circ</b> is the type of circuit we want to count
764 * timeouts from. In particular, we want it to have not completed yet
765 * (already completing indicates we cannibalized it), and we want it to
766 * have exactly three hops.
769 circuit_timeout_want_to_count_circ(origin_circuit_t *circ)
771 return !circ->has_opened
772 && circ->build_state->desired_path_len == DEFAULT_ROUTE_LEN;
775 #ifdef CURVE25519_ENABLED
776 /** Return true if the ntor handshake is enabled in the configuration, or if
777 * it's been set to "auto" in the configuration and it's enabled in the
778 * consensus. */
779 static int
780 circuits_can_use_ntor(void)
782 const or_options_t *options = get_options();
783 if (options->UseNTorHandshake != -1)
784 return options->UseNTorHandshake;
785 return networkstatus_get_param(NULL, "UseNTorHandshake", 0, 0, 1);
787 #endif
789 /** Decide whether to use a TAP or ntor handshake for connecting to <b>ei</b>
790 * directly, and set *<b>cell_type_out</b> and *<b>handshake_type_out</b>
791 * accordingly. */
792 static void
793 circuit_pick_create_handshake(uint8_t *cell_type_out,
794 uint16_t *handshake_type_out,
795 const extend_info_t *ei)
797 #ifdef CURVE25519_ENABLED
798 if (!tor_mem_is_zero((const char*)ei->curve25519_onion_key.public_key,
799 CURVE25519_PUBKEY_LEN) &&
800 circuits_can_use_ntor()) {
801 *cell_type_out = CELL_CREATE2;
802 *handshake_type_out = ONION_HANDSHAKE_TYPE_NTOR;
803 return;
805 #else
806 (void) ei;
807 #endif
809 *cell_type_out = CELL_CREATE;
810 *handshake_type_out = ONION_HANDSHAKE_TYPE_TAP;
813 /** Decide whether to use a TAP or ntor handshake for connecting to <b>ei</b>
814 * directly, and set *<b>handshake_type_out</b> accordingly. Decide whether,
815 * in extending through <b>node</b> to do so, we should use an EXTEND2 or an
816 * EXTEND cell to do so, and set *<b>cell_type_out</b> and
817 * *<b>create_cell_type_out</b> accordingly. */
818 static void
819 circuit_pick_extend_handshake(uint8_t *cell_type_out,
820 uint8_t *create_cell_type_out,
821 uint16_t *handshake_type_out,
822 const node_t *node_prev,
823 const extend_info_t *ei)
825 uint8_t t;
826 circuit_pick_create_handshake(&t, handshake_type_out, ei);
827 /* XXXX024 The check for whether the node has a curve25519 key is a bad
828 * proxy for whether it can do extend2 cells; once a version that
829 * handles extend2 cells is out, remove it. */
830 if (node_prev &&
831 *handshake_type_out != ONION_HANDSHAKE_TYPE_TAP &&
832 (node_has_curve25519_onion_key(node_prev) ||
833 (node_prev->rs && node_prev->rs->version_supports_extend2_cells))) {
834 *cell_type_out = RELAY_COMMAND_EXTEND2;
835 *create_cell_type_out = CELL_CREATE2;
836 } else {
837 *cell_type_out = RELAY_COMMAND_EXTEND;
838 *create_cell_type_out = CELL_CREATE;
842 /** This is the backbone function for building circuits.
844 * If circ's first hop is closed, then we need to build a create
845 * cell and send it forward.
847 * Otherwise, we need to build a relay extend cell and send it
848 * forward.
850 * Return -reason if we want to tear down circ, else return 0.
853 circuit_send_next_onion_skin(origin_circuit_t *circ)
855 crypt_path_t *hop;
856 const node_t *node;
858 tor_assert(circ);
860 if (circ->cpath->state == CPATH_STATE_CLOSED) {
861 /* This is the first hop. */
862 create_cell_t cc;
863 int fast;
864 int len;
865 log_debug(LD_CIRC,"First skin; sending create cell.");
866 memset(&cc, 0, sizeof(cc));
867 if (circ->build_state->onehop_tunnel)
868 control_event_bootstrap(BOOTSTRAP_STATUS_ONEHOP_CREATE, 0);
869 else
870 control_event_bootstrap(BOOTSTRAP_STATUS_CIRCUIT_CREATE, 0);
872 node = node_get_by_id(circ->base_.n_chan->identity_digest);
873 fast = should_use_create_fast_for_circuit(circ);
874 if (!fast) {
875 /* We are an OR and we know the right onion key: we should
876 * send a create cell.
878 circuit_pick_create_handshake(&cc.cell_type, &cc.handshake_type,
879 circ->cpath->extend_info);
880 note_request("cell: create", 1);
881 } else {
882 /* We are not an OR, and we're building the first hop of a circuit to a
883 * new OR: we can be speedy and use CREATE_FAST to save an RSA operation
884 * and a DH operation. */
885 cc.cell_type = CELL_CREATE_FAST;
886 cc.handshake_type = ONION_HANDSHAKE_TYPE_FAST;
887 note_request("cell: create fast", 1);
890 len = onion_skin_create(cc.handshake_type,
891 circ->cpath->extend_info,
892 &circ->cpath->handshake_state,
893 cc.onionskin);
894 if (len < 0) {
895 log_warn(LD_CIRC,"onion_skin_create (first hop) failed.");
896 return - END_CIRC_REASON_INTERNAL;
898 cc.handshake_len = len;
900 if (circuit_deliver_create_cell(TO_CIRCUIT(circ), &cc, 0) < 0)
901 return - END_CIRC_REASON_RESOURCELIMIT;
903 circ->cpath->state = CPATH_STATE_AWAITING_KEYS;
904 circuit_set_state(TO_CIRCUIT(circ), CIRCUIT_STATE_BUILDING);
905 log_info(LD_CIRC,"First hop: finished sending %s cell to '%s'",
906 fast ? "CREATE_FAST" : "CREATE",
907 node ? node_describe(node) : "<unnamed>");
908 } else {
909 extend_cell_t ec;
910 int len;
911 tor_assert(circ->cpath->state == CPATH_STATE_OPEN);
912 tor_assert(circ->base_.state == CIRCUIT_STATE_BUILDING);
913 log_debug(LD_CIRC,"starting to send subsequent skin.");
914 hop = onion_next_hop_in_cpath(circ->cpath);
915 memset(&ec, 0, sizeof(ec));
916 if (!hop) {
917 /* done building the circuit. whew. */
918 circuit_set_state(TO_CIRCUIT(circ), CIRCUIT_STATE_OPEN);
919 if (circuit_timeout_want_to_count_circ(circ)) {
920 struct timeval end;
921 long timediff;
922 tor_gettimeofday(&end);
923 timediff = tv_mdiff(&circ->base_.timestamp_began, &end);
926 * If the circuit build time is much greater than we would have cut
927 * it off at, we probably had a suspend event along this codepath,
928 * and we should discard the value.
930 if (timediff < 0 ||
931 timediff > 2*get_circuit_build_close_time_ms()+1000) {
932 log_notice(LD_CIRC, "Strange value for circuit build time: %ldmsec. "
933 "Assuming clock jump. Purpose %d (%s)", timediff,
934 circ->base_.purpose,
935 circuit_purpose_to_string(circ->base_.purpose));
936 } else if (!circuit_build_times_disabled()) {
937 /* Only count circuit times if the network is live */
938 if (circuit_build_times_network_check_live(
939 get_circuit_build_times())) {
940 circuit_build_times_add_time(get_circuit_build_times_mutable(),
941 (build_time_t)timediff);
942 circuit_build_times_set_timeout(get_circuit_build_times_mutable());
945 if (circ->base_.purpose != CIRCUIT_PURPOSE_C_MEASURE_TIMEOUT) {
946 circuit_build_times_network_circ_success(
947 get_circuit_build_times_mutable());
951 log_info(LD_CIRC,"circuit built!");
952 circuit_reset_failure_count(0);
954 if (circ->build_state->onehop_tunnel || circ->has_opened) {
955 control_event_bootstrap(BOOTSTRAP_STATUS_REQUESTING_STATUS, 0);
958 pathbias_count_build_success(circ);
959 circuit_rep_hist_note_result(circ);
960 circuit_has_opened(circ); /* do other actions as necessary */
962 if (!can_complete_circuit && !circ->build_state->onehop_tunnel) {
963 const or_options_t *options = get_options();
964 can_complete_circuit=1;
965 /* FFFF Log a count of known routers here */
966 log_notice(LD_GENERAL,
967 "Tor has successfully opened a circuit. "
968 "Looks like client functionality is working.");
969 control_event_bootstrap(BOOTSTRAP_STATUS_DONE, 0);
970 control_event_client_status(LOG_NOTICE, "CIRCUIT_ESTABLISHED");
971 clear_broken_connection_map(1);
972 if (server_mode(options) && !check_whether_orport_reachable()) {
973 inform_testing_reachability();
974 consider_testing_reachability(1, 1);
978 /* We're done with measurement circuits here. Just close them */
979 if (circ->base_.purpose == CIRCUIT_PURPOSE_C_MEASURE_TIMEOUT) {
980 circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_FINISHED);
982 return 0;
985 if (tor_addr_family(&hop->extend_info->addr) != AF_INET) {
986 log_warn(LD_BUG, "Trying to extend to a non-IPv4 address.");
987 return - END_CIRC_REASON_INTERNAL;
991 const node_t *prev_node;
992 prev_node = node_get_by_id(hop->prev->extend_info->identity_digest);
993 circuit_pick_extend_handshake(&ec.cell_type,
994 &ec.create_cell.cell_type,
995 &ec.create_cell.handshake_type,
996 prev_node,
997 hop->extend_info);
1000 tor_addr_copy(&ec.orport_ipv4.addr, &hop->extend_info->addr);
1001 ec.orport_ipv4.port = hop->extend_info->port;
1002 tor_addr_make_unspec(&ec.orport_ipv6.addr);
1003 memcpy(ec.node_id, hop->extend_info->identity_digest, DIGEST_LEN);
1005 len = onion_skin_create(ec.create_cell.handshake_type,
1006 hop->extend_info,
1007 &hop->handshake_state,
1008 ec.create_cell.onionskin);
1009 if (len < 0) {
1010 log_warn(LD_CIRC,"onion_skin_create failed.");
1011 return - END_CIRC_REASON_INTERNAL;
1013 ec.create_cell.handshake_len = len;
1015 log_info(LD_CIRC,"Sending extend relay cell.");
1016 note_request("cell: extend", 1);
1018 uint8_t command = 0;
1019 uint16_t payload_len=0;
1020 uint8_t payload[RELAY_PAYLOAD_SIZE];
1021 if (extend_cell_format(&command, &payload_len, payload, &ec)<0) {
1022 log_warn(LD_CIRC,"Couldn't format extend cell");
1023 return -END_CIRC_REASON_INTERNAL;
1026 /* send it to hop->prev, because it will transfer
1027 * it to a create cell and then send to hop */
1028 if (relay_send_command_from_edge(0, TO_CIRCUIT(circ),
1029 command,
1030 (char*)payload, payload_len,
1031 hop->prev) < 0)
1032 return 0; /* circuit is closed */
1034 hop->state = CPATH_STATE_AWAITING_KEYS;
1036 return 0;
1039 /** Our clock just jumped by <b>seconds_elapsed</b>. Assume
1040 * something has also gone wrong with our network: notify the user,
1041 * and abandon all not-yet-used circuits. */
1042 void
1043 circuit_note_clock_jumped(int seconds_elapsed)
1045 int severity = server_mode(get_options()) ? LOG_WARN : LOG_NOTICE;
1046 tor_log(severity, LD_GENERAL, "Your system clock just jumped %d seconds %s; "
1047 "assuming established circuits no longer work.",
1048 seconds_elapsed >=0 ? seconds_elapsed : -seconds_elapsed,
1049 seconds_elapsed >=0 ? "forward" : "backward");
1050 control_event_general_status(LOG_WARN, "CLOCK_JUMPED TIME=%d",
1051 seconds_elapsed);
1052 can_complete_circuit=0; /* so it'll log when it works again */
1053 control_event_client_status(severity, "CIRCUIT_NOT_ESTABLISHED REASON=%s",
1054 "CLOCK_JUMPED");
1055 circuit_mark_all_unused_circs();
1056 circuit_mark_all_dirty_circs_as_unusable();
1059 /** Take the 'extend' <b>cell</b>, pull out addr/port plus the onion
1060 * skin and identity digest for the next hop. If we're already connected,
1061 * pass the onion skin to the next hop using a create cell; otherwise
1062 * launch a new OR connection, and <b>circ</b> will notice when the
1063 * connection succeeds or fails.
1065 * Return -1 if we want to warn and tear down the circuit, else return 0.
1068 circuit_extend(cell_t *cell, circuit_t *circ)
1070 channel_t *n_chan;
1071 relay_header_t rh;
1072 extend_cell_t ec;
1073 const char *msg = NULL;
1074 int should_launch = 0;
1076 if (circ->n_chan) {
1077 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
1078 "n_chan already set. Bug/attack. Closing.");
1079 return -1;
1081 if (circ->n_hop) {
1082 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
1083 "conn to next hop already launched. Bug/attack. Closing.");
1084 return -1;
1087 if (!server_mode(get_options())) {
1088 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
1089 "Got an extend cell, but running as a client. Closing.");
1090 return -1;
1093 relay_header_unpack(&rh, cell->payload);
1095 if (extend_cell_parse(&ec, rh.command,
1096 cell->payload+RELAY_HEADER_SIZE,
1097 rh.length) < 0) {
1098 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
1099 "Can't parse extend cell. Closing circuit.");
1100 return -1;
1103 if (!ec.orport_ipv4.port || tor_addr_is_null(&ec.orport_ipv4.addr)) {
1104 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
1105 "Client asked me to extend to zero destination port or addr.");
1106 return -1;
1109 if (tor_addr_is_internal(&ec.orport_ipv4.addr, 0) &&
1110 !get_options()->ExtendAllowPrivateAddresses) {
1111 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
1112 "Client asked me to extend to a private address");
1113 return -1;
1116 /* Check if they asked us for 0000..0000. We support using
1117 * an empty fingerprint for the first hop (e.g. for a bridge relay),
1118 * but we don't want to let people send us extend cells for empty
1119 * fingerprints -- a) because it opens the user up to a mitm attack,
1120 * and b) because it lets an attacker force the relay to hold open a
1121 * new TLS connection for each extend request. */
1122 if (tor_digest_is_zero((const char*)ec.node_id)) {
1123 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
1124 "Client asked me to extend without specifying an id_digest.");
1125 return -1;
1128 /* Next, check if we're being asked to connect to the hop that the
1129 * extend cell came from. There isn't any reason for that, and it can
1130 * assist circular-path attacks. */
1131 if (tor_memeq(ec.node_id,
1132 TO_OR_CIRCUIT(circ)->p_chan->identity_digest,
1133 DIGEST_LEN)) {
1134 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
1135 "Client asked me to extend back to the previous hop.");
1136 return -1;
1139 n_chan = channel_get_for_extend((const char*)ec.node_id,
1140 &ec.orport_ipv4.addr,
1141 &msg,
1142 &should_launch);
1144 if (!n_chan) {
1145 log_debug(LD_CIRC|LD_OR,"Next router (%s): %s",
1146 fmt_addrport(&ec.orport_ipv4.addr,ec.orport_ipv4.port),
1147 msg?msg:"????");
1149 circ->n_hop = extend_info_new(NULL /*nickname*/,
1150 (const char*)ec.node_id,
1151 NULL /*onion_key*/,
1152 NULL /*curve25519_key*/,
1153 &ec.orport_ipv4.addr,
1154 ec.orport_ipv4.port);
1156 circ->n_chan_create_cell = tor_memdup(&ec.create_cell,
1157 sizeof(ec.create_cell));
1159 circuit_set_state(circ, CIRCUIT_STATE_CHAN_WAIT);
1161 if (should_launch) {
1162 /* we should try to open a connection */
1163 n_chan = channel_connect_for_circuit(&ec.orport_ipv4.addr,
1164 ec.orport_ipv4.port,
1165 (const char*)ec.node_id);
1166 if (!n_chan) {
1167 log_info(LD_CIRC,"Launching n_chan failed. Closing circuit.");
1168 circuit_mark_for_close(circ, END_CIRC_REASON_CONNECTFAILED);
1169 return 0;
1171 log_debug(LD_CIRC,"connecting in progress (or finished). Good.");
1173 /* return success. The onion/circuit/etc will be taken care of
1174 * automatically (may already have been) whenever n_chan reaches
1175 * OR_CONN_STATE_OPEN.
1177 return 0;
1180 tor_assert(!circ->n_hop); /* Connection is already established. */
1181 circ->n_chan = n_chan;
1182 log_debug(LD_CIRC,
1183 "n_chan is %s",
1184 channel_get_canonical_remote_descr(n_chan));
1186 if (circuit_deliver_create_cell(circ, &ec.create_cell, 1) < 0)
1187 return -1;
1189 return 0;
1192 /** Initialize cpath-\>{f|b}_{crypto|digest} from the key material in
1193 * key_data. key_data must contain CPATH_KEY_MATERIAL bytes, which are
1194 * used as follows:
1195 * - 20 to initialize f_digest
1196 * - 20 to initialize b_digest
1197 * - 16 to key f_crypto
1198 * - 16 to key b_crypto
1200 * (If 'reverse' is true, then f_XX and b_XX are swapped.)
1203 circuit_init_cpath_crypto(crypt_path_t *cpath, const char *key_data,
1204 int reverse)
1206 crypto_digest_t *tmp_digest;
1207 crypto_cipher_t *tmp_crypto;
1209 tor_assert(cpath);
1210 tor_assert(key_data);
1211 tor_assert(!(cpath->f_crypto || cpath->b_crypto ||
1212 cpath->f_digest || cpath->b_digest));
1214 cpath->f_digest = crypto_digest_new();
1215 crypto_digest_add_bytes(cpath->f_digest, key_data, DIGEST_LEN);
1216 cpath->b_digest = crypto_digest_new();
1217 crypto_digest_add_bytes(cpath->b_digest, key_data+DIGEST_LEN, DIGEST_LEN);
1219 if (!(cpath->f_crypto =
1220 crypto_cipher_new(key_data+(2*DIGEST_LEN)))) {
1221 log_warn(LD_BUG,"Forward cipher initialization failed.");
1222 return -1;
1224 if (!(cpath->b_crypto =
1225 crypto_cipher_new(key_data+(2*DIGEST_LEN)+CIPHER_KEY_LEN))) {
1226 log_warn(LD_BUG,"Backward cipher initialization failed.");
1227 return -1;
1230 if (reverse) {
1231 tmp_digest = cpath->f_digest;
1232 cpath->f_digest = cpath->b_digest;
1233 cpath->b_digest = tmp_digest;
1234 tmp_crypto = cpath->f_crypto;
1235 cpath->f_crypto = cpath->b_crypto;
1236 cpath->b_crypto = tmp_crypto;
1239 return 0;
1242 /** A "created" cell <b>reply</b> came back to us on circuit <b>circ</b>.
1243 * (The body of <b>reply</b> varies depending on what sort of handshake
1244 * this is.)
1246 * Calculate the appropriate keys and digests, make sure KH is
1247 * correct, and initialize this hop of the cpath.
1249 * Return - reason if we want to mark circ for close, else return 0.
1252 circuit_finish_handshake(origin_circuit_t *circ,
1253 const created_cell_t *reply)
1255 char keys[CPATH_KEY_MATERIAL_LEN];
1256 crypt_path_t *hop;
1257 int rv;
1259 if ((rv = pathbias_count_build_attempt(circ)) < 0)
1260 return rv;
1262 if (circ->cpath->state == CPATH_STATE_AWAITING_KEYS) {
1263 hop = circ->cpath;
1264 } else {
1265 hop = onion_next_hop_in_cpath(circ->cpath);
1266 if (!hop) { /* got an extended when we're all done? */
1267 log_warn(LD_PROTOCOL,"got extended when circ already built? Closing.");
1268 return - END_CIRC_REASON_TORPROTOCOL;
1271 tor_assert(hop->state == CPATH_STATE_AWAITING_KEYS);
1274 if (onion_skin_client_handshake(hop->handshake_state.tag,
1275 &hop->handshake_state,
1276 reply->reply, reply->handshake_len,
1277 (uint8_t*)keys, sizeof(keys),
1278 (uint8_t*)hop->rend_circ_nonce) < 0) {
1279 log_warn(LD_CIRC,"onion_skin_client_handshake failed.");
1280 return -END_CIRC_REASON_TORPROTOCOL;
1284 onion_handshake_state_release(&hop->handshake_state);
1286 if (circuit_init_cpath_crypto(hop, keys, 0)<0) {
1287 return -END_CIRC_REASON_TORPROTOCOL;
1290 hop->state = CPATH_STATE_OPEN;
1291 log_info(LD_CIRC,"Finished building circuit hop:");
1292 circuit_log_path(LOG_INFO,LD_CIRC,circ);
1293 control_event_circuit_status(circ, CIRC_EVENT_EXTENDED, 0);
1295 return 0;
1298 /** We received a relay truncated cell on circ.
1300 * Since we don't send truncates currently, getting a truncated
1301 * means that a connection broke or an extend failed. For now,
1302 * just give up: force circ to close, and return 0.
1305 circuit_truncated(origin_circuit_t *circ, crypt_path_t *layer, int reason)
1307 // crypt_path_t *victim;
1308 // connection_t *stream;
1310 tor_assert(circ);
1311 tor_assert(layer);
1313 /* XXX Since we don't send truncates currently, getting a truncated
1314 * means that a connection broke or an extend failed. For now,
1315 * just give up.
1317 circuit_mark_for_close(TO_CIRCUIT(circ),
1318 END_CIRC_REASON_FLAG_REMOTE|reason);
1319 return 0;
1321 #if 0
1322 while (layer->next != circ->cpath) {
1323 /* we need to clear out layer->next */
1324 victim = layer->next;
1325 log_debug(LD_CIRC, "Killing a layer of the cpath.");
1327 for (stream = circ->p_streams; stream; stream=stream->next_stream) {
1328 if (stream->cpath_layer == victim) {
1329 log_info(LD_APP, "Marking stream %d for close because of truncate.",
1330 stream->stream_id);
1331 /* no need to send 'end' relay cells,
1332 * because the other side's already dead
1334 connection_mark_unattached_ap(stream, END_STREAM_REASON_DESTROY);
1338 layer->next = victim->next;
1339 circuit_free_cpath_node(victim);
1342 log_info(LD_CIRC, "finished");
1343 return 0;
1344 #endif
1347 /** Given a response payload and keys, initialize, then send a created
1348 * cell back.
1351 onionskin_answer(or_circuit_t *circ,
1352 const created_cell_t *created_cell,
1353 const char *keys,
1354 const uint8_t *rend_circ_nonce)
1356 cell_t cell;
1357 crypt_path_t *tmp_cpath;
1359 if (created_cell_format(&cell, created_cell) < 0) {
1360 log_warn(LD_BUG,"couldn't format created cell (type=%d, len=%d)",
1361 (int)created_cell->cell_type, (int)created_cell->handshake_len);
1362 return -1;
1364 cell.circ_id = circ->p_circ_id;
1366 tmp_cpath = tor_malloc_zero(sizeof(crypt_path_t));
1367 tmp_cpath->magic = CRYPT_PATH_MAGIC;
1369 circuit_set_state(TO_CIRCUIT(circ), CIRCUIT_STATE_OPEN);
1371 log_debug(LD_CIRC,"init digest forward 0x%.8x, backward 0x%.8x.",
1372 (unsigned int)get_uint32(keys),
1373 (unsigned int)get_uint32(keys+20));
1374 if (circuit_init_cpath_crypto(tmp_cpath, keys, 0)<0) {
1375 log_warn(LD_BUG,"Circuit initialization failed");
1376 tor_free(tmp_cpath);
1377 return -1;
1379 circ->n_digest = tmp_cpath->f_digest;
1380 circ->n_crypto = tmp_cpath->f_crypto;
1381 circ->p_digest = tmp_cpath->b_digest;
1382 circ->p_crypto = tmp_cpath->b_crypto;
1383 tmp_cpath->magic = 0;
1384 tor_free(tmp_cpath);
1386 memcpy(circ->rend_circ_nonce, rend_circ_nonce, DIGEST_LEN);
1388 circ->is_first_hop = (created_cell->cell_type == CELL_CREATED_FAST);
1390 append_cell_to_circuit_queue(TO_CIRCUIT(circ),
1391 circ->p_chan, &cell, CELL_DIRECTION_IN, 0);
1392 log_debug(LD_CIRC,"Finished sending '%s' cell.",
1393 circ->is_first_hop ? "created_fast" : "created");
1395 if (!channel_is_local(circ->p_chan) &&
1396 !channel_is_outgoing(circ->p_chan)) {
1397 /* record that we could process create cells from a non-local conn
1398 * that we didn't initiate; presumably this means that create cells
1399 * can reach us too. */
1400 router_orport_found_reachable();
1403 return 0;
1406 /** Choose a length for a circuit of purpose <b>purpose</b>: three + the
1407 * number of endpoints that would give something away about our destination.
1409 * If the routerlist <b>nodes</b> doesn't have enough routers
1410 * to handle the desired path length, return -1.
1412 static int
1413 new_route_len(uint8_t purpose, extend_info_t *exit, smartlist_t *nodes)
1415 int num_acceptable_routers;
1416 int routelen;
1418 tor_assert(nodes);
1420 routelen = DEFAULT_ROUTE_LEN;
1421 if (exit &&
1422 purpose != CIRCUIT_PURPOSE_TESTING &&
1423 purpose != CIRCUIT_PURPOSE_S_ESTABLISH_INTRO)
1424 routelen++;
1426 num_acceptable_routers = count_acceptable_nodes(nodes);
1428 log_debug(LD_CIRC,"Chosen route length %d (%d/%d routers suitable).",
1429 routelen, num_acceptable_routers, smartlist_len(nodes));
1431 if (num_acceptable_routers < routelen) {
1432 log_info(LD_CIRC,
1433 "Not enough acceptable routers (%d/%d). Discarding this circuit.",
1434 num_acceptable_routers, routelen);
1435 return -1;
1438 return routelen;
1441 /** Return a newly allocated list of uint16_t * for each predicted port not
1442 * handled by a current circuit. */
1443 static smartlist_t *
1444 circuit_get_unhandled_ports(time_t now)
1446 smartlist_t *dest = rep_hist_get_predicted_ports(now);
1447 circuit_remove_handled_ports(dest);
1448 return dest;
1451 /** Return 1 if we already have circuits present or on the way for
1452 * all anticipated ports. Return 0 if we should make more.
1454 * If we're returning 0, set need_uptime and need_capacity to
1455 * indicate any requirements that the unhandled ports have.
1458 circuit_all_predicted_ports_handled(time_t now, int *need_uptime,
1459 int *need_capacity)
1461 int i, enough;
1462 uint16_t *port;
1463 smartlist_t *sl = circuit_get_unhandled_ports(now);
1464 smartlist_t *LongLivedServices = get_options()->LongLivedPorts;
1465 tor_assert(need_uptime);
1466 tor_assert(need_capacity);
1467 // Always predict need_capacity
1468 *need_capacity = 1;
1469 enough = (smartlist_len(sl) == 0);
1470 for (i = 0; i < smartlist_len(sl); ++i) {
1471 port = smartlist_get(sl, i);
1472 if (smartlist_contains_int_as_string(LongLivedServices, *port))
1473 *need_uptime = 1;
1474 tor_free(port);
1476 smartlist_free(sl);
1477 return enough;
1480 /** Return 1 if <b>node</b> can handle one or more of the ports in
1481 * <b>needed_ports</b>, else return 0.
1483 static int
1484 node_handles_some_port(const node_t *node, smartlist_t *needed_ports)
1485 { /* XXXX MOVE */
1486 int i;
1487 uint16_t port;
1489 for (i = 0; i < smartlist_len(needed_ports); ++i) {
1490 addr_policy_result_t r;
1491 /* alignment issues aren't a worry for this dereference, since
1492 needed_ports is explicitly a smartlist of uint16_t's */
1493 port = *(uint16_t *)smartlist_get(needed_ports, i);
1494 tor_assert(port);
1495 if (node)
1496 r = compare_tor_addr_to_node_policy(NULL, port, node);
1497 else
1498 continue;
1499 if (r != ADDR_POLICY_REJECTED && r != ADDR_POLICY_PROBABLY_REJECTED)
1500 return 1;
1502 return 0;
1505 /** Return true iff <b>conn</b> needs another general circuit to be
1506 * built. */
1507 static int
1508 ap_stream_wants_exit_attention(connection_t *conn)
1510 entry_connection_t *entry;
1511 if (conn->type != CONN_TYPE_AP)
1512 return 0;
1513 entry = TO_ENTRY_CONN(conn);
1515 if (conn->state == AP_CONN_STATE_CIRCUIT_WAIT &&
1516 !conn->marked_for_close &&
1517 !(entry->want_onehop) && /* ignore one-hop streams */
1518 !(entry->use_begindir) && /* ignore targeted dir fetches */
1519 !(entry->chosen_exit_name) && /* ignore defined streams */
1520 !connection_edge_is_rendezvous_stream(TO_EDGE_CONN(conn)) &&
1521 !circuit_stream_is_being_handled(TO_ENTRY_CONN(conn), 0,
1522 MIN_CIRCUITS_HANDLING_STREAM))
1523 return 1;
1524 return 0;
1527 /** Return a pointer to a suitable router to be the exit node for the
1528 * general-purpose circuit we're about to build.
1530 * Look through the connection array, and choose a router that maximizes
1531 * the number of pending streams that can exit from this router.
1533 * Return NULL if we can't find any suitable routers.
1535 static const node_t *
1536 choose_good_exit_server_general(int need_uptime, int need_capacity)
1538 int *n_supported;
1539 int n_pending_connections = 0;
1540 smartlist_t *connections;
1541 int best_support = -1;
1542 int n_best_support=0;
1543 const or_options_t *options = get_options();
1544 const smartlist_t *the_nodes;
1545 const node_t *node=NULL;
1547 connections = get_connection_array();
1549 /* Count how many connections are waiting for a circuit to be built.
1550 * We use this for log messages now, but in the future we may depend on it.
1552 SMARTLIST_FOREACH(connections, connection_t *, conn,
1554 if (ap_stream_wants_exit_attention(conn))
1555 ++n_pending_connections;
1557 // log_fn(LOG_DEBUG, "Choosing exit node; %d connections are pending",
1558 // n_pending_connections);
1559 /* Now we count, for each of the routers in the directory, how many
1560 * of the pending connections could possibly exit from that
1561 * router (n_supported[i]). (We can't be sure about cases where we
1562 * don't know the IP address of the pending connection.)
1564 * -1 means "Don't use this router at all."
1566 the_nodes = nodelist_get_list();
1567 n_supported = tor_malloc(sizeof(int)*smartlist_len(the_nodes));
1568 SMARTLIST_FOREACH_BEGIN(the_nodes, const node_t *, node) {
1569 const int i = node_sl_idx;
1570 if (router_digest_is_me(node->identity)) {
1571 n_supported[i] = -1;
1572 // log_fn(LOG_DEBUG,"Skipping node %s -- it's me.", router->nickname);
1573 /* XXX there's probably a reverse predecessor attack here, but
1574 * it's slow. should we take this out? -RD
1576 continue;
1578 if (!node_has_descriptor(node)) {
1579 n_supported[i] = -1;
1580 continue;
1582 if (!node->is_running || node->is_bad_exit) {
1583 n_supported[i] = -1;
1584 continue; /* skip routers that are known to be down or bad exits */
1586 if (node_get_purpose(node) != ROUTER_PURPOSE_GENERAL) {
1587 /* never pick a non-general node as a random exit. */
1588 n_supported[i] = -1;
1589 continue;
1591 if (routerset_contains_node(options->ExcludeExitNodesUnion_, node)) {
1592 n_supported[i] = -1;
1593 continue; /* user asked us not to use it, no matter what */
1595 if (options->ExitNodes &&
1596 !routerset_contains_node(options->ExitNodes, node)) {
1597 n_supported[i] = -1;
1598 continue; /* not one of our chosen exit nodes */
1601 if (node_is_unreliable(node, need_uptime, need_capacity, 0)) {
1602 n_supported[i] = -1;
1603 continue; /* skip routers that are not suitable. Don't worry if
1604 * this makes us reject all the possible routers: if so,
1605 * we'll retry later in this function with need_update and
1606 * need_capacity set to 0. */
1608 if (!(node->is_valid || options->AllowInvalid_ & ALLOW_INVALID_EXIT)) {
1609 /* if it's invalid and we don't want it */
1610 n_supported[i] = -1;
1611 // log_fn(LOG_DEBUG,"Skipping node %s (index %d) -- invalid router.",
1612 // router->nickname, i);
1613 continue; /* skip invalid routers */
1615 if (options->ExcludeSingleHopRelays &&
1616 node_allows_single_hop_exits(node)) {
1617 n_supported[i] = -1;
1618 continue;
1620 if (node_exit_policy_rejects_all(node)) {
1621 n_supported[i] = -1;
1622 // log_fn(LOG_DEBUG,"Skipping node %s (index %d) -- it rejects all.",
1623 // router->nickname, i);
1624 continue; /* skip routers that reject all */
1626 n_supported[i] = 0;
1627 /* iterate over connections */
1628 SMARTLIST_FOREACH_BEGIN(connections, connection_t *, conn) {
1629 if (!ap_stream_wants_exit_attention(conn))
1630 continue; /* Skip everything but APs in CIRCUIT_WAIT */
1631 if (connection_ap_can_use_exit(TO_ENTRY_CONN(conn), node)) {
1632 ++n_supported[i];
1633 // log_fn(LOG_DEBUG,"%s is supported. n_supported[%d] now %d.",
1634 // router->nickname, i, n_supported[i]);
1635 } else {
1636 // log_fn(LOG_DEBUG,"%s (index %d) would reject this stream.",
1637 // router->nickname, i);
1639 } SMARTLIST_FOREACH_END(conn);
1640 if (n_pending_connections > 0 && n_supported[i] == 0) {
1641 /* Leave best_support at -1 if that's where it is, so we can
1642 * distinguish it later. */
1643 continue;
1645 if (n_supported[i] > best_support) {
1646 /* If this router is better than previous ones, remember its index
1647 * and goodness, and start counting how many routers are this good. */
1648 best_support = n_supported[i]; n_best_support=1;
1649 // log_fn(LOG_DEBUG,"%s is new best supported option so far.",
1650 // router->nickname);
1651 } else if (n_supported[i] == best_support) {
1652 /* If this router is _as good_ as the best one, just increment the
1653 * count of equally good routers.*/
1654 ++n_best_support;
1656 } SMARTLIST_FOREACH_END(node);
1657 log_info(LD_CIRC,
1658 "Found %d servers that might support %d/%d pending connections.",
1659 n_best_support, best_support >= 0 ? best_support : 0,
1660 n_pending_connections);
1662 /* If any routers definitely support any pending connections, choose one
1663 * at random. */
1664 if (best_support > 0) {
1665 smartlist_t *supporting = smartlist_new();
1667 SMARTLIST_FOREACH(the_nodes, const node_t *, node, {
1668 if (n_supported[node_sl_idx] == best_support)
1669 smartlist_add(supporting, (void*)node);
1672 node = node_sl_choose_by_bandwidth(supporting, WEIGHT_FOR_EXIT);
1673 smartlist_free(supporting);
1674 } else {
1675 /* Either there are no pending connections, or no routers even seem to
1676 * possibly support any of them. Choose a router at random that satisfies
1677 * at least one predicted exit port. */
1679 int attempt;
1680 smartlist_t *needed_ports, *supporting;
1682 if (best_support == -1) {
1683 if (need_uptime || need_capacity) {
1684 log_info(LD_CIRC,
1685 "We couldn't find any live%s%s routers; falling back "
1686 "to list of all routers.",
1687 need_capacity?", fast":"",
1688 need_uptime?", stable":"");
1689 tor_free(n_supported);
1690 return choose_good_exit_server_general(0, 0);
1692 log_notice(LD_CIRC, "All routers are down or won't exit%s -- "
1693 "choosing a doomed exit at random.",
1694 options->ExcludeExitNodesUnion_ ? " or are Excluded" : "");
1696 supporting = smartlist_new();
1697 needed_ports = circuit_get_unhandled_ports(time(NULL));
1698 for (attempt = 0; attempt < 2; attempt++) {
1699 /* try once to pick only from routers that satisfy a needed port,
1700 * then if there are none, pick from any that support exiting. */
1701 SMARTLIST_FOREACH_BEGIN(the_nodes, const node_t *, node) {
1702 if (n_supported[node_sl_idx] != -1 &&
1703 (attempt || node_handles_some_port(node, needed_ports))) {
1704 // log_fn(LOG_DEBUG,"Try %d: '%s' is a possibility.",
1705 // try, router->nickname);
1706 smartlist_add(supporting, (void*)node);
1708 } SMARTLIST_FOREACH_END(node);
1710 node = node_sl_choose_by_bandwidth(supporting, WEIGHT_FOR_EXIT);
1711 if (node)
1712 break;
1713 smartlist_clear(supporting);
1714 /* If we reach this point, we can't actually support any unhandled
1715 * predicted ports, so clear all the remaining ones. */
1716 if (smartlist_len(needed_ports))
1717 rep_hist_remove_predicted_ports(needed_ports);
1719 SMARTLIST_FOREACH(needed_ports, uint16_t *, cp, tor_free(cp));
1720 smartlist_free(needed_ports);
1721 smartlist_free(supporting);
1724 tor_free(n_supported);
1725 if (node) {
1726 log_info(LD_CIRC, "Chose exit server '%s'", node_describe(node));
1727 return node;
1729 if (options->ExitNodes) {
1730 log_warn(LD_CIRC,
1731 "No specified %sexit routers seem to be running: "
1732 "can't choose an exit.",
1733 options->ExcludeExitNodesUnion_ ? "non-excluded " : "");
1735 return NULL;
1738 /** Return a pointer to a suitable router to be the exit node for the
1739 * circuit of purpose <b>purpose</b> that we're about to build (or NULL
1740 * if no router is suitable).
1742 * For general-purpose circuits, pass it off to
1743 * choose_good_exit_server_general()
1745 * For client-side rendezvous circuits, choose a random node, weighted
1746 * toward the preferences in 'options'.
1748 static const node_t *
1749 choose_good_exit_server(uint8_t purpose,
1750 int need_uptime, int need_capacity, int is_internal)
1752 const or_options_t *options = get_options();
1753 router_crn_flags_t flags = CRN_NEED_DESC;
1754 if (need_uptime)
1755 flags |= CRN_NEED_UPTIME;
1756 if (need_capacity)
1757 flags |= CRN_NEED_CAPACITY;
1759 switch (purpose) {
1760 case CIRCUIT_PURPOSE_C_GENERAL:
1761 if (options->AllowInvalid_ & ALLOW_INVALID_MIDDLE)
1762 flags |= CRN_ALLOW_INVALID;
1763 if (is_internal) /* pick it like a middle hop */
1764 return router_choose_random_node(NULL, options->ExcludeNodes, flags);
1765 else
1766 return choose_good_exit_server_general(need_uptime,need_capacity);
1767 case CIRCUIT_PURPOSE_C_ESTABLISH_REND:
1768 if (options->AllowInvalid_ & ALLOW_INVALID_RENDEZVOUS)
1769 flags |= CRN_ALLOW_INVALID;
1770 return router_choose_random_node(NULL, options->ExcludeNodes, flags);
1772 log_warn(LD_BUG,"Unhandled purpose %d", purpose);
1773 tor_fragile_assert();
1774 return NULL;
1777 /** Log a warning if the user specified an exit for the circuit that
1778 * has been excluded from use by ExcludeNodes or ExcludeExitNodes. */
1779 static void
1780 warn_if_last_router_excluded(origin_circuit_t *circ, const extend_info_t *exit)
1782 const or_options_t *options = get_options();
1783 routerset_t *rs = options->ExcludeNodes;
1784 const char *description;
1785 uint8_t purpose = circ->base_.purpose;
1787 if (circ->build_state->onehop_tunnel)
1788 return;
1790 switch (purpose)
1792 default:
1793 case CIRCUIT_PURPOSE_OR:
1794 case CIRCUIT_PURPOSE_INTRO_POINT:
1795 case CIRCUIT_PURPOSE_REND_POINT_WAITING:
1796 case CIRCUIT_PURPOSE_REND_ESTABLISHED:
1797 log_warn(LD_BUG, "Called on non-origin circuit (purpose %d, %s)",
1798 (int)purpose,
1799 circuit_purpose_to_string(purpose));
1800 return;
1801 case CIRCUIT_PURPOSE_C_GENERAL:
1802 if (circ->build_state->is_internal)
1803 return;
1804 description = "requested exit node";
1805 rs = options->ExcludeExitNodesUnion_;
1806 break;
1807 case CIRCUIT_PURPOSE_C_INTRODUCING:
1808 case CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT:
1809 case CIRCUIT_PURPOSE_C_INTRODUCE_ACKED:
1810 case CIRCUIT_PURPOSE_S_ESTABLISH_INTRO:
1811 case CIRCUIT_PURPOSE_S_CONNECT_REND:
1812 case CIRCUIT_PURPOSE_S_REND_JOINED:
1813 case CIRCUIT_PURPOSE_TESTING:
1814 return;
1815 case CIRCUIT_PURPOSE_C_ESTABLISH_REND:
1816 case CIRCUIT_PURPOSE_C_REND_READY:
1817 case CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED:
1818 case CIRCUIT_PURPOSE_C_REND_JOINED:
1819 description = "chosen rendezvous point";
1820 break;
1821 case CIRCUIT_PURPOSE_CONTROLLER:
1822 rs = options->ExcludeExitNodesUnion_;
1823 description = "controller-selected circuit target";
1824 break;
1827 if (routerset_contains_extendinfo(rs, exit)) {
1828 /* We should never get here if StrictNodes is set to 1. */
1829 if (options->StrictNodes) {
1830 log_warn(LD_BUG, "Using %s '%s' which is listed in ExcludeNodes%s, "
1831 "even though StrictNodes is set. Please report. "
1832 "(Circuit purpose: %s)",
1833 description, extend_info_describe(exit),
1834 rs==options->ExcludeNodes?"":" or ExcludeExitNodes",
1835 circuit_purpose_to_string(purpose));
1836 } else {
1837 log_warn(LD_CIRC, "Using %s '%s' which is listed in "
1838 "ExcludeNodes%s, because no better options were available. To "
1839 "prevent this (and possibly break your Tor functionality), "
1840 "set the StrictNodes configuration option. "
1841 "(Circuit purpose: %s)",
1842 description, extend_info_describe(exit),
1843 rs==options->ExcludeNodes?"":" or ExcludeExitNodes",
1844 circuit_purpose_to_string(purpose));
1846 circuit_log_path(LOG_WARN, LD_CIRC, circ);
1849 return;
1852 /** Decide a suitable length for circ's cpath, and pick an exit
1853 * router (or use <b>exit</b> if provided). Store these in the
1854 * cpath. Return 0 if ok, -1 if circuit should be closed. */
1855 static int
1856 onion_pick_cpath_exit(origin_circuit_t *circ, extend_info_t *exit)
1858 cpath_build_state_t *state = circ->build_state;
1860 if (state->onehop_tunnel) {
1861 log_debug(LD_CIRC, "Launching a one-hop circuit for dir tunnel.");
1862 state->desired_path_len = 1;
1863 } else {
1864 int r = new_route_len(circ->base_.purpose, exit, nodelist_get_list());
1865 if (r < 1) /* must be at least 1 */
1866 return -1;
1867 state->desired_path_len = r;
1870 if (exit) { /* the circuit-builder pre-requested one */
1871 warn_if_last_router_excluded(circ, exit);
1872 log_info(LD_CIRC,"Using requested exit node '%s'",
1873 extend_info_describe(exit));
1874 exit = extend_info_dup(exit);
1875 } else { /* we have to decide one */
1876 const node_t *node =
1877 choose_good_exit_server(circ->base_.purpose, state->need_uptime,
1878 state->need_capacity, state->is_internal);
1879 if (!node) {
1880 log_warn(LD_CIRC,"failed to choose an exit server");
1881 return -1;
1883 exit = extend_info_from_node(node, 0);
1884 tor_assert(exit);
1886 state->chosen_exit = exit;
1887 return 0;
1890 /** Give <b>circ</b> a new exit destination to <b>exit</b>, and add a
1891 * hop to the cpath reflecting this. Don't send the next extend cell --
1892 * the caller will do this if it wants to.
1895 circuit_append_new_exit(origin_circuit_t *circ, extend_info_t *exit)
1897 cpath_build_state_t *state;
1898 tor_assert(exit);
1899 tor_assert(circ);
1901 state = circ->build_state;
1902 tor_assert(state);
1903 extend_info_free(state->chosen_exit);
1904 state->chosen_exit = extend_info_dup(exit);
1906 ++circ->build_state->desired_path_len;
1907 onion_append_hop(&circ->cpath, exit);
1908 return 0;
1911 /** Take an open <b>circ</b>, and add a new hop at the end, based on
1912 * <b>info</b>. Set its state back to CIRCUIT_STATE_BUILDING, and then
1913 * send the next extend cell to begin connecting to that hop.
1916 circuit_extend_to_new_exit(origin_circuit_t *circ, extend_info_t *exit)
1918 int err_reason = 0;
1919 warn_if_last_router_excluded(circ, exit);
1921 tor_gettimeofday(&circ->base_.timestamp_began);
1923 circuit_append_new_exit(circ, exit);
1924 circuit_set_state(TO_CIRCUIT(circ), CIRCUIT_STATE_BUILDING);
1925 if ((err_reason = circuit_send_next_onion_skin(circ))<0) {
1926 log_warn(LD_CIRC, "Couldn't extend circuit to new point %s.",
1927 extend_info_describe(exit));
1928 circuit_mark_for_close(TO_CIRCUIT(circ), -err_reason);
1929 return -1;
1932 // XXX: Should cannibalized circuits be dirty or not? Not easy to say..
1934 return 0;
1937 /** Return the number of routers in <b>routers</b> that are currently up
1938 * and available for building circuits through.
1940 static int
1941 count_acceptable_nodes(smartlist_t *nodes)
1943 int num=0;
1945 SMARTLIST_FOREACH_BEGIN(nodes, const node_t *, node) {
1946 // log_debug(LD_CIRC,
1947 // "Contemplating whether router %d (%s) is a new option.",
1948 // i, r->nickname);
1949 if (! node->is_running)
1950 // log_debug(LD_CIRC,"Nope, the directory says %d is not running.",i);
1951 continue;
1952 if (! node->is_valid)
1953 // log_debug(LD_CIRC,"Nope, the directory says %d is not valid.",i);
1954 continue;
1955 if (! node_has_descriptor(node))
1956 continue;
1957 /* XXX This clause makes us count incorrectly: if AllowInvalidRouters
1958 * allows this node in some places, then we're getting an inaccurate
1959 * count. For now, be conservative and don't count it. But later we
1960 * should try to be smarter. */
1961 ++num;
1962 } SMARTLIST_FOREACH_END(node);
1964 // log_debug(LD_CIRC,"I like %d. num_acceptable_routers now %d.",i, num);
1966 return num;
1969 /** Add <b>new_hop</b> to the end of the doubly-linked-list <b>head_ptr</b>.
1970 * This function is used to extend cpath by another hop.
1972 void
1973 onion_append_to_cpath(crypt_path_t **head_ptr, crypt_path_t *new_hop)
1975 if (*head_ptr) {
1976 new_hop->next = (*head_ptr);
1977 new_hop->prev = (*head_ptr)->prev;
1978 (*head_ptr)->prev->next = new_hop;
1979 (*head_ptr)->prev = new_hop;
1980 } else {
1981 *head_ptr = new_hop;
1982 new_hop->prev = new_hop->next = new_hop;
1986 /** A helper function used by onion_extend_cpath(). Use <b>purpose</b>
1987 * and <b>state</b> and the cpath <b>head</b> (currently populated only
1988 * to length <b>cur_len</b> to decide a suitable middle hop for a
1989 * circuit. In particular, make sure we don't pick the exit node or its
1990 * family, and make sure we don't duplicate any previous nodes or their
1991 * families. */
1992 static const node_t *
1993 choose_good_middle_server(uint8_t purpose,
1994 cpath_build_state_t *state,
1995 crypt_path_t *head,
1996 int cur_len)
1998 int i;
1999 const node_t *r, *choice;
2000 crypt_path_t *cpath;
2001 smartlist_t *excluded;
2002 const or_options_t *options = get_options();
2003 router_crn_flags_t flags = CRN_NEED_DESC;
2004 tor_assert(CIRCUIT_PURPOSE_MIN_ <= purpose &&
2005 purpose <= CIRCUIT_PURPOSE_MAX_);
2007 log_debug(LD_CIRC, "Contemplating intermediate hop: random choice.");
2008 excluded = smartlist_new();
2009 if ((r = build_state_get_exit_node(state))) {
2010 nodelist_add_node_and_family(excluded, r);
2012 for (i = 0, cpath = head; i < cur_len; ++i, cpath=cpath->next) {
2013 if ((r = node_get_by_id(cpath->extend_info->identity_digest))) {
2014 nodelist_add_node_and_family(excluded, r);
2018 if (state->need_uptime)
2019 flags |= CRN_NEED_UPTIME;
2020 if (state->need_capacity)
2021 flags |= CRN_NEED_CAPACITY;
2022 if (options->AllowInvalid_ & ALLOW_INVALID_MIDDLE)
2023 flags |= CRN_ALLOW_INVALID;
2024 choice = router_choose_random_node(excluded, options->ExcludeNodes, flags);
2025 smartlist_free(excluded);
2026 return choice;
2029 /** Pick a good entry server for the circuit to be built according to
2030 * <b>state</b>. Don't reuse a chosen exit (if any), don't use this
2031 * router (if we're an OR), and respect firewall settings; if we're
2032 * configured to use entry guards, return one.
2034 * If <b>state</b> is NULL, we're choosing a router to serve as an entry
2035 * guard, not for any particular circuit.
2037 /* XXXX024 I'd like to have this be static again, but entrynodes.c needs it. */
2038 const node_t *
2039 choose_good_entry_server(uint8_t purpose, cpath_build_state_t *state)
2041 const node_t *choice;
2042 smartlist_t *excluded;
2043 const or_options_t *options = get_options();
2044 router_crn_flags_t flags = CRN_NEED_GUARD|CRN_NEED_DESC;
2045 const node_t *node;
2047 if (state && options->UseEntryGuards &&
2048 (purpose != CIRCUIT_PURPOSE_TESTING || options->BridgeRelay)) {
2049 /* This request is for an entry server to use for a regular circuit,
2050 * and we use entry guard nodes. Just return one of the guard nodes. */
2051 return choose_random_entry(state);
2054 excluded = smartlist_new();
2056 if (state && (node = build_state_get_exit_node(state))) {
2057 /* Exclude the exit node from the state, if we have one. Also exclude its
2058 * family. */
2059 nodelist_add_node_and_family(excluded, node);
2061 if (firewall_is_fascist_or()) {
2062 /* Exclude all ORs that we can't reach through our firewall */
2063 smartlist_t *nodes = nodelist_get_list();
2064 SMARTLIST_FOREACH(nodes, const node_t *, node, {
2065 if (!fascist_firewall_allows_node(node))
2066 smartlist_add(excluded, (void*)node);
2069 /* and exclude current entry guards and their families, if applicable */
2070 /*XXXX025 use the using_as_guard flag to accomplish this.*/
2071 if (options->UseEntryGuards) {
2072 SMARTLIST_FOREACH(get_entry_guards(), const entry_guard_t *, entry,
2074 if ((node = node_get_by_id(entry->identity))) {
2075 nodelist_add_node_and_family(excluded, node);
2080 if (state) {
2081 if (state->need_uptime)
2082 flags |= CRN_NEED_UPTIME;
2083 if (state->need_capacity)
2084 flags |= CRN_NEED_CAPACITY;
2086 if (options->AllowInvalid_ & ALLOW_INVALID_ENTRY)
2087 flags |= CRN_ALLOW_INVALID;
2089 choice = router_choose_random_node(excluded, options->ExcludeNodes, flags);
2090 smartlist_free(excluded);
2091 return choice;
2094 /** Return the first non-open hop in cpath, or return NULL if all
2095 * hops are open. */
2096 static crypt_path_t *
2097 onion_next_hop_in_cpath(crypt_path_t *cpath)
2099 crypt_path_t *hop = cpath;
2100 do {
2101 if (hop->state != CPATH_STATE_OPEN)
2102 return hop;
2103 hop = hop->next;
2104 } while (hop != cpath);
2105 return NULL;
2108 /** Choose a suitable next hop in the cpath <b>head_ptr</b>,
2109 * based on <b>state</b>. Append the hop info to head_ptr.
2111 * Return 1 if the path is complete, 0 if we successfully added a hop,
2112 * and -1 on error.
2114 static int
2115 onion_extend_cpath(origin_circuit_t *circ)
2117 uint8_t purpose = circ->base_.purpose;
2118 cpath_build_state_t *state = circ->build_state;
2119 int cur_len = circuit_get_cpath_len(circ);
2120 extend_info_t *info = NULL;
2122 if (cur_len >= state->desired_path_len) {
2123 log_debug(LD_CIRC, "Path is complete: %d steps long",
2124 state->desired_path_len);
2125 return 1;
2128 log_debug(LD_CIRC, "Path is %d long; we want %d", cur_len,
2129 state->desired_path_len);
2131 if (cur_len == state->desired_path_len - 1) { /* Picking last node */
2132 info = extend_info_dup(state->chosen_exit);
2133 } else if (cur_len == 0) { /* picking first node */
2134 const node_t *r = choose_good_entry_server(purpose, state);
2135 if (r) {
2136 /* If we're a client, use the preferred address rather than the
2137 primary address, for potentially connecting to an IPv6 OR
2138 port. */
2139 info = extend_info_from_node(r, server_mode(get_options()) == 0);
2140 tor_assert(info);
2142 } else {
2143 const node_t *r =
2144 choose_good_middle_server(purpose, state, circ->cpath, cur_len);
2145 if (r) {
2146 info = extend_info_from_node(r, 0);
2147 tor_assert(info);
2151 if (!info) {
2152 log_warn(LD_CIRC,"Failed to find node for hop %d of our path. Discarding "
2153 "this circuit.", cur_len);
2154 return -1;
2157 log_debug(LD_CIRC,"Chose router %s for hop %d (exit is %s)",
2158 extend_info_describe(info),
2159 cur_len+1, build_state_get_exit_nickname(state));
2161 onion_append_hop(&circ->cpath, info);
2162 extend_info_free(info);
2163 return 0;
2166 /** Create a new hop, annotate it with information about its
2167 * corresponding router <b>choice</b>, and append it to the
2168 * end of the cpath <b>head_ptr</b>. */
2169 static int
2170 onion_append_hop(crypt_path_t **head_ptr, extend_info_t *choice)
2172 crypt_path_t *hop = tor_malloc_zero(sizeof(crypt_path_t));
2174 /* link hop into the cpath, at the end. */
2175 onion_append_to_cpath(head_ptr, hop);
2177 hop->magic = CRYPT_PATH_MAGIC;
2178 hop->state = CPATH_STATE_CLOSED;
2180 hop->extend_info = extend_info_dup(choice);
2182 hop->package_window = circuit_initial_package_window();
2183 hop->deliver_window = CIRCWINDOW_START;
2185 return 0;
2188 /** Allocate a new extend_info object based on the various arguments. */
2189 extend_info_t *
2190 extend_info_new(const char *nickname, const char *digest,
2191 crypto_pk_t *onion_key,
2192 const curve25519_public_key_t *curve25519_key,
2193 const tor_addr_t *addr, uint16_t port)
2195 extend_info_t *info = tor_malloc_zero(sizeof(extend_info_t));
2196 memcpy(info->identity_digest, digest, DIGEST_LEN);
2197 if (nickname)
2198 strlcpy(info->nickname, nickname, sizeof(info->nickname));
2199 if (onion_key)
2200 info->onion_key = crypto_pk_dup_key(onion_key);
2201 #ifdef CURVE25519_ENABLED
2202 if (curve25519_key)
2203 memcpy(&info->curve25519_onion_key, curve25519_key,
2204 sizeof(curve25519_public_key_t));
2205 #else
2206 (void)curve25519_key;
2207 #endif
2208 tor_addr_copy(&info->addr, addr);
2209 info->port = port;
2210 return info;
2213 /** Allocate and return a new extend_info that can be used to build a
2214 * circuit to or through the node <b>node</b>. Use the primary address
2215 * of the node (i.e. its IPv4 address) unless
2216 * <b>for_direct_connect</b> is true, in which case the preferred
2217 * address is used instead. May return NULL if there is not enough
2218 * info about <b>node</b> to extend to it--for example, if there is no
2219 * routerinfo_t or microdesc_t.
2221 extend_info_t *
2222 extend_info_from_node(const node_t *node, int for_direct_connect)
2224 tor_addr_port_t ap;
2226 if (node->ri == NULL && (node->rs == NULL || node->md == NULL))
2227 return NULL;
2229 if (for_direct_connect)
2230 node_get_pref_orport(node, &ap);
2231 else
2232 node_get_prim_orport(node, &ap);
2234 log_debug(LD_CIRC, "using %s for %s",
2235 fmt_addrport(&ap.addr, ap.port),
2236 node->ri ? node->ri->nickname : node->rs->nickname);
2238 if (node->ri)
2239 return extend_info_new(node->ri->nickname,
2240 node->identity,
2241 node->ri->onion_pkey,
2242 node->ri->onion_curve25519_pkey,
2243 &ap.addr,
2244 ap.port);
2245 else if (node->rs && node->md)
2246 return extend_info_new(node->rs->nickname,
2247 node->identity,
2248 node->md->onion_pkey,
2249 node->md->onion_curve25519_pkey,
2250 &ap.addr,
2251 ap.port);
2252 else
2253 return NULL;
2256 /** Release storage held by an extend_info_t struct. */
2257 void
2258 extend_info_free(extend_info_t *info)
2260 if (!info)
2261 return;
2262 crypto_pk_free(info->onion_key);
2263 tor_free(info);
2266 /** Allocate and return a new extend_info_t with the same contents as
2267 * <b>info</b>. */
2268 extend_info_t *
2269 extend_info_dup(extend_info_t *info)
2271 extend_info_t *newinfo;
2272 tor_assert(info);
2273 newinfo = tor_malloc(sizeof(extend_info_t));
2274 memcpy(newinfo, info, sizeof(extend_info_t));
2275 if (info->onion_key)
2276 newinfo->onion_key = crypto_pk_dup_key(info->onion_key);
2277 else
2278 newinfo->onion_key = NULL;
2279 return newinfo;
2282 /** Return the routerinfo_t for the chosen exit router in <b>state</b>.
2283 * If there is no chosen exit, or if we don't know the routerinfo_t for
2284 * the chosen exit, return NULL.
2286 const node_t *
2287 build_state_get_exit_node(cpath_build_state_t *state)
2289 if (!state || !state->chosen_exit)
2290 return NULL;
2291 return node_get_by_id(state->chosen_exit->identity_digest);
2294 /** Return the nickname for the chosen exit router in <b>state</b>. If
2295 * there is no chosen exit, or if we don't know the routerinfo_t for the
2296 * chosen exit, return NULL.
2298 const char *
2299 build_state_get_exit_nickname(cpath_build_state_t *state)
2301 if (!state || !state->chosen_exit)
2302 return NULL;
2303 return state->chosen_exit->nickname;