tor  0.4.2.1-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-2019, The Tor Project, Inc. */
5 /* See LICENSE for licensing information */
6 
28 #define CIRCUITBUILD_PRIVATE
29 #define OCIRC_EVENT_PRIVATE
30 
31 #include "core/or/or.h"
32 #include "app/config/config.h"
33 #include "lib/confmgt/confparse.h"
34 #include "core/crypto/hs_ntor.h"
36 #include "core/crypto/onion_fast.h"
37 #include "core/crypto/onion_tap.h"
38 #include "core/crypto/relay_crypto.h"
40 #include "core/mainloop/mainloop.h"
41 #include "core/or/channel.h"
42 #include "core/or/circuitbuild.h"
43 #include "core/or/circuitlist.h"
44 #include "core/or/circuitstats.h"
45 #include "core/or/circuituse.h"
46 #include "core/or/circuitpadding.h"
47 #include "core/or/command.h"
49 #include "core/or/connection_or.h"
50 #include "core/or/onion.h"
51 #include "core/or/ocirc_event.h"
52 #include "core/or/policies.h"
53 #include "core/or/relay.h"
54 #include "core/or/crypt_path.h"
55 #include "feature/client/bridges.h"
56 #include "feature/client/circpathbias.h"
68 #include "feature/nodelist/routerset.h"
69 #include "feature/relay/router.h"
71 #include "feature/relay/selftest.h"
73 #include "feature/stats/predict_ports.h"
75 
76 #include "core/or/cell_st.h"
77 #include "core/or/cpath_build_state_st.h"
78 #include "core/or/entry_connection_st.h"
79 #include "core/or/extend_info_st.h"
80 #include "feature/nodelist/node_st.h"
81 #include "core/or/or_circuit_st.h"
82 #include "core/or/origin_circuit_st.h"
83 #include "feature/nodelist/microdesc_st.h"
84 #include "feature/nodelist/routerinfo_st.h"
85 #include "feature/nodelist/routerstatus_st.h"
86 
88  uint16_t port,
89  const char *id_digest,
90  const ed25519_public_key_t *ed_id);
91 static int circuit_deliver_create_cell(circuit_t *circ,
92  const create_cell_t *create_cell,
93  int relayed);
97  crypt_path_t *hop);
98 static const node_t *choose_good_middle_server(uint8_t purpose,
99  cpath_build_state_t *state,
100  crypt_path_t *head,
101  int cur_len);
102 
107 static channel_t *
108 channel_connect_for_circuit(const tor_addr_t *addr, uint16_t port,
109  const char *id_digest,
110  const ed25519_public_key_t *ed_id)
111 {
112  channel_t *chan;
113 
114  chan = channel_connect(addr, port, id_digest, ed_id);
115  if (chan) command_setup_channel(chan);
116 
117  return chan;
118 }
119 
126 STATIC circid_t
128 {
129 /* This number is chosen somewhat arbitrarily; see comment below for more
130  * info. When the space is 80% full, it gives a one-in-a-million failure
131  * chance; when the space is 90% full, it gives a one-in-850 chance; and when
132  * the space is 95% full, it gives a one-in-26 failure chance. That seems
133  * okay, though you could make a case IMO for anything between N=32 and
134  * N=256. */
135 #define MAX_CIRCID_ATTEMPTS 64
136  int in_use;
137  unsigned n_with_circ = 0, n_pending_destroy = 0, n_weird_pending_destroy = 0;
138  circid_t test_circ_id;
139  circid_t attempts=0;
140  circid_t high_bit, max_range, mask;
141  int64_t pending_destroy_time_total = 0;
142  int64_t pending_destroy_time_max = 0;
143 
144  tor_assert(chan);
145 
146  if (chan->circ_id_type == CIRC_ID_TYPE_NEITHER) {
147  log_warn(LD_BUG,
148  "Trying to pick a circuit ID for a connection from "
149  "a client with no identity.");
150  return 0;
151  }
152  max_range = (chan->wide_circ_ids) ? (1u<<31) : (1u<<15);
153  mask = max_range - 1;
154  high_bit = (chan->circ_id_type == CIRC_ID_TYPE_HIGHER) ? max_range : 0;
155  do {
156  if (++attempts > MAX_CIRCID_ATTEMPTS) {
157  /* Make sure we don't loop forever because all circuit IDs are used.
158  *
159  * Once, we would try until we had tried every possible circuit ID. But
160  * that's quite expensive. Instead, we try MAX_CIRCID_ATTEMPTS random
161  * circuit IDs, and then give up.
162  *
163  * This potentially causes us to give up early if our circuit ID space
164  * is nearly full. If we have N circuit IDs in use, then we will reject
165  * a new circuit with probability (N / max_range) ^ MAX_CIRCID_ATTEMPTS.
166  * This means that in practice, a few percent of our circuit ID capacity
167  * will go unused.
168  *
169  * The alternative here, though, is to do a linear search over the
170  * whole circuit ID space every time we extend a circuit, which is
171  * not so great either.
172  */
173  int64_t queued_destroys;
175  approx_time());
176  if (m == NULL)
177  return 0; /* This message has been rate-limited away. */
178  if (n_pending_destroy)
179  pending_destroy_time_total /= n_pending_destroy;
180  log_warn(LD_CIRC,"No unused circIDs found on channel %s wide "
181  "circID support, with %u inbound and %u outbound circuits. "
182  "Found %u circuit IDs in use by circuits, and %u with "
183  "pending destroy cells. (%u of those were marked bogusly.) "
184  "The ones with pending destroy cells "
185  "have been marked unusable for an average of %ld seconds "
186  "and a maximum of %ld seconds. This channel is %ld seconds "
187  "old. Failing a circuit.%s",
188  chan->wide_circ_ids ? "with" : "without",
189  chan->num_p_circuits, chan->num_n_circuits,
190  n_with_circ, n_pending_destroy, n_weird_pending_destroy,
191  (long)pending_destroy_time_total,
192  (long)pending_destroy_time_max,
193  (long)(approx_time() - chan->timestamp_created),
194  m);
195  tor_free(m);
196 
197  if (!chan->cmux) {
198  /* This warning should be impossible. */
199  log_warn(LD_BUG, " This channel somehow has no cmux on it!");
200  return 0;
201  }
202 
203  /* analysis so far on 12184 suggests that we're running out of circuit
204  IDs because it looks like we have too many pending destroy
205  cells. Let's see how many we really have pending.
206  */
207  queued_destroys = circuitmux_count_queued_destroy_cells(chan,
208  chan->cmux);
209 
210  log_warn(LD_CIRC, " Circuitmux on this channel has %u circuits, "
211  "of which %u are active. It says it has %"PRId64
212  " destroy cells queued.",
215  (queued_destroys));
216 
217  /* Change this into "if (1)" in order to get more information about
218  * possible failure modes here. You'll need to know how to use gdb with
219  * Tor: this will make Tor exit with an assertion failure if the cmux is
220  * corrupt. */
221  if (0)
222  circuitmux_assert_okay(chan->cmux);
223 
224  channel_dump_statistics(chan, LOG_WARN);
225 
226  return 0;
227  }
228 
229  do {
230  crypto_rand((char*) &test_circ_id, sizeof(test_circ_id));
231  test_circ_id &= mask;
232  } while (test_circ_id == 0);
233 
234  test_circ_id |= high_bit;
235 
236  in_use = circuit_id_in_use_on_channel(test_circ_id, chan);
237  if (in_use == 1)
238  ++n_with_circ;
239  else if (in_use == 2) {
240  time_t since_when;
241  ++n_pending_destroy;
242  since_when =
243  circuit_id_when_marked_unusable_on_channel(test_circ_id, chan);
244  if (since_when) {
245  time_t waiting = approx_time() - since_when;
246  pending_destroy_time_total += waiting;
247  if (waiting > pending_destroy_time_max)
248  pending_destroy_time_max = waiting;
249  } else {
250  ++n_weird_pending_destroy;
251  }
252  }
253  } while (in_use);
254  return test_circ_id;
255 }
256 
263 static char *
264 circuit_list_path_impl(origin_circuit_t *circ, int verbose, int verbose_names)
265 {
266  crypt_path_t *hop;
267  smartlist_t *elements;
268  const char *states[] = {"closed", "waiting for keys", "open"};
269  char *s;
270 
271  elements = smartlist_new();
272 
273  if (verbose) {
274  const char *nickname = build_state_get_exit_nickname(circ->build_state);
275  smartlist_add_asprintf(elements, "%s%s circ (length %d%s%s):",
276  circ->build_state->is_internal ? "internal" : "exit",
277  circ->build_state->need_uptime ? " (high-uptime)" : "",
279  circ->base_.state == CIRCUIT_STATE_OPEN ? "" : ", last hop ",
280  circ->base_.state == CIRCUIT_STATE_OPEN ? "" :
281  (nickname?nickname:"*unnamed*"));
282  }
283 
284  hop = circ->cpath;
285  do {
286  char *elt;
287  const char *id;
288  const node_t *node;
289  if (!hop)
290  break;
291  if (!verbose && hop->state != CPATH_STATE_OPEN)
292  break;
293  if (!hop->extend_info)
294  break;
295  id = hop->extend_info->identity_digest;
296  if (verbose_names) {
297  elt = tor_malloc(MAX_VERBOSE_NICKNAME_LEN+1);
298  if ((node = node_get_by_id(id))) {
299  node_get_verbose_nickname(node, elt);
300  } else if (is_legal_nickname(hop->extend_info->nickname)) {
301  elt[0] = '$';
302  base16_encode(elt+1, HEX_DIGEST_LEN+1, id, DIGEST_LEN);
303  elt[HEX_DIGEST_LEN+1]= '~';
304  strlcpy(elt+HEX_DIGEST_LEN+2,
306  } else {
307  elt[0] = '$';
308  base16_encode(elt+1, HEX_DIGEST_LEN+1, id, DIGEST_LEN);
309  }
310  } else { /* ! verbose_names */
311  elt = tor_malloc(HEX_DIGEST_LEN+2);
312  elt[0] = '$';
313  base16_encode(elt+1, HEX_DIGEST_LEN+1, id, DIGEST_LEN);
314  }
315  tor_assert(elt);
316  if (verbose) {
317  tor_assert(hop->state <= 2);
318  smartlist_add_asprintf(elements,"%s(%s)",elt,states[hop->state]);
319  tor_free(elt);
320  } else {
321  smartlist_add(elements, elt);
322  }
323  hop = hop->next;
324  } while (hop != circ->cpath);
325 
326  s = smartlist_join_strings(elements, verbose?" ":",", 0, NULL);
327  SMARTLIST_FOREACH(elements, char*, cp, tor_free(cp));
328  smartlist_free(elements);
329  return s;
330 }
331 
337 char *
339 {
340  return circuit_list_path_impl(circ, verbose, 0);
341 }
342 
346 char *
348 {
349  return circuit_list_path_impl(circ, 0, 1);
350 }
351 
356 void
357 circuit_log_path(int severity, unsigned int domain, origin_circuit_t *circ)
358 {
359  char *s = circuit_list_path(circ,1);
360  tor_log(severity,domain,"%s",s);
361  tor_free(s);
362 }
363 
365 static int
367 {
368  crypt_path_t *head, *cpath;
369 
370  cpath = head = circ->cpath;
371  do {
372  /* if the extend_info is missing, we can't tell if it supports ntor */
373  if (!cpath->extend_info) {
374  return 0;
375  }
376 
377  /* if the key is blank, it definitely doesn't support ntor */
378  if (!extend_info_supports_ntor(cpath->extend_info)) {
379  return 0;
380  }
381  cpath = cpath->next;
382  } while (cpath != head);
383 
384  return 1;
385 }
386 
389 static int
391 {
392  int r = 0;
393 
394  /* onion_extend_cpath assumes these are non-NULL */
395  tor_assert(circ);
396  tor_assert(circ->build_state);
397 
398  while (r == 0) {
399  r = onion_extend_cpath(circ);
400  if (r < 0) {
401  log_info(LD_CIRC,"Generating cpath hop failed.");
402  return -1;
403  }
404  }
405 
406  /* The path is complete */
407  tor_assert(r == 1);
408 
409  /* Does every node in this path support ntor? */
410  int path_supports_ntor = circuit_cpath_supports_ntor(circ);
411 
412  /* We would like every path to support ntor, but we have to allow for some
413  * edge cases. */
415  if (circuit_can_use_tap(circ)) {
416  /* Circuits from clients to intro points, and hidden services to rend
417  * points do not support ntor, because the hidden service protocol does
418  * not include ntor onion keys. This is also true for Single Onion
419  * Services. */
420  return 0;
421  }
422 
423  if (circuit_get_cpath_len(circ) == 1) {
424  /* Allow for bootstrapping: when we're fetching directly from a fallback,
425  * authority, or bridge, we have no way of knowing its ntor onion key
426  * before we connect to it. So instead, we try connecting, and end up using
427  * CREATE_FAST. */
428  tor_assert(circ->cpath);
429  tor_assert(circ->cpath->extend_info);
430  const node_t *node = node_get_by_id(
432  /* If we don't know the node and its descriptor, we must be bootstrapping.
433  */
434  if (!node || !node_has_preferred_descriptor(node, 1)) {
435  return 0;
436  }
437  }
438 
439  if (BUG(!path_supports_ntor)) {
440  /* If we're building a multi-hop path, and it's not one of the HS or
441  * bootstrapping exceptions, and it doesn't support ntor, something has
442  * gone wrong. */
443  return -1;
444  }
445 
446  return 0;
447 }
448 
453 origin_circuit_init(uint8_t purpose, int flags)
454 {
455  /* sets circ->p_circ_id and circ->p_chan */
458  circ->build_state = tor_malloc_zero(sizeof(cpath_build_state_t));
459  circ->build_state->onehop_tunnel =
460  ((flags & CIRCLAUNCH_ONEHOP_TUNNEL) ? 1 : 0);
461  circ->build_state->need_uptime =
462  ((flags & CIRCLAUNCH_NEED_UPTIME) ? 1 : 0);
463  circ->build_state->need_capacity =
464  ((flags & CIRCLAUNCH_NEED_CAPACITY) ? 1 : 0);
465  circ->build_state->is_internal =
466  ((flags & CIRCLAUNCH_IS_INTERNAL) ? 1 : 0);
467  circ->base_.purpose = purpose;
468  return circ;
469 }
470 
479 circuit_establish_circuit(uint8_t purpose, extend_info_t *exit_ei, int flags)
480 {
481  origin_circuit_t *circ;
482  int err_reason = 0;
483  int is_hs_v3_rp_circuit = 0;
484 
485  if (flags & CIRCLAUNCH_IS_V3_RP) {
486  is_hs_v3_rp_circuit = 1;
487  }
488 
489  circ = origin_circuit_init(purpose, flags);
490 
491  if (onion_pick_cpath_exit(circ, exit_ei, is_hs_v3_rp_circuit) < 0 ||
492  onion_populate_cpath(circ) < 0) {
493  circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_NOPATH);
494  return NULL;
495  }
496 
497  circuit_event_status(circ, CIRC_EVENT_LAUNCHED, 0);
498 
499  if ((err_reason = circuit_handle_first_hop(circ)) < 0) {
500  circuit_mark_for_close(TO_CIRCUIT(circ), -err_reason);
501  return NULL;
502  }
503  return circ;
504 }
505 
507 circuit_guard_state_t *
509 {
510  return circ->guard_state;
511 }
512 
522 static void
524 {
525  ocirc_chan_msg_t *msg = tor_malloc(sizeof(*msg));
526 
527  msg->gid = circ->global_identifier;
528  msg->chan = chan->global_identifier;
529  msg->onehop = circ->build_state->onehop_tunnel;
530 
531  ocirc_chan_publish(msg);
532 }
533 
538 int
540 {
541  crypt_path_t *firsthop;
542  channel_t *n_chan;
543  int err_reason = 0;
544  const char *msg = NULL;
545  int should_launch = 0;
546  const or_options_t *options = get_options();
547 
548  firsthop = cpath_get_next_non_open_hop(circ->cpath);
549  tor_assert(firsthop);
550  tor_assert(firsthop->extend_info);
551 
552  /* Some bridges are on private addresses. Others pass a dummy private
553  * address to the pluggable transport, which ignores it.
554  * Deny the connection if:
555  * - the address is internal, and
556  * - we're not connecting to a configured bridge, and
557  * - we're not configured to allow extends to private addresses. */
558  if (tor_addr_is_internal(&firsthop->extend_info->addr, 0) &&
560  !options->ExtendAllowPrivateAddresses) {
561  log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
562  "Client asked me to connect directly to a private address");
563  return -END_CIRC_REASON_TORPROTOCOL;
564  }
565 
566  /* now see if we're already connected to the first OR in 'route' */
567  log_debug(LD_CIRC,"Looking for firsthop '%s'",
568  fmt_addrport(&firsthop->extend_info->addr,
569  firsthop->extend_info->port));
570 
572  &firsthop->extend_info->ed_identity,
573  &firsthop->extend_info->addr,
574  &msg,
575  &should_launch);
576 
577  if (!n_chan) {
578  /* not currently connected in a useful way. */
579  log_info(LD_CIRC, "Next router is %s: %s",
580  safe_str_client(extend_info_describe(firsthop->extend_info)),
581  msg?msg:"???");
582  circ->base_.n_hop = extend_info_dup(firsthop->extend_info);
583 
584  if (should_launch) {
586  &firsthop->extend_info->addr,
587  firsthop->extend_info->port,
588  firsthop->extend_info->identity_digest,
589  &firsthop->extend_info->ed_identity);
590  if (!n_chan) { /* connect failed, forget the whole thing */
591  log_info(LD_CIRC,"connect to firsthop failed. Closing.");
592  return -END_CIRC_REASON_CONNECTFAILED;
593  }
594  circuit_chan_publish(circ, n_chan);
595  }
596 
597  log_debug(LD_CIRC,"connecting in progress (or finished). Good.");
598  /* return success. The onion/circuit/etc will be taken care of
599  * automatically (may already have been) whenever n_chan reaches
600  * OR_CONN_STATE_OPEN.
601  */
602  return 0;
603  } else { /* it's already open. use it. */
604  tor_assert(!circ->base_.n_hop);
605  circ->base_.n_chan = n_chan;
606  circuit_chan_publish(circ, n_chan);
607  log_debug(LD_CIRC,"Conn open. Delivering first onion skin.");
608  if ((err_reason = circuit_send_next_onion_skin(circ)) < 0) {
609  log_info(LD_CIRC,"circuit_send_next_onion_skin failed.");
610  circ->base_.n_chan = NULL;
611  return err_reason;
612  }
613  }
614  return 0;
615 }
616 
626 void
627 circuit_n_chan_done(channel_t *chan, int status, int close_origin_circuits)
628 {
629  smartlist_t *pending_circs;
630  int err_reason = 0;
631 
632  tor_assert(chan);
633 
634  log_debug(LD_CIRC,"chan to %s, status=%d",
635  channel_get_canonical_remote_descr(chan), status);
636 
637  pending_circs = smartlist_new();
638  circuit_get_all_pending_on_channel(pending_circs, chan);
639 
640  SMARTLIST_FOREACH_BEGIN(pending_circs, circuit_t *, circ)
641  {
642  /* These checks are redundant wrt get_all_pending_on_or_conn, but I'm
643  * leaving them in in case it's possible for the status of a circuit to
644  * change as we're going down the list. */
645  if (circ->marked_for_close || circ->n_chan || !circ->n_hop ||
646  circ->state != CIRCUIT_STATE_CHAN_WAIT)
647  continue;
648 
649  if (tor_digest_is_zero(circ->n_hop->identity_digest)) {
650  /* Look at addr/port. This is an unkeyed connection. */
651  if (!channel_matches_extend_info(chan, circ->n_hop))
652  continue;
653  } else {
654  /* We expected a key. See if it's the right one. */
655  if (tor_memneq(chan->identity_digest,
656  circ->n_hop->identity_digest, DIGEST_LEN))
657  continue;
658  }
659  if (!status) { /* chan failed; close circ */
660  log_info(LD_CIRC,"Channel failed; closing circ.");
661  circuit_mark_for_close(circ, END_CIRC_REASON_CHANNEL_CLOSED);
662  continue;
663  }
664  if (close_origin_circuits && CIRCUIT_IS_ORIGIN(circ)) {
665  log_info(LD_CIRC,"Channel deprecated for origin circs; closing circ.");
666  circuit_mark_for_close(circ, END_CIRC_REASON_CHANNEL_CLOSED);
667  continue;
668  }
669  log_debug(LD_CIRC, "Found circ, sending create cell.");
670  /* circuit_deliver_create_cell will set n_circ_id and add us to
671  * chan_circuid_circuit_map, so we don't need to call
672  * set_circid_chan here. */
673  circ->n_chan = chan;
674  extend_info_free(circ->n_hop);
675  circ->n_hop = NULL;
676 
677  if (CIRCUIT_IS_ORIGIN(circ)) {
678  if ((err_reason =
680  log_info(LD_CIRC,
681  "send_next_onion_skin failed; circuit marked for closing.");
682  circuit_mark_for_close(circ, -err_reason);
683  continue;
684  /* XXX could this be bad, eg if next_onion_skin failed because conn
685  * died? */
686  }
687  } else {
688  /* pull the create cell out of circ->n_chan_create_cell, and send it */
689  tor_assert(circ->n_chan_create_cell);
690  if (circuit_deliver_create_cell(circ, circ->n_chan_create_cell, 1)<0) {
691  circuit_mark_for_close(circ, END_CIRC_REASON_RESOURCELIMIT);
692  continue;
693  }
694  tor_free(circ->n_chan_create_cell);
696  }
697  }
698  SMARTLIST_FOREACH_END(circ);
699 
700  smartlist_free(pending_circs);
701 }
702 
710 static int
712  int relayed)
713 {
714  cell_t cell;
715  circid_t id;
716  int r;
717 
718  tor_assert(circ);
719  tor_assert(circ->n_chan);
720  tor_assert(create_cell);
721  tor_assert(create_cell->cell_type == CELL_CREATE ||
722  create_cell->cell_type == CELL_CREATE_FAST ||
723  create_cell->cell_type == CELL_CREATE2);
724 
726  if (!id) {
727  static ratelim_t circid_warning_limit = RATELIM_INIT(9600);
728  log_fn_ratelim(&circid_warning_limit, LOG_WARN, LD_CIRC,
729  "failed to get unique circID.");
730  goto error;
731  }
732 
733  memset(&cell, 0, sizeof(cell_t));
734  r = relayed ? create_cell_format_relayed(&cell, create_cell)
735  : create_cell_format(&cell, create_cell);
736  if (r < 0) {
737  log_warn(LD_CIRC,"Couldn't format create cell");
738  goto error;
739  }
740  log_debug(LD_CIRC,"Chosen circID %u.", (unsigned)id);
741  circuit_set_n_circid_chan(circ, id, circ->n_chan);
742  cell.circ_id = circ->n_circ_id;
743 
744  append_cell_to_circuit_queue(circ, circ->n_chan, &cell,
745  CELL_DIRECTION_OUT, 0);
746 
747  if (CIRCUIT_IS_ORIGIN(circ)) {
748  /* Update began timestamp for circuits starting their first hop */
749  if (TO_ORIGIN_CIRCUIT(circ)->cpath->state == CPATH_STATE_CLOSED) {
750  if (!CHANNEL_IS_OPEN(circ->n_chan)) {
751  log_warn(LD_CIRC,
752  "Got first hop for a circuit without an opened channel. "
753  "State: %s.", channel_state_to_string(circ->n_chan->state));
755  }
756 
757  tor_gettimeofday(&circ->timestamp_began);
758  }
759 
760  /* mark it so it gets better rate limiting treatment. */
762  }
763 
764  return 0;
765  error:
766  circ->n_chan = NULL;
767  return -1;
768 }
769 
773 int
775 {
776  char dirbuf[128];
777  char *address;
778  const routerinfo_t *me = router_get_my_routerinfo();
779  if (!me)
780  return 0;
781  address = tor_dup_ip(me->addr);
783  "CHECKING_REACHABILITY ORADDRESS=%s:%d",
784  address, me->or_port);
785  if (me->dir_port) {
786  tor_snprintf(dirbuf, sizeof(dirbuf), " and DirPort %s:%d",
787  address, me->dir_port);
789  "CHECKING_REACHABILITY DIRADDRESS=%s:%d",
790  address, me->dir_port);
791  }
792  log_notice(LD_OR, "Now checking whether ORPort %s:%d%s %s reachable... "
793  "(this may take up to %d minutes -- look for log "
794  "messages indicating success)",
795  address, me->or_port,
796  me->dir_port ? dirbuf : "",
797  me->dir_port ? "are" : "is",
799 
800  tor_free(address);
801  return 1;
802 }
803 
806 static inline int
808 {
809  const or_options_t *options = get_options();
810  tor_assert(circ->cpath);
811  tor_assert(circ->cpath->extend_info);
812 
813  if (!circuit_has_usable_onion_key(circ)) {
814  /* We don't have ntor, and we don't have or can't use TAP,
815  * so our hand is forced: only a create_fast will work. */
816  return 1;
817  }
818  if (public_server_mode(options)) {
819  /* We're a server, and we have a usable onion key. We can choose.
820  * Prefer to blend our circuit into the other circuits we are
821  * creating on behalf of others. */
822  return 0;
823  }
824  return networkstatus_get_param(NULL, "usecreatefast", 0, 0, 1);
825 }
826 
840 int
842 {
843  return !circ->has_opened
846 }
847 
855 static void
856 circuit_pick_create_handshake(uint8_t *cell_type_out,
857  uint16_t *handshake_type_out,
858  const extend_info_t *ei)
859 {
860  /* torspec says: In general, clients SHOULD use CREATE whenever they are
861  * using the TAP handshake, and CREATE2 otherwise. */
862  if (extend_info_supports_ntor(ei)) {
863  *cell_type_out = CELL_CREATE2;
864  *handshake_type_out = ONION_HANDSHAKE_TYPE_NTOR;
865  } else {
866  /* XXXX030 Remove support for deciding to use TAP and EXTEND. */
867  *cell_type_out = CELL_CREATE;
868  *handshake_type_out = ONION_HANDSHAKE_TYPE_TAP;
869  }
870 }
871 
881 static void
882 circuit_pick_extend_handshake(uint8_t *cell_type_out,
883  uint8_t *create_cell_type_out,
884  uint16_t *handshake_type_out,
885  const extend_info_t *ei)
886 {
887  uint8_t t;
888  circuit_pick_create_handshake(&t, handshake_type_out, ei);
889 
890  /* torspec says: Clients SHOULD use the EXTEND format whenever sending a TAP
891  * handshake... In other cases, clients SHOULD use EXTEND2. */
892  if (*handshake_type_out != ONION_HANDSHAKE_TYPE_TAP) {
893  *cell_type_out = RELAY_COMMAND_EXTEND2;
894  *create_cell_type_out = CELL_CREATE2;
895  } else {
896  /* XXXX030 Remove support for deciding to use TAP and EXTEND. */
897  *cell_type_out = RELAY_COMMAND_EXTEND;
898  *create_cell_type_out = CELL_CREATE;
899  }
900 }
901 
907 static int
909 {
910  switch (purpose) {
913  /* Testing circuits may omit guards because they're measuring
914  * liveness or performance, and don't want guards to interfere. */
915  return 1;
916  default:
917  /* All other multihop circuits should use guards if guards are
918  * enabled. */
919  return 0;
920  }
921 }
922 
936 int
938 {
939  tor_assert(circ);
940 
941  if (circ->cpath->state == CPATH_STATE_CLOSED) {
942  /* Case one: we're on the first hop. */
943  return circuit_send_first_onion_skin(circ);
944  }
945 
946  tor_assert(circ->cpath->state == CPATH_STATE_OPEN);
947  tor_assert(circ->base_.state == CIRCUIT_STATE_BUILDING);
948 
951 
953 
954  if (hop) {
955  /* Case two: we're on a hop after the first. */
956  return circuit_send_intermediate_onion_skin(circ, hop);
957  }
958 
959  /* Case three: the circuit is finished. Do housekeeping tasks on it. */
961  return circuit_build_no_more_hops(circ);
962 }
963 
970 static int
972 {
973  int fast;
974  int len;
975  const node_t *node;
976  create_cell_t cc;
977  memset(&cc, 0, sizeof(cc));
978 
979  log_debug(LD_CIRC,"First skin; sending create cell.");
980 
981  if (circ->build_state->onehop_tunnel) {
982  control_event_bootstrap(BOOTSTRAP_STATUS_ONEHOP_CREATE, 0);
983  } else {
984  control_event_bootstrap(BOOTSTRAP_STATUS_CIRCUIT_CREATE, 0);
985 
986  /* If this is not a one-hop tunnel, the channel is being used
987  * for traffic that wants anonymity and protection from traffic
988  * analysis (such as netflow record retention). That means we want
989  * to pad it.
990  */
991  if (circ->base_.n_chan->channel_usage < CHANNEL_USED_FOR_FULL_CIRCS)
992  circ->base_.n_chan->channel_usage = CHANNEL_USED_FOR_FULL_CIRCS;
993  }
994 
995  node = node_get_by_id(circ->base_.n_chan->identity_digest);
997  if (!fast) {
998  /* We know the right onion key: we should send a create cell. */
1000  circ->cpath->extend_info);
1001  } else {
1002  /* We don't know an onion key, so we need to fall back to CREATE_FAST. */
1003  cc.cell_type = CELL_CREATE_FAST;
1004  cc.handshake_type = ONION_HANDSHAKE_TYPE_FAST;
1005  }
1006 
1008  circ->cpath->extend_info,
1009  &circ->cpath->handshake_state,
1010  cc.onionskin);
1011  if (len < 0) {
1012  log_warn(LD_CIRC,"onion_skin_create (first hop) failed.");
1013  return - END_CIRC_REASON_INTERNAL;
1014  }
1015  cc.handshake_len = len;
1016 
1017  if (circuit_deliver_create_cell(TO_CIRCUIT(circ), &cc, 0) < 0)
1018  return - END_CIRC_REASON_RESOURCELIMIT;
1019 
1020  circ->cpath->state = CPATH_STATE_AWAITING_KEYS;
1022  log_info(LD_CIRC,"First hop: finished sending %s cell to '%s'",
1023  fast ? "CREATE_FAST" : "CREATE",
1024  node ? node_describe(node) : "<unnamed>");
1025  return 0;
1026 }
1027 
1034 static int
1036 {
1037  guard_usable_t r;
1038  if (! circ->guard_state) {
1039  if (circuit_get_cpath_len(circ) != 1 &&
1040  ! circuit_purpose_may_omit_guard(circ->base_.purpose) &&
1041  get_options()->UseEntryGuards) {
1042  log_warn(LD_BUG, "%d-hop circuit %p with purpose %d has no "
1043  "guard state",
1044  circuit_get_cpath_len(circ), circ, circ->base_.purpose);
1045  }
1046  r = GUARD_USABLE_NOW;
1047  } else {
1048  r = entry_guard_succeeded(&circ->guard_state);
1049  }
1050  const int is_usable_for_streams = (r == GUARD_USABLE_NOW);
1051  if (r == GUARD_USABLE_NOW) {
1053  } else if (r == GUARD_MAYBE_USABLE_LATER) {
1054  // Wait till either a better guard succeeds, or till
1055  // all better guards fail.
1057  } else {
1058  tor_assert_nonfatal(r == GUARD_USABLE_NEVER);
1059  return - END_CIRC_REASON_INTERNAL;
1060  }
1061 
1062  /* XXXX #21422 -- the rest of this branch needs careful thought!
1063  * Some of the things here need to happen when a circuit becomes
1064  * mechanically open; some need to happen when it is actually usable.
1065  * I think I got them right, but more checking would be wise. -NM
1066  */
1067 
1068  log_info(LD_CIRC,"circuit built!");
1070 
1071  if (circ->build_state->onehop_tunnel || circ->has_opened) {
1072  control_event_bootstrap(BOOTSTRAP_STATUS_REQUESTING_STATUS, 0);
1073  }
1074 
1076  if (is_usable_for_streams)
1077  circuit_has_opened(circ); /* do other actions as necessary */
1078 
1080  const or_options_t *options = get_options();
1082  /* FFFF Log a count of known routers here */
1083  log_info(LD_GENERAL,
1084  "Tor has successfully opened a circuit. "
1085  "Looks like client functionality is working.");
1086  control_event_bootstrap(BOOTSTRAP_STATUS_DONE, 0);
1087  control_event_client_status(LOG_NOTICE, "CIRCUIT_ESTABLISHED");
1089  if (server_mode(options) && !check_whether_orport_reachable(options)) {
1092  }
1093  }
1094 
1095  /* We're done with measurement circuits here. Just close them */
1096  if (circ->base_.purpose == CIRCUIT_PURPOSE_C_MEASURE_TIMEOUT) {
1097  circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_FINISHED);
1098  }
1099  return 0;
1100 }
1101 
1108 static int
1110  crypt_path_t *hop)
1111 {
1112  int len;
1113  extend_cell_t ec;
1114  memset(&ec, 0, sizeof(ec));
1115 
1116  log_debug(LD_CIRC,"starting to send subsequent skin.");
1117 
1118  if (tor_addr_family(&hop->extend_info->addr) != AF_INET) {
1119  log_warn(LD_BUG, "Trying to extend to a non-IPv4 address.");
1120  return - END_CIRC_REASON_INTERNAL;
1121  }
1122 
1124  &ec.create_cell.cell_type,
1126  hop->extend_info);
1127 
1128  tor_addr_copy(&ec.orport_ipv4.addr, &hop->extend_info->addr);
1129  ec.orport_ipv4.port = hop->extend_info->port;
1131  memcpy(ec.node_id, hop->extend_info->identity_digest, DIGEST_LEN);
1132  /* Set the ED25519 identity too -- it will only get included
1133  * in the extend2 cell if we're configured to use it, though. */
1135 
1137  hop->extend_info,
1138  &hop->handshake_state,
1139  ec.create_cell.onionskin);
1140  if (len < 0) {
1141  log_warn(LD_CIRC,"onion_skin_create failed.");
1142  return - END_CIRC_REASON_INTERNAL;
1143  }
1144  ec.create_cell.handshake_len = len;
1145 
1146  log_info(LD_CIRC,"Sending extend relay cell.");
1147  {
1148  uint8_t command = 0;
1149  uint16_t payload_len=0;
1150  uint8_t payload[RELAY_PAYLOAD_SIZE];
1151  if (extend_cell_format(&command, &payload_len, payload, &ec)<0) {
1152  log_warn(LD_CIRC,"Couldn't format extend cell");
1153  return -END_CIRC_REASON_INTERNAL;
1154  }
1155 
1156  /* send it to hop->prev, because that relay will transfer
1157  * it to a create cell and then send to hop */
1158  if (relay_send_command_from_edge(0, TO_CIRCUIT(circ),
1159  command,
1160  (char*)payload, payload_len,
1161  hop->prev) < 0)
1162  return 0; /* circuit is closed */
1163  }
1164  hop->state = CPATH_STATE_AWAITING_KEYS;
1165  return 0;
1166 }
1167 
1172 void
1173 circuit_note_clock_jumped(int64_t seconds_elapsed, bool was_idle)
1174 {
1175  int severity = server_mode(get_options()) ? LOG_WARN : LOG_NOTICE;
1176  if (was_idle) {
1177  tor_log(severity, LD_GENERAL, "Tor has been idle for %"PRId64
1178  " seconds; assuming established circuits no longer work.",
1179  (seconds_elapsed));
1180  } else {
1181  tor_log(severity, LD_GENERAL,
1182  "Your system clock just jumped %"PRId64" seconds %s; "
1183  "assuming established circuits no longer work.",
1184  (
1185  seconds_elapsed >=0 ? seconds_elapsed : -seconds_elapsed),
1186  seconds_elapsed >=0 ? "forward" : "backward");
1187  }
1188  control_event_general_status(LOG_WARN, "CLOCK_JUMPED TIME=%"PRId64
1189  " IDLE=%d",
1190  (seconds_elapsed), was_idle?1:0);
1191  /* so we log when it works again */
1193  control_event_client_status(severity, "CIRCUIT_NOT_ESTABLISHED REASON=%s",
1194  "CLOCK_JUMPED");
1197  if (seconds_elapsed < 0) {
1198  /* Restart all the timers in case we jumped a long way into the past. */
1200  }
1201 }
1202 
1211 int
1213 {
1214  channel_t *n_chan;
1215  relay_header_t rh;
1216  extend_cell_t ec;
1217  const char *msg = NULL;
1218  int should_launch = 0;
1219 
1220  if (circ->n_chan) {
1221  log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
1222  "n_chan already set. Bug/attack. Closing.");
1223  return -1;
1224  }
1225  if (circ->n_hop) {
1226  log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
1227  "conn to next hop already launched. Bug/attack. Closing.");
1228  return -1;
1229  }
1230 
1231  if (!server_mode(get_options())) {
1232  log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
1233  "Got an extend cell, but running as a client. Closing.");
1234  return -1;
1235  }
1236 
1237  relay_header_unpack(&rh, cell->payload);
1238 
1239  if (extend_cell_parse(&ec, rh.command,
1240  cell->payload+RELAY_HEADER_SIZE,
1241  rh.length) < 0) {
1242  log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
1243  "Can't parse extend cell. Closing circuit.");
1244  return -1;
1245  }
1246 
1247  if (!ec.orport_ipv4.port || tor_addr_is_null(&ec.orport_ipv4.addr)) {
1248  log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
1249  "Client asked me to extend to zero destination port or addr.");
1250  return -1;
1251  }
1252 
1253  if (tor_addr_is_internal(&ec.orport_ipv4.addr, 0) &&
1254  !get_options()->ExtendAllowPrivateAddresses) {
1255  log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
1256  "Client asked me to extend to a private address");
1257  return -1;
1258  }
1259 
1260  /* Check if they asked us for 0000..0000. We support using
1261  * an empty fingerprint for the first hop (e.g. for a bridge relay),
1262  * but we don't want to let clients send us extend cells for empty
1263  * fingerprints -- a) because it opens the user up to a mitm attack,
1264  * and b) because it lets an attacker force the relay to hold open a
1265  * new TLS connection for each extend request. */
1266  if (tor_digest_is_zero((const char*)ec.node_id)) {
1267  log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
1268  "Client asked me to extend without specifying an id_digest.");
1269  return -1;
1270  }
1271 
1272  /* Fill in ed_pubkey if it was not provided and we can infer it from
1273  * our networkstatus */
1275  const node_t *node = node_get_by_id((const char*)ec.node_id);
1276  const ed25519_public_key_t *node_ed_id = NULL;
1277  if (node &&
1279  (node_ed_id = node_get_ed25519_id(node))) {
1280  ed25519_pubkey_copy(&ec.ed_pubkey, node_ed_id);
1281  }
1282  }
1283 
1284  /* Next, check if we're being asked to connect to the hop that the
1285  * extend cell came from. There isn't any reason for that, and it can
1286  * assist circular-path attacks. */
1287  if (tor_memeq(ec.node_id,
1288  TO_OR_CIRCUIT(circ)->p_chan->identity_digest,
1289  DIGEST_LEN)) {
1290  log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
1291  "Client asked me to extend back to the previous hop.");
1292  return -1;
1293  }
1294 
1295  /* Check the previous hop Ed25519 ID too */
1298  &TO_OR_CIRCUIT(circ)->p_chan->ed25519_identity)) {
1299  log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
1300  "Client asked me to extend back to the previous hop "
1301  "(by Ed25519 ID).");
1302  return -1;
1303  }
1304 
1305  n_chan = channel_get_for_extend((const char*)ec.node_id,
1306  &ec.ed_pubkey,
1307  &ec.orport_ipv4.addr,
1308  &msg,
1309  &should_launch);
1310 
1311  if (!n_chan) {
1312  log_debug(LD_CIRC|LD_OR,"Next router (%s): %s",
1313  fmt_addrport(&ec.orport_ipv4.addr,ec.orport_ipv4.port),
1314  msg?msg:"????");
1315 
1316  circ->n_hop = extend_info_new(NULL /*nickname*/,
1317  (const char*)ec.node_id,
1318  &ec.ed_pubkey,
1319  NULL, /*onion_key*/
1320  NULL, /*curve25519_key*/
1321  &ec.orport_ipv4.addr,
1322  ec.orport_ipv4.port);
1323 
1324  circ->n_chan_create_cell = tor_memdup(&ec.create_cell,
1325  sizeof(ec.create_cell));
1326 
1328 
1329  if (should_launch) {
1330  /* we should try to open a connection */
1331  n_chan = channel_connect_for_circuit(&ec.orport_ipv4.addr,
1332  ec.orport_ipv4.port,
1333  (const char*)ec.node_id,
1334  &ec.ed_pubkey);
1335  if (!n_chan) {
1336  log_info(LD_CIRC,"Launching n_chan failed. Closing circuit.");
1337  circuit_mark_for_close(circ, END_CIRC_REASON_CONNECTFAILED);
1338  return 0;
1339  }
1340  log_debug(LD_CIRC,"connecting in progress (or finished). Good.");
1341  }
1342  /* return success. The onion/circuit/etc will be taken care of
1343  * automatically (may already have been) whenever n_chan reaches
1344  * OR_CONN_STATE_OPEN.
1345  */
1346  return 0;
1347  }
1348 
1349  tor_assert(!circ->n_hop); /* Connection is already established. */
1350  circ->n_chan = n_chan;
1351  log_debug(LD_CIRC,
1352  "n_chan is %s",
1354 
1355  if (circuit_deliver_create_cell(circ, &ec.create_cell, 1) < 0)
1356  return -1;
1357 
1358  return 0;
1359 }
1360 
1370 int
1372  const created_cell_t *reply)
1373 {
1374  char keys[CPATH_KEY_MATERIAL_LEN];
1375  crypt_path_t *hop;
1376  int rv;
1377 
1378  if ((rv = pathbias_count_build_attempt(circ)) < 0) {
1379  log_warn(LD_CIRC, "pathbias_count_build_attempt failed: %d", rv);
1380  return rv;
1381  }
1382 
1383  if (circ->cpath->state == CPATH_STATE_AWAITING_KEYS) {
1384  hop = circ->cpath;
1385  } else {
1386  hop = cpath_get_next_non_open_hop(circ->cpath);
1387  if (!hop) { /* got an extended when we're all done? */
1388  log_warn(LD_PROTOCOL,"got extended when circ already built? Closing.");
1389  return - END_CIRC_REASON_TORPROTOCOL;
1390  }
1391  }
1392  tor_assert(hop->state == CPATH_STATE_AWAITING_KEYS);
1393 
1394  {
1395  const char *msg = NULL;
1397  &hop->handshake_state,
1398  reply->reply, reply->handshake_len,
1399  (uint8_t*)keys, sizeof(keys),
1400  (uint8_t*)hop->rend_circ_nonce,
1401  &msg) < 0) {
1402  if (msg)
1403  log_warn(LD_CIRC,"onion_skin_client_handshake failed: %s", msg);
1404  return -END_CIRC_REASON_TORPROTOCOL;
1405  }
1406  }
1407 
1409 
1410  if (cpath_init_circuit_crypto(hop, keys, sizeof(keys), 0, 0)<0) {
1411  return -END_CIRC_REASON_TORPROTOCOL;
1412  }
1413 
1414  hop->state = CPATH_STATE_OPEN;
1415  log_info(LD_CIRC,"Finished building circuit hop:");
1417  circuit_event_status(circ, CIRC_EVENT_EXTENDED, 0);
1418 
1419  return 0;
1420 }
1421 
1428 int
1430 {
1431 // crypt_path_t *victim;
1432 // connection_t *stream;
1433 
1434  tor_assert(circ);
1435 
1436  /* XXX Since we don't send truncates currently, getting a truncated
1437  * means that a connection broke or an extend failed. For now,
1438  * just give up.
1439  */
1440  circuit_mark_for_close(TO_CIRCUIT(circ),
1442  return 0;
1443 
1444 #if 0
1445  while (layer->next != circ->cpath) {
1446  /* we need to clear out layer->next */
1447  victim = layer->next;
1448  log_debug(LD_CIRC, "Killing a layer of the cpath.");
1449 
1450  for (stream = circ->p_streams; stream; stream=stream->next_stream) {
1451  if (stream->cpath_layer == victim) {
1452  log_info(LD_APP, "Marking stream %d for close because of truncate.",
1453  stream->stream_id);
1454  /* no need to send 'end' relay cells,
1455  * because the other side's already dead
1456  */
1457  connection_mark_unattached_ap(stream, END_STREAM_REASON_DESTROY);
1458  }
1459  }
1460 
1461  layer->next = victim->next;
1462  cpath_free(victim);
1463  }
1464 
1465  log_info(LD_CIRC, "finished");
1466  return 0;
1467 #endif /* 0 */
1468 }
1469 
1473 int
1475  const created_cell_t *created_cell,
1476  const char *keys, size_t keys_len,
1477  const uint8_t *rend_circ_nonce)
1478 {
1479  cell_t cell;
1480 
1481  tor_assert(keys_len == CPATH_KEY_MATERIAL_LEN);
1482 
1483  if (created_cell_format(&cell, created_cell) < 0) {
1484  log_warn(LD_BUG,"couldn't format created cell (type=%d, len=%d)",
1485  (int)created_cell->cell_type, (int)created_cell->handshake_len);
1486  return -1;
1487  }
1488  cell.circ_id = circ->p_circ_id;
1489 
1491 
1492  log_debug(LD_CIRC,"init digest forward 0x%.8x, backward 0x%.8x.",
1493  (unsigned int)get_uint32(keys),
1494  (unsigned int)get_uint32(keys+20));
1495  if (relay_crypto_init(&circ->crypto, keys, keys_len, 0, 0)<0) {
1496  log_warn(LD_BUG,"Circuit initialization failed");
1497  return -1;
1498  }
1499 
1500  memcpy(circ->rend_circ_nonce, rend_circ_nonce, DIGEST_LEN);
1501 
1502  int used_create_fast = (created_cell->cell_type == CELL_CREATED_FAST);
1503 
1505  circ->p_chan, &cell, CELL_DIRECTION_IN, 0);
1506  log_debug(LD_CIRC,"Finished sending '%s' cell.",
1507  used_create_fast ? "created_fast" : "created");
1508 
1509  /* Ignore the local bit when ExtendAllowPrivateAddresses is set:
1510  * it violates the assumption that private addresses are local.
1511  * Also, many test networks run on local addresses, and
1512  * TestingTorNetwork sets ExtendAllowPrivateAddresses. */
1513  if ((!channel_is_local(circ->p_chan)
1514  || get_options()->ExtendAllowPrivateAddresses)
1515  && !channel_is_outgoing(circ->p_chan)) {
1516  /* record that we could process create cells from a non-local conn
1517  * that we didn't initiate; presumably this means that create cells
1518  * can reach us too. */
1520  }
1521 
1522  return 0;
1523 }
1524 
1565 int
1566 route_len_for_purpose(uint8_t purpose, extend_info_t *exit_ei)
1567 {
1568  int routelen = DEFAULT_ROUTE_LEN;
1569  int known_purpose = 0;
1570 
1571  if (circuit_should_use_vanguards(purpose)) {
1572  /* Clients want an extra hop for rends to avoid linkability.
1573  * Services want it for intro points to avoid publishing their
1574  * layer3 guards. They want it for hsdir posts to use
1575  * their full layer3 guard set for those connections.
1576  * Ex: C - G - L2 - L3 - R
1577  * S - G - L2 - L3 - HSDIR
1578  * S - G - L2 - L3 - I
1579  */
1580  if (purpose == CIRCUIT_PURPOSE_C_ESTABLISH_REND ||
1581  purpose == CIRCUIT_PURPOSE_S_HSDIR_POST ||
1582  purpose == CIRCUIT_PURPOSE_HS_VANGUARDS ||
1584  return routelen+1;
1585 
1586  /* If we only have Layer2 vanguards, then we do not need
1587  * the extra hop for linkabilty reasons (see below).
1588  * This means all hops can be of the form:
1589  * S/C - G - L2 - M - R/HSDir/I
1590  */
1591  if (get_options()->HSLayer2Nodes && !get_options()->HSLayer3Nodes)
1592  return routelen+1;
1593 
1594  /* For connections to hsdirs, clients want two extra hops
1595  * when using layer3 guards, to avoid linkability.
1596  * Same goes for intro points. Note that the route len
1597  * includes the intro point or hsdir, hence the +2.
1598  * Ex: C - G - L2 - L3 - M - I
1599  * C - G - L2 - L3 - M - HSDIR
1600  * S - G - L2 - L3 - M - R
1601  */
1602  if (purpose == CIRCUIT_PURPOSE_S_CONNECT_REND ||
1603  purpose == CIRCUIT_PURPOSE_C_HSDIR_GET ||
1604  purpose == CIRCUIT_PURPOSE_C_INTRODUCING)
1605  return routelen+2;
1606  }
1607 
1608  if (!exit_ei)
1609  return routelen;
1610 
1611  switch (purpose) {
1612  /* These two purposes connect to a router that we chose, so
1613  * DEFAULT_ROUTE_LEN is safe. */
1615  /* hidden service connecting to introduction point */
1617  /* router reachability testing */
1618  known_purpose = 1;
1619  break;
1620 
1621  /* These three purposes connect to a router that someone else
1622  * might have chosen, so add an extra hop to protect anonymity. */
1626  /* connecting to hidden service directory */
1628  /* client connecting to introduction point */
1630  /* hidden service connecting to rendezvous point */
1631  known_purpose = 1;
1632  routelen++;
1633  break;
1634 
1635  default:
1636  /* Got a purpose not listed above along with a chosen exit.
1637  * Increase the circuit length by one anyway for safety. */
1638  routelen++;
1639  break;
1640  }
1641 
1642  if (BUG(exit_ei && !known_purpose)) {
1643  log_warn(LD_BUG, "Unhandled purpose %d with a chosen exit; "
1644  "assuming routelen %d.", purpose, routelen);
1645  }
1646  return routelen;
1647 }
1648 
1655 STATIC int
1656 new_route_len(uint8_t purpose, extend_info_t *exit_ei,
1657  const smartlist_t *nodes)
1658 {
1659  int routelen;
1660 
1661  tor_assert(nodes);
1662 
1663  routelen = route_len_for_purpose(purpose, exit_ei);
1664 
1665  int num_acceptable_direct = count_acceptable_nodes(nodes, 1);
1666  int num_acceptable_indirect = count_acceptable_nodes(nodes, 0);
1667 
1668  log_debug(LD_CIRC,"Chosen route length %d (%d direct and %d indirect "
1669  "routers suitable).", routelen, num_acceptable_direct,
1670  num_acceptable_indirect);
1671 
1672  if (num_acceptable_direct < 1 || num_acceptable_indirect < routelen - 1) {
1673  log_info(LD_CIRC,
1674  "Not enough acceptable routers (%d/%d direct and %d/%d "
1675  "indirect routers suitable). Discarding this circuit.",
1676  num_acceptable_direct, routelen,
1677  num_acceptable_indirect, routelen);
1678  return -1;
1679  }
1680 
1681  return routelen;
1682 }
1683 
1686 static smartlist_t *
1688 {
1691  return dest;
1692 }
1693 
1701 circuit_all_predicted_ports_handled, (time_t now, int *need_uptime,
1702  int *need_capacity))
1703 {
1704  int i, enough;
1705  uint16_t *port;
1707  smartlist_t *LongLivedServices = get_options()->LongLivedPorts;
1708  tor_assert(need_uptime);
1709  tor_assert(need_capacity);
1710  // Always predict need_capacity
1711  *need_capacity = 1;
1712  enough = (smartlist_len(sl) == 0);
1713  for (i = 0; i < smartlist_len(sl); ++i) {
1714  port = smartlist_get(sl, i);
1715  if (smartlist_contains_int_as_string(LongLivedServices, *port))
1716  *need_uptime = 1;
1717  tor_free(port);
1718  }
1719  smartlist_free(sl);
1720  return enough;
1721 }
1722 
1726 static int
1727 node_handles_some_port(const node_t *node, smartlist_t *needed_ports)
1728 { /* XXXX MOVE */
1729  int i;
1730  uint16_t port;
1731 
1732  for (i = 0; i < smartlist_len(needed_ports); ++i) {
1734  /* alignment issues aren't a worry for this dereference, since
1735  needed_ports is explicitly a smartlist of uint16_t's */
1736  port = *(uint16_t *)smartlist_get(needed_ports, i);
1737  tor_assert(port);
1738  if (node)
1739  r = compare_tor_addr_to_node_policy(NULL, port, node);
1740  else
1741  continue;
1743  return 1;
1744  }
1745  return 0;
1746 }
1747 
1750 static int
1752 {
1753  entry_connection_t *entry;
1754  if (conn->type != CONN_TYPE_AP)
1755  return 0;
1756  entry = TO_ENTRY_CONN(conn);
1757 
1758  if (conn->state == AP_CONN_STATE_CIRCUIT_WAIT &&
1759  !conn->marked_for_close &&
1760  !(entry->want_onehop) && /* ignore one-hop streams */
1761  !(entry->use_begindir) && /* ignore targeted dir fetches */
1762  !(entry->chosen_exit_name) && /* ignore defined streams */
1764  !circuit_stream_is_being_handled(TO_ENTRY_CONN(conn), 0,
1766  return 1;
1767  return 0;
1768 }
1769 
1778 static const node_t *
1780 {
1781  int *n_supported;
1782  int n_pending_connections = 0;
1783  smartlist_t *connections;
1784  int best_support = -1;
1785  int n_best_support=0;
1786  const or_options_t *options = get_options();
1787  const smartlist_t *the_nodes;
1788  const node_t *selected_node=NULL;
1789  const int need_uptime = (flags & CRN_NEED_UPTIME) != 0;
1790  const int need_capacity = (flags & CRN_NEED_CAPACITY) != 0;
1791  const int direct_conn = (flags & CRN_DIRECT_CONN) != 0;
1792 
1793  connections = get_connection_array();
1794 
1795  /* Count how many connections are waiting for a circuit to be built.
1796  * We use this for log messages now, but in the future we may depend on it.
1797  */
1798  SMARTLIST_FOREACH(connections, connection_t *, conn,
1799  {
1801  ++n_pending_connections;
1802  });
1803 // log_fn(LOG_DEBUG, "Choosing exit node; %d connections are pending",
1804 // n_pending_connections);
1805  /* Now we count, for each of the routers in the directory, how many
1806  * of the pending connections could possibly exit from that
1807  * router (n_supported[i]). (We can't be sure about cases where we
1808  * don't know the IP address of the pending connection.)
1809  *
1810  * -1 means "Don't use this router at all."
1811  */
1812  the_nodes = nodelist_get_list();
1813  n_supported = tor_calloc(smartlist_len(the_nodes), sizeof(int));
1814  SMARTLIST_FOREACH_BEGIN(the_nodes, const node_t *, node) {
1815  const int i = node_sl_idx;
1816  if (router_digest_is_me(node->identity)) {
1817  n_supported[i] = -1;
1818 // log_fn(LOG_DEBUG,"Skipping node %s -- it's me.", router->nickname);
1819  /* XXX there's probably a reverse predecessor attack here, but
1820  * it's slow. should we take this out? -RD
1821  */
1822  continue;
1823  }
1824  if (!node_has_preferred_descriptor(node, direct_conn)) {
1825  n_supported[i] = -1;
1826  continue;
1827  }
1828  if (!node->is_running || node->is_bad_exit) {
1829  n_supported[i] = -1;
1830  continue; /* skip routers that are known to be down or bad exits */
1831  }
1832  if (node_get_purpose(node) != ROUTER_PURPOSE_GENERAL) {
1833  /* never pick a non-general node as a random exit. */
1834  n_supported[i] = -1;
1835  continue;
1836  }
1837  if (routerset_contains_node(options->ExcludeExitNodesUnion_, node)) {
1838  n_supported[i] = -1;
1839  continue; /* user asked us not to use it, no matter what */
1840  }
1841  if (options->ExitNodes &&
1842  !routerset_contains_node(options->ExitNodes, node)) {
1843  n_supported[i] = -1;
1844  continue; /* not one of our chosen exit nodes */
1845  }
1846 
1847  if (node_is_unreliable(node, need_uptime, need_capacity, 0)) {
1848  n_supported[i] = -1;
1849  continue; /* skip routers that are not suitable. Don't worry if
1850  * this makes us reject all the possible routers: if so,
1851  * we'll retry later in this function with need_update and
1852  * need_capacity set to 0. */
1853  }
1854  if (!(node->is_valid)) {
1855  /* if it's invalid and we don't want it */
1856  n_supported[i] = -1;
1857 // log_fn(LOG_DEBUG,"Skipping node %s (index %d) -- invalid router.",
1858 // router->nickname, i);
1859  continue; /* skip invalid routers */
1860  }
1861  /* We do not allow relays that allow single hop exits by default. Option
1862  * was deprecated in 0.2.9.2-alpha and removed in 0.3.1.0-alpha. */
1863  if (node_allows_single_hop_exits(node)) {
1864  n_supported[i] = -1;
1865  continue;
1866  }
1867  if (node_exit_policy_rejects_all(node)) {
1868  n_supported[i] = -1;
1869 // log_fn(LOG_DEBUG,"Skipping node %s (index %d) -- it rejects all.",
1870 // router->nickname, i);
1871  continue; /* skip routers that reject all */
1872  }
1873  n_supported[i] = 0;
1874  /* iterate over connections */
1875  SMARTLIST_FOREACH_BEGIN(connections, connection_t *, conn) {
1876  if (!ap_stream_wants_exit_attention(conn))
1877  continue; /* Skip everything but APs in CIRCUIT_WAIT */
1878  if (connection_ap_can_use_exit(TO_ENTRY_CONN(conn), node)) {
1879  ++n_supported[i];
1880 // log_fn(LOG_DEBUG,"%s is supported. n_supported[%d] now %d.",
1881 // router->nickname, i, n_supported[i]);
1882  } else {
1883 // log_fn(LOG_DEBUG,"%s (index %d) would reject this stream.",
1884 // router->nickname, i);
1885  }
1886  } SMARTLIST_FOREACH_END(conn);
1887  if (n_pending_connections > 0 && n_supported[i] == 0) {
1888  /* Leave best_support at -1 if that's where it is, so we can
1889  * distinguish it later. */
1890  continue;
1891  }
1892  if (n_supported[i] > best_support) {
1893  /* If this router is better than previous ones, remember its index
1894  * and goodness, and start counting how many routers are this good. */
1895  best_support = n_supported[i]; n_best_support=1;
1896 // log_fn(LOG_DEBUG,"%s is new best supported option so far.",
1897 // router->nickname);
1898  } else if (n_supported[i] == best_support) {
1899  /* If this router is _as good_ as the best one, just increment the
1900  * count of equally good routers.*/
1901  ++n_best_support;
1902  }
1903  } SMARTLIST_FOREACH_END(node);
1904  log_info(LD_CIRC,
1905  "Found %d servers that might support %d/%d pending connections.",
1906  n_best_support, best_support >= 0 ? best_support : 0,
1907  n_pending_connections);
1908 
1909  /* If any routers definitely support any pending connections, choose one
1910  * at random. */
1911  if (best_support > 0) {
1912  smartlist_t *supporting = smartlist_new();
1913 
1914  SMARTLIST_FOREACH(the_nodes, const node_t *, node, {
1915  if (n_supported[node_sl_idx] == best_support)
1916  smartlist_add(supporting, (void*)node);
1917  });
1918 
1919  selected_node = node_sl_choose_by_bandwidth(supporting, WEIGHT_FOR_EXIT);
1920  smartlist_free(supporting);
1921  } else {
1922  /* Either there are no pending connections, or no routers even seem to
1923  * possibly support any of them. Choose a router at random that satisfies
1924  * at least one predicted exit port. */
1925 
1926  int attempt;
1927  smartlist_t *needed_ports, *supporting;
1928 
1929  if (best_support == -1) {
1930  if (need_uptime || need_capacity) {
1931  log_info(LD_CIRC,
1932  "We couldn't find any live%s%s routers; falling back "
1933  "to list of all routers.",
1934  need_capacity?", fast":"",
1935  need_uptime?", stable":"");
1936  tor_free(n_supported);
1937  flags &= ~(CRN_NEED_UPTIME|CRN_NEED_CAPACITY);
1938  return choose_good_exit_server_general(flags);
1939  }
1940  log_notice(LD_CIRC, "All routers are down or won't exit%s -- "
1941  "choosing a doomed exit at random.",
1942  options->ExcludeExitNodesUnion_ ? " or are Excluded" : "");
1943  }
1944  supporting = smartlist_new();
1945  needed_ports = circuit_get_unhandled_ports(time(NULL));
1946  for (attempt = 0; attempt < 2; attempt++) {
1947  /* try once to pick only from routers that satisfy a needed port,
1948  * then if there are none, pick from any that support exiting. */
1949  SMARTLIST_FOREACH_BEGIN(the_nodes, const node_t *, node) {
1950  if (n_supported[node_sl_idx] != -1 &&
1951  (attempt || node_handles_some_port(node, needed_ports))) {
1952 // log_fn(LOG_DEBUG,"Try %d: '%s' is a possibility.",
1953 // try, router->nickname);
1954  smartlist_add(supporting, (void*)node);
1955  }
1956  } SMARTLIST_FOREACH_END(node);
1957 
1958  selected_node = node_sl_choose_by_bandwidth(supporting, WEIGHT_FOR_EXIT);
1959  if (selected_node)
1960  break;
1961  smartlist_clear(supporting);
1962  /* If we reach this point, we can't actually support any unhandled
1963  * predicted ports, so clear all the remaining ones. */
1964  if (smartlist_len(needed_ports))
1965  rep_hist_remove_predicted_ports(needed_ports);
1966  }
1967  SMARTLIST_FOREACH(needed_ports, uint16_t *, cp, tor_free(cp));
1968  smartlist_free(needed_ports);
1969  smartlist_free(supporting);
1970  }
1971 
1972  tor_free(n_supported);
1973  if (selected_node) {
1974  log_info(LD_CIRC, "Chose exit server '%s'", node_describe(selected_node));
1975  return selected_node;
1976  }
1977  if (options->ExitNodes) {
1978  log_warn(LD_CIRC,
1979  "No exits in ExitNodes%s seem to be running: "
1980  "can't choose an exit.",
1981  options->ExcludeExitNodesUnion_ ?
1982  ", except possibly those excluded by your configuration, " : "");
1983  }
1984  return NULL;
1985 }
1986 
1987 /* Pick a Rendezvous Point for our HS circuits according to <b>flags</b>. */
1988 static const node_t *
1989 pick_rendezvous_node(router_crn_flags_t flags)
1990 {
1991  const or_options_t *options = get_options();
1992  return router_choose_random_node(NULL, options->ExcludeNodes, flags);
1993 }
1994 
1995 /*
1996  * Helper function to pick a configured restricted middle node
1997  * (either HSLayer2Nodes or HSLayer3Nodes).
1998  *
1999  * Make sure that the node we chose is alive, and not excluded,
2000  * and return it.
2001  *
2002  * The exclude_set is a routerset of nodes that the selected node
2003  * must not match, and the exclude_list is a simple list of nodes
2004  * that the selected node must not be in. Either or both may be
2005  * NULL.
2006  *
2007  * Return NULL if no usable nodes could be found. */
2008 static const node_t *
2010  const routerset_t *pick_from,
2011  const routerset_t *exclude_set,
2012  const smartlist_t *exclude_list,
2013  int position_hint)
2014 {
2015  const node_t *middle_node = NULL;
2016 
2017  smartlist_t *whitelisted_live_middles = smartlist_new();
2018  smartlist_t *all_live_nodes = smartlist_new();
2019 
2020  tor_assert(pick_from);
2021 
2022  /* Add all running nodes to all_live_nodes */
2024  (flags & CRN_NEED_UPTIME) != 0,
2025  (flags & CRN_NEED_CAPACITY) != 0,
2026  (flags & CRN_NEED_GUARD) != 0,
2027  (flags & CRN_NEED_DESC) != 0,
2028  (flags & CRN_PREF_ADDR) != 0,
2029  (flags & CRN_DIRECT_CONN) != 0);
2030 
2031  /* Filter all_live_nodes to only add live *and* whitelisted middles
2032  * to the list whitelisted_live_middles. */
2033  SMARTLIST_FOREACH_BEGIN(all_live_nodes, node_t *, live_node) {
2034  if (routerset_contains_node(pick_from, live_node)) {
2035  smartlist_add(whitelisted_live_middles, live_node);
2036  }
2037  } SMARTLIST_FOREACH_END(live_node);
2038 
2039  /* Honor ExcludeNodes */
2040  if (exclude_set) {
2041  routerset_subtract_nodes(whitelisted_live_middles, exclude_set);
2042  }
2043 
2044  if (exclude_list) {
2045  smartlist_subtract(whitelisted_live_middles, exclude_list);
2046  }
2047 
2054 #define MAX_SANE_RESTRICTED_NODES 20
2055  /* If the user (or associated tor controller) selected only a few nodes,
2056  * assume they took load balancing into account and don't do it for them.
2057  *
2058  * If there are a lot of nodes in here, assume they did not load balance
2059  * and do it for them, but also warn them that they may be Doing It Wrong.
2060  */
2061  if (smartlist_len(whitelisted_live_middles) <=
2062  MAX_SANE_RESTRICTED_NODES) {
2063  middle_node = smartlist_choose(whitelisted_live_middles);
2064  } else {
2065  static ratelim_t pinned_notice_limit = RATELIM_INIT(24*3600);
2066  log_fn_ratelim(&pinned_notice_limit, LOG_NOTICE, LD_CIRC,
2067  "Your _HSLayer%dNodes setting has resulted "
2068  "in %d total nodes. This is a lot of nodes. "
2069  "You may want to consider using a Tor controller "
2070  "to select and update a smaller set of nodes instead.",
2071  position_hint, smartlist_len(whitelisted_live_middles));
2072 
2073  /* NO_WEIGHTING here just means don't take node flags into account
2074  * (ie: use consensus measurement only). This is done so that
2075  * we don't further surprise the user by not using Exits that they
2076  * specified at all */
2077  middle_node = node_sl_choose_by_bandwidth(whitelisted_live_middles,
2078  NO_WEIGHTING);
2079  }
2080 
2081  smartlist_free(whitelisted_live_middles);
2082  smartlist_free(all_live_nodes);
2083 
2084  return middle_node;
2085 }
2086 
2097 static const node_t *
2099  router_crn_flags_t flags, int is_internal)
2100 {
2101  const or_options_t *options = get_options();
2102  flags |= CRN_NEED_DESC;
2103 
2104  switch (TO_CIRCUIT(circ)->purpose) {
2108  /* For these three, we want to pick the exit like a middle hop,
2109  * since it should be random. */
2110  tor_assert_nonfatal(is_internal);
2111  /* Falls through */
2113  if (is_internal) /* pick it like a middle hop */
2114  return router_choose_random_node(NULL, options->ExcludeNodes, flags);
2115  else
2116  return choose_good_exit_server_general(flags);
2118  {
2119  /* Pick a new RP */
2120  const node_t *rendezvous_node = pick_rendezvous_node(flags);
2121  log_info(LD_REND, "Picked new RP: %s",
2122  safe_str_client(node_describe(rendezvous_node)));
2123  return rendezvous_node;
2124  }
2125  }
2126  log_warn(LD_BUG,"Unhandled purpose %d", TO_CIRCUIT(circ)->purpose);
2128  return NULL;
2129 }
2130 
2133 static void
2135  const extend_info_t *exit_ei)
2136 {
2137  const or_options_t *options = get_options();
2138  routerset_t *rs = options->ExcludeNodes;
2139  const char *description;
2140  uint8_t purpose = circ->base_.purpose;
2141 
2142  if (circ->build_state->onehop_tunnel)
2143  return;
2144 
2145  switch (purpose)
2146  {
2147  default:
2148  case CIRCUIT_PURPOSE_OR:
2152  log_warn(LD_BUG, "Called on non-origin circuit (purpose %d, %s)",
2153  (int)purpose,
2154  circuit_purpose_to_string(purpose));
2155  return;
2159  if (circ->build_state->is_internal)
2160  return;
2161  description = "requested exit node";
2162  rs = options->ExcludeExitNodesUnion_;
2163  break;
2171  return;
2176  description = "chosen rendezvous point";
2177  break;
2179  rs = options->ExcludeExitNodesUnion_;
2180  description = "controller-selected circuit target";
2181  break;
2182  }
2183 
2184  if (routerset_contains_extendinfo(rs, exit_ei)) {
2185  /* We should never get here if StrictNodes is set to 1. */
2186  if (options->StrictNodes) {
2187  log_warn(LD_BUG, "Using %s '%s' which is listed in ExcludeNodes%s, "
2188  "even though StrictNodes is set. Please report. "
2189  "(Circuit purpose: %s)",
2190  description, extend_info_describe(exit_ei),
2191  rs==options->ExcludeNodes?"":" or ExcludeExitNodes",
2192  circuit_purpose_to_string(purpose));
2193  } else {
2194  log_warn(LD_CIRC, "Using %s '%s' which is listed in "
2195  "ExcludeNodes%s, because no better options were available. To "
2196  "prevent this (and possibly break your Tor functionality), "
2197  "set the StrictNodes configuration option. "
2198  "(Circuit purpose: %s)",
2199  description, extend_info_describe(exit_ei),
2200  rs==options->ExcludeNodes?"":" or ExcludeExitNodes",
2201  circuit_purpose_to_string(purpose));
2202  }
2204  }
2205 
2206  return;
2207 }
2208 
2217 STATIC int
2219  int is_hs_v3_rp_circuit)
2220 {
2221  cpath_build_state_t *state = circ->build_state;
2222 
2223  if (state->onehop_tunnel) {
2224  log_debug(LD_CIRC, "Launching a one-hop circuit for dir tunnel%s.",
2225  (rend_allow_non_anonymous_connection(get_options()) ?
2226  ", or intro or rendezvous connection" : ""));
2227  state->desired_path_len = 1;
2228  } else {
2229  int r = new_route_len(circ->base_.purpose, exit_ei, nodelist_get_list());
2230  if (r < 1) /* must be at least 1 */
2231  return -1;
2232  state->desired_path_len = r;
2233  }
2234 
2235  if (exit_ei) { /* the circuit-builder pre-requested one */
2236  warn_if_last_router_excluded(circ, exit_ei);
2237  log_info(LD_CIRC,"Using requested exit node '%s'",
2238  extend_info_describe(exit_ei));
2239  exit_ei = extend_info_dup(exit_ei);
2240  } else { /* we have to decide one */
2241  router_crn_flags_t flags = CRN_NEED_DESC;
2242  if (state->need_uptime)
2243  flags |= CRN_NEED_UPTIME;
2244  if (state->need_capacity)
2245  flags |= CRN_NEED_CAPACITY;
2246  if (is_hs_v3_rp_circuit)
2247  flags |= CRN_RENDEZVOUS_V3;
2248  if (state->onehop_tunnel)
2249  flags |= CRN_DIRECT_CONN;
2250  const node_t *node =
2251  choose_good_exit_server(circ, flags, state->is_internal);
2252  if (!node) {
2253  log_warn(LD_CIRC,"Failed to choose an exit server");
2254  return -1;
2255  }
2256  exit_ei = extend_info_from_node(node, state->onehop_tunnel);
2257  if (BUG(exit_ei == NULL))
2258  return -1;
2259  }
2260  state->chosen_exit = exit_ei;
2261  return 0;
2262 }
2263 
2268 int
2270 {
2271  cpath_build_state_t *state;
2272  tor_assert(exit_ei);
2273  tor_assert(circ);
2274 
2275  state = circ->build_state;
2276  tor_assert(state);
2277  extend_info_free(state->chosen_exit);
2278  state->chosen_exit = extend_info_dup(exit_ei);
2279 
2280  ++circ->build_state->desired_path_len;
2281  cpath_append_hop(&circ->cpath, exit_ei);
2282  return 0;
2283 }
2284 
2289 int
2291 {
2292  int err_reason = 0;
2293  warn_if_last_router_excluded(circ, exit_ei);
2294 
2295  tor_gettimeofday(&circ->base_.timestamp_began);
2296 
2297  circuit_append_new_exit(circ, exit_ei);
2299  if ((err_reason = circuit_send_next_onion_skin(circ))<0) {
2300  log_warn(LD_CIRC, "Couldn't extend circuit to new point %s.",
2301  extend_info_describe(exit_ei));
2302  circuit_mark_for_close(TO_CIRCUIT(circ), -err_reason);
2303  return -1;
2304  }
2305 
2306  // XXX: Should cannibalized circuits be dirty or not? Not easy to say..
2307 
2308  return 0;
2309 }
2310 
2318 MOCK_IMPL(STATIC int,
2319 count_acceptable_nodes, (const smartlist_t *nodes, int direct))
2320 {
2321  int num=0;
2322 
2323  SMARTLIST_FOREACH_BEGIN(nodes, const node_t *, node) {
2324  // log_debug(LD_CIRC,
2325 // "Contemplating whether router %d (%s) is a new option.",
2326 // i, r->nickname);
2327  if (! node->is_running)
2328 // log_debug(LD_CIRC,"Nope, the directory says %d is not running.",i);
2329  continue;
2330  if (! node->is_valid)
2331 // log_debug(LD_CIRC,"Nope, the directory says %d is not valid.",i);
2332  continue;
2333  if (! node_has_preferred_descriptor(node, direct))
2334  continue;
2335  /* The node has a descriptor, so we can just check the ntor key directly */
2336  if (!node_has_curve25519_onion_key(node))
2337  continue;
2338  ++num;
2339  } SMARTLIST_FOREACH_END(node);
2340 
2341 // log_debug(LD_CIRC,"I like %d. num_acceptable_routers now %d.",i, num);
2342 
2343  return num;
2344 }
2345 
2366 static smartlist_t *
2368  cpath_build_state_t *state,
2369  crypt_path_t *head,
2370  int cur_len)
2371 {
2372  smartlist_t *excluded;
2373  const node_t *r;
2374  crypt_path_t *cpath;
2375  int i;
2376 
2377  (void) purpose;
2378 
2379  excluded = smartlist_new();
2380 
2381  /* Add the exit to the exclude list (note that the exit/last hop is always
2382  * chosen first in circuit_establish_circuit()). */
2383  if ((r = build_state_get_exit_node(state))) {
2384  smartlist_add(excluded, (node_t*)r);
2385  }
2386 
2387  /* If we are picking the 4th hop, allow that node to be the guard too.
2388  * This prevents us from avoiding the Guard for those hops, which
2389  * gives the adversary information about our guard if they control
2390  * the RP, IP, or HSDIR. We don't do this check based on purpose
2391  * because we also want to allow HS_VANGUARDS pre-build circuits
2392  * to use the guard for that last hop.
2393  */
2394  if (cur_len == DEFAULT_ROUTE_LEN+1) {
2395  /* Skip the first hop for the exclude list below */
2396  head = head->next;
2397  cur_len--;
2398  }
2399 
2400  for (i = 0, cpath = head; cpath && i < cur_len; ++i, cpath=cpath->next) {
2401  if ((r = node_get_by_id(cpath->extend_info->identity_digest))) {
2402  smartlist_add(excluded, (node_t*)r);
2403  }
2404  }
2405 
2406  return excluded;
2407 }
2408 
2413 static smartlist_t *
2415  cpath_build_state_t *state,
2416  crypt_path_t *head,
2417  int cur_len)
2418 {
2419  smartlist_t *excluded;
2420  const node_t *r;
2421  crypt_path_t *cpath;
2422  int i;
2423 
2425  if (circuit_should_use_vanguards(purpose)) {
2426  return build_vanguard_middle_exclude_list(purpose, state, head, cur_len);
2427  }
2428 
2429  excluded = smartlist_new();
2430 
2431  /* For non-vanguard circuits, add the exit and its family to the exclude list
2432  * (note that the exit/last hop is always chosen first in
2433  * circuit_establish_circuit()). */
2434  if ((r = build_state_get_exit_node(state))) {
2435  nodelist_add_node_and_family(excluded, r);
2436  }
2437 
2438  /* also exclude all other already chosen nodes and their family */
2439  for (i = 0, cpath = head; cpath && i < cur_len; ++i, cpath=cpath->next) {
2440  if ((r = node_get_by_id(cpath->extend_info->identity_digest))) {
2441  nodelist_add_node_and_family(excluded, r);
2442  }
2443  }
2444 
2445  return excluded;
2446 }
2447 
2449 static int
2451  uint8_t purpose, int cur_len)
2452 {
2453  /* If this is not a hidden service circuit, don't use vanguards */
2454  if (!circuit_purpose_is_hidden_service(purpose)) {
2455  return 0;
2456  }
2457 
2458  /* If we have sticky L2 nodes, and this is an L2 pick, use vanguards */
2459  if (options->HSLayer2Nodes && cur_len == 1) {
2460  return 1;
2461  }
2462 
2463  /* If we have sticky L3 nodes, and this is an L3 pick, use vanguards */
2464  if (options->HSLayer3Nodes && cur_len == 2) {
2465  return 1;
2466  }
2467 
2468  return 0;
2469 }
2470 
2473 static const node_t *
2475  router_crn_flags_t flags, int cur_len,
2476  const smartlist_t *excluded)
2477 {
2478  const routerset_t *vanguard_routerset = NULL;
2479  const node_t *node = NULL;
2480 
2481  /* Pick the right routerset based on the current hop */
2482  if (cur_len == 1) {
2483  vanguard_routerset = options->HSLayer2Nodes;
2484  } else if (cur_len == 2) {
2485  vanguard_routerset = options->HSLayer3Nodes;
2486  } else {
2487  /* guaranteed by middle_node_should_be_vanguard() */
2488  tor_assert_nonfatal_unreached();
2489  return NULL;
2490  }
2491 
2492  node = pick_restricted_middle_node(flags, vanguard_routerset,
2493  options->ExcludeNodes, excluded,
2494  cur_len+1);
2495 
2496  if (!node) {
2497  static ratelim_t pinned_warning_limit = RATELIM_INIT(300);
2498  log_fn_ratelim(&pinned_warning_limit, LOG_WARN, LD_CIRC,
2499  "Could not find a node that matches the configured "
2500  "_HSLayer%dNodes set", cur_len+1);
2501  }
2502 
2503  return node;
2504 }
2505 
2512 static const node_t *
2514  cpath_build_state_t *state,
2515  crypt_path_t *head,
2516  int cur_len)
2517 {
2518  const node_t *choice;
2519  smartlist_t *excluded;
2520  const or_options_t *options = get_options();
2521  router_crn_flags_t flags = CRN_NEED_DESC;
2522  tor_assert(CIRCUIT_PURPOSE_MIN_ <= purpose &&
2523  purpose <= CIRCUIT_PURPOSE_MAX_);
2524 
2525  log_debug(LD_CIRC, "Contemplating intermediate hop #%d: random choice.",
2526  cur_len+1);
2527 
2528  excluded = build_middle_exclude_list(purpose, state, head, cur_len);
2529 
2530  if (state->need_uptime)
2531  flags |= CRN_NEED_UPTIME;
2532  if (state->need_capacity)
2533  flags |= CRN_NEED_CAPACITY;
2534 
2536  if (middle_node_must_be_vanguard(options, purpose, cur_len)) {
2537  log_debug(LD_GENERAL, "Picking a sticky node (cur_len = %d)", cur_len);
2538  choice = pick_vanguard_middle_node(options, flags, cur_len, excluded);
2539  smartlist_free(excluded);
2540  return choice;
2541  }
2542 
2543  if (options->MiddleNodes) {
2544  smartlist_t *sl = smartlist_new();
2545  routerset_get_all_nodes(sl, options->MiddleNodes,
2546  options->ExcludeNodes, 1);
2547 
2548  smartlist_subtract(sl, excluded);
2549 
2550  choice = node_sl_choose_by_bandwidth(sl, WEIGHT_FOR_MID);
2551  smartlist_free(sl);
2552  if (choice) {
2553  log_fn(LOG_INFO, LD_CIRC, "Chose fixed middle node: %s",
2554  hex_str(choice->identity, DIGEST_LEN));
2555  } else {
2556  log_fn(LOG_NOTICE, LD_CIRC, "Restricted middle not available");
2557  }
2558  } else {
2559  choice = router_choose_random_node(excluded, options->ExcludeNodes, flags);
2560  }
2561  smartlist_free(excluded);
2562  return choice;
2563 }
2564 
2574 const node_t *
2576  circuit_guard_state_t **guard_state_out)
2577 {
2578  const node_t *choice;
2579  smartlist_t *excluded;
2580  const or_options_t *options = get_options();
2581  /* If possible, choose an entry server with a preferred address,
2582  * otherwise, choose one with an allowed address */
2583  router_crn_flags_t flags = (CRN_NEED_GUARD|CRN_NEED_DESC|CRN_PREF_ADDR|
2584  CRN_DIRECT_CONN);
2585  const node_t *node;
2586 
2587  /* Once we used this function to select a node to be a guard. We had
2588  * 'state == NULL' be the signal for that. But we don't do that any more.
2589  */
2590  tor_assert_nonfatal(state);
2591 
2592  if (state && options->UseEntryGuards &&
2593  (purpose != CIRCUIT_PURPOSE_TESTING || options->BridgeRelay)) {
2594  /* This request is for an entry server to use for a regular circuit,
2595  * and we use entry guard nodes. Just return one of the guard nodes. */
2596  tor_assert(guard_state_out);
2597  return guards_choose_guard(state, purpose, guard_state_out);
2598  }
2599 
2600  excluded = smartlist_new();
2601 
2602  if (state && (node = build_state_get_exit_node(state))) {
2603  /* Exclude the exit node from the state, if we have one. Also exclude its
2604  * family. */
2605  nodelist_add_node_and_family(excluded, node);
2606  }
2607 
2608  if (state) {
2609  if (state->need_uptime)
2610  flags |= CRN_NEED_UPTIME;
2611  if (state->need_capacity)
2612  flags |= CRN_NEED_CAPACITY;
2613  }
2614 
2615  choice = router_choose_random_node(excluded, options->ExcludeNodes, flags);
2616  smartlist_free(excluded);
2617  return choice;
2618 }
2619 
2626 STATIC int
2628 {
2629  uint8_t purpose = circ->base_.purpose;
2630  cpath_build_state_t *state = circ->build_state;
2631  int cur_len = circuit_get_cpath_len(circ);
2632  extend_info_t *info = NULL;
2633 
2634  if (cur_len >= state->desired_path_len) {
2635  log_debug(LD_CIRC, "Path is complete: %d steps long",
2636  state->desired_path_len);
2637  return 1;
2638  }
2639 
2640  log_debug(LD_CIRC, "Path is %d long; we want %d", cur_len,
2641  state->desired_path_len);
2642 
2643  if (cur_len == state->desired_path_len - 1) { /* Picking last node */
2644  info = extend_info_dup(state->chosen_exit);
2645  } else if (cur_len == 0) { /* picking first node */
2646  const node_t *r = choose_good_entry_server(purpose, state,
2647  &circ->guard_state);
2648  if (r) {
2649  /* If we're a client, use the preferred address rather than the
2650  primary address, for potentially connecting to an IPv6 OR
2651  port. Servers always want the primary (IPv4) address. */
2652  int client = (server_mode(get_options()) == 0);
2653  info = extend_info_from_node(r, client);
2654  /* Clients can fail to find an allowed address */
2655  tor_assert_nonfatal(info || client);
2656  }
2657  } else {
2658  const node_t *r =
2659  choose_good_middle_server(purpose, state, circ->cpath, cur_len);
2660  if (r) {
2661  info = extend_info_from_node(r, 0);
2662  tor_assert_nonfatal(info);
2663  }
2664  }
2665 
2666  if (!info) {
2667  log_warn(LD_CIRC,"Failed to find node for hop #%d of our path. Discarding "
2668  "this circuit.", cur_len+1);
2669  return -1;
2670  }
2671 
2672  log_debug(LD_CIRC,"Chose router %s for hop #%d (exit is %s)",
2673  extend_info_describe(info),
2674  cur_len+1, build_state_get_exit_nickname(state));
2675 
2676  cpath_append_hop(&circ->cpath, info);
2677  extend_info_free(info);
2678  return 0;
2679 }
2680 
2682 extend_info_t *
2683 extend_info_new(const char *nickname,
2684  const char *rsa_id_digest,
2685  const ed25519_public_key_t *ed_id,
2686  crypto_pk_t *onion_key,
2687  const curve25519_public_key_t *ntor_key,
2688  const tor_addr_t *addr, uint16_t port)
2689 {
2690  extend_info_t *info = tor_malloc_zero(sizeof(extend_info_t));
2691  memcpy(info->identity_digest, rsa_id_digest, DIGEST_LEN);
2692  if (ed_id && !ed25519_public_key_is_zero(ed_id))
2693  memcpy(&info->ed_identity, ed_id, sizeof(ed25519_public_key_t));
2694  if (nickname)
2695  strlcpy(info->nickname, nickname, sizeof(info->nickname));
2696  if (onion_key)
2697  info->onion_key = crypto_pk_dup_key(onion_key);
2698  if (ntor_key)
2699  memcpy(&info->curve25519_onion_key, ntor_key,
2700  sizeof(curve25519_public_key_t));
2701  tor_addr_copy(&info->addr, addr);
2702  info->port = port;
2703  return info;
2704 }
2705 
2716 extend_info_t *
2717 extend_info_from_node(const node_t *node, int for_direct_connect)
2718 {
2719  crypto_pk_t *rsa_pubkey = NULL;
2720  extend_info_t *info = NULL;
2721  tor_addr_port_t ap;
2722  int valid_addr = 0;
2723 
2724  if (!node_has_preferred_descriptor(node, for_direct_connect)) {
2725  return NULL;
2726  }
2727 
2728  /* Choose a preferred address first, but fall back to an allowed address. */
2729  if (for_direct_connect)
2730  fascist_firewall_choose_address_node(node, FIREWALL_OR_CONNECTION, 0, &ap);
2731  else {
2732  node_get_prim_orport(node, &ap);
2733  }
2734  valid_addr = tor_addr_port_is_valid_ap(&ap, 0);
2735 
2736  if (valid_addr)
2737  log_debug(LD_CIRC, "using %s for %s",
2738  fmt_addrport(&ap.addr, ap.port),
2739  node->ri ? node->ri->nickname : node->rs->nickname);
2740  else
2741  log_warn(LD_CIRC, "Could not choose valid address for %s",
2742  node->ri ? node->ri->nickname : node->rs->nickname);
2743 
2744  /* Every node we connect or extend to must support ntor */
2745  if (!node_has_curve25519_onion_key(node)) {
2746  log_fn(LOG_PROTOCOL_WARN, LD_CIRC,
2747  "Attempted to create extend_info for a node that does not support "
2748  "ntor: %s", node_describe(node));
2749  return NULL;
2750  }
2751 
2752  const ed25519_public_key_t *ed_pubkey = NULL;
2753 
2754  /* Don't send the ed25519 pubkey unless the target node actually supports
2755  * authenticating with it. */
2757  log_info(LD_CIRC, "Including Ed25519 ID for %s", node_describe(node));
2758  ed_pubkey = node_get_ed25519_id(node);
2759  } else if (node_get_ed25519_id(node)) {
2760  log_info(LD_CIRC, "Not including the ed25519 ID for %s, since it won't "
2761  "be able to authenticate it.",
2762  node_describe(node));
2763  }
2764 
2765  /* Retrieve the curve25519 pubkey. */
2766  const curve25519_public_key_t *curve_pubkey =
2768  rsa_pubkey = node_get_rsa_onion_key(node);
2769 
2770  if (valid_addr && node->ri) {
2771  info = extend_info_new(node->ri->nickname,
2772  node->identity,
2773  ed_pubkey,
2774  rsa_pubkey,
2775  curve_pubkey,
2776  &ap.addr,
2777  ap.port);
2778  } else if (valid_addr && node->rs && node->md) {
2779  info = extend_info_new(node->rs->nickname,
2780  node->identity,
2781  ed_pubkey,
2782  rsa_pubkey,
2783  curve_pubkey,
2784  &ap.addr,
2785  ap.port);
2786  }
2787 
2788  crypto_pk_free(rsa_pubkey);
2789  return info;
2790 }
2791 
2793 void
2795 {
2796  if (!info)
2797  return;
2798  crypto_pk_free(info->onion_key);
2799  tor_free(info);
2800 }
2801 
2804 extend_info_t *
2806 {
2807  extend_info_t *newinfo;
2808  tor_assert(info);
2809  newinfo = tor_malloc(sizeof(extend_info_t));
2810  memcpy(newinfo, info, sizeof(extend_info_t));
2811  if (info->onion_key)
2812  newinfo->onion_key = crypto_pk_dup_key(info->onion_key);
2813  else
2814  newinfo->onion_key = NULL;
2815  return newinfo;
2816 }
2817 
2822 const node_t *
2824 {
2825  if (!state || !state->chosen_exit)
2826  return NULL;
2827  return node_get_by_id(state->chosen_exit->identity_digest);
2828 }
2829 
2833 const uint8_t *
2835 {
2836  if (!state || !state->chosen_exit)
2837  return NULL;
2838  return (const uint8_t *) state->chosen_exit->identity_digest;
2839 }
2840 
2845 const char *
2847 {
2848  if (!state || !state->chosen_exit)
2849  return NULL;
2850  return state->chosen_exit->nickname;
2851 }
2852 
2854 int
2856 {
2857  tor_assert(addr);
2858 
2859  /* Check if we have a private address and if we can extend to it. */
2860  if ((tor_addr_is_internal(addr, 0) || tor_addr_is_multicast(addr)) &&
2861  !get_options()->ExtendAllowPrivateAddresses) {
2862  goto disallow;
2863  }
2864  /* Allowed! */
2865  return 1;
2866  disallow:
2867  return 0;
2868 }
2869 
2870 /* Does ei have a valid TAP key? */
2871 int
2872 extend_info_supports_tap(const extend_info_t* ei)
2873 {
2874  tor_assert(ei);
2875  /* Valid TAP keys are not NULL */
2876  return ei->onion_key != NULL;
2877 }
2878 
2879 /* Does ei have a valid ntor key? */
2880 int
2881 extend_info_supports_ntor(const extend_info_t* ei)
2882 {
2883  tor_assert(ei);
2884  /* Valid ntor keys have at least one non-zero byte */
2885  return !fast_mem_is_zero(
2886  (const char*)ei->curve25519_onion_key.public_key,
2888 }
2889 
2890 /* Is circuit purpose allowed to use the deprecated TAP encryption protocol?
2891  * The hidden service protocol still uses TAP for some connections, because
2892  * ntor onion keys aren't included in HS descriptors or INTRODUCE cells. */
2893 static int
2894 circuit_purpose_can_use_tap_impl(uint8_t purpose)
2895 {
2896  return (purpose == CIRCUIT_PURPOSE_S_CONNECT_REND ||
2897  purpose == CIRCUIT_PURPOSE_C_INTRODUCING);
2898 }
2899 
2900 /* Is circ allowed to use the deprecated TAP encryption protocol?
2901  * The hidden service protocol still uses TAP for some connections, because
2902  * ntor onion keys aren't included in HS descriptors or INTRODUCE cells. */
2903 int
2904 circuit_can_use_tap(const origin_circuit_t *circ)
2905 {
2906  tor_assert(circ);
2907  tor_assert(circ->cpath);
2908  tor_assert(circ->cpath->extend_info);
2909  return (circuit_purpose_can_use_tap_impl(circ->base_.purpose) &&
2910  extend_info_supports_tap(circ->cpath->extend_info));
2911 }
2912 
2913 /* Does circ have an onion key which it's allowed to use? */
2914 int
2915 circuit_has_usable_onion_key(const origin_circuit_t *circ)
2916 {
2917  tor_assert(circ);
2918  tor_assert(circ->cpath);
2919  tor_assert(circ->cpath->extend_info);
2920  return (extend_info_supports_ntor(circ->cpath->extend_info) ||
2921  circuit_can_use_tap(circ));
2922 }
2923 
2924 /* Does ei have an onion key which it would prefer to use?
2925  * Currently, we prefer ntor keys*/
2926 int
2927 extend_info_has_preferred_onion_key(const extend_info_t* ei)
2928 {
2929  tor_assert(ei);
2930  return extend_info_supports_ntor(ei);
2931 }
2932 
2936 void
2938 {
2939  smartlist_t *to_upgrade =
2941 
2942  if (to_upgrade == NULL)
2943  return;
2944 
2945  log_info(LD_GUARD, "Upgrading %d circuits from 'waiting for better guard' "
2946  "to 'open'.", smartlist_len(to_upgrade));
2947 
2948  SMARTLIST_FOREACH_BEGIN(to_upgrade, origin_circuit_t *, circ) {
2950  circuit_has_opened(circ);
2951  } SMARTLIST_FOREACH_END(circ);
2952 
2953  smartlist_free(to_upgrade);
2954 }
#define RELAY_PAYLOAD_SIZE
Definition: or.h:605
#define CIRCUIT_PURPOSE_C_INTRODUCING
Definition: circuitlist.h:74
channel_state_t state
Definition: channel.h:192
Header file for circuitstats.c.
#define CIRCLAUNCH_ONEHOP_TUNNEL
Definition: circuituse.h:39
Header file for rendcommon.c.
void circuit_get_all_pending_on_channel(smartlist_t *out, channel_t *chan)
Definition: circuitlist.c:573
#define CIRCLAUNCH_IS_INTERNAL
Definition: circuituse.h:46
static void warn_if_last_router_excluded(origin_circuit_t *circ, const extend_info_t *exit_ei)
uint8_t onionskin[CELL_PAYLOAD_SIZE - 4]
Definition: onion.h:32
struct circuit_guard_state_t * guard_state
circ_id_type_bitfield_t circ_id_type
Definition: channel.h:411
static smartlist_t * build_middle_exclude_list(uint8_t purpose, cpath_build_state_t *state, crypt_path_t *head, int cur_len)
const char * channel_get_canonical_remote_descr(channel_t *chan)
Definition: channel.c:2847
int node_allows_single_hop_exits(const node_t *node)
Definition: nodelist.c:1419
#define CIRCUIT_PURPOSE_C_MEASURE_TIMEOUT
Definition: circuitlist.h:94
int routerset_contains_extendinfo(const routerset_t *set, const extend_info_t *ei)
Definition: routerset.c:293
static void circuit_chan_publish(const origin_circuit_t *circ, const channel_t *chan)
Definition: circuitbuild.c:523
#define CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED
Definition: circuitlist.h:87
int channel_is_outgoing(channel_t *chan)
Definition: channel.c:3071
void pathbias_count_build_success(origin_circuit_t *circ)
Definition: circpathbias.c:512
static smartlist_t * circuit_get_unhandled_ports(time_t now)
Header file for circuitbuild.c.
uint8_t payload[CELL_PAYLOAD_SIZE]
Definition: cell_st.h:16
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)
Common functions for using (pseudo-)random number generators.
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:591
Definition: node_st.h:28
uint8_t cell_type
Definition: onion.h:38
int node_supports_ed25519_link_authentication(const node_t *node, int compatible_with_us)
Definition: nodelist.c:1135
#define SMARTLIST_FOREACH_BEGIN(sl, type, var)
uint16_t handshake_len
Definition: onion.h:30
int routerset_contains_node(const routerset_t *set, const node_t *node)
Definition: routerset.c:338
Header file for command.c.
void tor_addr_make_unspec(tor_addr_t *a)
Definition: address.c:225
extend_info_t * extend_info_from_node(const node_t *node, int for_direct_connect)
channel_t * channel_get_for_extend(const char *rsa_id_digest, const ed25519_public_key_t *ed_id, const tor_addr_t *target_addr, const char **msg_out, int *launch_out)
Definition: channel.c:2394
int circuit_handle_first_hop(origin_circuit_t *circ)
Definition: circuitbuild.c:539
addr_policy_result_t
Definition: policies.h:38
struct crypt_path_t * next
Definition: crypt_path_st.h:67
Header file for node_select.c.
void circpad_machine_event_circ_added_hop(origin_circuit_t *on_circ)
const char * extend_info_describe(const extend_info_t *ei)
Definition: describe.c:204
Header file for connection.c.
void circuit_n_chan_done(channel_t *chan, int status, int close_origin_circuits)
Definition: circuitbuild.c:627
Definition: cell_st.h:12
#define LD_GENERAL
Definition: log.h:60
int route_len_for_purpose(uint8_t purpose, extend_info_t *exit_ei)
#define CIRCUIT_IS_ORIGIN(c)
Definition: circuitlist.h:145
time_t timestamp_created
Definition: channel.h:295
#define CIRCLAUNCH_NEED_UPTIME
Definition: circuituse.h:41
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:3004
int circuit_finish_handshake(origin_circuit_t *circ, const created_cell_t *reply)
origin_circuit_t * origin_circuit_init(uint8_t purpose, int flags)
Definition: circuitbuild.c:453
uint8_t state
Definition: connection_st.h:44
#define CIRCUIT_PURPOSE_REND_POINT_WAITING
Definition: circuitlist.h:44
const char * circuit_purpose_to_string(uint8_t purpose)
Definition: circuitlist.c:898
void rep_hist_remove_predicted_ports(const smartlist_t *rmv_ports)
#define LOG_INFO
Definition: log.h:43
Header file for describe.c.
#define DEFAULT_ROUTE_LEN
Definition: or.h:1007
Header file for nodelist.c.
STATIC int new_route_len(uint8_t purpose, extend_info_t *exit_ei, const smartlist_t *nodes)
crypt_path_t * cpath
void tor_log(int severity, log_domain_mask_t domain, const char *format,...)
Definition: log.c:633
const ed25519_public_key_t * node_get_ed25519_id(const node_t *node)
Definition: nodelist.c:1051
void node_get_prim_orport(const node_t *node, tor_addr_port_t *ap_out)
Definition: nodelist.c:1694
void relay_header_unpack(relay_header_t *dest, const uint8_t *src)
Definition: relay.c:488
Header file for directory.c.
int circuit_purpose_is_hidden_service(uint8_t purpose)
Definition: circuituse.c:1965
void smartlist_add(smartlist_t *sl, void *element)
void note_that_we_maybe_cant_complete_circuits(void)
Definition: mainloop.c:234
crypt_path_t * cpath_get_next_non_open_hop(crypt_path_t *cpath)
Definition: crypt_path.c:228
Header file for onion_tap.c.
void note_that_we_completed_a_circuit(void)
Definition: mainloop.c:226
int circuit_id_in_use_on_channel(circid_t circ_id, channel_t *chan)
Definition: circuitlist.c:1540
int circuit_extend(cell_t *cell, circuit_t *circ)
char * rate_limit_log(ratelim_t *lim, time_t now)
Definition: ratelim.c:41
int circuit_truncated(origin_circuit_t *circ, int reason)
#define MAX_NICKNAME_LEN
Definition: or.h:113
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
#define TO_CIRCUIT(x)
Definition: or.h:951
#define CIRCUIT_PURPOSE_C_REND_READY
Definition: circuitlist.h:84
Header file for config.c.
Header file for nickname.c.
void router_do_reachability_checks(int test_or, int test_dir)
Definition: selftest.c:172
int circuit_stream_is_being_handled(entry_connection_t *conn, uint16_t port, int min)
Definition: circuituse.c:1039
int fast_mem_is_zero(const char *mem, size_t len)
Definition: util_string.c:74
char * circuit_list_path_for_controller(origin_circuit_t *circ)
Definition: circuitbuild.c:347
Header file for microdesc.c.
#define CIRCUIT_PURPOSE_S_ESTABLISH_INTRO
Definition: circuitlist.h:102
Header file for onion.c.
void circuit_set_state(circuit_t *circ, uint8_t state)
Definition: circuitlist.c:540
const node_t * choose_good_entry_server(uint8_t purpose, cpath_build_state_t *state, circuit_guard_state_t **guard_state_out)
const char * channel_state_to_string(channel_state_t state)
Definition: channel.c:315
static int circuit_purpose_may_omit_guard(int purpose)
Definition: circuitbuild.c:908
int circuit_event_status(origin_circuit_t *circ, circuit_status_event_t tp, int reason_code)
Definition: circuitlist.c:496
int circuit_timeout_want_to_count_circ(const origin_circuit_t *circ)
Definition: circuitbuild.c:841
unsigned int num_n_circuits
Definition: channel.h:416
channel_usage_info_t channel_usage
Definition: channel.h:228
#define tor_free(p)
Definition: malloc.h:52
int channel_is_local(channel_t *chan)
Definition: channel.c:3025
#define tor_fragile_assert()
Definition: util_bug.h:241
int node_has_preferred_descriptor(const node_t *node, int for_direct_connect)
Definition: nodelist.c:1351
#define LOG_NOTICE
Definition: log.h:48
int smartlist_contains_int_as_string(const smartlist_t *sl, int num)
Definition: smartlist.c:147
Header file for mainloop.c.
#define CIRCUIT_PURPOSE_REND_ESTABLISHED
Definition: circuitlist.h:46
circuitmux_t * cmux
Definition: channel.h:403
int circuit_get_cpath_len(origin_circuit_t *circ)
Definition: circuitlist.c:2035
uint8_t purpose
Definition: circuit_st.h:100
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:3103
STATIC int onion_pick_cpath_exit(origin_circuit_t *circ, extend_info_t *exit_ei, int is_hs_v3_rp_circuit)
char rend_circ_nonce[DIGEST_LEN]
Definition: or_circuit_st.h:53
int extend_cell_parse(extend_cell_t *cell_out, const uint8_t command, const uint8_t *payload, size_t payload_length)
Definition: onion.c:378
int node_has_curve25519_onion_key(const node_t *node)
Definition: nodelist.c:1882
origin_circuit_t * circuit_establish_circuit(uint8_t purpose, extend_info_t *exit_ei, int flags)
Definition: circuitbuild.c:479
circuit_guard_state_t * origin_circuit_get_guard_state(origin_circuit_t *circ)
Definition: circuitbuild.c:508
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)
edge_connection_t * TO_EDGE_CONN(connection_t *c)
struct ed25519_public_key_t ed_pubkey
Definition: onion.h:57
#define END_CIRC_REASON_FLAG_REMOTE
Definition: or.h:328
static uint32_t get_uint32(const void *cp)
Definition: bytes.h:49
crypto_pk_t * onion_key
#define CIRCUIT_PURPOSE_C_HSDIR_GET
Definition: circuitlist.h:91
#define CIRCLAUNCH_IS_V3_RP
Definition: circuituse.h:49
extend_info_t * n_hop
Definition: circuit_st.h:76
int node_is_unreliable(const node_t *node, int need_uptime, int need_capacity, int need_guard)
Definition: nodelist.c:2205
void reset_all_main_loop_timers(void)
Definition: mainloop.c:1438
struct create_cell_t * n_chan_create_cell
Definition: circuit_st.h:142
int circuit_should_use_vanguards(uint8_t purpose)
Definition: circuituse.c:1997
static const node_t * choose_good_exit_server_general(router_crn_flags_t flags)
void control_event_bootstrap(bootstrap_status_t status, int progress)
#define MIN_CIRCUITS_HANDLING_STREAM
Definition: or.h:180
Header file for policies.c.
channel_t * p_chan
Definition: or_circuit_st.h:37
int ed25519_pubkey_eq(const ed25519_public_key_t *key1, const ed25519_public_key_t *key2)
#define LD_APP
Definition: log.h:76
int control_event_general_status(int severity, const char *format,...)
#define CIRCUIT_PURPOSE_CONTROLLER
Definition: circuitlist.h:119
void nodelist_add_node_and_family(smartlist_t *sl, const node_t *node)
Definition: nodelist.c:2109
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:882
const curve25519_public_key_t * node_get_curve25519_onion_key(const node_t *node)
Definition: nodelist.c:1889
Header file for channel.c.
int ExtendAllowPrivateAddresses
tor_assert(buffer)
void channel_timestamp_client(channel_t *chan)
Definition: channel.c:3219
routerset_t * ExitNodes
Definition: or_options_st.h:73
#define MAX_VERBOSE_NICKNAME_LEN
Definition: or.h:119
guard_usable_t entry_guard_succeeded(circuit_guard_state_t **guard_state_p)
Definition: entrynodes.c:2432
int node_get_purpose(const node_t *node)
Definition: nodelist.c:1372
#define LD_CIRC
Definition: log.h:80
uint8_t state
Definition: circuit_st.h:99
Header file for routermode.c.
int connection_ap_can_use_exit(const entry_connection_t *conn, const node_t *exit_node)
#define LD_GUARD
Definition: log.h:107
int tor_memeq(const void *a, const void *b, size_t sz)
Definition: di_ops.c:107
const node_t * guards_choose_guard(cpath_build_state_t *state, uint8_t purpose, circuit_guard_state_t **guard_state_out)
Definition: entrynodes.c:3620
static int circuit_build_no_more_hops(origin_circuit_t *circ)
const char * fmt_addrport(const tor_addr_t *addr, uint16_t port)
Definition: address.c:1169
void clear_broken_connection_map(int stop_recording)
routerset_t * ExcludeNodes
Definition: or_options_st.h:85
circid_t n_circ_id
Definition: circuit_st.h:67
static int circuit_deliver_create_cell(circuit_t *circ, const create_cell_t *create_cell, int relayed)
Definition: circuitbuild.c:711
time_t circuit_id_when_marked_unusable_on_channel(circid_t circ_id, channel_t *chan)
Definition: circuitlist.c:1553
Header file for circuitpadding.c.
char nickname[MAX_HEX_NICKNAME_LEN+1]
#define DIGEST_LEN
Definition: digest_sizes.h:20
#define CIRCUIT_PURPOSE_C_INTRODUCE_ACKED
Definition: circuitlist.h:80
#define CIRCUIT_PURPOSE_TESTING
Definition: circuitlist.h:117
const char * node_describe(const node_t *node)
Definition: describe.c:143
void smartlist_add_asprintf(struct smartlist_t *sl, const char *pattern,...)
Definition: smartlist.c:36
int ed25519_public_key_is_zero(const ed25519_public_key_t *pubkey)
char identity[DIGEST_LEN]
Definition: node_st.h:40
Header file for circuitbuild.c.
void ed25519_pubkey_copy(ed25519_public_key_t *dest, const ed25519_public_key_t *src)
static int circuit_cpath_supports_ntor(const origin_circuit_t *circ)
Definition: circuitbuild.c:366
Master header file for Tor-specific functionality.
#define CIRCUIT_STATE_OPEN
Definition: circuitlist.h:31
uint8_t reply[CELL_PAYLOAD_SIZE - 2]
Definition: onion.h:42
const char * hex_str(const char *from, size_t fromlen)
Definition: binascii.c:34
int extend_info_is_a_configured_bridge(const extend_info_t *ei)
Definition: bridges.c:264
Header file for circuitbuild.c.
void node_get_verbose_nickname(const node_t *node, char *verbose_name_out)
Definition: nodelist.c:1384
uint16_t marked_for_close
void circuit_mark_all_unused_circs(void)
Definition: circuitlist.c:2087
#define AP_CONN_STATE_CIRCUIT_WAIT
STATIC circid_t get_unique_circ_id_by_chan(channel_t *chan)
Definition: circuitbuild.c:127
Header file for onion_fast.c.
void cpath_free(crypt_path_t *victim)
Definition: crypt_path.c:162
uint8_t cell_type
Definition: onion.h:26
circid_t circ_id
Definition: cell_st.h:13
#define LOG_WARN
Definition: log.h:51
extend_info_t * extend_info_dup(extend_info_t *info)
int tor_addr_is_null(const tor_addr_t *addr)
Definition: address.c:770
unsigned int type
Definition: connection_st.h:45
const node_t * router_choose_random_node(smartlist_t *excludedsmartlist, routerset_t *excludedset, router_crn_flags_t flags)
Definition: node_select.c:903
static int middle_node_must_be_vanguard(const or_options_t *options, uint8_t purpose, int cur_len)
#define log_fn_ratelim(ratelim, severity, domain, args,...)
Definition: log.h:279
char nickname[MAX_NICKNAME_LEN+1]
char rend_circ_nonce[DIGEST_LEN]
Definition: crypt_path_st.h:53
Header file for circuituse.c.
void base16_encode(char *dest, size_t destlen, const char *src, size_t srclen)
Definition: binascii.c:478
int onionskin_answer(or_circuit_t *circ, const created_cell_t *created_cell, const char *keys, size_t keys_len, const uint8_t *rend_circ_nonce)
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)
static int should_use_create_fast_for_circuit(origin_circuit_t *circ)
Definition: circuitbuild.c:807
static channel_t * channel_connect_for_circuit(const tor_addr_t *addr, uint16_t port, const char *id_digest, const ed25519_public_key_t *ed_id)
Definition: circuitbuild.c:108
const node_t * build_state_get_exit_node(cpath_build_state_t *state)
#define CIRCUIT_PURPOSE_C_ESTABLISH_REND
Definition: circuitlist.h:82
static const node_t * choose_good_middle_server(uint8_t purpose, cpath_build_state_t *state, crypt_path_t *head, int cur_len)
static int ap_stream_wants_exit_attention(connection_t *conn)
circid_t p_circ_id
Definition: or_circuit_st.h:33
void circuit_remove_handled_ports(smartlist_t *needed_ports)
Definition: circuituse.c:1014
#define CIRCUIT_PURPOSE_S_CONNECT_REND
Definition: circuitlist.h:108
#define LD_REND
Definition: log.h:82
routerset_t * HSLayer2Nodes
Header file for circuitlist.c.
crypto_pk_t * crypto_pk_dup_key(crypto_pk_t *orig)
int control_event_client_status(int severity, const char *format,...)
void circuit_log_path(int severity, unsigned int domain, origin_circuit_t *circ)
Definition: circuitbuild.c:357
Headers for transports.c.
smartlist_t * rep_hist_get_predicted_ports(time_t now)
#define LD_OR
Definition: log.h:90
int channel_matches_extend_info(channel_t *chan, extend_info_t *extend_info)
Definition: channel.c:3313
int tor_digest_is_zero(const char *digest)
Definition: util_string.c:96
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
#define CIRCLAUNCH_NEED_CAPACITY
Definition: circuituse.h:43
int tor_addr_is_multicast(const tor_addr_t *a)
Definition: address.c:1530
uint8_t cell_type
Definition: onion.h:48
router_crn_flags_t
Definition: node_select.h:16
int connection_edge_is_rendezvous_stream(const edge_connection_t *conn)
int is_legal_nickname(const char *s)
Definition: nickname.c:19
#define HEX_DIGEST_LEN
Definition: crypto_digest.h:35
void smartlist_subtract(smartlist_t *sl1, const smartlist_t *sl2)
Definition: smartlist.c:264
#define CIRCUIT_PURPOSE_HS_VANGUARDS
Definition: circuitlist.h:129
#define END_CIRC_REASON_NOPATH
Definition: or.h:303
uint16_t length
Definition: or.h:642
uint8_t command
Definition: or.h:638
struct crypt_path_t * prev
Definition: crypt_path_st.h:70
cpath_build_state_t * build_state
Header file for connection_edge.c.
routerset_t * HSLayer3Nodes
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:504
routerset_t * ExcludeExitNodesUnion_
Definition: or_options_st.h:94
origin_circuit_t * TO_ORIGIN_CIRCUIT(circuit_t *x)
Definition: circuitlist.c:163
void circuit_has_opened(origin_circuit_t *circ)
Definition: circuituse.c:1685
Header file for crypt_path.c.
int tor_snprintf(char *str, size_t size, const char *format,...)
Definition: printf.c:27
char * smartlist_join_strings(smartlist_t *sl, const char *join, int terminate, size_t *len_out)
Definition: smartlist.c:279
int circuit_send_next_onion_skin(origin_circuit_t *circ)
Definition: circuitbuild.c:937
void circuit_mark_all_dirty_circs_as_unusable(void)
Definition: circuitlist.c:2106
#define CIRCUIT_PURPOSE_INTRO_POINT
Definition: circuitlist.h:41
Header file for relay.c.
edge_connection_t * p_streams
char identity_digest[DIGEST_LEN]
#define SMARTLIST_FOREACH(sl, type, var, cmd)
unsigned int has_opened
#define CIRCUIT_PURPOSE_S_HSDIR_POST
Definition: circuitlist.h:113
Header file for router.c.
void routerset_subtract_nodes(smartlist_t *lst, const routerset_t *routerset)
Definition: routerset.c:398
origin_circuit_t * origin_circuit_new(void)
Definition: circuitlist.c:1013
int created_cell_format(cell_t *cell_out, const created_cell_t *cell_in)
Definition: onion.c:546
static char * circuit_list_path_impl(origin_circuit_t *circ, int verbose, int verbose_names)
Definition: circuitbuild.c:264
#define CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT
Definition: circuitlist.h:77
int circuit_get_cpath_opened_len(const origin_circuit_t *circ)
Definition: circuitlist.c:2051
char * nickname
Definition: routerinfo_st.h:17
#define CIRCUIT_PURPOSE_C_REND_JOINED
Definition: circuitlist.h:89
uint8_t state
Definition: crypt_path_st.h:63
onion_handshake_state_t handshake_state
Definition: crypt_path_st.h:47
uint16_t handshake_type
Definition: onion.h:28
uint32_t circid_t
Definition: or.h:608
#define CIRCUIT_PURPOSE_OR
Definition: circuitlist.h:38
uint16_t dir_port
Definition: routerinfo_st.h:21
struct timeval timestamp_began
Definition: circuit_st.h:154
#define log_fn(severity, domain, args,...)
Definition: log.h:274
#define CIRCUIT_STATE_GUARD_WAIT
Definition: circuitlist.h:29
ratelim_t last_warned_circ_ids_exhausted
Definition: channel.h:444
static void circuit_pick_create_handshake(uint8_t *cell_type_out, uint16_t *handshake_type_out, const extend_info_t *ei)
Definition: circuitbuild.c:856
#define CIRCUIT_STATE_BUILDING
Definition: circuitlist.h:20
uint8_t node_id[DIGEST_LEN]
Definition: onion.h:55
int router_digest_is_me(const char *digest)
Definition: router.c:1592
or_circuit_t * TO_OR_CIRCUIT(circuit_t *x)
Definition: circuitlist.c:151
unsigned int circuitmux_num_circuits(circuitmux_t *cmux)
Definition: circuitmux.c:763
const node_t * node_sl_choose_by_bandwidth(const smartlist_t *sl, bandwidth_weight_rule_t rule)
Definition: node_select.c:803
static int node_handles_some_port(const node_t *node, smartlist_t *needed_ports)
void circpad_machine_event_circ_built(origin_circuit_t *circ)
void circuit_reset_failure_count(int timeout)
Definition: circuituse.c:2194
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:2316
char * circuit_list_path(origin_circuit_t *circ, int verbose)
Definition: circuitbuild.c:338
#define CIRCUIT_PURPOSE_C_GENERAL
Definition: circuitlist.h:71
static const node_t * choose_good_exit_server(origin_circuit_t *circ, router_crn_flags_t flags, int is_internal)
time_t approx_time(void)
Definition: approx_time.c:32
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:1100
int node_exit_policy_rejects_all(const node_t *node)
Definition: nodelist.c:1430
routerset_t * MiddleNodes
Definition: or_options_st.h:76
extend_info_t * extend_info
Definition: crypt_path_st.h:56
#define CIRCUIT_STATE_CHAN_WAIT
Definition: circuitlist.h:25
uint32_t addr
Definition: routerinfo_st.h:19
void circuit_set_n_circid_chan(circuit_t *circ, circid_t id, channel_t *chan)
Definition: circuitlist.c:471
#define TIMEOUT_UNTIL_UNREACHABILITY_COMPLAINT
Definition: or.h:549
void command_setup_channel(channel_t *chan)
Definition: command.c:683
tor_addr_port_t orport_ipv4
Definition: onion.h:50
Header file for selftest.c.
int pathbias_count_build_attempt(origin_circuit_t *circ)
Definition: circpathbias.c:424
Header file for ocirc_event.c.
void circuit_build_times_handle_completed_hop(origin_circuit_t *circ)
Definition: circuitstats.c:683
Header file for connection_or.c.
int control_event_server_status(int severity, const char *format,...)
int circuit_append_new_exit(origin_circuit_t *circ, extend_info_t *exit_ei)
void routerset_get_all_nodes(smartlist_t *out, const routerset_t *routerset, const routerset_t *excludeset, int running_only)
Definition: routerset.c:364
extend_info_t * chosen_exit
unsigned int circuitmux_num_active_circuits(circuitmux_t *cmux)
Definition: circuitmux.c:751
static smartlist_t * build_vanguard_middle_exclude_list(uint8_t purpose, cpath_build_state_t *state, crypt_path_t *head, int cur_len)
char identity_digest[DIGEST_LEN]
Definition: channel.h:384
uint16_t handshake_len
Definition: onion.h:40
relay_crypto_t crypto
Definition: or_circuit_st.h:46
struct edge_connection_t * next_stream
tor_addr_t addr
void tor_addr_copy(tor_addr_t *dest, const tor_addr_t *src)
Definition: address.c:904
void onion_handshake_state_release(onion_handshake_state_t *state)
Definition: onion_crypto.c:79
void extend_info_free_(extend_info_t *info)
STATIC int onion_extend_cpath(origin_circuit_t *circ)
#define CIRCUIT_PURPOSE_S_REND_JOINED
Definition: circuitlist.h:111
#define CONN_TYPE_AP
Definition: connection.h:31
Header file for control_events.c.
ed25519_public_key_t ed_identity
void smartlist_clear(smartlist_t *sl)
#define LD_PROTOCOL
Definition: log.h:70
static int onion_populate_cpath(origin_circuit_t *circ)
Definition: circuitbuild.c:390
smartlist_t * circuit_find_circuits_to_upgrade_from_guard_wait(void)
Definition: circuitlist.c:2007
void router_orport_found_reachable(void)
Definition: selftest.c:220
const char * build_state_get_exit_nickname(cpath_build_state_t *state)
static int circuit_send_intermediate_onion_skin(origin_circuit_t *circ, crypt_path_t *hop)
#define RELAY_HEADER_SIZE
Definition: or.h:603
int check_whether_orport_reachable(const or_options_t *options)
Definition: selftest.c:75
int extend_info_addr_is_allowed(const tor_addr_t *addr)
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
Header file for networkstatus.c.
#define LD_BUG
Definition: log.h:84
void circuit_upgrade_circuits_from_guard_wait(void)
int cpath_append_hop(crypt_path_t **head_ptr, extend_info_t *choice)
Definition: crypt_path.c:61
int circuit_extend_to_new_exit(origin_circuit_t *circ, extend_info_t *exit_ei)
#define CURVE25519_PUBKEY_LEN
Definition: x25519_sizes.h:20
int inform_testing_reachability(void)
Definition: circuitbuild.c:774
MOCK_IMPL(int, circuit_all_predicted_ports_handled,(time_t now, int *need_uptime, int *need_capacity))
Header file for routerlist.c.
const uint8_t * build_state_get_exit_rsa_id(cpath_build_state_t *state)
uint16_t or_port
Definition: routerinfo_st.h:20
channel_t * n_chan
Definition: circuit_st.h:58
static int circuit_send_first_onion_skin(origin_circuit_t *circ)
Definition: circuitbuild.c:971
static sa_family_t tor_addr_family(const tor_addr_t *a)
Definition: address.h:179
void * smartlist_choose(const smartlist_t *sl)
Definition: crypto_rand.c:590
create_cell_t create_cell
Definition: onion.h:61
Header for confparse.c.
void circuit_note_clock_jumped(int64_t seconds_elapsed, bool was_idle)
int have_completed_a_circuit(void)
Definition: mainloop.c:218
tor_addr_port_t orport_ipv6
Definition: onion.h:53
uint64_t global_identifier
Definition: channel.h:197
Header file for onion_crypto.c.
char * tor_dup_ip(uint32_t addr)
Definition: address.c:1948