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