Tor  0.4.3.0-alpha-dev
entrynodes.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 
7 /**
8  * \file entrynodes.c
9  * \brief Code to manage our fixed first nodes for various functions.
10  *
11  * Entry nodes can be guards (for general use) or bridges (for censorship
12  * circumvention).
13  *
14  * In general, we use entry guards to prevent traffic-sampling attacks:
15  * if we chose every circuit independently, an adversary controlling
16  * some fraction of paths on the network would observe a sample of every
17  * user's traffic. Using guards gives users a chance of not being
18  * profiled.
19  *
20  * The current entry guard selection code is designed to try to avoid
21  * _ever_ trying every guard on the network, to try to stick to guards
22  * that we've used before, to handle hostile/broken networks, and
23  * to behave sanely when the network goes up and down.
24  *
25  * Our algorithm works as follows: First, we maintain a SAMPLE of guards
26  * we've seen in the networkstatus consensus. We maintain this sample
27  * over time, and store it persistently; it is chosen without reference
28  * to our configuration or firewall rules. Guards remain in the sample
29  * as they enter and leave the consensus. We expand this sample as
30  * needed, up to a maximum size.
31  *
32  * As a subset of the sample, we maintain a FILTERED SET of the guards
33  * that we would be willing to use if we could connect to them. The
34  * filter removes all the guards that we're excluding because they're
35  * bridges (or not bridges), because we have restrictive firewall rules,
36  * because of ExcludeNodes, because we of path bias restrictions,
37  * because they're absent from the network at present, and so on.
38  *
39  * As a subset of the filtered set, we keep a REACHABLE FILTERED SET
40  * (also called a "usable filtered set") of those guards that we call
41  * "reachable" or "maybe reachable". A guard is reachable if we've
42  * connected to it more recently than we've failed. A guard is "maybe
43  * reachable" if we have never tried to connect to it, or if we
44  * failed to connect to it so long ago that we no longer think our
45  * failure means it's down.
46  *
47  * As a persistent ordered list whose elements are taken from the
48  * sampled set, we track a CONFIRMED GUARDS LIST. A guard becomes
49  * confirmed when we successfully build a circuit through it, and decide
50  * to use that circuit. We order the guards on this list by the order
51  * in which they became confirmed.
52  *
53  * And as a final group, we have an ordered list of PRIMARY GUARDS,
54  * whose elements are taken from the filtered set. We prefer
55  * confirmed guards to non-confirmed guards for this list, and place
56  * other restrictions on it. The primary guards are the ones that we
57  * connect to "when nothing is wrong" -- circuits through them can be used
58  * immediately.
59  *
60  * To build circuits, we take a primary guard if possible -- or a
61  * reachable filtered confirmed guard if no primary guard is possible --
62  * or a random reachable filtered guard otherwise. If the guard is
63  * primary, we can use the circuit immediately on success. Otherwise,
64  * the guard is now "pending" -- we won't use its circuit unless all
65  * of the circuits we're trying to build through better guards have
66  * definitely failed.
67  *
68  * While we're building circuits, we track a little "guard state" for
69  * each circuit. We use this to keep track of whether the circuit is
70  * one that we can use as soon as it's done, or whether it's one that
71  * we should keep around to see if we can do better. In the latter case,
72  * a periodic call to entry_guards_upgrade_waiting_circuits() will
73  * eventually upgrade it.
74  **/
75 /* DOCDOC -- expand this.
76  *
77  * Information invariants:
78  *
79  * [x] whenever a guard becomes unreachable, clear its usable_filtered flag.
80  *
81  * [x] Whenever a guard becomes reachable or maybe-reachable, if its filtered
82  * flag is set, set its usable_filtered flag.
83  *
84  * [x] Whenever we get a new consensus, call update_from_consensus(). (LATER.)
85  *
86  * [x] Whenever the configuration changes in a relevant way, update the
87  * filtered/usable flags. (LATER.)
88  *
89  * [x] Whenever we add a guard to the sample, make sure its filtered/usable
90  * flags are set as possible.
91  *
92  * [x] Whenever we remove a guard from the sample, remove it from the primary
93  * and confirmed lists.
94  *
95  * [x] When we make a guard confirmed, update the primary list.
96  *
97  * [x] When we make a guard filtered or unfiltered, update the primary list.
98  *
99  * [x] When we are about to pick a guard, make sure that the primary list is
100  * full.
101  *
102  * [x] Before calling sample_reachable_filtered_entry_guards(), make sure
103  * that the filtered, primary, and confirmed flags are up-to-date.
104  *
105  * [x] Call entry_guard_consider_retry every time we are about to check
106  * is_usable_filtered or is_reachable, and every time we set
107  * is_filtered to 1.
108  *
109  * [x] Call entry_guards_changed_for_guard_selection() whenever we update
110  * a persistent field.
111  */
112 
113 #define ENTRYNODES_PRIVATE
114 
115 #include "core/or/or.h"
116 #include "app/config/config.h"
117 #include "lib/confmgt/confmgt.h"
118 #include "app/config/statefile.h"
120 #include "core/mainloop/mainloop.h"
121 #include "core/or/channel.h"
122 #include "core/or/circuitbuild.h"
123 #include "core/or/circuitlist.h"
124 #include "core/or/circuitstats.h"
125 #include "core/or/circuituse.h"
126 #include "core/or/policies.h"
127 #include "feature/client/bridges.h"
128 #include "feature/client/circpathbias.h"
140 #include "feature/relay/router.h"
142 #include "lib/crypt_ops/digestset.h"
143 #include "lib/encoding/confline.h"
144 #include "lib/math/fp.h"
145 
148 #include "app/config/or_state_st.h"
149 
150 /** A list of existing guard selection contexts. */
152 /** The currently enabled guard selection context. */
153 static guard_selection_t *curr_guard_context = NULL;
154 
155 /** A value of 1 means that at least one context has changed,
156  * and those changes need to be flushed to disk. */
157 static int entry_guards_dirty = 0;
158 
159 static void entry_guard_set_filtered_flags(const or_options_t *options,
160  guard_selection_t *gs,
161  entry_guard_t *guard);
162 static void pathbias_check_use_success_count(entry_guard_t *guard);
163 static void pathbias_check_close_success_count(entry_guard_t *guard);
164 static int node_is_possible_guard(const node_t *node);
165 static int node_passes_guard_filter(const or_options_t *options,
166  const node_t *node);
167 static entry_guard_t *entry_guard_add_to_sample_impl(guard_selection_t *gs,
168  const uint8_t *rsa_id_digest,
169  const char *nickname,
170  const tor_addr_port_t *bridge_addrport);
171 static entry_guard_t *get_sampled_guard_by_bridge_addr(guard_selection_t *gs,
172  const tor_addr_port_t *addrport);
173 static int entry_guard_obeys_restriction(const entry_guard_t *guard,
174  const entry_guard_restriction_t *rst);
175 
176 /** Return 0 if we should apply guardfraction information found in the
177  * consensus. A specific consensus can be specified with the
178  * <b>ns</b> argument, if NULL the most recent one will be picked.*/
179 int
181 {
182  /* We need to check the corresponding torrc option and the consensus
183  * parameter if we need to. */
184  const or_options_t *options = get_options();
185 
186  /* If UseGuardFraction is 'auto' then check the same-named consensus
187  * parameter. If the consensus parameter is not present, default to
188  * "off". */
189  if (options->UseGuardFraction == -1) {
190  return networkstatus_get_param(ns, "UseGuardFraction",
191  0, /* default to "off" */
192  0, 1);
193  }
194 
195  return options->UseGuardFraction;
196 }
197 
198 /** Return true iff we know a preferred descriptor for <b>guard</b> */
199 static int
200 guard_has_descriptor(const entry_guard_t *guard)
201 {
202  const node_t *node = node_get_by_id(guard->identity);
203  if (!node)
204  return 0;
205  return node_has_preferred_descriptor(node, 1);
206 }
207 
208 /**
209  * Try to determine the correct type for a selection named "name",
210  * if <b>type</b> is GS_TYPE_INFER.
211  */
212 STATIC guard_selection_type_t
213 guard_selection_infer_type(guard_selection_type_t type,
214  const char *name)
215 {
216  if (type == GS_TYPE_INFER) {
217  if (!strcmp(name, "bridges"))
218  type = GS_TYPE_BRIDGE;
219  else if (!strcmp(name, "restricted"))
220  type = GS_TYPE_RESTRICTED;
221  else
222  type = GS_TYPE_NORMAL;
223  }
224  return type;
225 }
226 
227 /**
228  * Allocate and return a new guard_selection_t, with the name <b>name</b>.
229  */
230 STATIC guard_selection_t *
232  guard_selection_type_t type)
233 {
234  guard_selection_t *gs;
235 
236  type = guard_selection_infer_type(type, name);
237 
238  gs = tor_malloc_zero(sizeof(*gs));
239  gs->name = tor_strdup(name);
240  gs->type = type;
241  gs->sampled_entry_guards = smartlist_new();
242  gs->confirmed_entry_guards = smartlist_new();
243  gs->primary_entry_guards = smartlist_new();
244 
245  return gs;
246 }
247 
248 /**
249  * Return the guard selection called <b>name</b>. If there is none, and
250  * <b>create_if_absent</b> is true, then create and return it. If there
251  * is none, and <b>create_if_absent</b> is false, then return NULL.
252  */
253 STATIC guard_selection_t *
255  guard_selection_type_t type,
256  int create_if_absent)
257 {
258  if (!guard_contexts) {
260  }
261  SMARTLIST_FOREACH_BEGIN(guard_contexts, guard_selection_t *, gs) {
262  if (!strcmp(gs->name, name))
263  return gs;
264  } SMARTLIST_FOREACH_END(gs);
265 
266  if (! create_if_absent)
267  return NULL;
268 
269  log_debug(LD_GUARD, "Creating a guard selection called %s", name);
270  guard_selection_t *new_selection = guard_selection_new(name, type);
271  smartlist_add(guard_contexts, new_selection);
272 
273  return new_selection;
274 }
275 
276 /**
277  * Allocate the first guard context that we're planning to use,
278  * and make it the current context.
279  */
280 static void
282 {
284  if (!guard_contexts) {
286  }
287  guard_selection_type_t type = GS_TYPE_INFER;
288  const char *name = choose_guard_selection(
289  get_options(),
291  approx_time(),
293  NULL,
294  &type);
295  tor_assert(name); // "name" can only be NULL if we had an old name.
296  tor_assert(type != GS_TYPE_INFER);
297  log_notice(LD_GUARD, "Starting with guard context \"%s\"", name);
299 }
300 
301 /** Get current default guard_selection_t, creating it if necessary */
302 guard_selection_t *
304 {
305  if (!curr_guard_context) {
307  }
308 
309  return curr_guard_context;
310 }
311 
312 /** Return a statically allocated human-readable description of <b>guard</b>
313  */
314 const char *
315 entry_guard_describe(const entry_guard_t *guard)
316 {
317  static char buf[256];
318  tor_snprintf(buf, sizeof(buf),
319  "%s ($%s)",
320  strlen(guard->nickname) ? guard->nickname : "[bridge]",
321  hex_str(guard->identity, DIGEST_LEN));
322  return buf;
323 }
324 
325 /** Return <b>guard</b>'s 20-byte RSA identity digest */
326 const char *
327 entry_guard_get_rsa_id_digest(const entry_guard_t *guard)
328 {
329  return guard->identity;
330 }
331 
332 /** Return the pathbias state associated with <b>guard</b>. */
334 entry_guard_get_pathbias_state(entry_guard_t *guard)
335 {
336  return &guard->pb;
337 }
338 
339 HANDLE_IMPL(entry_guard, entry_guard_t, ATTR_UNUSED STATIC)
340 
341 /** Return an interval betweeen 'now' and 'max_backdate' seconds in the past,
342  * chosen uniformly at random. We use this before recording persistent
343  * dates, so that we aren't leaking exactly when we recorded it.
344  */
345 MOCK_IMPL(STATIC time_t,
346 randomize_time,(time_t now, time_t max_backdate))
347 {
348  tor_assert(max_backdate > 0);
349 
350  time_t earliest = now - max_backdate;
351  time_t latest = now;
352  if (earliest <= 0)
353  earliest = 1;
354  if (latest <= earliest)
355  latest = earliest + 1;
356 
357  return crypto_rand_time_range(earliest, latest);
358 }
359 
360 /**
361  * @name parameters for networkstatus algorithm
362  *
363  * These parameters are taken from the consensus; some are overrideable in
364  * the torrc.
365  */
366 /**@{*/
367 /**
368  * We never let our sampled guard set grow larger than this fraction
369  * of the guards on the network.
370  */
371 STATIC double
373 {
374  int32_t pct =
375  networkstatus_get_param(NULL, "guard-max-sample-threshold-percent",
376  DFLT_MAX_SAMPLE_THRESHOLD_PERCENT,
377  1, 100);
378  return pct / 100.0;
379 }
380 /**
381  * We never let our sampled guard set grow larger than this number.
382  */
383 STATIC int
385 {
386  return (int) networkstatus_get_param(NULL, "guard-max-sample-size",
387  DFLT_MAX_SAMPLE_SIZE,
388  1, INT32_MAX);
389 }
390 /**
391  * We always try to make our sample contain at least this many guards.
392  */
393 STATIC int
395 {
396  return networkstatus_get_param(NULL, "guard-min-filtered-sample-size",
397  DFLT_MIN_FILTERED_SAMPLE_SIZE,
398  1, INT32_MAX);
399 }
400 /**
401  * If a guard is unlisted for this many days in a row, we remove it.
402  */
403 STATIC int
405 {
406  return networkstatus_get_param(NULL,
407  "guard-remove-unlisted-guards-after-days",
408  DFLT_REMOVE_UNLISTED_GUARDS_AFTER_DAYS,
409  1, 365*10);
410 }
411 
412 /**
413  * Return number of seconds that will make a guard no longer eligible
414  * for selection if unlisted for this long.
415  */
416 static time_t
418 {
419  return get_remove_unlisted_guards_after_days() * 24 * 60 * 60;
420 }
421 
422 /**
423  * We remove unconfirmed guards from the sample after this many days,
424  * regardless of whether they are listed or unlisted.
425  */
426 STATIC int
428 {
429  if (get_options()->GuardLifetime >= 86400)
430  return get_options()->GuardLifetime;
431  int32_t days;
432  days = networkstatus_get_param(NULL,
433  "guard-lifetime-days",
434  DFLT_GUARD_LIFETIME_DAYS, 1, 365*10);
435  return days * 86400;
436 }
437 /**
438  * We remove confirmed guards from the sample if they were sampled
439  * GUARD_LIFETIME_DAYS ago and confirmed this many days ago.
440  */
441 STATIC int
443 {
444  if (get_options()->GuardLifetime >= 86400)
445  return get_options()->GuardLifetime;
446  int32_t days;
447  days = networkstatus_get_param(NULL, "guard-confirmed-min-lifetime-days",
448  DFLT_GUARD_CONFIRMED_MIN_LIFETIME_DAYS,
449  1, 365*10);
450  return days * 86400;
451 }
452 /**
453  * How many guards do we try to keep on our primary guard list?
454  */
455 STATIC int
457 {
458  /* If the user has explicitly configured the number of primary guards, do
459  * what the user wishes to do */
460  const int configured_primaries = get_options()->NumPrimaryGuards;
461  if (configured_primaries) {
462  return configured_primaries;
463  }
464 
465  /* otherwise check for consensus parameter and if that's not set either, just
466  * use the default value. */
467  return networkstatus_get_param(NULL,
468  "guard-n-primary-guards",
469  DFLT_N_PRIMARY_GUARDS, 1, INT32_MAX);
470 }
471 /**
472  * Return the number of the live primary guards we should look at when
473  * making a circuit.
474  */
475 STATIC int
477 {
478  int configured;
479  const char *param_name;
480  int param_default;
481 
482  /* If the user has explicitly configured the amount of guards, use
483  that. Otherwise, fall back to the default value. */
484  if (usage == GUARD_USAGE_DIRGUARD) {
485  configured = get_options()->NumDirectoryGuards;
486  param_name = "guard-n-primary-dir-guards-to-use";
487  param_default = DFLT_N_PRIMARY_DIR_GUARDS_TO_USE;
488  } else {
489  configured = get_options()->NumEntryGuards;
490  param_name = "guard-n-primary-guards-to-use";
491  param_default = DFLT_N_PRIMARY_GUARDS_TO_USE;
492  }
493  if (configured >= 1) {
494  return configured;
495  }
496  return networkstatus_get_param(NULL,
497  param_name, param_default, 1, INT32_MAX);
498 }
499 /**
500  * If we haven't successfully built or used a circuit in this long, then
501  * consider that the internet is probably down.
502  */
503 STATIC int
505 {
506  return networkstatus_get_param(NULL, "guard-internet-likely-down-interval",
507  DFLT_INTERNET_LIKELY_DOWN_INTERVAL,
508  1, INT32_MAX);
509 }
510 /**
511  * If we're trying to connect to a nonprimary guard for at least this
512  * many seconds, and we haven't gotten the connection to work, we will treat
513  * lower-priority guards as usable.
514  */
515 STATIC int
517 {
518  return networkstatus_get_param(NULL,
519  "guard-nonprimary-guard-connect-timeout",
520  DFLT_NONPRIMARY_GUARD_CONNECT_TIMEOUT,
521  1, INT32_MAX);
522 }
523 /**
524  * If a circuit has been sitting around in 'waiting for better guard' state
525  * for at least this long, we'll expire it.
526  */
527 STATIC int
529 {
530  return networkstatus_get_param(NULL,
531  "guard-nonprimary-guard-idle-timeout",
532  DFLT_NONPRIMARY_GUARD_IDLE_TIMEOUT,
533  1, INT32_MAX);
534 }
535 /**
536  * If our configuration retains fewer than this fraction of guards from the
537  * torrc, we are in a restricted setting.
538  */
539 STATIC double
541 {
542  int32_t pct = networkstatus_get_param(NULL,
543  "guard-meaningful-restriction-percent",
544  DFLT_MEANINGFUL_RESTRICTION_PERCENT,
545  1, INT32_MAX);
546  return pct / 100.0;
547 }
548 /**
549  * If our configuration retains fewer than this fraction of guards from the
550  * torrc, we are in an extremely restricted setting, and should warn.
551  */
552 STATIC double
554 {
555  int32_t pct = networkstatus_get_param(NULL,
556  "guard-extreme-restriction-percent",
557  DFLT_EXTREME_RESTRICTION_PERCENT,
558  1, INT32_MAX);
559  return pct / 100.0;
560 }
561 
562 /* Mark <b>guard</b> as maybe reachable again. */
563 static void
564 mark_guard_maybe_reachable(entry_guard_t *guard)
565 {
566  if (guard->is_reachable != GUARD_REACHABLE_NO) {
567  return;
568  }
569 
570  /* Note that we do not clear failing_since: this guard is now only
571  * _maybe-reachable_. */
572  guard->is_reachable = GUARD_REACHABLE_MAYBE;
573  if (guard->is_filtered_guard)
574  guard->is_usable_filtered_guard = 1;
575 }
576 
577 /**
578  * Called when the network comes up after having seemed to be down for
579  * a while: Mark the primary guards as maybe-reachable so that we'll
580  * try them again.
581  */
582 STATIC void
584 {
585  tor_assert(gs);
586 
587  if (!gs->primary_guards_up_to_date)
589 
590  SMARTLIST_FOREACH_BEGIN(gs->primary_entry_guards, entry_guard_t *, guard) {
591  mark_guard_maybe_reachable(guard);
592  } SMARTLIST_FOREACH_END(guard);
593 }
594 
595 /* Called when we exhaust all guards in our sampled set: Marks all guards as
596  maybe-reachable so that we 'll try them again. */
597 static void
598 mark_all_guards_maybe_reachable(guard_selection_t *gs)
599 {
600  tor_assert(gs);
601 
602  SMARTLIST_FOREACH_BEGIN(gs->sampled_entry_guards, entry_guard_t *, guard) {
603  mark_guard_maybe_reachable(guard);
604  } SMARTLIST_FOREACH_END(guard);
605 }
606 
607 /**@}*/
608 
609 /**
610  * Given our options and our list of nodes, return the name of the
611  * guard selection that we should use. Return NULL for "use the
612  * same selection you were using before.
613  */
614 STATIC const char *
616  const networkstatus_t *live_ns,
617  const guard_selection_t *old_selection,
618  guard_selection_type_t *type_out)
619 {
620  tor_assert(options);
621  tor_assert(type_out);
622 
623  if (options->UseBridges) {
624  *type_out = GS_TYPE_BRIDGE;
625  return "bridges";
626  }
627 
628  if (! live_ns) {
629  /* without a networkstatus, we can't tell any more than that. */
630  *type_out = GS_TYPE_NORMAL;
631  return "default";
632  }
633 
634  const smartlist_t *nodes = nodelist_get_list();
635  int n_guards = 0, n_passing_filter = 0;
636  SMARTLIST_FOREACH_BEGIN(nodes, const node_t *, node) {
637  if (node_is_possible_guard(node)) {
638  ++n_guards;
639  if (node_passes_guard_filter(options, node)) {
640  ++n_passing_filter;
641  }
642  }
643  } SMARTLIST_FOREACH_END(node);
644 
645  /* We use separate 'high' and 'low' thresholds here to prevent flapping
646  * back and forth */
647  const int meaningful_threshold_high =
648  (int)(n_guards * get_meaningful_restriction_threshold() * 1.05);
649  const int meaningful_threshold_mid =
650  (int)(n_guards * get_meaningful_restriction_threshold());
651  const int meaningful_threshold_low =
652  (int)(n_guards * get_meaningful_restriction_threshold() * .95);
653  const int extreme_threshold =
654  (int)(n_guards * get_extreme_restriction_threshold());
655 
656  /*
657  If we have no previous selection, then we're "restricted" iff we are
658  below the meaningful restriction threshold. That's easy enough.
659 
660  But if we _do_ have a previous selection, we make it a little
661  "sticky": we only move from "restricted" to "default" when we find
662  that we're above the threshold plus 5%, and we only move from
663  "default" to "restricted" when we're below the threshold minus 5%.
664  That should prevent us from flapping back and forth if we happen to
665  be hovering very close to the default.
666 
667  The extreme threshold is for warning only.
668  */
669 
670  static int have_warned_extreme_threshold = 0;
671  if (n_guards &&
672  n_passing_filter < extreme_threshold &&
673  ! have_warned_extreme_threshold) {
674  have_warned_extreme_threshold = 1;
675  const double exclude_frac =
676  (n_guards - n_passing_filter) / (double)n_guards;
677  log_warn(LD_GUARD, "Your configuration excludes %d%% of all possible "
678  "guards. That's likely to make you stand out from the "
679  "rest of the world.", (int)(exclude_frac * 100));
680  }
681 
682  /* Easy case: no previous selection. Just check if we are in restricted or
683  normal guard selection. */
684  if (old_selection == NULL) {
685  if (n_passing_filter >= meaningful_threshold_mid) {
686  *type_out = GS_TYPE_NORMAL;
687  return "default";
688  } else {
689  *type_out = GS_TYPE_RESTRICTED;
690  return "restricted";
691  }
692  }
693 
694  /* Trickier case: we do have a previous guard selection context. */
695  tor_assert(old_selection);
696 
697  /* Use high and low thresholds to decide guard selection, and if we fall in
698  the middle then keep the current guard selection context. */
699  if (n_passing_filter >= meaningful_threshold_high) {
700  *type_out = GS_TYPE_NORMAL;
701  return "default";
702  } else if (n_passing_filter < meaningful_threshold_low) {
703  *type_out = GS_TYPE_RESTRICTED;
704  return "restricted";
705  } else {
706  /* we are in the middle: maintain previous guard selection */
707  *type_out = old_selection->type;
708  return old_selection->name;
709  }
710 }
711 
712 /**
713  * Check whether we should switch from our current guard selection to a
714  * different one. If so, switch and return 1. Return 0 otherwise.
715  *
716  * On a 1 return, the caller should mark all currently live circuits unusable
717  * for new streams, by calling circuit_mark_all_unused_circs() and
718  * circuit_mark_all_dirty_circs_as_unusable().
719  */
720 int
722 {
723  if (!curr_guard_context) {
725  return 1;
726  }
727 
728  guard_selection_type_t type = GS_TYPE_INFER;
729  const char *new_name = choose_guard_selection(
730  options,
732  approx_time(),
735  &type);
736  tor_assert(new_name);
737  tor_assert(type != GS_TYPE_INFER);
738 
739  const char *cur_name = curr_guard_context->name;
740  if (! strcmp(cur_name, new_name)) {
741  log_debug(LD_GUARD,
742  "Staying with guard context \"%s\" (no change)", new_name);
743  return 0; // No change
744  }
745 
746  log_notice(LD_GUARD, "Switching to guard context \"%s\" (was using \"%s\")",
747  new_name, cur_name);
748  guard_selection_t *new_guard_context;
749  new_guard_context = get_guard_selection_by_name(new_name, type, 1);
750  tor_assert(new_guard_context);
751  tor_assert(new_guard_context != curr_guard_context);
752  curr_guard_context = new_guard_context;
753 
754  return 1;
755 }
756 
757 /**
758  * Return true iff <b>node</b> has all the flags needed for us to consider it
759  * a possible guard when sampling guards.
760  */
761 static int
763 {
764  /* The "GUARDS" set is all nodes in the nodelist for which this predicate
765  * holds. */
766 
767  tor_assert(node);
768  return (node->is_possible_guard &&
769  node->is_stable &&
770  node->is_fast &&
771  node->is_valid &&
772  node_is_dir(node) &&
773  !router_digest_is_me(node->identity));
774 }
775 
776 /**
777  * Return the sampled guard with the RSA identity digest <b>rsa_id</b>, or
778  * NULL if we don't have one. */
779 STATIC entry_guard_t *
780 get_sampled_guard_with_id(guard_selection_t *gs,
781  const uint8_t *rsa_id)
782 {
783  tor_assert(gs);
784  tor_assert(rsa_id);
785  SMARTLIST_FOREACH_BEGIN(gs->sampled_entry_guards, entry_guard_t *, guard) {
786  if (tor_memeq(guard->identity, rsa_id, DIGEST_LEN))
787  return guard;
788  } SMARTLIST_FOREACH_END(guard);
789  return NULL;
790 }
791 
792 /** If <b>gs</b> contains a sampled entry guard matching <b>bridge</b>,
793  * return that guard. Otherwise return NULL. */
794 static entry_guard_t *
795 get_sampled_guard_for_bridge(guard_selection_t *gs,
796  const bridge_info_t *bridge)
797 {
798  const uint8_t *id = bridge_get_rsa_id_digest(bridge);
799  const tor_addr_port_t *addrport = bridge_get_addr_port(bridge);
800  entry_guard_t *guard;
801  if (BUG(!addrport))
802  return NULL; // LCOV_EXCL_LINE
803  guard = get_sampled_guard_by_bridge_addr(gs, addrport);
804  if (! guard || (id && tor_memneq(id, guard->identity, DIGEST_LEN)))
805  return NULL;
806  else
807  return guard;
808 }
809 
810 /** If we know a bridge_info_t matching <b>guard</b>, return that
811  * bridge. Otherwise return NULL. */
812 static bridge_info_t *
813 get_bridge_info_for_guard(const entry_guard_t *guard)
814 {
815  const uint8_t *identity = NULL;
816  if (! tor_digest_is_zero(guard->identity)) {
817  identity = (const uint8_t *)guard->identity;
818  }
819  if (BUG(guard->bridge_addr == NULL))
820  return NULL;
821 
823  &guard->bridge_addr->addr,
824  guard->bridge_addr->port,
825  (const char*)identity);
826 }
827 
828 /**
829  * Return true iff we have a sampled guard with the RSA identity digest
830  * <b>rsa_id</b>. */
831 static inline int
832 have_sampled_guard_with_id(guard_selection_t *gs, const uint8_t *rsa_id)
833 {
834  return get_sampled_guard_with_id(gs, rsa_id) != NULL;
835 }
836 
837 /**
838  * Allocate a new entry_guard_t object for <b>node</b>, add it to the
839  * sampled entry guards in <b>gs</b>, and return it. <b>node</b> must
840  * not currently be a sampled guard in <b>gs</b>.
841  */
842 STATIC entry_guard_t *
843 entry_guard_add_to_sample(guard_selection_t *gs,
844  const node_t *node)
845 {
846  log_info(LD_GUARD, "Adding %s to the entry guard sample set.",
847  node_describe(node));
848 
849  /* make sure that the guard is not already sampled. */
850  if (BUG(have_sampled_guard_with_id(gs, (const uint8_t*)node->identity)))
851  return NULL; // LCOV_EXCL_LINE
852 
854  (const uint8_t*)node->identity,
855  node_get_nickname(node),
856  NULL);
857 }
858 
859 /**
860  * Backend: adds a new sampled guard to <b>gs</b>, with given identity,
861  * nickname, and ORPort. rsa_id_digest and bridge_addrport are optional, but
862  * we need one of them. nickname is optional. The caller is responsible for
863  * maintaining the size limit of the SAMPLED_GUARDS set.
864  */
865 static entry_guard_t *
866 entry_guard_add_to_sample_impl(guard_selection_t *gs,
867  const uint8_t *rsa_id_digest,
868  const char *nickname,
869  const tor_addr_port_t *bridge_addrport)
870 {
871  const int GUARD_LIFETIME = get_guard_lifetime();
872  tor_assert(gs);
873 
874  // XXXX #20827 take ed25519 identity here too.
875 
876  /* Make sure we can actually identify the guard. */
877  if (BUG(!rsa_id_digest && !bridge_addrport))
878  return NULL; // LCOV_EXCL_LINE
879 
880  entry_guard_t *guard = tor_malloc_zero(sizeof(entry_guard_t));
881 
882  /* persistent fields */
883  guard->is_persistent = (rsa_id_digest != NULL);
884  guard->selection_name = tor_strdup(gs->name);
885  if (rsa_id_digest)
886  memcpy(guard->identity, rsa_id_digest, DIGEST_LEN);
887  if (nickname)
888  strlcpy(guard->nickname, nickname, sizeof(guard->nickname));
889  guard->sampled_on_date = randomize_time(approx_time(), GUARD_LIFETIME/10);
890  tor_free(guard->sampled_by_version);
891  guard->sampled_by_version = tor_strdup(VERSION);
892  guard->currently_listed = 1;
893  guard->confirmed_idx = -1;
894 
895  /* non-persistent fields */
896  guard->is_reachable = GUARD_REACHABLE_MAYBE;
897  if (bridge_addrport)
898  guard->bridge_addr = tor_memdup(bridge_addrport, sizeof(*bridge_addrport));
899 
900  smartlist_add(gs->sampled_entry_guards, guard);
901  guard->in_selection = gs;
904  return guard;
905 }
906 
907 /**
908  * Add an entry guard to the "bridges" guard selection sample, with
909  * information taken from <b>bridge</b>. Return that entry guard.
910  */
911 static entry_guard_t *
912 entry_guard_add_bridge_to_sample(guard_selection_t *gs,
913  const bridge_info_t *bridge)
914 {
915  const uint8_t *id_digest = bridge_get_rsa_id_digest(bridge);
916  const tor_addr_port_t *addrport = bridge_get_addr_port(bridge);
917 
918  tor_assert(addrport);
919 
920  /* make sure that the guard is not already sampled. */
921  if (BUG(get_sampled_guard_for_bridge(gs, bridge)))
922  return NULL; // LCOV_EXCL_LINE
923 
924  return entry_guard_add_to_sample_impl(gs, id_digest, NULL, addrport);
925 }
926 
927 /**
928  * Return the entry_guard_t in <b>gs</b> whose address is <b>addrport</b>,
929  * or NULL if none exists.
930 */
931 static entry_guard_t *
932 get_sampled_guard_by_bridge_addr(guard_selection_t *gs,
933  const tor_addr_port_t *addrport)
934 {
935  if (! gs)
936  return NULL;
937  if (BUG(!addrport))
938  return NULL;
939  SMARTLIST_FOREACH_BEGIN(gs->sampled_entry_guards, entry_guard_t *, g) {
940  if (g->bridge_addr && tor_addr_port_eq(addrport, g->bridge_addr))
941  return g;
942  } SMARTLIST_FOREACH_END(g);
943  return NULL;
944 }
945 
946 /** Update the guard subsystem's knowledge of the identity of the bridge
947  * at <b>addrport</b>. Idempotent.
948  */
949 void
951  const uint8_t *rsa_id_digest)
952 {
953  guard_selection_t *gs = get_guard_selection_by_name("bridges",
954  GS_TYPE_BRIDGE,
955  0);
956  if (!gs)
957  return;
958 
959  entry_guard_t *g = get_sampled_guard_by_bridge_addr(gs, addrport);
960  if (!g)
961  return;
962 
963  int make_persistent = 0;
964 
965  if (tor_digest_is_zero(g->identity)) {
966  memcpy(g->identity, rsa_id_digest, DIGEST_LEN);
967  make_persistent = 1;
968  } else if (tor_memeq(g->identity, rsa_id_digest, DIGEST_LEN)) {
969  /* Nothing to see here; we learned something we already knew. */
970  if (BUG(! g->is_persistent))
971  make_persistent = 1;
972  } else {
973  char old_id[HEX_DIGEST_LEN+1];
974  base16_encode(old_id, sizeof(old_id), g->identity, sizeof(g->identity));
975  log_warn(LD_BUG, "We 'learned' an identity %s for a bridge at %s:%d, but "
976  "we already knew a different one (%s). Ignoring the new info as "
977  "possibly bogus.",
978  hex_str((const char *)rsa_id_digest, DIGEST_LEN),
979  fmt_and_decorate_addr(&addrport->addr), addrport->port,
980  old_id);
981  return; // redundant, but let's be clear: we're not making this persistent.
982  }
983 
984  if (make_persistent) {
985  g->is_persistent = 1;
987  }
988 }
989 
990 /**
991  * Return the number of sampled guards in <b>gs</b> that are "filtered"
992  * (that is, we're willing to connect to them) and that are "usable"
993  * (that is, either "reachable" or "maybe reachable").
994  *
995  * If a restriction is provided in <b>rst</b>, do not count any guards that
996  * violate it.
997  */
998 STATIC int
999 num_reachable_filtered_guards(const guard_selection_t *gs,
1000  const entry_guard_restriction_t *rst)
1001 {
1002  int n_reachable_filtered_guards = 0;
1003  SMARTLIST_FOREACH_BEGIN(gs->sampled_entry_guards, entry_guard_t *, guard) {
1005  if (! entry_guard_obeys_restriction(guard, rst))
1006  continue;
1007  if (guard->is_usable_filtered_guard)
1008  ++n_reachable_filtered_guards;
1009  } SMARTLIST_FOREACH_END(guard);
1010  return n_reachable_filtered_guards;
1011 }
1012 
1013 /** Return the actual maximum size for the sample in <b>gs</b>,
1014  * given that we know about <b>n_guards</b> total. */
1015 static int
1016 get_max_sample_size(guard_selection_t *gs,
1017  int n_guards)
1018 {
1019  const int using_bridges = (gs->type == GS_TYPE_BRIDGE);
1020  const int min_sample = get_min_filtered_sample_size();
1021 
1022  /* If we are in bridge mode, expand our sample set as needed without worrying
1023  * about max size. We should respect the user's wishes to use many bridges if
1024  * that's what they have specified in their configuration file. */
1025  if (using_bridges)
1026  return INT_MAX;
1027 
1028  const int max_sample_by_pct = (int)(n_guards * get_max_sample_threshold());
1029  const int max_sample_absolute = get_max_sample_size_absolute();
1030  const int max_sample = MIN(max_sample_by_pct, max_sample_absolute);
1031  if (max_sample < min_sample)
1032  return min_sample;
1033  else
1034  return max_sample;
1035 }
1036 
1037 /**
1038  * Return a smartlist of the all the guards that are not currently
1039  * members of the sample (GUARDS - SAMPLED_GUARDS). The elements of
1040  * this list are node_t pointers in the non-bridge case, and
1041  * bridge_info_t pointers in the bridge case. Set *<b>n_guards_out</b>
1042  * to the number of guards that we found in GUARDS, including those
1043  * that were already sampled.
1044  */
1045 static smartlist_t *
1047  guard_selection_t *gs,
1048  int *n_guards_out)
1049 {
1050  /* Construct eligible_guards as GUARDS - SAMPLED_GUARDS */
1051  smartlist_t *eligible_guards = smartlist_new();
1052  int n_guards = 0; // total size of "GUARDS"
1053 
1054  if (gs->type == GS_TYPE_BRIDGE) {
1055  const smartlist_t *bridges = bridge_list_get();
1056  SMARTLIST_FOREACH_BEGIN(bridges, bridge_info_t *, bridge) {
1057  ++n_guards;
1058  if (NULL != get_sampled_guard_for_bridge(gs, bridge)) {
1059  continue;
1060  }
1061  smartlist_add(eligible_guards, bridge);
1062  } SMARTLIST_FOREACH_END(bridge);
1063  } else {
1064  const smartlist_t *nodes = nodelist_get_list();
1065  const int n_sampled = smartlist_len(gs->sampled_entry_guards);
1066 
1067  /* Build a bloom filter of our current guards: let's keep this O(N). */
1068  digestset_t *sampled_guard_ids = digestset_new(n_sampled);
1069  SMARTLIST_FOREACH_BEGIN(gs->sampled_entry_guards, const entry_guard_t *,
1070  guard) {
1071  digestset_add(sampled_guard_ids, guard->identity);
1072  } SMARTLIST_FOREACH_END(guard);
1073 
1074  SMARTLIST_FOREACH_BEGIN(nodes, const node_t *, node) {
1075  if (! node_is_possible_guard(node))
1076  continue;
1077  if (gs->type == GS_TYPE_RESTRICTED) {
1078  /* In restricted mode, we apply the filter BEFORE sampling, so
1079  * that we are sampling from the nodes that we might actually
1080  * select. If we sampled first, we might wind up with a sample
1081  * that didn't include any EntryNodes at all. */
1082  if (! node_passes_guard_filter(options, node))
1083  continue;
1084  }
1085  ++n_guards;
1086  if (digestset_probably_contains(sampled_guard_ids, node->identity))
1087  continue;
1088  smartlist_add(eligible_guards, (node_t*)node);
1089  } SMARTLIST_FOREACH_END(node);
1090 
1091  /* Now we can free that bloom filter. */
1092  digestset_free(sampled_guard_ids);
1093  }
1094 
1095  *n_guards_out = n_guards;
1096  return eligible_guards;
1097 }
1098 
1099 /** Helper: given a smartlist of either bridge_info_t (if gs->type is
1100  * GS_TYPE_BRIDGE) or node_t (otherwise), pick one that can be a guard,
1101  * add it as a guard, remove it from the list, and return a new
1102  * entry_guard_t. Return NULL on failure. */
1103 static entry_guard_t *
1105  smartlist_t *eligible_guards)
1106 {
1107  entry_guard_t *added_guard;
1108  if (gs->type == GS_TYPE_BRIDGE) {
1109  const bridge_info_t *bridge = smartlist_choose(eligible_guards);
1110  if (BUG(!bridge))
1111  return NULL; // LCOV_EXCL_LINE
1112  smartlist_remove(eligible_guards, bridge);
1113  added_guard = entry_guard_add_bridge_to_sample(gs, bridge);
1114  } else {
1115  const node_t *node =
1116  node_sl_choose_by_bandwidth(eligible_guards, WEIGHT_FOR_GUARD);
1117  if (BUG(!node))
1118  return NULL; // LCOV_EXCL_LINE
1119  smartlist_remove(eligible_guards, node);
1120  added_guard = entry_guard_add_to_sample(gs, node);
1121  }
1122 
1123  return added_guard;
1124 }
1125 
1126 /**
1127  * Return true iff we need a consensus to update our guards, but we don't
1128  * have one. (We can return 0 here either if the consensus is _not_ missing,
1129  * or if we don't need a consensus because we're using bridges.)
1130  */
1131 static int
1132 reasonably_live_consensus_is_missing(const guard_selection_t *gs)
1133 {
1134  tor_assert(gs);
1135  if (gs->type == GS_TYPE_BRIDGE) {
1136  /* We don't update bridges from the consensus; they aren't there. */
1137  return 0;
1138  }
1140  approx_time(),
1141  usable_consensus_flavor()) == NULL;
1142 }
1143 
1144 /**
1145  * Add new guards to the sampled guards in <b>gs</b> until there are
1146  * enough usable filtered guards, but never grow the sample beyond its
1147  * maximum size. Return the last guard added, or NULL if none were
1148  * added.
1149  */
1150 STATIC entry_guard_t *
1151 entry_guards_expand_sample(guard_selection_t *gs)
1152 {
1153  tor_assert(gs);
1154  const or_options_t *options = get_options();
1155 
1157  log_info(LD_GUARD, "Not expanding the sample guard set; we have "
1158  "no reasonably live consensus.");
1159  return NULL;
1160  }
1161 
1162  int n_sampled = smartlist_len(gs->sampled_entry_guards);
1163  entry_guard_t *added_guard = NULL;
1164  int n_usable_filtered_guards = num_reachable_filtered_guards(gs, NULL);
1165  int n_guards = 0;
1166  smartlist_t *eligible_guards = get_eligible_guards(options, gs, &n_guards);
1167 
1168  const int max_sample = get_max_sample_size(gs, n_guards);
1169  const int min_filtered_sample = get_min_filtered_sample_size();
1170 
1171  log_info(LD_GUARD, "Expanding the sample guard set. We have %d guards "
1172  "in the sample, and %d eligible guards to extend it with.",
1173  n_sampled, smartlist_len(eligible_guards));
1174 
1175  while (n_usable_filtered_guards < min_filtered_sample) {
1176  /* Has our sample grown too large to expand? */
1177  if (n_sampled >= max_sample) {
1178  log_info(LD_GUARD, "Not expanding the guard sample any further; "
1179  "just hit the maximum sample threshold of %d",
1180  max_sample);
1181  goto done;
1182  }
1183 
1184  /* Did we run out of guards? */
1185  if (smartlist_len(eligible_guards) == 0) {
1186  /* LCOV_EXCL_START
1187  As long as MAX_SAMPLE_THRESHOLD makes can't be adjusted to
1188  allow all guards to be sampled, this can't be reached.
1189  */
1190  log_info(LD_GUARD, "Not expanding the guard sample any further; "
1191  "just ran out of eligible guards");
1192  goto done;
1193  /* LCOV_EXCL_STOP */
1194  }
1195 
1196  /* Otherwise we can add at least one new guard. */
1197  added_guard = select_and_add_guard_item_for_sample(gs, eligible_guards);
1198  if (!added_guard)
1199  goto done; // LCOV_EXCL_LINE -- only fails on BUG.
1200 
1201  ++n_sampled;
1202 
1203  if (added_guard->is_usable_filtered_guard)
1204  ++n_usable_filtered_guards;
1205  }
1206 
1207  done:
1208  smartlist_free(eligible_guards);
1209  return added_guard;
1210 }
1211 
1212 /**
1213  * Helper: <b>guard</b> has just been removed from the sampled guards:
1214  * also remove it from primary and confirmed. */
1215 static void
1217  entry_guard_t *guard)
1218 {
1219  if (guard->is_primary) {
1220  guard->is_primary = 0;
1221  smartlist_remove_keeporder(gs->primary_entry_guards, guard);
1222  } else {
1223  if (BUG(smartlist_contains(gs->primary_entry_guards, guard))) {
1224  smartlist_remove_keeporder(gs->primary_entry_guards, guard);
1225  }
1226  }
1227 
1228  if (guard->confirmed_idx >= 0) {
1229  smartlist_remove_keeporder(gs->confirmed_entry_guards, guard);
1230  guard->confirmed_idx = -1;
1231  guard->confirmed_on_date = 0;
1232  } else {
1233  if (BUG(smartlist_contains(gs->confirmed_entry_guards, guard))) {
1234  // LCOV_EXCL_START
1235  smartlist_remove_keeporder(gs->confirmed_entry_guards, guard);
1236  // LCOV_EXCL_STOP
1237  }
1238  }
1239 }
1240 
1241 /** Return true iff <b>guard</b> is currently "listed" -- that is, it
1242  * appears in the consensus, or as a configured bridge (as
1243  * appropriate) */
1244 MOCK_IMPL(STATIC int,
1245 entry_guard_is_listed,(guard_selection_t *gs, const entry_guard_t *guard))
1246 {
1247  if (gs->type == GS_TYPE_BRIDGE) {
1248  return NULL != get_bridge_info_for_guard(guard);
1249  } else {
1250  const node_t *node = node_get_by_id(guard->identity);
1251 
1252  return node && node_is_possible_guard(node);
1253  }
1254 }
1255 
1256 /**
1257  * Enumerate <b>sampled_entry_guards</b> smartlist in <b>gs</b>.
1258  * For each <b>entry_guard_t</b> object in smartlist, do the following:
1259  * * Update <b>currently_listed</b> field to reflect if guard is listed
1260  * in guard selection <b>gs</b>.
1261  * * Set <b>unlisted_since_date</b> to approximate UNIX time of
1262  * unlisting if guard is unlisted (randomize within 20% of
1263  * get_remove_unlisted_guards_after_seconds()). Otherwise,
1264  * set it to 0.
1265  *
1266  * Require <b>gs</b> to be non-null pointer.
1267  * Return a number of entries updated.
1268  */
1269 static size_t
1271 {
1272  size_t n_changes = 0;
1273 
1274  tor_assert(gs);
1275 
1276  const time_t unlisted_since_slop =
1278 
1279  SMARTLIST_FOREACH_BEGIN(gs->sampled_entry_guards, entry_guard_t *, guard) {
1280  /* XXXX #20827 check ed ID too */
1281  const int is_listed = entry_guard_is_listed(gs, guard);
1282 
1283  if (is_listed && ! guard->currently_listed) {
1284  ++n_changes;
1285  guard->currently_listed = 1;
1286  guard->unlisted_since_date = 0;
1287  log_info(LD_GUARD, "Sampled guard %s is now listed again.",
1288  entry_guard_describe(guard));
1289  } else if (!is_listed && guard->currently_listed) {
1290  ++n_changes;
1291  guard->currently_listed = 0;
1292  guard->unlisted_since_date = randomize_time(approx_time(),
1293  unlisted_since_slop);
1294  log_info(LD_GUARD, "Sampled guard %s is now unlisted.",
1295  entry_guard_describe(guard));
1296  } else if (is_listed && guard->currently_listed) {
1297  log_debug(LD_GUARD, "Sampled guard %s is still listed.",
1298  entry_guard_describe(guard));
1299  } else {
1300  tor_assert(! is_listed && ! guard->currently_listed);
1301  log_debug(LD_GUARD, "Sampled guard %s is still unlisted.",
1302  entry_guard_describe(guard));
1303  }
1304 
1305  /* Clean up unlisted_since_date, just in case. */
1306  if (guard->currently_listed && guard->unlisted_since_date) {
1307  ++n_changes;
1308  guard->unlisted_since_date = 0;
1309  log_warn(LD_BUG, "Sampled guard %s was listed, but with "
1310  "unlisted_since_date set. Fixing.",
1311  entry_guard_describe(guard));
1312  } else if (!guard->currently_listed && ! guard->unlisted_since_date) {
1313  ++n_changes;
1314  guard->unlisted_since_date = randomize_time(approx_time(),
1315  unlisted_since_slop);
1316  log_warn(LD_BUG, "Sampled guard %s was unlisted, but with "
1317  "unlisted_since_date unset. Fixing.",
1318  entry_guard_describe(guard));
1319  }
1320  } SMARTLIST_FOREACH_END(guard);
1321 
1322  return n_changes;
1323 }
1324 
1325 /**
1326  * Enumerate <b>sampled_entry_guards</b> smartlist in <b>gs</b>.
1327  * For each <b>entry_guard_t</b> object in smartlist, do the following:
1328  * * If <b>currently_listed</b> is false and <b>unlisted_since_date</b>
1329  * is earlier than <b>remove_if_unlisted_since</b> - remove it.
1330  * * Otherwise, check if <b>sampled_on_date</b> is earlier than
1331  * <b>maybe_remove_if_sampled_before</b>.
1332  * * When above condition is correct, remove the guard if:
1333  * * It was never confirmed.
1334  * * It was confirmed before <b>remove_if_confirmed_before</b>.
1335  *
1336  * Require <b>gs</b> to be non-null pointer.
1337  * Return number of entries deleted.
1338  */
1339 static size_t
1341  const time_t remove_if_unlisted_since,
1342  const time_t maybe_remove_if_sampled_before,
1343  const time_t remove_if_confirmed_before)
1344 {
1345  size_t n_changes = 0;
1346 
1347  tor_assert(gs);
1348 
1349  SMARTLIST_FOREACH_BEGIN(gs->sampled_entry_guards, entry_guard_t *, guard) {
1350  int rmv = 0;
1351 
1352  if (guard->currently_listed == 0 &&
1353  guard->unlisted_since_date < remove_if_unlisted_since) {
1354  /*
1355  "We have a live consensus, and {IS_LISTED} is false, and
1356  {FIRST_UNLISTED_AT} is over get_remove_unlisted_guards_after_days()
1357  days in the past."
1358  */
1359  log_info(LD_GUARD, "Removing sampled guard %s: it has been unlisted "
1360  "for over %d days", entry_guard_describe(guard),
1362  rmv = 1;
1363  } else if (guard->sampled_on_date < maybe_remove_if_sampled_before) {
1364  /* We have a live consensus, and {ADDED_ON_DATE} is over
1365  {GUARD_LIFETIME} ago, *and* {CONFIRMED_ON_DATE} is either
1366  "never", or over {GUARD_CONFIRMED_MIN_LIFETIME} ago.
1367  */
1368  if (guard->confirmed_on_date == 0) {
1369  rmv = 1;
1370  log_info(LD_GUARD, "Removing sampled guard %s: it was sampled "
1371  "over %d days ago, but never confirmed.",
1372  entry_guard_describe(guard),
1373  get_guard_lifetime() / 86400);
1374  } else if (guard->confirmed_on_date < remove_if_confirmed_before) {
1375  rmv = 1;
1376  log_info(LD_GUARD, "Removing sampled guard %s: it was sampled "
1377  "over %d days ago, and confirmed over %d days ago.",
1378  entry_guard_describe(guard),
1379  get_guard_lifetime() / 86400,
1381  }
1382  }
1383 
1384  if (rmv) {
1385  ++n_changes;
1386  SMARTLIST_DEL_CURRENT(gs->sampled_entry_guards, guard);
1388  entry_guard_free(guard);
1389  }
1390  } SMARTLIST_FOREACH_END(guard);
1391 
1392  return n_changes;
1393 }
1394 
1395 /**
1396  * Update the status of all sampled guards based on the arrival of a
1397  * new consensus networkstatus document. This will include marking
1398  * some guards as listed or unlisted, and removing expired guards. */
1399 STATIC void
1401 {
1402  tor_assert(gs);
1403 
1404  // It's important to use a reasonably live consensus here; we want clients
1405  // to bootstrap even if their clock is skewed by more than 2-3 hours.
1406  // But we don't want to make changes based on anything that's really old.
1408  log_info(LD_GUARD, "Not updating the sample guard set; we have "
1409  "no reasonably live consensus.");
1410  return;
1411  }
1412  log_info(LD_GUARD, "Updating sampled guard status based on received "
1413  "consensus.");
1414 
1415  /* First: Update listed/unlisted. */
1416  size_t n_changes = sampled_guards_update_consensus_presence(gs);
1417 
1418  const time_t remove_if_unlisted_since =
1420  const time_t maybe_remove_if_sampled_before =
1422  const time_t remove_if_confirmed_before =
1424 
1425  /* Then: remove the ones that have been junk for too long */
1426  n_changes +=
1428  remove_if_unlisted_since,
1429  maybe_remove_if_sampled_before,
1430  remove_if_confirmed_before);
1431 
1432  if (n_changes) {
1433  gs->primary_guards_up_to_date = 0;
1435  /* We don't need to rebuild the confirmed list right here -- we may have
1436  * removed confirmed guards above, but we can't have added any new
1437  * confirmed guards.
1438  */
1440  }
1441 }
1442 
1443 /**
1444  * Return true iff <b>node</b> is a Tor relay that we are configured to
1445  * be able to connect to. */
1446 static int
1448  const node_t *node)
1449 {
1450  /* NOTE: Make sure that this function stays in sync with
1451  * options_transition_affects_entry_guards */
1452  if (routerset_contains_node(options->ExcludeNodes, node))
1453  return 0;
1454 
1455  if (options->EntryNodes &&
1456  !routerset_contains_node(options->EntryNodes, node))
1457  return 0;
1458 
1459  if (!fascist_firewall_allows_node(node, FIREWALL_OR_CONNECTION, 0))
1460  return 0;
1461 
1462  if (node_is_a_configured_bridge(node))
1463  return 0;
1464 
1465  return 1;
1466 }
1467 
1468 /** Helper: Return true iff <b>bridge</b> passes our configuration
1469  * filter-- if it is a relay that we are configured to be able to
1470  * connect to. */
1471 static int
1473  const bridge_info_t *bridge)
1474 {
1475  tor_assert(bridge);
1476  if (!bridge)
1477  return 0;
1478 
1479  if (routerset_contains_bridge(options->ExcludeNodes, bridge))
1480  return 0;
1481 
1482  /* Ignore entrynodes */
1483  const tor_addr_port_t *addrport = bridge_get_addr_port(bridge);
1484 
1485  if (!fascist_firewall_allows_address_addr(&addrport->addr,
1486  addrport->port,
1487  FIREWALL_OR_CONNECTION,
1488  0, 0))
1489  return 0;
1490 
1491  return 1;
1492 }
1493 
1494 /**
1495  * Return true iff <b>guard</b> is a Tor relay that we are configured to
1496  * be able to connect to, and we haven't disabled it for omission from
1497  * the consensus or path bias issues. */
1498 static int
1499 entry_guard_passes_filter(const or_options_t *options, guard_selection_t *gs,
1500  entry_guard_t *guard)
1501 {
1502  if (guard->currently_listed == 0)
1503  return 0;
1504  if (guard->pb.path_bias_disabled)
1505  return 0;
1506 
1507  if (gs->type == GS_TYPE_BRIDGE) {
1508  const bridge_info_t *bridge = get_bridge_info_for_guard(guard);
1509  if (bridge == NULL)
1510  return 0;
1511  return bridge_passes_guard_filter(options, bridge);
1512  } else {
1513  const node_t *node = node_get_by_id(guard->identity);
1514  if (node == NULL) {
1515  // This can happen when currently_listed is true, and we're not updating
1516  // it because we don't have a live consensus.
1517  return 0;
1518  }
1519 
1520  return node_passes_guard_filter(options, node);
1521  }
1522 }
1523 
1524 /** Return true iff <b>guard</b> is in the same family as <b>node</b>.
1525  */
1526 static int
1527 guard_in_node_family(const entry_guard_t *guard, const node_t *node)
1528 {
1529  const node_t *guard_node = node_get_by_id(guard->identity);
1530  if (guard_node) {
1531  return nodes_in_same_family(guard_node, node);
1532  } else {
1533  /* If we don't have a node_t for the guard node, we might have
1534  * a bridge_info_t for it. So let's check to see whether the bridge
1535  * address matches has any family issues.
1536  *
1537  * (Strictly speaking, I believe this check is unnecessary, since we only
1538  * use it to avoid the exit's family when building circuits, and we don't
1539  * build multihop circuits until we have a routerinfo_t for the
1540  * bridge... at which point, we'll also have a node_t for the
1541  * bridge. Nonetheless, it seems wise to include it, in case our
1542  * assumptions change down the road. -nickm.)
1543  */
1544  if (get_options()->EnforceDistinctSubnets && guard->bridge_addr) {
1545  tor_addr_t node_addr;
1546  node_get_addr(node, &node_addr);
1547  if (addrs_in_same_network_family(&node_addr,
1548  &guard->bridge_addr->addr)) {
1549  return 1;
1550  }
1551  }
1552  return 0;
1553  }
1554 }
1555 
1556 /* Allocate and return a new exit guard restriction (where <b>exit_id</b> is of
1557  * size DIGEST_LEN) */
1558 STATIC entry_guard_restriction_t *
1559 guard_create_exit_restriction(const uint8_t *exit_id)
1560 {
1561  entry_guard_restriction_t *rst = NULL;
1562  rst = tor_malloc_zero(sizeof(entry_guard_restriction_t));
1563  rst->type = RST_EXIT_NODE;
1564  memcpy(rst->exclude_id, exit_id, DIGEST_LEN);
1565  return rst;
1566 }
1567 
1568 /** If we have fewer than this many possible usable guards, don't set
1569  * MD-availability-based restrictions: we might blacklist all of them. */
1570 #define MIN_GUARDS_FOR_MD_RESTRICTION 10
1571 
1572 /** Return true if we should set md dirserver restrictions. We might not want
1573  * to set those if our guard options are too restricted, since we don't want
1574  * to blacklist all of them. */
1575 static int
1577 {
1578  const guard_selection_t *gs = get_guard_selection_info();
1579  int num_usable_guards = num_reachable_filtered_guards(gs, NULL);
1580 
1581  /* Don't set restriction if too few reachable filtered guards. */
1582  if (num_usable_guards < MIN_GUARDS_FOR_MD_RESTRICTION) {
1583  log_info(LD_GUARD, "Not setting md restriction: only %d"
1584  " usable guards.", num_usable_guards);
1585  return 0;
1586  }
1587 
1588  /* We have enough usable guards: set MD restriction */
1589  return 1;
1590 }
1591 
1592 /** Allocate and return an outdated md guard restriction. Return NULL if no
1593  * such restriction is needed. */
1594 STATIC entry_guard_restriction_t *
1596 {
1597  entry_guard_restriction_t *rst = NULL;
1598 
1600  log_debug(LD_GUARD, "Not setting md restriction: too few "
1601  "filtered guards.");
1602  return NULL;
1603  }
1604 
1605  rst = tor_malloc_zero(sizeof(entry_guard_restriction_t));
1606  rst->type = RST_OUTDATED_MD_DIRSERVER;
1607 
1608  return rst;
1609 }
1610 
1611 /* Return True if <b>guard</b> obeys the exit restriction <b>rst</b>. */
1612 static int
1613 guard_obeys_exit_restriction(const entry_guard_t *guard,
1614  const entry_guard_restriction_t *rst)
1615 {
1616  tor_assert(rst->type == RST_EXIT_NODE);
1617 
1618  // Exclude the exit ID and all of its family.
1619  const node_t *node = node_get_by_id((const char*)rst->exclude_id);
1620  if (node && guard_in_node_family(guard, node))
1621  return 0;
1622 
1623  return tor_memneq(guard->identity, rst->exclude_id, DIGEST_LEN);
1624 }
1625 
1626 /** Return True if <b>guard</b> should be used as a dirserver for fetching
1627  * microdescriptors. */
1628 static int
1629 guard_obeys_md_dirserver_restriction(const entry_guard_t *guard)
1630 {
1631  /* If this guard is an outdated dirserver, don't use it. */
1632  if (microdesc_relay_is_outdated_dirserver(guard->identity)) {
1633  log_info(LD_GENERAL, "Skipping %s dirserver: outdated",
1634  hex_str(guard->identity, DIGEST_LEN));
1635  return 0;
1636  }
1637 
1638  log_debug(LD_GENERAL, "%s dirserver obeys md restrictions",
1639  hex_str(guard->identity, DIGEST_LEN));
1640 
1641  return 1;
1642 }
1643 
1644 /**
1645  * Return true iff <b>guard</b> obeys the restrictions defined in <b>rst</b>.
1646  * (If <b>rst</b> is NULL, there are no restrictions.)
1647  */
1648 static int
1649 entry_guard_obeys_restriction(const entry_guard_t *guard,
1650  const entry_guard_restriction_t *rst)
1651 {
1652  tor_assert(guard);
1653  if (! rst)
1654  return 1; // No restriction? No problem.
1655 
1656  if (rst->type == RST_EXIT_NODE) {
1657  return guard_obeys_exit_restriction(guard, rst);
1658  } else if (rst->type == RST_OUTDATED_MD_DIRSERVER) {
1660  }
1661 
1662  tor_assert_nonfatal_unreached();
1663  return 0;
1664 }
1665 
1666 /**
1667  * Update the <b>is_filtered_guard</b> and <b>is_usable_filtered_guard</b>
1668  * flags on <b>guard</b>. */
1669 void
1671  guard_selection_t *gs,
1672  entry_guard_t *guard)
1673 {
1674  unsigned was_filtered = guard->is_filtered_guard;
1675  guard->is_filtered_guard = 0;
1676  guard->is_usable_filtered_guard = 0;
1677 
1678  if (entry_guard_passes_filter(options, gs, guard)) {
1679  guard->is_filtered_guard = 1;
1680 
1681  if (guard->is_reachable != GUARD_REACHABLE_NO)
1682  guard->is_usable_filtered_guard = 1;
1683 
1685  }
1686  log_debug(LD_GUARD, "Updated sampled guard %s: filtered=%d; "
1687  "reachable_filtered=%d.", entry_guard_describe(guard),
1688  guard->is_filtered_guard, guard->is_usable_filtered_guard);
1689 
1690  if (!bool_eq(was_filtered, guard->is_filtered_guard)) {
1691  /* This guard might now be primary or nonprimary. */
1692  gs->primary_guards_up_to_date = 0;
1693  }
1694 }
1695 
1696 /**
1697  * Update the <b>is_filtered_guard</b> and <b>is_usable_filtered_guard</b>
1698  * flag on every guard in <b>gs</b>. */
1699 STATIC void
1701 {
1702  const or_options_t *options = get_options();
1703 
1704  SMARTLIST_FOREACH_BEGIN(gs->sampled_entry_guards, entry_guard_t *, guard) {
1705  entry_guard_set_filtered_flags(options, gs, guard);
1706  } SMARTLIST_FOREACH_END(guard);
1707 }
1708 
1709 /**
1710  * Return a random guard from the reachable filtered sample guards
1711  * in <b>gs</b>, subject to the exclusion rules listed in <b>flags</b>.
1712  * Return NULL if no such guard can be found.
1713  *
1714  * Make sure that the sample is big enough, and that all the filter flags
1715  * are set correctly, before calling this function.
1716  *
1717  * If a restriction is provided in <b>rst</b>, do not return any guards that
1718  * violate it.
1719  **/
1720 STATIC entry_guard_t *
1722  const entry_guard_restriction_t *rst,
1723  unsigned flags)
1724 {
1725  tor_assert(gs);
1726  entry_guard_t *result = NULL;
1727  const unsigned exclude_confirmed = flags & SAMPLE_EXCLUDE_CONFIRMED;
1728  const unsigned exclude_primary = flags & SAMPLE_EXCLUDE_PRIMARY;
1729  const unsigned exclude_pending = flags & SAMPLE_EXCLUDE_PENDING;
1730  const unsigned no_update_primary = flags & SAMPLE_NO_UPDATE_PRIMARY;
1731  const unsigned need_descriptor = flags & SAMPLE_EXCLUDE_NO_DESCRIPTOR;
1732 
1733  SMARTLIST_FOREACH_BEGIN(gs->sampled_entry_guards, entry_guard_t *, guard) {
1735  } SMARTLIST_FOREACH_END(guard);
1736 
1737  const int n_reachable_filtered = num_reachable_filtered_guards(gs, rst);
1738 
1739  log_info(LD_GUARD, "Trying to sample a reachable guard: We know of %d "
1740  "in the USABLE_FILTERED set.", n_reachable_filtered);
1741 
1742  const int min_filtered_sample = get_min_filtered_sample_size();
1743  if (n_reachable_filtered < min_filtered_sample) {
1744  log_info(LD_GUARD, " (That isn't enough. Trying to expand the sample.)");
1746  }
1747 
1748  if (exclude_primary && !gs->primary_guards_up_to_date && !no_update_primary)
1750 
1751  /* Build the set of reachable filtered guards. */
1752  smartlist_t *reachable_filtered_sample = smartlist_new();
1753  SMARTLIST_FOREACH_BEGIN(gs->sampled_entry_guards, entry_guard_t *, guard) {
1754  entry_guard_consider_retry(guard);// redundant, but cheap.
1755  if (! entry_guard_obeys_restriction(guard, rst))
1756  continue;
1757  if (! guard->is_usable_filtered_guard)
1758  continue;
1759  if (exclude_confirmed && guard->confirmed_idx >= 0)
1760  continue;
1761  if (exclude_primary && guard->is_primary)
1762  continue;
1763  if (exclude_pending && guard->is_pending)
1764  continue;
1765  if (need_descriptor && !guard_has_descriptor(guard))
1766  continue;
1767  smartlist_add(reachable_filtered_sample, guard);
1768  } SMARTLIST_FOREACH_END(guard);
1769 
1770  log_info(LD_GUARD, " (After filters [%x], we have %d guards to consider.)",
1771  flags, smartlist_len(reachable_filtered_sample));
1772 
1773  if (smartlist_len(reachable_filtered_sample)) {
1774  result = smartlist_choose(reachable_filtered_sample);
1775  log_info(LD_GUARD, " (Selected %s.)",
1776  result ? entry_guard_describe(result) : "<null>");
1777  }
1778  smartlist_free(reachable_filtered_sample);
1779 
1780  return result;
1781 }
1782 
1783 /**
1784  * Helper: compare two entry_guard_t by their confirmed_idx values.
1785  * Used to sort the confirmed list.
1786  */
1787 static int
1788 compare_guards_by_confirmed_idx(const void **a_, const void **b_)
1789 {
1790  const entry_guard_t *a = *a_, *b = *b_;
1791  if (a->confirmed_idx < b->confirmed_idx)
1792  return -1;
1793  else if (a->confirmed_idx > b->confirmed_idx)
1794  return 1;
1795  else
1796  return 0;
1797 }
1798 
1799 /**
1800  * Find the confirmed guards from among the sampled guards in <b>gs</b>,
1801  * and put them in confirmed_entry_guards in the correct
1802  * order. Recalculate their indices.
1803  */
1804 STATIC void
1805 entry_guards_update_confirmed(guard_selection_t *gs)
1806 {
1807  smartlist_clear(gs->confirmed_entry_guards);
1808  SMARTLIST_FOREACH_BEGIN(gs->sampled_entry_guards, entry_guard_t *, guard) {
1809  if (guard->confirmed_idx >= 0)
1810  smartlist_add(gs->confirmed_entry_guards, guard);
1811  } SMARTLIST_FOREACH_END(guard);
1812 
1813  smartlist_sort(gs->confirmed_entry_guards, compare_guards_by_confirmed_idx);
1814 
1815  int any_changed = 0;
1816  SMARTLIST_FOREACH_BEGIN(gs->confirmed_entry_guards, entry_guard_t *, guard) {
1817  if (guard->confirmed_idx != guard_sl_idx) {
1818  any_changed = 1;
1819  guard->confirmed_idx = guard_sl_idx;
1820  }
1821  } SMARTLIST_FOREACH_END(guard);
1822 
1823  gs->next_confirmed_idx = smartlist_len(gs->confirmed_entry_guards);
1824 
1825  if (any_changed) {
1827  }
1828 }
1829 
1830 /**
1831  * Mark <b>guard</b> as a confirmed guard -- that is, one that we have
1832  * connected to, and intend to use again.
1833  */
1834 STATIC void
1835 make_guard_confirmed(guard_selection_t *gs, entry_guard_t *guard)
1836 {
1837  if (BUG(guard->confirmed_on_date && guard->confirmed_idx >= 0))
1838  return; // LCOV_EXCL_LINE
1839 
1840  if (BUG(smartlist_contains(gs->confirmed_entry_guards, guard)))
1841  return; // LCOV_EXCL_LINE
1842 
1843  const int GUARD_LIFETIME = get_guard_lifetime();
1844  guard->confirmed_on_date = randomize_time(approx_time(), GUARD_LIFETIME/10);
1845 
1846  log_info(LD_GUARD, "Marking %s as a confirmed guard (index %d)",
1847  entry_guard_describe(guard),
1848  gs->next_confirmed_idx);
1849 
1850  guard->confirmed_idx = gs->next_confirmed_idx++;
1851  smartlist_add(gs->confirmed_entry_guards, guard);
1852 
1853  // This confirmed guard might kick something else out of the primary
1854  // guards.
1855  gs->primary_guards_up_to_date = 0;
1856 
1858 }
1859 
1860 /**
1861  * Recalculate the list of primary guards (the ones we'd prefer to use) from
1862  * the filtered sample and the confirmed list.
1863  */
1864 STATIC void
1865 entry_guards_update_primary(guard_selection_t *gs)
1866 {
1867  tor_assert(gs);
1868 
1869  // prevent recursion. Recursion is potentially very bad here.
1870  static int running = 0;
1871  tor_assert(!running);
1872  running = 1;
1873 
1874  const int N_PRIMARY_GUARDS = get_n_primary_guards();
1875 
1876  smartlist_t *new_primary_guards = smartlist_new();
1877  smartlist_t *old_primary_guards = smartlist_new();
1878  smartlist_add_all(old_primary_guards, gs->primary_entry_guards);
1879 
1880  /* Set this flag now, to prevent the calls below from recursing. */
1881  gs->primary_guards_up_to_date = 1;
1882 
1883  /* First, can we fill it up with confirmed guards? */
1884  SMARTLIST_FOREACH_BEGIN(gs->confirmed_entry_guards, entry_guard_t *, guard) {
1885  if (smartlist_len(new_primary_guards) >= N_PRIMARY_GUARDS)
1886  break;
1887  if (! guard->is_filtered_guard)
1888  continue;
1889  guard->is_primary = 1;
1890  smartlist_add(new_primary_guards, guard);
1891  } SMARTLIST_FOREACH_END(guard);
1892 
1893  SMARTLIST_FOREACH_BEGIN(old_primary_guards, entry_guard_t *, guard) {
1894  /* Can we keep any older primary guards? First remove all the ones
1895  * that we already kept. */
1896  if (smartlist_contains(new_primary_guards, guard)) {
1897  SMARTLIST_DEL_CURRENT_KEEPORDER(old_primary_guards, guard);
1898  continue;
1899  }
1900 
1901  /* Now add any that are still good. */
1902  if (smartlist_len(new_primary_guards) < N_PRIMARY_GUARDS &&
1903  guard->is_filtered_guard) {
1904  guard->is_primary = 1;
1905  smartlist_add(new_primary_guards, guard);
1906  SMARTLIST_DEL_CURRENT_KEEPORDER(old_primary_guards, guard);
1907  } else {
1908  /* Mark the remaining previous primary guards as non-primary */
1909  guard->is_primary = 0;
1910  }
1911  } SMARTLIST_FOREACH_END(guard);
1912 
1913  /* Finally, fill out the list with sampled guards. */
1914  while (smartlist_len(new_primary_guards) < N_PRIMARY_GUARDS) {
1915  entry_guard_t *guard = sample_reachable_filtered_entry_guards(gs, NULL,
1916  SAMPLE_EXCLUDE_CONFIRMED|
1917  SAMPLE_EXCLUDE_PRIMARY|
1918  SAMPLE_NO_UPDATE_PRIMARY);
1919  if (!guard)
1920  break;
1921  guard->is_primary = 1;
1922  smartlist_add(new_primary_guards, guard);
1923  }
1924 
1925 #if 1
1926  /* Debugging. */
1927  SMARTLIST_FOREACH(gs->sampled_entry_guards, entry_guard_t *, guard, {
1928  tor_assert_nonfatal(
1929  bool_eq(guard->is_primary,
1930  smartlist_contains(new_primary_guards, guard)));
1931  });
1932 #endif /* 1 */
1933 
1934  const int any_change = !smartlist_ptrs_eq(gs->primary_entry_guards,
1935  new_primary_guards);
1936  if (any_change) {
1937  log_info(LD_GUARD, "Primary entry guards have changed. "
1938  "New primary guard list is: ");
1939  int n = smartlist_len(new_primary_guards);
1940  SMARTLIST_FOREACH_BEGIN(new_primary_guards, entry_guard_t *, g) {
1941  log_info(LD_GUARD, " %d/%d: %s%s%s",
1942  g_sl_idx+1, n, entry_guard_describe(g),
1943  g->confirmed_idx >= 0 ? " (confirmed)" : "",
1944  g->is_filtered_guard ? "" : " (excluded by filter)");
1945  } SMARTLIST_FOREACH_END(g);
1946  }
1947 
1948  smartlist_free(old_primary_guards);
1949  smartlist_free(gs->primary_entry_guards);
1950  gs->primary_entry_guards = new_primary_guards;
1951  gs->primary_guards_up_to_date = 1;
1952  running = 0;
1953 }
1954 
1955 /**
1956  * Return the number of seconds after the last attempt at which we should
1957  * retry a guard that has been failing since <b>failing_since</b>.
1958  */
1959 static int
1960 get_retry_schedule(time_t failing_since, time_t now,
1961  int is_primary)
1962 {
1963  const unsigned SIX_HOURS = 6 * 3600;
1964  const unsigned FOUR_DAYS = 4 * 86400;
1965  const unsigned SEVEN_DAYS = 7 * 86400;
1966 
1967  time_t tdiff;
1968  if (now > failing_since) {
1969  tdiff = now - failing_since;
1970  } else {
1971  tdiff = 0;
1972  }
1973 
1974  const struct {
1975  time_t maximum; int primary_delay; int nonprimary_delay;
1976  } delays[] = {
1977  { SIX_HOURS, 10*60, 1*60*60 },
1978  { FOUR_DAYS, 90*60, 4*60*60 },
1979  { SEVEN_DAYS, 4*60*60, 18*60*60 },
1980  { TIME_MAX, 9*60*60, 36*60*60 }
1981  };
1982 
1983  unsigned i;
1984  for (i = 0; i < ARRAY_LENGTH(delays); ++i) {
1985  if (tdiff <= delays[i].maximum) {
1986  return is_primary ? delays[i].primary_delay : delays[i].nonprimary_delay;
1987  }
1988  }
1989  /* LCOV_EXCL_START -- can't reach, since delays ends with TIME_MAX. */
1990  tor_assert_nonfatal_unreached();
1991  return 36*60*60;
1992  /* LCOV_EXCL_STOP */
1993 }
1994 
1995 /**
1996  * If <b>guard</b> is unreachable, consider whether enough time has passed
1997  * to consider it maybe-reachable again.
1998  */
1999 STATIC void
2000 entry_guard_consider_retry(entry_guard_t *guard)
2001 {
2002  if (guard->is_reachable != GUARD_REACHABLE_NO)
2003  return; /* No retry needed. */
2004 
2005  const time_t now = approx_time();
2006  const int delay =
2007  get_retry_schedule(guard->failing_since, now, guard->is_primary);
2008  const time_t last_attempt = guard->last_tried_to_connect;
2009 
2010  if (BUG(last_attempt == 0) ||
2011  now >= last_attempt + delay) {
2012  /* We should mark this retriable. */
2013  char tbuf[ISO_TIME_LEN+1];
2014  format_local_iso_time(tbuf, last_attempt);
2015  log_info(LD_GUARD, "Marked %s%sguard %s for possible retry, since we "
2016  "haven't tried to use it since %s.",
2017  guard->is_primary?"primary ":"",
2018  guard->confirmed_idx>=0?"confirmed ":"",
2019  entry_guard_describe(guard),
2020  tbuf);
2021 
2022  guard->is_reachable = GUARD_REACHABLE_MAYBE;
2023  if (guard->is_filtered_guard)
2024  guard->is_usable_filtered_guard = 1;
2025  }
2026 }
2027 
2028 /** Tell the entry guards subsystem that we have confirmed that as of
2029  * just now, we're on the internet. */
2030 void
2032 {
2033  gs->last_time_on_internet = approx_time();
2034 }
2035 
2036 /**
2037  * Pick a primary guard for use with a circuit, if available. Update the
2038  * <b>last_tried_to_connect</b> time and the <b>is_pending</b> fields of the
2039  * guard as appropriate. Set <b>state_out</b> to the new guard-state
2040  * of the circuit.
2041  */
2042 static entry_guard_t *
2043 select_primary_guard_for_circuit(guard_selection_t *gs,
2044  guard_usage_t usage,
2045  const entry_guard_restriction_t *rst,
2046  unsigned *state_out)
2047 {
2048  const int need_descriptor = (usage == GUARD_USAGE_TRAFFIC);
2049  entry_guard_t *chosen_guard = NULL;
2050 
2051  int num_entry_guards = get_n_primary_guards_to_use(usage);
2052  smartlist_t *usable_primary_guards = smartlist_new();
2053 
2054  SMARTLIST_FOREACH_BEGIN(gs->primary_entry_guards, entry_guard_t *, guard) {
2056  if (! entry_guard_obeys_restriction(guard, rst))
2057  continue;
2058  if (guard->is_reachable != GUARD_REACHABLE_NO) {
2059  if (need_descriptor && !guard_has_descriptor(guard)) {
2060  continue;
2061  }
2062  *state_out = GUARD_CIRC_STATE_USABLE_ON_COMPLETION;
2063  guard->last_tried_to_connect = approx_time();
2064  smartlist_add(usable_primary_guards, guard);
2065  if (smartlist_len(usable_primary_guards) >= num_entry_guards)
2066  break;
2067  }
2068  } SMARTLIST_FOREACH_END(guard);
2069 
2070  if (smartlist_len(usable_primary_guards)) {
2071  chosen_guard = smartlist_choose(usable_primary_guards);
2072  smartlist_free(usable_primary_guards);
2073  log_info(LD_GUARD, "Selected primary guard %s for circuit.",
2074  entry_guard_describe(chosen_guard));
2075  }
2076 
2077  smartlist_free(usable_primary_guards);
2078  return chosen_guard;
2079 }
2080 
2081 /**
2082  * For use with a circuit, pick a non-pending running filtered confirmed guard,
2083  * if one is available. Update the <b>last_tried_to_connect</b> time and the
2084  * <b>is_pending</b> fields of the guard as appropriate. Set <b>state_out</b>
2085  * to the new guard-state of the circuit.
2086  */
2087 static entry_guard_t *
2089  guard_usage_t usage,
2090  const entry_guard_restriction_t *rst,
2091  unsigned *state_out)
2092 {
2093  const int need_descriptor = (usage == GUARD_USAGE_TRAFFIC);
2094 
2095  SMARTLIST_FOREACH_BEGIN(gs->confirmed_entry_guards, entry_guard_t *, guard) {
2096  if (guard->is_primary)
2097  continue; /* we already considered this one. */
2098  if (! entry_guard_obeys_restriction(guard, rst))
2099  continue;
2101  if (guard->is_usable_filtered_guard && ! guard->is_pending) {
2102  if (need_descriptor && !guard_has_descriptor(guard))
2103  continue; /* not a bug */
2104  guard->is_pending = 1;
2105  guard->last_tried_to_connect = approx_time();
2106  *state_out = GUARD_CIRC_STATE_USABLE_IF_NO_BETTER_GUARD;
2107  log_info(LD_GUARD, "No primary guards available. Selected confirmed "
2108  "guard %s for circuit. Will try other guards before using "
2109  "this circuit.",
2110  entry_guard_describe(guard));
2111  return guard;
2112  }
2113  } SMARTLIST_FOREACH_END(guard);
2114 
2115  return NULL;
2116 }
2117 
2118 /**
2119  * For use with a circuit, pick a confirmed usable filtered guard
2120  * at random. Update the <b>last_tried_to_connect</b> time and the
2121  * <b>is_pending</b> fields of the guard as appropriate. Set <b>state_out</b>
2122  * to the new guard-state of the circuit.
2123  */
2124 static entry_guard_t *
2126  guard_usage_t usage,
2127  const entry_guard_restriction_t *rst,
2128  unsigned *state_out)
2129 {
2130  const int need_descriptor = (usage == GUARD_USAGE_TRAFFIC);
2131  entry_guard_t *chosen_guard = NULL;
2132  unsigned flags = 0;
2133  if (need_descriptor)
2134  flags |= SAMPLE_EXCLUDE_NO_DESCRIPTOR;
2135  chosen_guard = sample_reachable_filtered_entry_guards(gs,
2136  rst,
2137  SAMPLE_EXCLUDE_CONFIRMED |
2138  SAMPLE_EXCLUDE_PRIMARY |
2139  SAMPLE_EXCLUDE_PENDING |
2140  flags);
2141  if (!chosen_guard) {
2142  return NULL;
2143  }
2144 
2145  chosen_guard->is_pending = 1;
2146  chosen_guard->last_tried_to_connect = approx_time();
2147  *state_out = GUARD_CIRC_STATE_USABLE_IF_NO_BETTER_GUARD;
2148  log_info(LD_GUARD, "No primary or confirmed guards available. Selected "
2149  "random guard %s for circuit. Will try other guards before "
2150  "using this circuit.",
2151  entry_guard_describe(chosen_guard));
2152  return chosen_guard;
2153 }
2154 
2155 /**
2156  * Get a guard for use with a circuit. Prefer to pick a running primary
2157  * guard; then a non-pending running filtered confirmed guard; then a
2158  * non-pending runnable filtered guard. Update the
2159  * <b>last_tried_to_connect</b> time and the <b>is_pending</b> fields of the
2160  * guard as appropriate. Set <b>state_out</b> to the new guard-state
2161  * of the circuit.
2162  */
2163 STATIC entry_guard_t *
2164 select_entry_guard_for_circuit(guard_selection_t *gs,
2165  guard_usage_t usage,
2166  const entry_guard_restriction_t *rst,
2167  unsigned *state_out)
2168 {
2169  entry_guard_t *chosen_guard = NULL;
2170  tor_assert(gs);
2171  tor_assert(state_out);
2172 
2173  if (!gs->primary_guards_up_to_date)
2175 
2176  /* "If any entry in PRIMARY_GUARDS has {is_reachable} status of
2177  <maybe> or <yes>, return the first such guard." */
2178  chosen_guard = select_primary_guard_for_circuit(gs, usage, rst, state_out);
2179  if (chosen_guard)
2180  return chosen_guard;
2181 
2182  /* "Otherwise, if the ordered intersection of {CONFIRMED_GUARDS}
2183  and {USABLE_FILTERED_GUARDS} is nonempty, return the first
2184  entry in that intersection that has {is_pending} set to
2185  false." */
2186  chosen_guard = select_confirmed_guard_for_circuit(gs, usage, rst, state_out);
2187  if (chosen_guard)
2188  return chosen_guard;
2189 
2190  /* "Otherwise, if there is no such entry, select a member at
2191  random from {USABLE_FILTERED_GUARDS}." */
2192  chosen_guard = select_filtered_guard_for_circuit(gs, usage, rst, state_out);
2193 
2194  if (chosen_guard == NULL) {
2195  log_info(LD_GUARD, "Absolutely no sampled guards were available. "
2196  "Marking all guards for retry and starting from top again.");
2197  mark_all_guards_maybe_reachable(gs);
2198  return NULL;
2199  }
2200 
2201  return chosen_guard;
2202 }
2203 
2204 /**
2205  * Note that we failed to connect to or build circuits through <b>guard</b>.
2206  * Use with a guard returned by select_entry_guard_for_circuit().
2207  */
2208 STATIC void
2209 entry_guards_note_guard_failure(guard_selection_t *gs,
2210  entry_guard_t *guard)
2211 {
2212  tor_assert(gs);
2213 
2214  guard->is_reachable = GUARD_REACHABLE_NO;
2215  guard->is_usable_filtered_guard = 0;
2216 
2217  guard->is_pending = 0;
2218  if (guard->failing_since == 0)
2219  guard->failing_since = approx_time();
2220 
2221  log_info(LD_GUARD, "Recorded failure for %s%sguard %s",
2222  guard->is_primary?"primary ":"",
2223  guard->confirmed_idx>=0?"confirmed ":"",
2224  entry_guard_describe(guard));
2225 }
2226 
2227 /**
2228  * Note that we successfully connected to, and built a circuit through
2229  * <b>guard</b>. Given the old guard-state of the circuit in <b>old_state</b>,
2230  * return the new guard-state of the circuit.
2231  *
2232  * Be aware: the circuit is only usable when its guard-state becomes
2233  * GUARD_CIRC_STATE_COMPLETE.
2234  **/
2235 STATIC unsigned
2236 entry_guards_note_guard_success(guard_selection_t *gs,
2237  entry_guard_t *guard,
2238  unsigned old_state)
2239 {
2240  tor_assert(gs);
2241 
2242  /* Save this, since we're about to overwrite it. */
2243  const time_t last_time_on_internet = gs->last_time_on_internet;
2244  gs->last_time_on_internet = approx_time();
2245 
2246  guard->is_reachable = GUARD_REACHABLE_YES;
2247  guard->failing_since = 0;
2248  guard->is_pending = 0;
2249  if (guard->is_filtered_guard)
2250  guard->is_usable_filtered_guard = 1;
2251 
2252  if (guard->confirmed_idx < 0) {
2253  make_guard_confirmed(gs, guard);
2254  if (!gs->primary_guards_up_to_date)
2256  }
2257 
2258  unsigned new_state;
2259  switch (old_state) {
2260  case GUARD_CIRC_STATE_COMPLETE:
2261  case GUARD_CIRC_STATE_USABLE_ON_COMPLETION:
2262  new_state = GUARD_CIRC_STATE_COMPLETE;
2263  break;
2264  default:
2265  tor_assert_nonfatal_unreached();
2266  /* Fall through. */
2267  case GUARD_CIRC_STATE_USABLE_IF_NO_BETTER_GUARD:
2268  if (guard->is_primary) {
2269  /* XXXX #20832 -- I don't actually like this logic. It seems to make
2270  * us a little more susceptible to evil-ISP attacks. The mitigations
2271  * I'm thinking of, however, aren't local to this point, so I'll leave
2272  * it alone. */
2273  /* This guard may have become primary by virtue of being confirmed.
2274  * If so, the circuit for it is now complete.
2275  */
2276  new_state = GUARD_CIRC_STATE_COMPLETE;
2277  } else {
2278  new_state = GUARD_CIRC_STATE_WAITING_FOR_BETTER_GUARD;
2279  }
2280  break;
2281  }
2282 
2283  if (! guard->is_primary) {
2284  if (last_time_on_internet + get_internet_likely_down_interval()
2285  < approx_time()) {
2287  }
2288  }
2289 
2290  log_info(LD_GUARD, "Recorded success for %s%sguard %s",
2291  guard->is_primary?"primary ":"",
2292  guard->confirmed_idx>=0?"confirmed ":"",
2293  entry_guard_describe(guard));
2294 
2295  return new_state;
2296 }
2297 
2298 /**
2299  * Helper: Return true iff <b>a</b> has higher priority than <b>b</b>.
2300  */
2301 STATIC int
2302 entry_guard_has_higher_priority(entry_guard_t *a, entry_guard_t *b)
2303 {
2304  tor_assert(a && b);
2305  if (a == b)
2306  return 0;
2307 
2308  /* Confirmed is always better than unconfirmed; lower index better
2309  than higher */
2310  if (a->confirmed_idx < 0) {
2311  if (b->confirmed_idx >= 0)
2312  return 0;
2313  } else {
2314  if (b->confirmed_idx < 0)
2315  return 1;
2316 
2317  /* Lower confirmed_idx is better than higher. */
2318  return (a->confirmed_idx < b->confirmed_idx);
2319  }
2320 
2321  /* If we reach this point, both are unconfirmed. If one is pending, it
2322  * has higher priority. */
2323  if (a->is_pending) {
2324  if (! b->is_pending)
2325  return 1;
2326 
2327  /* Both are pending: earlier last_tried_connect wins. */
2328  return a->last_tried_to_connect < b->last_tried_to_connect;
2329  } else {
2330  if (b->is_pending)
2331  return 0;
2332 
2333  /* Neither is pending: priorities are equal. */
2334  return 0;
2335  }
2336 }
2337 
2338 /** Release all storage held in <b>restriction</b> */
2339 STATIC void
2340 entry_guard_restriction_free_(entry_guard_restriction_t *rst)
2341 {
2342  tor_free(rst);
2343 }
2344 
2345 /**
2346  * Release all storage held in <b>state</b>.
2347  */
2348 void
2349 circuit_guard_state_free_(circuit_guard_state_t *state)
2350 {
2351  if (!state)
2352  return;
2353  entry_guard_restriction_free(state->restrictions);
2354  entry_guard_handle_free(state->guard);
2355  tor_free(state);
2356 }
2357 
2358 /** Allocate and return a new circuit_guard_state_t to track the result
2359  * of using <b>guard</b> for a given operation. */
2360 MOCK_IMPL(STATIC circuit_guard_state_t *,
2361 circuit_guard_state_new,(entry_guard_t *guard, unsigned state,
2362  entry_guard_restriction_t *rst))
2363 {
2364  circuit_guard_state_t *result;
2365 
2366  result = tor_malloc_zero(sizeof(circuit_guard_state_t));
2367  result->guard = entry_guard_handle_new(guard);
2368  result->state = state;
2369  result->state_set_at = approx_time();
2370  result->restrictions = rst;
2371 
2372  return result;
2373 }
2374 
2375 /**
2376  * Pick a suitable entry guard for a circuit in, and place that guard
2377  * in *<b>chosen_node_out</b>. Set *<b>guard_state_out</b> to an opaque
2378  * state object that will record whether the circuit is ready to be used
2379  * or not. Return 0 on success; on failure, return -1.
2380  *
2381  * If a restriction is provided in <b>rst</b>, do not return any guards that
2382  * violate it, and remember that restriction in <b>guard_state_out</b> for
2383  * later use. (Takes ownership of the <b>rst</b> object.)
2384  */
2385 int
2386 entry_guard_pick_for_circuit(guard_selection_t *gs,
2387  guard_usage_t usage,
2388  entry_guard_restriction_t *rst,
2389  const node_t **chosen_node_out,
2390  circuit_guard_state_t **guard_state_out)
2391 {
2392  tor_assert(gs);
2393  tor_assert(chosen_node_out);
2394  tor_assert(guard_state_out);
2395  *chosen_node_out = NULL;
2396  *guard_state_out = NULL;
2397 
2398  unsigned state = 0;
2399  entry_guard_t *guard =
2400  select_entry_guard_for_circuit(gs, usage, rst, &state);
2401  if (! guard)
2402  goto fail;
2403  if (BUG(state == 0))
2404  goto fail;
2405  const node_t *node = node_get_by_id(guard->identity);
2406  // XXXX #20827 check Ed ID.
2407  if (! node)
2408  goto fail;
2409  if (BUG(usage != GUARD_USAGE_DIRGUARD &&
2410  !node_has_preferred_descriptor(node, 1)))
2411  goto fail;
2412 
2413  *chosen_node_out = node;
2414  *guard_state_out = circuit_guard_state_new(guard, state, rst);
2415 
2416  return 0;
2417  fail:
2418  entry_guard_restriction_free(rst);
2419  return -1;
2420 }
2421 
2422 /**
2423  * Called by the circuit building module when a circuit has succeeded: informs
2424  * the guards code that the guard in *<b>guard_state_p</b> is working, and
2425  * advances the state of the guard module. On a GUARD_USABLE_NEVER return
2426  * value, the circuit is broken and should not be used. On a GUARD_USABLE_NOW
2427  * return value, the circuit is ready to use. On a GUARD_MAYBE_USABLE_LATER
2428  * return value, the circuit should not be used until we find out whether
2429  * preferred guards will work for us.
2430  */
2431 guard_usable_t
2432 entry_guard_succeeded(circuit_guard_state_t **guard_state_p)
2433 {
2434  if (BUG(*guard_state_p == NULL))
2435  return GUARD_USABLE_NEVER;
2436 
2437  entry_guard_t *guard = entry_guard_handle_get((*guard_state_p)->guard);
2438  if (! guard || BUG(guard->in_selection == NULL))
2439  return GUARD_USABLE_NEVER;
2440 
2441  unsigned newstate =
2442  entry_guards_note_guard_success(guard->in_selection, guard,
2443  (*guard_state_p)->state);
2444 
2445  (*guard_state_p)->state = newstate;
2446  (*guard_state_p)->state_set_at = approx_time();
2447 
2448  if (newstate == GUARD_CIRC_STATE_COMPLETE) {
2449  return GUARD_USABLE_NOW;
2450  } else {
2451  return GUARD_MAYBE_USABLE_LATER;
2452  }
2453 }
2454 
2455 /** Cancel the selection of *<b>guard_state_p</b> without declaring
2456  * success or failure. It is safe to call this function if success or
2457  * failure _has_ already been declared. */
2458 void
2459 entry_guard_cancel(circuit_guard_state_t **guard_state_p)
2460 {
2461  if (BUG(*guard_state_p == NULL))
2462  return;
2463  entry_guard_t *guard = entry_guard_handle_get((*guard_state_p)->guard);
2464  if (! guard)
2465  return;
2466 
2467  /* XXXX prop271 -- last_tried_to_connect_at will be erroneous here, but this
2468  * function will only get called in "bug" cases anyway. */
2469  guard->is_pending = 0;
2470  circuit_guard_state_free(*guard_state_p);
2471  *guard_state_p = NULL;
2472 }
2473 
2474 /**
2475  * Called by the circuit building module when a circuit has failed:
2476  * informs the guards code that the guard in *<b>guard_state_p</b> is
2477  * not working, and advances the state of the guard module.
2478  */
2479 void
2480 entry_guard_failed(circuit_guard_state_t **guard_state_p)
2481 {
2482  if (BUG(*guard_state_p == NULL))
2483  return;
2484 
2485  entry_guard_t *guard = entry_guard_handle_get((*guard_state_p)->guard);
2486  if (! guard || BUG(guard->in_selection == NULL))
2487  return;
2488 
2489  entry_guards_note_guard_failure(guard->in_selection, guard);
2490 
2491  (*guard_state_p)->state = GUARD_CIRC_STATE_DEAD;
2492  (*guard_state_p)->state_set_at = approx_time();
2493 }
2494 
2495 /**
2496  * Run the entry_guard_failed() function on every circuit that is
2497  * pending on <b>chan</b>.
2498  */
2499 void
2500 entry_guard_chan_failed(channel_t *chan)
2501 {
2502  if (!chan)
2503  return;
2504 
2505  smartlist_t *pending = smartlist_new();
2506  circuit_get_all_pending_on_channel(pending, chan);
2507  SMARTLIST_FOREACH_BEGIN(pending, circuit_t *, circ) {
2508  if (!CIRCUIT_IS_ORIGIN(circ))
2509  continue;
2510 
2511  origin_circuit_t *origin_circ = TO_ORIGIN_CIRCUIT(circ);
2512  if (origin_circ->guard_state) {
2513  /* We might have no guard state if we didn't use a guard on this
2514  * circuit (eg it's for a fallback directory). */
2515  entry_guard_failed(&origin_circ->guard_state);
2516  }
2517  } SMARTLIST_FOREACH_END(circ);
2518  smartlist_free(pending);
2519 }
2520 
2521 /**
2522  * Return true iff every primary guard in <b>gs</b> is believed to
2523  * be unreachable.
2524  */
2525 STATIC int
2527 {
2528  tor_assert(gs);
2529  if (!gs->primary_guards_up_to_date)
2531  SMARTLIST_FOREACH_BEGIN(gs->primary_entry_guards, entry_guard_t *, guard) {
2533  if (guard->is_reachable != GUARD_REACHABLE_NO)
2534  return 0;
2535  } SMARTLIST_FOREACH_END(guard);
2536  return 1;
2537 }
2538 
2539 /** Wrapper for entry_guard_has_higher_priority that compares the
2540  * guard-priorities of a pair of circuits. Return 1 if <b>a</b> has higher
2541  * priority than <b>b</b>.
2542  *
2543  * If a restriction is provided in <b>rst</b>, then do not consider
2544  * <b>a</b> to have higher priority if it violates the restriction.
2545  */
2546 static int
2548  const entry_guard_restriction_t *rst,
2549  origin_circuit_t *b)
2550 {
2551  circuit_guard_state_t *state_a = origin_circuit_get_guard_state(a);
2552  circuit_guard_state_t *state_b = origin_circuit_get_guard_state(b);
2553 
2554  tor_assert(state_a);
2555  tor_assert(state_b);
2556 
2557  entry_guard_t *guard_a = entry_guard_handle_get(state_a->guard);
2558  entry_guard_t *guard_b = entry_guard_handle_get(state_b->guard);
2559 
2560  if (! guard_a) {
2561  /* Unknown guard -- never higher priority. */
2562  return 0;
2563  } else if (! guard_b) {
2564  /* Known guard -- higher priority than any unknown guard. */
2565  return 1;
2566  } else if (! entry_guard_obeys_restriction(guard_a, rst)) {
2567  /* Restriction violated; guard_a cannot have higher priority. */
2568  return 0;
2569  } else {
2570  /* Both known -- compare.*/
2571  return entry_guard_has_higher_priority(guard_a, guard_b);
2572  }
2573 }
2574 
2575 /**
2576  * Look at all of the origin_circuit_t * objects in <b>all_circuits_in</b>,
2577  * and see if any of them that were previously not ready to use for
2578  * guard-related reasons are now ready to use. Place those circuits
2579  * in <b>newly_complete_out</b>, and mark them COMPLETE.
2580  *
2581  * Return 1 if we upgraded any circuits, and 0 otherwise.
2582  */
2583 int
2585  const smartlist_t *all_circuits_in,
2586  smartlist_t *newly_complete_out)
2587 {
2588  tor_assert(gs);
2589  tor_assert(all_circuits_in);
2590  tor_assert(newly_complete_out);
2591 
2593  /* We only upgrade a waiting circuit if the primary guards are all
2594  * down. */
2595  log_debug(LD_GUARD, "Considered upgrading guard-stalled circuits, "
2596  "but not all primary guards were definitely down.");
2597  return 0;
2598  }
2599 
2600  int n_waiting = 0;
2601  int n_complete = 0;
2602  int n_complete_blocking = 0;
2603  origin_circuit_t *best_waiting_circuit = NULL;
2604  smartlist_t *all_circuits = smartlist_new();
2605  SMARTLIST_FOREACH_BEGIN(all_circuits_in, origin_circuit_t *, circ) {
2606  // We filter out circuits that aren't ours, or which we can't
2607  // reason about.
2608  circuit_guard_state_t *state = origin_circuit_get_guard_state(circ);
2609  if (state == NULL)
2610  continue;
2611  entry_guard_t *guard = entry_guard_handle_get(state->guard);
2612  if (!guard || guard->in_selection != gs)
2613  continue;
2614  if (TO_CIRCUIT(circ)->marked_for_close) {
2615  /* Don't consider any marked for close circuits. */
2616  continue;
2617  }
2618 
2619  smartlist_add(all_circuits, circ);
2620  } SMARTLIST_FOREACH_END(circ);
2621 
2622  SMARTLIST_FOREACH_BEGIN(all_circuits, origin_circuit_t *, circ) {
2623  circuit_guard_state_t *state = origin_circuit_get_guard_state(circ);
2624  if (BUG(state == NULL))
2625  continue;
2626 
2627  if (state->state == GUARD_CIRC_STATE_WAITING_FOR_BETTER_GUARD) {
2628  ++n_waiting;
2629  if (! best_waiting_circuit ||
2630  circ_state_has_higher_priority(circ, NULL, best_waiting_circuit)) {
2631  best_waiting_circuit = circ;
2632  }
2633  }
2634  } SMARTLIST_FOREACH_END(circ);
2635 
2636  if (! best_waiting_circuit) {
2637  log_debug(LD_GUARD, "Considered upgrading guard-stalled circuits, "
2638  "but didn't find any.");
2639  goto no_change;
2640  }
2641 
2642  /* We'll need to keep track of what restrictions were used when picking this
2643  * circuit, so that we don't allow any circuit without those restrictions to
2644  * block it. */
2645  const entry_guard_restriction_t *rst_on_best_waiting =
2646  origin_circuit_get_guard_state(best_waiting_circuit)->restrictions;
2647 
2648  /* First look at the complete circuits: Do any block this circuit? */
2649  SMARTLIST_FOREACH_BEGIN(all_circuits, origin_circuit_t *, circ) {
2650  /* "C2 "blocks" C1 if:
2651  * C2 obeys all the restrictions that C1 had to obey, AND
2652  * C2 has higher priority than C1, AND
2653  * Either C2 is <complete>, or C2 is <waiting_for_better_guard>,
2654  or C2 has been <usable_if_no_better_guard> for no more than
2655  {NONPRIMARY_GUARD_CONNECT_TIMEOUT} seconds."
2656  */
2657  circuit_guard_state_t *state = origin_circuit_get_guard_state(circ);
2658  if BUG((state == NULL))
2659  continue;
2660  if (state->state != GUARD_CIRC_STATE_COMPLETE)
2661  continue;
2662  ++n_complete;
2663  if (circ_state_has_higher_priority(circ, rst_on_best_waiting,
2664  best_waiting_circuit))
2665  ++n_complete_blocking;
2666  } SMARTLIST_FOREACH_END(circ);
2667 
2668  if (n_complete_blocking) {
2669  log_debug(LD_GUARD, "Considered upgrading guard-stalled circuits: found "
2670  "%d complete and %d guard-stalled. At least one complete "
2671  "circuit had higher priority, so not upgrading.",
2672  n_complete, n_waiting);
2673  goto no_change;
2674  }
2675 
2676  /* " * If any circuit C1 is <waiting_for_better_guard>, AND:
2677  * All primary guards have reachable status of <no>.
2678  * There is no circuit C2 that "blocks" C1.
2679  Then, upgrade C1 to <complete>.""
2680  */
2681  int n_blockers_found = 0;
2682  const time_t state_set_at_cutoff =
2684  SMARTLIST_FOREACH_BEGIN(all_circuits, origin_circuit_t *, circ) {
2685  circuit_guard_state_t *state = origin_circuit_get_guard_state(circ);
2686  if (BUG(state == NULL))
2687  continue;
2688  if (state->state != GUARD_CIRC_STATE_USABLE_IF_NO_BETTER_GUARD)
2689  continue;
2690  if (state->state_set_at <= state_set_at_cutoff)
2691  continue;
2692  if (circ_state_has_higher_priority(circ, rst_on_best_waiting,
2693  best_waiting_circuit))
2694  ++n_blockers_found;
2695  } SMARTLIST_FOREACH_END(circ);
2696 
2697  if (n_blockers_found) {
2698  log_debug(LD_GUARD, "Considered upgrading guard-stalled circuits: found "
2699  "%d guard-stalled, but %d pending circuit(s) had higher "
2700  "guard priority, so not upgrading.",
2701  n_waiting, n_blockers_found);
2702  goto no_change;
2703  }
2704 
2705  /* Okay. We have a best waiting circuit, and we aren't waiting for
2706  anything better. Add all circuits with that priority to the
2707  list, and call them COMPLETE. */
2708  int n_succeeded = 0;
2709  SMARTLIST_FOREACH_BEGIN(all_circuits, origin_circuit_t *, circ) {
2710  circuit_guard_state_t *state = origin_circuit_get_guard_state(circ);
2711  if (BUG(state == NULL))
2712  continue;
2713  if (circ != best_waiting_circuit && rst_on_best_waiting) {
2714  /* Can't upgrade other circ with same priority as best; might
2715  be blocked. */
2716  continue;
2717  }
2718  if (state->state != GUARD_CIRC_STATE_WAITING_FOR_BETTER_GUARD)
2719  continue;
2720  if (circ_state_has_higher_priority(best_waiting_circuit, NULL, circ))
2721  continue;
2722 
2723  state->state = GUARD_CIRC_STATE_COMPLETE;
2724  state->state_set_at = approx_time();
2725  smartlist_add(newly_complete_out, circ);
2726  ++n_succeeded;
2727  } SMARTLIST_FOREACH_END(circ);
2728 
2729  log_info(LD_GUARD, "Considered upgrading guard-stalled circuits: found "
2730  "%d guard-stalled, %d complete. %d of the guard-stalled "
2731  "circuit(s) had high enough priority to upgrade.",
2732  n_waiting, n_complete, n_succeeded);
2733 
2734  tor_assert_nonfatal(n_succeeded >= 1);
2735  smartlist_free(all_circuits);
2736  return 1;
2737 
2738  no_change:
2739  smartlist_free(all_circuits);
2740  return 0;
2741 }
2742 
2743 /**
2744  * Return true iff the circuit whose state is <b>guard_state</b> should
2745  * expire.
2746  */
2747 int
2748 entry_guard_state_should_expire(circuit_guard_state_t *guard_state)
2749 {
2750  if (guard_state == NULL)
2751  return 0;
2752  const time_t expire_if_waiting_since =
2754  return (guard_state->state == GUARD_CIRC_STATE_WAITING_FOR_BETTER_GUARD
2755  && guard_state->state_set_at < expire_if_waiting_since);
2756 }
2757 
2758 /**
2759  * Update all derived pieces of the guard selection state in <b>gs</b>.
2760  * Return true iff we should stop using all previously generated circuits.
2761  */
2762 int
2763 entry_guards_update_all(guard_selection_t *gs)
2764 {
2769  return 0;
2770 }
2771 
2772 /**
2773  * Return a newly allocated string for encoding the persistent parts of
2774  * <b>guard</b> to the state file.
2775  */
2776 STATIC char *
2777 entry_guard_encode_for_state(entry_guard_t *guard)
2778 {
2779  /*
2780  * The meta-format we use is K=V K=V K=V... where K can be any
2781  * characters excepts space and =, and V can be any characters except
2782  * space. The order of entries is not allowed to matter.
2783  * Unrecognized K=V entries are persisted; recognized but erroneous
2784  * entries are corrected.
2785  */
2786 
2787  smartlist_t *result = smartlist_new();
2788  char tbuf[ISO_TIME_LEN+1];
2789 
2790  tor_assert(guard);
2791 
2792  smartlist_add_asprintf(result, "in=%s", guard->selection_name);
2793  smartlist_add_asprintf(result, "rsa_id=%s",
2794  hex_str(guard->identity, DIGEST_LEN));
2795  if (guard->bridge_addr) {
2796  smartlist_add_asprintf(result, "bridge_addr=%s:%d",
2797  fmt_and_decorate_addr(&guard->bridge_addr->addr),
2798  guard->bridge_addr->port);
2799  }
2800  if (strlen(guard->nickname) && is_legal_nickname(guard->nickname)) {
2801  smartlist_add_asprintf(result, "nickname=%s", guard->nickname);
2802  }
2803 
2804  format_iso_time_nospace(tbuf, guard->sampled_on_date);
2805  smartlist_add_asprintf(result, "sampled_on=%s", tbuf);
2806 
2807  if (guard->sampled_by_version) {
2808  smartlist_add_asprintf(result, "sampled_by=%s",
2809  guard->sampled_by_version);
2810  }
2811 
2812  if (guard->unlisted_since_date > 0) {
2813  format_iso_time_nospace(tbuf, guard->unlisted_since_date);
2814  smartlist_add_asprintf(result, "unlisted_since=%s", tbuf);
2815  }
2816 
2817  smartlist_add_asprintf(result, "listed=%d",
2818  (int)guard->currently_listed);
2819 
2820  if (guard->confirmed_idx >= 0) {
2821  format_iso_time_nospace(tbuf, guard->confirmed_on_date);
2822  smartlist_add_asprintf(result, "confirmed_on=%s", tbuf);
2823 
2824  smartlist_add_asprintf(result, "confirmed_idx=%d", guard->confirmed_idx);
2825  }
2826 
2827  const double EPSILON = 1.0e-6;
2828 
2829  /* Make a copy of the pathbias object, since we will want to update
2830  some of them */
2831  guard_pathbias_t *pb = tor_memdup(&guard->pb, sizeof(*pb));
2834 
2835  #define PB_FIELD(field) do { \
2836  if (pb->field >= EPSILON) { \
2837  smartlist_add_asprintf(result, "pb_" #field "=%f", pb->field); \
2838  } \
2839  } while (0)
2840  PB_FIELD(use_attempts);
2841  PB_FIELD(use_successes);
2842  PB_FIELD(circ_attempts);
2843  PB_FIELD(circ_successes);
2844  PB_FIELD(successful_circuits_closed);
2845  PB_FIELD(collapsed_circuits);
2846  PB_FIELD(unusable_circuits);
2847  PB_FIELD(timeouts);
2848  tor_free(pb);
2849 #undef PB_FIELD
2850 
2851  if (guard->extra_state_fields)
2852  smartlist_add_strdup(result, guard->extra_state_fields);
2853 
2854  char *joined = smartlist_join_strings(result, " ", 0, NULL);
2855  SMARTLIST_FOREACH(result, char *, cp, tor_free(cp));
2856  smartlist_free(result);
2857 
2858  return joined;
2859 }
2860 
2861 /**
2862  * Given a string generated by entry_guard_encode_for_state(), parse it
2863  * (if possible) and return an entry_guard_t object for it. Return NULL
2864  * on complete failure.
2865  */
2866 STATIC entry_guard_t *
2868 {
2869  /* Unrecognized entries get put in here. */
2870  smartlist_t *extra = smartlist_new();
2871 
2872  /* These fields get parsed from the string. */
2873  char *in = NULL;
2874  char *rsa_id = NULL;
2875  char *nickname = NULL;
2876  char *sampled_on = NULL;
2877  char *sampled_by = NULL;
2878  char *unlisted_since = NULL;
2879  char *listed = NULL;
2880  char *confirmed_on = NULL;
2881  char *confirmed_idx = NULL;
2882  char *bridge_addr = NULL;
2883 
2884  // pathbias
2885  char *pb_use_attempts = NULL;
2886  char *pb_use_successes = NULL;
2887  char *pb_circ_attempts = NULL;
2888  char *pb_circ_successes = NULL;
2889  char *pb_successful_circuits_closed = NULL;
2890  char *pb_collapsed_circuits = NULL;
2891  char *pb_unusable_circuits = NULL;
2892  char *pb_timeouts = NULL;
2893 
2894  /* Split up the entries. Put the ones we know about in strings and the
2895  * rest in "extra". */
2896  {
2897  smartlist_t *entries = smartlist_new();
2898 
2899  strmap_t *vals = strmap_new(); // Maps keyword to location
2900 #define FIELD(f) \
2901  strmap_set(vals, #f, &f);
2902  FIELD(in);
2903  FIELD(rsa_id);
2904  FIELD(nickname);
2905  FIELD(sampled_on);
2906  FIELD(sampled_by);
2907  FIELD(unlisted_since);
2908  FIELD(listed);
2909  FIELD(confirmed_on);
2910  FIELD(confirmed_idx);
2911  FIELD(bridge_addr);
2912  FIELD(pb_use_attempts);
2913  FIELD(pb_use_successes);
2914  FIELD(pb_circ_attempts);
2915  FIELD(pb_circ_successes);
2916  FIELD(pb_successful_circuits_closed);
2917  FIELD(pb_collapsed_circuits);
2918  FIELD(pb_unusable_circuits);
2919  FIELD(pb_timeouts);
2920 #undef FIELD
2921 
2922  smartlist_split_string(entries, s, " ",
2923  SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
2924 
2925  SMARTLIST_FOREACH_BEGIN(entries, char *, entry) {
2926  const char *eq = strchr(entry, '=');
2927  if (!eq) {
2928  smartlist_add(extra, entry);
2929  continue;
2930  }
2931  char *key = tor_strndup(entry, eq-entry);
2932  char **target = strmap_get(vals, key);
2933  if (target == NULL || *target != NULL) {
2934  /* unrecognized or already set */
2935  smartlist_add(extra, entry);
2936  tor_free(key);
2937  continue;
2938  }
2939 
2940  *target = tor_strdup(eq+1);
2941  tor_free(key);
2942  tor_free(entry);
2943  } SMARTLIST_FOREACH_END(entry);
2944 
2945  smartlist_free(entries);
2946  strmap_free(vals, NULL);
2947  }
2948 
2949  entry_guard_t *guard = tor_malloc_zero(sizeof(entry_guard_t));
2950  guard->is_persistent = 1;
2951 
2952  if (in == NULL) {
2953  log_warn(LD_CIRC, "Guard missing 'in' field");
2954  goto err;
2955  }
2956 
2957  guard->selection_name = in;
2958  in = NULL;
2959 
2960  if (rsa_id == NULL) {
2961  log_warn(LD_CIRC, "Guard missing RSA ID field");
2962  goto err;
2963  }
2964 
2965  /* Process the identity and nickname. */
2966  if (base16_decode(guard->identity, sizeof(guard->identity),
2967  rsa_id, strlen(rsa_id)) != DIGEST_LEN) {
2968  log_warn(LD_CIRC, "Unable to decode guard identity %s", escaped(rsa_id));
2969  goto err;
2970  }
2971 
2972  if (nickname) {
2973  strlcpy(guard->nickname, nickname, sizeof(guard->nickname));
2974  } else {
2975  guard->nickname[0]='$';
2976  base16_encode(guard->nickname+1, sizeof(guard->nickname)-1,
2977  guard->identity, DIGEST_LEN);
2978  }
2979 
2980  if (bridge_addr) {
2981  tor_addr_port_t res;
2982  memset(&res, 0, sizeof(res));
2983  int r = tor_addr_port_parse(LOG_WARN, bridge_addr,
2984  &res.addr, &res.port, -1);
2985  if (r == 0)
2986  guard->bridge_addr = tor_memdup(&res, sizeof(res));
2987  /* On error, we already warned. */
2988  }
2989 
2990  /* Process the various time fields. */
2991 
2992 #define HANDLE_TIME(field) do { \
2993  if (field) { \
2994  int r = parse_iso_time_nospace(field, &field ## _time); \
2995  if (r < 0) { \
2996  log_warn(LD_CIRC, "Unable to parse %s %s from guard", \
2997  #field, escaped(field)); \
2998  field##_time = -1; \
2999  } \
3000  } \
3001  } while (0)
3002 
3003  time_t sampled_on_time = 0;
3004  time_t unlisted_since_time = 0;
3005  time_t confirmed_on_time = 0;
3006 
3007  HANDLE_TIME(sampled_on);
3008  HANDLE_TIME(unlisted_since);
3009  HANDLE_TIME(confirmed_on);
3010 
3011  if (sampled_on_time <= 0)
3012  sampled_on_time = approx_time();
3013  if (unlisted_since_time < 0)
3014  unlisted_since_time = 0;
3015  if (confirmed_on_time < 0)
3016  confirmed_on_time = 0;
3017 
3018  #undef HANDLE_TIME
3019 
3020  guard->sampled_on_date = sampled_on_time;
3021  guard->unlisted_since_date = unlisted_since_time;
3022  guard->confirmed_on_date = confirmed_on_time;
3023 
3024  /* Take sampled_by_version verbatim. */
3025  guard->sampled_by_version = sampled_by;
3026  sampled_by = NULL; /* prevent free */
3027 
3028  /* Listed is a boolean */
3029  if (listed && strcmp(listed, "0"))
3030  guard->currently_listed = 1;
3031 
3032  /* The index is a nonnegative integer. */
3033  guard->confirmed_idx = -1;
3034  if (confirmed_idx) {
3035  int ok=1;
3036  long idx = tor_parse_long(confirmed_idx, 10, 0, INT_MAX, &ok, NULL);
3037  if (! ok) {
3038  log_warn(LD_GUARD, "Guard has invalid confirmed_idx %s",
3039  escaped(confirmed_idx));
3040  } else {
3041  guard->confirmed_idx = (int)idx;
3042  }
3043  }
3044 
3045  /* Anything we didn't recognize gets crammed together */
3046  if (smartlist_len(extra) > 0) {
3047  guard->extra_state_fields = smartlist_join_strings(extra, " ", 0, NULL);
3048  }
3049 
3050  /* initialize non-persistent fields */
3051  guard->is_reachable = GUARD_REACHABLE_MAYBE;
3052 
3053 #define PB_FIELD(field) \
3054  do { \
3055  if (pb_ ## field) { \
3056  int ok = 1; \
3057  double r = tor_parse_double(pb_ ## field, 0.0, 1e9, &ok, NULL); \
3058  if (! ok) { \
3059  log_warn(LD_CIRC, "Guard has invalid pb_%s %s", \
3060  #field, pb_ ## field); \
3061  } else { \
3062  guard->pb.field = r; \
3063  } \
3064  } \
3065  } while (0)
3066  PB_FIELD(use_attempts);
3067  PB_FIELD(use_successes);
3068  PB_FIELD(circ_attempts);
3069  PB_FIELD(circ_successes);
3070  PB_FIELD(successful_circuits_closed);
3071  PB_FIELD(collapsed_circuits);
3072  PB_FIELD(unusable_circuits);
3073  PB_FIELD(timeouts);
3074 #undef PB_FIELD
3075 
3078 
3079  /* We update everything on this guard later, after we've parsed
3080  * everything. */
3081 
3082  goto done;
3083 
3084  err:
3085  // only consider it an error if the guard state was totally unparseable.
3086  entry_guard_free(guard);
3087  guard = NULL;
3088 
3089  done:
3090  tor_free(in);
3091  tor_free(rsa_id);
3092  tor_free(nickname);
3093  tor_free(sampled_on);
3094  tor_free(sampled_by);
3095  tor_free(unlisted_since);
3096  tor_free(listed);
3097  tor_free(confirmed_on);
3098  tor_free(confirmed_idx);
3099  tor_free(bridge_addr);
3100  tor_free(pb_use_attempts);
3101  tor_free(pb_use_successes);
3102  tor_free(pb_circ_attempts);
3103  tor_free(pb_circ_successes);
3104  tor_free(pb_successful_circuits_closed);
3105  tor_free(pb_collapsed_circuits);
3106  tor_free(pb_unusable_circuits);
3107  tor_free(pb_timeouts);
3108 
3109  SMARTLIST_FOREACH(extra, char *, cp, tor_free(cp));
3110  smartlist_free(extra);
3111 
3112  return guard;
3113 }
3114 
3115 /**
3116  * Replace the Guards entries in <b>state</b> with a list of all our sampled
3117  * guards.
3118  */
3119 static void
3121 {
3122  if (!guard_contexts)
3123  return;
3124  config_line_t *lines = NULL;
3125  config_line_t **nextline = &lines;
3126 
3127  SMARTLIST_FOREACH_BEGIN(guard_contexts, guard_selection_t *, gs) {
3128  SMARTLIST_FOREACH_BEGIN(gs->sampled_entry_guards, entry_guard_t *, guard) {
3129  if (guard->is_persistent == 0)
3130  continue;
3131  *nextline = tor_malloc_zero(sizeof(config_line_t));
3132  (*nextline)->key = tor_strdup("Guard");
3133  (*nextline)->value = entry_guard_encode_for_state(guard);
3134  nextline = &(*nextline)->next;
3135  } SMARTLIST_FOREACH_END(guard);
3136  } SMARTLIST_FOREACH_END(gs);
3137 
3138  config_free_lines(state->Guard);
3139  state->Guard = lines;
3140 }
3141 
3142 /**
3143  * Replace our sampled guards from the Guards entries in <b>state</b>. Return 0
3144  * on success, -1 on failure. (If <b>set</b> is true, replace nothing -- only
3145  * check whether replacing would work.)
3146  */
3147 static int
3149 {
3150  const config_line_t *line = state->Guard;
3151  int n_errors = 0;
3152 
3153  if (!guard_contexts)
3155 
3156  /* Wipe all our existing guard info. (we shouldn't have any, but
3157  * let's be safe.) */
3158  if (set) {
3159  SMARTLIST_FOREACH_BEGIN(guard_contexts, guard_selection_t *, gs) {
3160  guard_selection_free(gs);
3161  if (curr_guard_context == gs)
3162  curr_guard_context = NULL;
3164  } SMARTLIST_FOREACH_END(gs);
3165  }
3166 
3167  for ( ; line != NULL; line = line->next) {
3168  entry_guard_t *guard = entry_guard_parse_from_state(line->value);
3169  if (guard == NULL) {
3170  ++n_errors;
3171  continue;
3172  }
3173  tor_assert(guard->selection_name);
3174  if (!strcmp(guard->selection_name, "legacy")) {
3175  ++n_errors;
3176  entry_guard_free(guard);
3177  continue;
3178  }
3179 
3180  if (set) {
3181  guard_selection_t *gs;
3182  gs = get_guard_selection_by_name(guard->selection_name,
3183  GS_TYPE_INFER, 1);
3184  tor_assert(gs);
3185  smartlist_add(gs->sampled_entry_guards, guard);
3186  guard->in_selection = gs;
3187  } else {
3188  entry_guard_free(guard);
3189  }
3190  }
3191 
3192  if (set) {
3193  SMARTLIST_FOREACH_BEGIN(guard_contexts, guard_selection_t *, gs) {
3195  } SMARTLIST_FOREACH_END(gs);
3196  }
3197  return n_errors ? -1 : 0;
3198 }
3199 
3200 /** If <b>digest</b> matches the identity of any node in the
3201  * entry_guards list for the provided guard selection state,
3202  return that node. Else return NULL. */
3203 entry_guard_t *
3205  const char *digest)
3206 {
3207  return get_sampled_guard_with_id(gs, (const uint8_t*)digest);
3208 }
3209 
3210 /** Return the node_t associated with a single entry_guard_t. May
3211  * return NULL if the guard is not currently in the consensus. */
3212 const node_t *
3213 entry_guard_find_node(const entry_guard_t *guard)
3214 {
3215  tor_assert(guard);
3216  return node_get_by_id(guard->identity);
3217 }
3218 
3219 /** If <b>digest</b> matches the identity of any node in the
3220  * entry_guards list for the default guard selection state,
3221  return that node. Else return NULL. */
3222 entry_guard_t *
3223 entry_guard_get_by_id_digest(const char *digest)
3224 {
3226  get_guard_selection_info(), digest);
3227 }
3228 
3229 /** We are about to connect to bridge with identity <b>digest</b> to fetch its
3230  * descriptor. Create a new guard state for this connection and return it. */
3231 circuit_guard_state_t *
3233 {
3234  circuit_guard_state_t *guard_state = NULL;
3235  entry_guard_t *guard = NULL;
3236 
3238  get_guard_selection_info(), digest);
3239  if (!guard) {
3240  return NULL;
3241  }
3242 
3243  /* Update the guard last_tried_to_connect time since it's checked by the
3244  * guard susbsystem. */
3245  guard->last_tried_to_connect = approx_time();
3246 
3247  /* Create the guard state */
3248  guard_state = circuit_guard_state_new(guard,
3249  GUARD_CIRC_STATE_USABLE_ON_COMPLETION,
3250  NULL);
3251 
3252  return guard_state;
3253 }
3254 
3255 /** Release all storage held by <b>e</b>. */
3256 STATIC void
3257 entry_guard_free_(entry_guard_t *e)
3258 {
3259  if (!e)
3260  return;
3261  entry_guard_handles_clear(e);
3262  tor_free(e->sampled_by_version);
3263  tor_free(e->extra_state_fields);
3264  tor_free(e->selection_name);
3265  tor_free(e->bridge_addr);
3266  tor_free(e);
3267 }
3268 
3269 /** Return 0 if we're fine adding arbitrary routers out of the
3270  * directory to our entry guard list, or return 1 if we have a
3271  * list already and we must stick to it.
3272  */
3273 int
3275 {
3276  // XXXX #21425 look at the current selection.
3277  if (options->EntryNodes)
3278  return 1;
3279  if (options->UseBridges)
3280  return 1;
3281  return 0;
3282 }
3283 
3284 /** Return the number of bridges that have descriptors that are marked with
3285  * purpose 'bridge' and are running. If use_maybe_reachable is
3286  * true, include bridges that might be reachable in the count.
3287  * Otherwise, if it is false, only include bridges that have recently been
3288  * found running in the count.
3289  *
3290  * We use this function to decide if we're ready to start building
3291  * circuits through our bridges, or if we need to wait until the
3292  * directory "server/authority" requests finish. */
3293 MOCK_IMPL(int,
3294 num_bridges_usable,(int use_maybe_reachable))
3295 {
3296  int n_options = 0;
3297 
3298  if (BUG(!get_options()->UseBridges)) {
3299  return 0;
3300  }
3301  guard_selection_t *gs = get_guard_selection_info();
3302  if (BUG(gs->type != GS_TYPE_BRIDGE)) {
3303  return 0;
3304  }
3305 
3306  SMARTLIST_FOREACH_BEGIN(gs->sampled_entry_guards, entry_guard_t *, guard) {
3307  /* Not a bridge, or not one we are configured to be able to use. */
3308  if (! guard->is_filtered_guard)
3309  continue;
3310  /* Definitely not usable */
3311  if (guard->is_reachable == GUARD_REACHABLE_NO)
3312  continue;
3313  /* If we want to be really sure the bridges will work, skip maybes */
3314  if (!use_maybe_reachable && guard->is_reachable == GUARD_REACHABLE_MAYBE)
3315  continue;
3316  if (tor_digest_is_zero(guard->identity))
3317  continue;
3318  const node_t *node = node_get_by_id(guard->identity);
3319  if (node && node->ri)
3320  ++n_options;
3321  } SMARTLIST_FOREACH_END(guard);
3322 
3323  return n_options;
3324 }
3325 
3326 /** Check the pathbias use success count of <b>node</b> and disable it if it
3327  * goes over our thresholds. */
3328 static void
3330 {
3331  const or_options_t *options = get_options();
3332  const double EPSILON = 1.0e-9;
3333 
3334  /* Note: We rely on the < comparison here to allow us to set a 0
3335  * rate and disable the feature entirely. If refactoring, don't
3336  * change to <= */
3337  if (node->pb.use_attempts > EPSILON &&
3338  pathbias_get_use_success_count(node)/node->pb.use_attempts
3339  < pathbias_get_extreme_use_rate(options) &&
3340  pathbias_get_dropguards(options)) {
3341  node->pb.path_bias_disabled = 1;
3342  log_info(LD_GENERAL,
3343  "Path use bias is too high (%f/%f); disabling node %s",
3344  node->pb.circ_successes, node->pb.circ_attempts,
3345  node->nickname);
3346  }
3347 }
3348 
3349 /** Check the pathbias close count of <b>node</b> and disable it if it goes
3350  * over our thresholds. */
3351 static void
3353 {
3354  const or_options_t *options = get_options();
3355  const double EPSILON = 1.0e-9;
3356 
3357  /* Note: We rely on the < comparison here to allow us to set a 0
3358  * rate and disable the feature entirely. If refactoring, don't
3359  * change to <= */
3360  if (node->pb.circ_attempts > EPSILON &&
3361  pathbias_get_close_success_count(node)/node->pb.circ_attempts
3362  < pathbias_get_extreme_rate(options) &&
3363  pathbias_get_dropguards(options)) {
3364  node->pb.path_bias_disabled = 1;
3365  log_info(LD_GENERAL,
3366  "Path bias is too high (%f/%f); disabling node %s",
3367  node->pb.circ_successes, node->pb.circ_attempts,
3368  node->nickname);
3369  }
3370 }
3371 
3372 /** Parse <b>state</b> and learn about the entry guards it describes.
3373  * If <b>set</b> is true, and there are no errors, replace the guard
3374  * list in the default guard selection context with what we find.
3375  * On success, return 0. On failure, alloc into *<b>msg</b> a string
3376  * describing the error, and return -1.
3377  */
3378 int
3379 entry_guards_parse_state(or_state_t *state, int set, char **msg)
3380 {
3381  entry_guards_dirty = 0;
3382  int r1 = entry_guards_load_guards_from_state(state, set);
3383  entry_guards_dirty = 0;
3384 
3385  if (r1 < 0) {
3386  if (msg && *msg == NULL) {
3387  *msg = tor_strdup("parsing error");
3388  }
3389  return -1;
3390  }
3391  return 0;
3392 }
3393 
3394 /** How long will we let a change in our guard nodes stay un-saved
3395  * when we are trying to avoid disk writes? */
3396 #define SLOW_GUARD_STATE_FLUSH_TIME 600
3397 /** How long will we let a change in our guard nodes stay un-saved
3398  * when we are not trying to avoid disk writes? */
3399 #define FAST_GUARD_STATE_FLUSH_TIME 30
3400 
3401 /** Our list of entry guards has changed for a particular guard selection
3402  * context, or some element of one of our entry guards has changed for one.
3403  * Write the changes to disk within the next few minutes.
3404  */
3405 void
3407 {
3408  time_t when;
3409 
3410  tor_assert(gs != NULL);
3411 
3412  entry_guards_dirty = 1;
3413 
3414  if (get_options()->AvoidDiskWrites)
3415  when = time(NULL) + SLOW_GUARD_STATE_FLUSH_TIME;
3416  else
3417  when = time(NULL) + FAST_GUARD_STATE_FLUSH_TIME;
3418 
3419  /* or_state_save() will call entry_guards_update_state() and
3420  entry_guards_update_guards_in_state()
3421  */
3423 }
3424 
3425 /** Our list of entry guards has changed for the default guard selection
3426  * context, or some element of one of our entry guards has changed. Write
3427  * the changes to disk within the next few minutes.
3428  */
3429 void
3431 {
3433 }
3434 
3435 /** If the entry guard info has not changed, do nothing and return.
3436  * Otherwise, free the EntryGuards piece of <b>state</b> and create
3437  * a new one out of the global entry_guards list, and then mark
3438  * <b>state</b> dirty so it will get saved to disk.
3439  */
3440 void
3442 {
3443  entry_guards_dirty = 0;
3444 
3445  // Handles all guard info.
3447 
3448  entry_guards_dirty = 0;
3449 
3450  if (!get_options()->AvoidDiskWrites)
3452  entry_guards_dirty = 0;
3453 }
3454 
3455 /** Return true iff the circuit's guard can succeed that is can be used. */
3456 int
3457 entry_guard_could_succeed(const circuit_guard_state_t *guard_state)
3458 {
3459  if (!guard_state) {
3460  return 0;
3461  }
3462 
3463  entry_guard_t *guard = entry_guard_handle_get(guard_state->guard);
3464  if (!guard || BUG(guard->in_selection == NULL)) {
3465  return 0;
3466  }
3467 
3468  return 1;
3469 }
3470 
3471 /**
3472  * Format a single entry guard in the format expected by the controller.
3473  * Return a newly allocated string.
3474  */
3475 STATIC char *
3477 {
3478  const char *status = NULL;
3479  time_t when = 0;
3480  const node_t *node;
3481  char tbuf[ISO_TIME_LEN+1];
3482  char nbuf[MAX_VERBOSE_NICKNAME_LEN+1];
3483 
3484  /* This is going to be a bit tricky, since the status
3485  * codes weren't really intended for prop271 guards.
3486  *
3487  * XXXX use a more appropriate format for exporting this information
3488  */
3489  if (e->confirmed_idx < 0) {
3490  status = "never-connected";
3491  } else if (! e->currently_listed) {
3492  when = e->unlisted_since_date;
3493  status = "unusable";
3494  } else if (! e->is_filtered_guard) {
3495  status = "unusable";
3496  } else if (e->is_reachable == GUARD_REACHABLE_NO) {
3497  when = e->failing_since;
3498  status = "down";
3499  } else {
3500  status = "up";
3501  }
3502 
3503  node = entry_guard_find_node(e);
3504  if (node) {
3505  node_get_verbose_nickname(node, nbuf);
3506  } else {
3507  nbuf[0] = '$';
3508  base16_encode(nbuf+1, sizeof(nbuf)-1, e->identity, DIGEST_LEN);
3509  /* e->nickname field is not very reliable if we don't know about
3510  * this router any longer; don't include it. */
3511  }
3512 
3513  char *result = NULL;
3514  if (when) {
3515  format_iso_time(tbuf, when);
3516  tor_asprintf(&result, "%s %s %s\n", nbuf, status, tbuf);
3517  } else {
3518  tor_asprintf(&result, "%s %s\n", nbuf, status);
3519  }
3520  return result;
3521 }
3522 
3523 /** If <b>question</b> is the string "entry-guards", then dump
3524  * to *<b>answer</b> a newly allocated string describing all of
3525  * the nodes in the global entry_guards list. See control-spec.txt
3526  * for details.
3527  * For backward compatibility, we also handle the string "helper-nodes".
3528  *
3529  * XXX this should be totally redesigned after prop 271 too, and that's
3530  * going to take some control spec work.
3531  * */
3532 int
3534  const char *question, char **answer,
3535  const char **errmsg)
3536 {
3537  guard_selection_t *gs = get_guard_selection_info();
3538 
3539  tor_assert(gs != NULL);
3540 
3541  (void) conn;
3542  (void) errmsg;
3543 
3544  if (!strcmp(question,"entry-guards") ||
3545  !strcmp(question,"helper-nodes")) {
3546  const smartlist_t *guards;
3547  guards = gs->sampled_entry_guards;
3548 
3549  smartlist_t *sl = smartlist_new();
3550 
3551  SMARTLIST_FOREACH_BEGIN(guards, const entry_guard_t *, e) {
3553  smartlist_add(sl, cp);
3554  } SMARTLIST_FOREACH_END(e);
3555  *answer = smartlist_join_strings(sl, "", 0, NULL);
3556  SMARTLIST_FOREACH(sl, char *, c, tor_free(c));
3557  smartlist_free(sl);
3558  }
3559  return 0;
3560 }
3561 
3562 /* Given the original bandwidth of a guard and its guardfraction,
3563  * calculate how much bandwidth the guard should have as a guard and
3564  * as a non-guard.
3565  *
3566  * Quoting from proposal236:
3567  *
3568  * Let Wpf denote the weight from the 'bandwidth-weights' line a
3569  * client would apply to N for position p if it had the guard
3570  * flag, Wpn the weight if it did not have the guard flag, and B the
3571  * measured bandwidth of N in the consensus. Then instead of choosing
3572  * N for position p proportionally to Wpf*B or Wpn*B, clients should
3573  * choose N proportionally to F*Wpf*B + (1-F)*Wpn*B.
3574  *
3575  * This function fills the <b>guardfraction_bw</b> structure. It sets
3576  * <b>guard_bw</b> to F*B and <b>non_guard_bw</b> to (1-F)*B.
3577  */
3578 void
3579 guard_get_guardfraction_bandwidth(guardfraction_bandwidth_t *guardfraction_bw,
3580  int orig_bandwidth,
3581  uint32_t guardfraction_percentage)
3582 {
3583  double guardfraction_fraction;
3584 
3585  /* Turn the percentage into a fraction. */
3586  tor_assert(guardfraction_percentage <= 100);
3587  guardfraction_fraction = guardfraction_percentage / 100.0;
3588 
3589  long guard_bw = tor_lround(guardfraction_fraction * orig_bandwidth);
3590  tor_assert(guard_bw <= INT_MAX);
3591 
3592  guardfraction_bw->guard_bw = (int) guard_bw;
3593 
3594  guardfraction_bw->non_guard_bw = orig_bandwidth - (int) guard_bw;
3595 }
3596 
3597 /** Helper: Update the status of all entry guards, in whatever algorithm
3598  * is used. Return true if we should stop using all previously generated
3599  * circuits, by calling circuit_mark_all_unused_circs() and
3600  * circuit_mark_all_dirty_circs_as_unusable().
3601  */
3602 int
3604 {
3605  int mark_circuits = 0;
3607  mark_circuits = 1;
3608 
3610 
3612  mark_circuits = 1;
3613 
3614  return mark_circuits;
3615 }
3616 
3617 /** Helper: pick a guard for a circuit, with whatever algorithm is
3618  used. */
3619 const node_t *
3621  uint8_t purpose,
3622  circuit_guard_state_t **guard_state_out)
3623 {
3624  const node_t *r = NULL;
3625  const uint8_t *exit_id = NULL;
3626  entry_guard_restriction_t *rst = NULL;
3627 
3628  /* Only apply restrictions if we have a specific exit node in mind, and only
3629  * if we are not doing vanguard circuits: we don't want to apply guard
3630  * restrictions to vanguard circuits. */
3631  if (state && !circuit_should_use_vanguards(purpose) &&
3632  (exit_id = build_state_get_exit_rsa_id(state))) {
3633  /* We're building to a targeted exit node, so that node can't be
3634  * chosen as our guard for this circuit. Remember that fact in a
3635  * restriction. */
3636  rst = guard_create_exit_restriction(exit_id);
3637  tor_assert(rst);
3638  }
3640  GUARD_USAGE_TRAFFIC,
3641  rst,
3642  &r,
3643  guard_state_out) < 0) {
3644  tor_assert(r == NULL);
3645  }
3646  return r;
3647 }
3648 
3649 /** Remove all currently listed entry guards for a given guard selection
3650  * context. This frees and replaces <b>gs</b>, so don't use <b>gs</b>
3651  * after calling this function. */
3652 void
3654 {
3655  // This function shouldn't exist. XXXX
3656  tor_assert(gs != NULL);
3657  char *old_name = tor_strdup(gs->name);
3658  guard_selection_type_t old_type = gs->type;
3659 
3660  SMARTLIST_FOREACH(gs->sampled_entry_guards, entry_guard_t *, entry, {
3661  control_event_guard(entry->nickname, entry->identity, "DROPPED");
3662  });
3663 
3664  if (gs == curr_guard_context) {
3665  curr_guard_context = NULL;
3666  }
3667 
3669  guard_selection_free(gs);
3670 
3671  gs = get_guard_selection_by_name(old_name, old_type, 1);
3673  tor_free(old_name);
3674 }
3675 
3676 /** Remove all currently listed entry guards, so new ones will be chosen.
3677  *
3678  * XXXX This function shouldn't exist -- it's meant to support the DROPGUARDS
3679  * command, which is deprecated.
3680  */
3681 void
3683 {
3685 }
3686 
3687 /** Helper: pick a directory guard, with whatever algorithm is used. */
3688 const node_t *
3689 guards_choose_dirguard(uint8_t dir_purpose,
3690  circuit_guard_state_t **guard_state_out)
3691 {
3692  const node_t *r = NULL;
3693  entry_guard_restriction_t *rst = NULL;
3694 
3695  /* If we are fetching microdescs, don't query outdated dirservers. */
3696  if (dir_purpose == DIR_PURPOSE_FETCH_MICRODESC) {
3698  }
3699 
3701  GUARD_USAGE_DIRGUARD,
3702  rst,
3703  &r,
3704  guard_state_out) < 0) {
3705  tor_assert(r == NULL);
3706  }
3707  return r;
3708 }
3709 
3710 /**
3711  * If we're running with a constrained guard set, then maybe mark our guards
3712  * usable. Return 1 if we do; 0 if we don't.
3713  */
3714 int
3716 {
3717  if (! entry_list_is_constrained(options))
3718  return 0;
3719 
3721 
3722  return 1;
3723 }
3724 
3725 /**
3726  * Check if we are missing any crucial dirinfo for the guard subsystem to
3727  * work. Return NULL if everything went well, otherwise return a newly
3728  * allocated string with an informative error message. In the latter case, use
3729  * the genreal descriptor information <b>using_mds</b>, <b>num_present</b> and
3730  * <b>num_usable</b> to improve the error message. */
3731 char *
3733  int using_mds,
3734  int num_present, int num_usable)
3735 {
3736  if (!gs->primary_guards_up_to_date)
3738 
3739  char *ret_str = NULL;
3740  int n_missing_descriptors = 0;
3741  int n_considered = 0;
3742  int num_primary_to_check;
3743 
3744  /* We want to check for the descriptor of at least the first two primary
3745  * guards in our list, since these are the guards that we typically use for
3746  * circuits. */
3747  num_primary_to_check = get_n_primary_guards_to_use(GUARD_USAGE_TRAFFIC);
3748  num_primary_to_check++;
3749 
3750  SMARTLIST_FOREACH_BEGIN(gs->primary_entry_guards, entry_guard_t *, guard) {
3752  if (guard->is_reachable == GUARD_REACHABLE_NO)
3753  continue;
3754  n_considered++;
3755  if (!guard_has_descriptor(guard))
3756  n_missing_descriptors++;
3757  if (n_considered >= num_primary_to_check)
3758  break;
3759  } SMARTLIST_FOREACH_END(guard);
3760 
3761  /* If we are not missing any descriptors, return NULL. */
3762  if (!n_missing_descriptors) {
3763  return NULL;
3764  }
3765 
3766  /* otherwise return a helpful error string */
3767  tor_asprintf(&ret_str, "We're missing descriptors for %d/%d of our "
3768  "primary entry guards (total %sdescriptors: %d/%d). "
3769  "That's ok. We will try to fetch missing descriptors soon.",
3770  n_missing_descriptors, num_primary_to_check,
3771  using_mds?"micro":"", num_present, num_usable);
3772 
3773  return ret_str;
3774 }
3775 
3776 /** As guard_selection_have_enough_dir_info_to_build_circuits, but uses
3777  * the default guard selection. */
3778 char *
3780  int num_present, int num_usable)
3781 {
3784  using_mds,
3785  num_present, num_usable);
3786 }
3787 
3788 /** Free one guard selection context */
3789 STATIC void
3790 guard_selection_free_(guard_selection_t *gs)
3791 {
3792  if (!gs) return;
3793 
3794  tor_free(gs->name);
3795 
3796  if (gs->sampled_entry_guards) {
3797  SMARTLIST_FOREACH(gs->sampled_entry_guards, entry_guard_t *, e,
3798  entry_guard_free(e));
3799  smartlist_free(gs->sampled_entry_guards);
3800  gs->sampled_entry_guards = NULL;
3801  }
3802 
3803  smartlist_free(gs->confirmed_entry_guards);
3804  smartlist_free(gs->primary_entry_guards);
3805 
3806  tor_free(gs);
3807 }
3808 
3809 /** Release all storage held by the list of entry guards and related
3810  * memory structs. */
3811 void
3813 {
3814  /* Null out the default */
3815  curr_guard_context = NULL;
3816  /* Free all the guard contexts */
3817  if (guard_contexts != NULL) {
3818  SMARTLIST_FOREACH_BEGIN(guard_contexts, guard_selection_t *, gs) {
3819  guard_selection_free(gs);
3820  } SMARTLIST_FOREACH_END(gs);
3821  smartlist_free(guard_contexts);
3822  guard_contexts = NULL;
3823  }
3825 }
unsigned int is_stable
Definition: node_st.h:67
#define MIN_GUARDS_FOR_MD_RESTRICTION
Definition: entrynodes.c:1570
Header file for circuitstats.c.
static int guard_has_descriptor(const entry_guard_t *guard)
Definition: entrynodes.c:200
Header for statefile.c.
STATIC int get_guard_lifetime(void)
Definition: entrynodes.c:427
void circuit_get_all_pending_on_channel(smartlist_t *out, channel_t *chan)
Definition: circuitlist.c:576
static int compare_guards_by_confirmed_idx(const void **a_, const void **b_)
Definition: entrynodes.c:1788
STATIC double get_max_sample_threshold(void)
Definition: entrynodes.c:372
STATIC guard_selection_type_t guard_selection_infer_type(guard_selection_type_t type, const char *name)
Definition: entrynodes.c:213
void circuit_guard_state_free_(circuit_guard_state_t *state)
Definition: entrynodes.c:2349
int should_apply_guardfraction(const networkstatus_t *ns)
Definition: entrynodes.c:180
Header for confline.c.
static entry_guard_t * select_confirmed_guard_for_circuit(guard_selection_t *gs, guard_usage_t usage, const entry_guard_restriction_t *rst, unsigned *state_out)
Definition: entrynodes.c:2088
unsigned int is_possible_guard
Definition: node_st.h:68
void entry_guard_learned_bridge_identity(const tor_addr_port_t *addrport, const uint8_t *rsa_id_digest)
Definition: entrynodes.c:950
Header file for circuitbuild.c.
int update_guard_selection_choice(const or_options_t *options)
Definition: entrynodes.c:721
Common functions for using (pseudo-)random number generators.
#define SMARTLIST_DEL_CURRENT_KEEPORDER(sl, var)
unsigned int is_valid
Definition: node_st.h:64
Definition: node_st.h:33
static void entry_guards_update_guards_in_state(or_state_t *state)
Definition: entrynodes.c:3120
static void create_initial_guard_context(void)
Definition: entrynodes.c:281
struct config_line_t * Guard
Definition: or_state_st.h:45
#define SMARTLIST_FOREACH_BEGIN(sl, type, var)
int32_t networkstatus_get_param(const networkstatus_t *ns, const char *param_name, int32_t default_val, int32_t min_val, int32_t max_val)
void entry_guard_cancel(circuit_guard_state_t **guard_state_p)
Definition: entrynodes.c:2459
int routerset_contains_node(const routerset_t *set, const node_t *node)
Definition: routerset.c:338
#define MOCK_IMPL(rv, funcname, arglist)
Definition: testsupport.h:133
STATIC void make_guard_confirmed(guard_selection_t *gs, entry_guard_t *guard)
Definition: entrynodes.c:1835
static bridge_info_t * get_bridge_info_for_guard(const entry_guard_t *guard)
Definition: entrynodes.c:813
void remove_all_entry_guards_for_guard_selection(guard_selection_t *gs)
Definition: entrynodes.c:3653
Header file for node_select.c.
void format_local_iso_time(char *buf, time_t t)
Definition: time_fmt.c:285
STATIC void entry_guard_consider_retry(entry_guard_t *guard)
Definition: entrynodes.c:2000
static int reasonably_live_consensus_is_missing(const guard_selection_t *gs)
Definition: entrynodes.c:1132
Header file for connection.c.
static entry_guard_t * select_filtered_guard_for_circuit(guard_selection_t *gs, guard_usage_t usage, const entry_guard_restriction_t *rst, unsigned *state_out)
Definition: entrynodes.c:2125
void smartlist_add_strdup(struct smartlist_t *sl, const char *string)
STATIC guard_selection_t * get_guard_selection_by_name(const char *name, guard_selection_type_t type, int create_if_absent)
Definition: entrynodes.c:254
int guards_update_all(void)
Definition: entrynodes.c:3603
#define LD_GENERAL
Definition: log.h:62
#define CIRCUIT_IS_ORIGIN(c)
Definition: circuitlist.h:146
STATIC void entry_guards_update_primary(guard_selection_t *gs)
Definition: entrynodes.c:1865
static int entry_guards_load_guards_from_state(or_state_t *state, int set)
Definition: entrynodes.c:3148
static entry_guard_t * entry_guard_add_to_sample_impl(guard_selection_t *gs, const uint8_t *rsa_id_digest, const char *nickname, const tor_addr_port_t *bridge_addrport)
Definition: entrynodes.c:866
int tor_addr_port_eq(const tor_addr_port_t *a, const tor_addr_port_t *b)
Definition: address.c:2006
Header file for describe.c.
static size_t sampled_guards_update_consensus_presence(guard_selection_t *gs)
Definition: entrynodes.c:1270
Header file for nodelist.c.
const uint8_t * bridge_get_rsa_id_digest(const bridge_info_t *bridge)
Definition: bridges.c:147
STATIC guard_selection_t * guard_selection_new(const char *name, guard_selection_type_t type)
Definition: entrynodes.c:231
static smartlist_t * guard_contexts
Definition: entrynodes.c:151
#define SLOW_GUARD_STATE_FLUSH_TIME
Definition: entrynodes.c:3396
Header file for directory.c.
void smartlist_add(smartlist_t *sl, void *element)
static smartlist_t * get_eligible_guards(const or_options_t *options, guard_selection_t *gs, int *n_guards_out)
Definition: entrynodes.c:1046
int pathbias_get_dropguards(const or_options_t *options)
Definition: circpathbias.c:141
void digestset_add(digestset_t *set, const char *digest)
Definition: digestset.c:44
Node information structure.
STATIC int get_guard_confirmed_min_lifetime(void)
Definition: entrynodes.c:442
int smartlist_contains(const smartlist_t *sl, const void *element)
#define TO_CIRCUIT(x)
Definition: or.h:951
Header file for config.c.
STATIC time_t randomize_time(time_t now, time_t max_backdate)
Definition: entrynodes.c:346
#define fmt_and_decorate_addr(a)
Definition: address.h:214
Header file for nickname.c.
const or_options_t * get_options(void)
Definition: config.c:941
#define tor_assert(expr)
Definition: util_bug.h:102
Header file for microdesc.c.
guard_selection_t * get_guard_selection_info(void)
Definition: entrynodes.c:303
STATIC void entry_guards_note_guard_failure(guard_selection_t *gs, entry_guard_t *guard)
Definition: entrynodes.c:2209
static int get_retry_schedule(time_t failing_since, time_t now, int is_primary)
Definition: entrynodes.c:1960
#define tor_free(p)
Definition: malloc.h:52
int node_has_preferred_descriptor(const node_t *node, int for_direct_connect)
Definition: nodelist.c:1351
const char * name
Definition: config.c:2211
STATIC int num_reachable_filtered_guards(const guard_selection_t *gs, const entry_guard_restriction_t *rst)
Definition: entrynodes.c:999
#define SMARTLIST_DEL_CURRENT(sl, var)
Header file for mainloop.c.
static int entry_guards_dirty
Definition: entrynodes.c:157
smartlist_t * smartlist_new(void)
STATIC int entry_guards_all_primary_guards_are_down(guard_selection_t *gs)
Definition: entrynodes.c:2526
int entry_guards_parse_state(or_state_t *state, int set, char **msg)
Definition: entrynodes.c:3379
static int should_set_md_dirserver_restriction(void)
Definition: entrynodes.c:1576
#define bool_eq(a, b)
Definition: logic.h:16
static int entry_guard_passes_filter(const or_options_t *options, guard_selection_t *gs, entry_guard_t *guard)
Definition: entrynodes.c:1499
double successful_circuits_closed
Definition: entrynodes.h:52
circuit_guard_state_t * origin_circuit_get_guard_state(origin_circuit_t *circ)
Definition: circuitbuild.c:508
int entry_guard_state_should_expire(circuit_guard_state_t *guard_state)
Definition: entrynodes.c:2748
#define STATIC
Definition: testsupport.h:32
#define tor_memneq(a, b, sz)
Definition: di_ops.h:21
int entry_guards_upgrade_waiting_circuits(guard_selection_t *gs, const smartlist_t *all_circuits_in, smartlist_t *newly_complete_out)
Definition: entrynodes.c:2584
static int node_passes_guard_filter(const or_options_t *options, const node_t *node)
Definition: entrynodes.c:1447
Header file for routerset.c.
STATIC unsigned entry_guards_note_guard_success(guard_selection_t *gs, entry_guard_t *guard, unsigned old_state)
Definition: entrynodes.c:2236
void circuit_build_times_free_timeouts(circuit_build_times_t *cbt)
Definition: circuitstats.c:595
int getinfo_helper_entry_guards(control_connection_t *conn, const char *question, char **answer, const char **errmsg)
Definition: entrynodes.c:3533
int circuit_should_use_vanguards(uint8_t purpose)
Definition: circuituse.c:1998
const char * entry_guard_describe(const entry_guard_t *guard)
Definition: entrynodes.c:315
static entry_guard_t * get_sampled_guard_by_bridge_addr(guard_selection_t *gs, const tor_addr_port_t *addrport)
Definition: entrynodes.c:932
STATIC void mark_primary_guards_maybe_reachable(guard_selection_t *gs)
Definition: entrynodes.c:583
Header file for policies.c.
static int get_max_sample_size(guard_selection_t *gs, int n_guards)
Definition: entrynodes.c:1016
void entry_guard_failed(circuit_guard_state_t **guard_state_p)
Definition: entrynodes.c:2480
STATIC entry_guard_restriction_t * guard_create_dirserver_md_restriction(void)
Definition: entrynodes.c:1595
double pathbias_get_extreme_use_rate(const or_options_t *options)
Definition: circpathbias.c:232
void entry_guards_changed(void)
Definition: entrynodes.c:3430
static entry_guard_t * select_primary_guard_for_circuit(guard_selection_t *gs, guard_usage_t usage, const entry_guard_restriction_t *rst, unsigned *state_out)
Definition: entrynodes.c:2043
STATIC void entry_guard_free_(entry_guard_t *e)
Definition: entrynodes.c:3257
int node_is_dir(const node_t *node)
Definition: nodelist.c:1315
Header file for channel.c.
static int bridge_passes_guard_filter(const or_options_t *options, const bridge_info_t *bridge)
Definition: entrynodes.c:1472
STATIC void entry_guards_update_filtered_sets(guard_selection_t *gs)
Definition: entrynodes.c:1700
const char * node_get_nickname(const node_t *node)
Definition: nodelist.c:1301
networkstatus_t * networkstatus_get_reasonably_live_consensus(time_t now, int flavor)
#define MAX_VERBOSE_NICKNAME_LEN
Definition: or.h:119
Header for fp.c.
guard_usable_t entry_guard_succeeded(circuit_guard_state_t **guard_state_p)
Definition: entrynodes.c:2432
#define LD_CIRC
Definition: log.h:82
STATIC char * entry_guard_encode_for_state(entry_guard_t *guard)
Definition: entrynodes.c:2777
long tor_lround(double d)
Definition: fp.c:31
#define LD_GUARD
Definition: log.h:109
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
int tor_asprintf(char **strp, const char *fmt,...)
Definition: printf.c:75
STATIC int get_max_sample_size_absolute(void)
Definition: entrynodes.c:384
static void remove_guard_from_confirmed_and_primary_lists(guard_selection_t *gs, entry_guard_t *guard)
Definition: entrynodes.c:1216
int tor_addr_port_parse(int severity, const char *addrport, tor_addr_t *address_out, uint16_t *port_out, int default_port)
Definition: address.c:1759
int num_bridges_usable(int use_maybe_reachable)
Definition: entrynodes.c:3294
static entry_guard_t * get_sampled_guard_for_bridge(guard_selection_t *gs, const bridge_info_t *bridge)
Definition: entrynodes.c:795
#define DIGEST_LEN
Definition: digest_sizes.h:20
Origin circuit structure.
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
static int circ_state_has_higher_priority(origin_circuit_t *a, const entry_guard_restriction_t *rst, origin_circuit_t *b)
Definition: entrynodes.c:2547
Header file for circuitbuild.c.
int usable_consensus_flavor(void)
Definition: microdesc.c:1084
STATIC entry_guard_t * select_entry_guard_for_circuit(guard_selection_t *gs, guard_usage_t usage, const entry_guard_restriction_t *rst, unsigned *state_out)
Definition: entrynodes.c:2164
Master header file for Tor-specific functionality.
int addrs_in_same_network_family(const tor_addr_t *a1, const tor_addr_t *a2)
Definition: nodelist.c:1960
void entry_guard_chan_failed(channel_t *chan)
Definition: entrynodes.c:2500
static entry_guard_t * entry_guard_add_bridge_to_sample(guard_selection_t *gs, const bridge_info_t *bridge)
Definition: entrynodes.c:912
const char * hex_str(const char *from, size_t fromlen)
Definition: binascii.c:34
STATIC int entry_guard_is_listed(guard_selection_t *gs, const entry_guard_t *guard)
Definition: entrynodes.c:1245
Header file for circuitbuild.c.
void node_get_verbose_nickname(const node_t *node, char *verbose_name_out)
Definition: nodelist.c:1384
STATIC int get_n_primary_guards_to_use(guard_usage_t usage)
Definition: entrynodes.c:476
static time_t get_remove_unlisted_guards_after_seconds(void)
Definition: entrynodes.c:417
STATIC const char * choose_guard_selection(const or_options_t *options, const networkstatus_t *live_ns, const guard_selection_t *old_selection, guard_selection_type_t *type_out)
Definition: entrynodes.c:615
const node_t * node_get_by_id(const char *identity_digest)
Definition: nodelist.c:223
char identity[DIGEST_LEN]
Definition: node_st.h:45
STATIC entry_guard_t * entry_guard_add_to_sample(guard_selection_t *gs, const node_t *node)
Definition: entrynodes.c:843
void smartlist_remove(smartlist_t *sl, const void *element)
void entry_guards_free_all(void)
Definition: entrynodes.c:3812
#define LOG_WARN
Definition: log.h:53
static guard_selection_t * curr_guard_context
Definition: entrynodes.c:153
STATIC int get_remove_unlisted_guards_after_days(void)
Definition: entrynodes.c:404
entry_guard_t * entry_guard_get_by_id_digest(const char *digest)
Definition: entrynodes.c:3223
bridge_info_t * get_configured_bridge_by_exact_addr_port_digest(const tor_addr_t *addr, uint16_t port, const char *digest)
Definition: bridges.c:226
void format_iso_time_nospace(char *buf, time_t t)
Definition: time_fmt.c:313
Header file for circuituse.c.
void base16_encode(char *dest, size_t destlen, const char *src, size_t srclen)
Definition: binascii.c:478
void entry_guards_changed_for_guard_selection(guard_selection_t *gs)
Definition: entrynodes.c:3406
int fascist_firewall_allows_address_addr(const tor_addr_t *addr, uint16_t port, firewall_connection_t fw_connection, int pref_only, int pref_ipv6)
Definition: policies.c:557
double pathbias_get_close_success_count(entry_guard_t *guard)
STATIC int get_n_primary_guards(void)
Definition: entrynodes.c:456
Header file for circuitlist.c.
double pathbias_get_extreme_rate(const or_options_t *options)
Definition: circpathbias.c:125
int microdesc_relay_is_outdated_dirserver(const char *relay_digest)
Definition: microdesc.c:161
Types to handle sets of digests, based on bloom filters.
Headers for transports.c.
int tor_digest_is_zero(const char *digest)
Definition: util_string.c:96
static int have_sampled_guard_with_id(guard_selection_t *gs, const uint8_t *rsa_id)
Definition: entrynodes.c:832
STATIC char * getinfo_helper_format_single_entry_guard(const entry_guard_t *e)
Definition: entrynodes.c:3476
STATIC entry_guard_t * entry_guard_parse_from_state(const char *s)
Definition: entrynodes.c:2867
circuit_guard_state_t * get_guard_state_for_bridge_desc_fetch(const char *digest)
Definition: entrynodes.c:3232
int is_legal_nickname(const char *s)
Definition: nickname.c:19
#define HEX_DIGEST_LEN
Definition: crypto_digest.h:35
const smartlist_t * nodelist_get_list(void)
Definition: nodelist.c:948
static int guard_obeys_md_dirserver_restriction(const entry_guard_t *guard)
Definition: entrynodes.c:1629
static void pathbias_check_close_success_count(entry_guard_t *guard)
Definition: entrynodes.c:3352
static int node_is_possible_guard(const node_t *node)
Definition: entrynodes.c:762
void entry_guards_note_internet_connectivity(guard_selection_t *gs)
Definition: entrynodes.c:2031
STATIC double get_extreme_restriction_threshold(void)
Definition: entrynodes.c:553
int digestset_probably_contains(const digestset_t *set, const char *digest)
Definition: digestset.c:54
origin_circuit_t * TO_ORIGIN_CIRCUIT(circuit_t *x)
Definition: circuitlist.c:166
STATIC int get_min_filtered_sample_size(void)
Definition: entrynodes.c:394
int tor_snprintf(char *str, size_t size, const char *format,...)
Definition: printf.c:27
void format_iso_time(char *buf, time_t t)
Definition: time_fmt.c:295
char * smartlist_join_strings(smartlist_t *sl, const char *join, int terminate, size_t *len_out)
Definition: smartlist.c:279
static void pathbias_check_use_success_count(entry_guard_t *guard)
Definition: entrynodes.c:3329
routerset_t * EntryNodes
Definition: or_options_st.h:75
const node_t * entry_guard_find_node(const entry_guard_t *guard)
Definition: entrynodes.c:3213
#define SMARTLIST_FOREACH(sl, type, var, cmd)
The or_state_t structure, which represents Tor's state file.
Header file for router.c.
const char * escaped(const char *s)
Definition: escape.c:126
entry_guard_t * entry_guard_get_by_id_digest_for_guard_selection(guard_selection_t *gs, const char *digest)
Definition: entrynodes.c:3204
char identity[DIGEST_LEN]
Definition: bridges.c:55
int fascist_firewall_allows_node(const node_t *node, firewall_connection_t fw_connection, int pref_only)
Definition: policies.c:733
circuit_build_times_t * get_circuit_build_times_mutable(void)
Definition: circuitstats.c:89
STATIC void entry_guards_update_confirmed(guard_selection_t *gs)
Definition: entrynodes.c:1805
#define ARRAY_LENGTH(x)
int smartlist_ptrs_eq(const smartlist_t *s1, const smartlist_t *s2)
Definition: smartlist.c:198
char * entry_guards_get_err_str_if_dir_info_missing(int using_mds, int num_present, int num_usable)
Definition: entrynodes.c:3779
STATIC int entry_guard_has_higher_priority(entry_guard_t *a, entry_guard_t *b)
Definition: entrynodes.c:2302
int router_digest_is_me(const char *digest)
Definition: router.c:1586
void smartlist_add_all(smartlist_t *s1, const smartlist_t *s2)
STATIC int get_internet_likely_down_interval(void)
Definition: entrynodes.c:504
STATIC int get_nonprimary_guard_idle_timeout(void)
Definition: entrynodes.c:528
static entry_guard_t * select_and_add_guard_item_for_sample(guard_selection_t *gs, smartlist_t *eligible_guards)
Definition: entrynodes.c:1104
STATIC void guard_selection_free_(guard_selection_t *gs)
Definition: entrynodes.c:3790
#define DIR_PURPOSE_FETCH_MICRODESC
Definition: directory.h:70
const node_t * node_sl_choose_by_bandwidth(const smartlist_t *sl, bandwidth_weight_rule_t rule)
Definition: node_select.c:803
int entry_guard_pick_for_circuit(guard_selection_t *gs, guard_usage_t usage, entry_guard_restriction_t *rst, const node_t **chosen_node_out, circuit_guard_state_t **guard_state_out)
Definition: entrynodes.c:2386
STATIC entry_guard_t * get_sampled_guard_with_id(guard_selection_t *gs, const uint8_t *rsa_id)
Definition: entrynodes.c:780
void entry_guards_update_state(or_state_t *state)
Definition: entrynodes.c:3441
struct circuit_guard_state_t * guard_state
time_t approx_time(void)
Definition: approx_time.c:32
char * guard_selection_get_err_str_if_dir_info_missing(guard_selection_t *gs, int using_mds, int num_present, int num_usable)
Definition: entrynodes.c:3732
Header for confmgt.c.
void or_state_mark_dirty(or_state_t *state, time_t when)
Definition: statefile.c:731
void smartlist_remove_keeporder(smartlist_t *sl, const void *element)
long tor_parse_long(const char *s, int base, long min, long max, int *ok, char **next)
Definition: parse_int.c:59
int node_is_a_configured_bridge(const node_t *node)
Definition: bridges.c:348
int NumDirectoryGuards
static size_t sampled_guards_prune_obsolete_entries(guard_selection_t *gs, const time_t remove_if_unlisted_since, const time_t maybe_remove_if_sampled_before, const time_t remove_if_confirmed_before)
Definition: entrynodes.c:1340
STATIC double get_meaningful_restriction_threshold(void)
Definition: entrynodes.c:540
int base16_decode(char *dest, size_t destlen, const char *src, size_t srclen)
Definition: binascii.c:506
const tor_addr_port_t * bridge_get_addr_port(const bridge_info_t *bridge)
Definition: bridges.c:161
int entry_list_is_constrained(const or_options_t *options)
Definition: entrynodes.c:3274
double pathbias_get_use_success_count(entry_guard_t *guard)
static int guard_in_node_family(const entry_guard_t *guard, const node_t *node)
Definition: entrynodes.c:1527
STATIC void sampled_guards_update_from_consensus(guard_selection_t *gs)
Definition: entrynodes.c:1400
int entry_guard_could_succeed(const circuit_guard_state_t *guard_state)
Definition: entrynodes.c:3457
STATIC circuit_guard_state_t * circuit_guard_state_new(entry_guard_t *guard, unsigned state, entry_guard_restriction_t *rst)
Definition: entrynodes.c:2362
digestset_t * digestset_new(int max_guess)
Definition: digestset.c:30
or_state_t * get_or_state(void)
Definition: statefile.c:198
time_t crypto_rand_time_range(time_t min, time_t max)
int entry_guards_update_all(guard_selection_t *gs)
Definition: entrynodes.c:2763
static int entry_guard_obeys_restriction(const entry_guard_t *guard, const entry_guard_restriction_t *rst)
Definition: entrynodes.c:1649
const smartlist_t * bridge_list_get(void)
Definition: bridges.c:135
Header file for control_events.c.
void smartlist_clear(smartlist_t *sl)
#define FAST_GUARD_STATE_FLUSH_TIME
Definition: entrynodes.c:3399
guard_usage_t
Definition: entrynodes.h:358
int guards_retry_optimistic(const or_options_t *options)
Definition: entrynodes.c:3715
void smartlist_sort(smartlist_t *sl, int(*compare)(const void **a, const void **b))
Definition: smartlist.c:334
int nodes_in_same_family(const node_t *node1, const node_t *node2)
Definition: nodelist.c:2062
int routerset_contains_bridge(const routerset_t *set, const bridge_info_t *bridge)
Definition: routerset.c:350
guard_pathbias_t * entry_guard_get_pathbias_state(entry_guard_t *guard)
Definition: entrynodes.c:334
static void entry_guard_set_filtered_flags(const or_options_t *options, guard_selection_t *gs, entry_guard_t *guard)
Definition: entrynodes.c:1670
void remove_all_entry_guards(void)
Definition: entrynodes.c:3682
const node_t * guards_choose_dirguard(uint8_t dir_purpose, circuit_guard_state_t **guard_state_out)
Definition: entrynodes.c:3689
STATIC entry_guard_t * entry_guards_expand_sample(guard_selection_t *gs)
Definition: entrynodes.c:1151
void node_get_addr(const node_t *node, tor_addr_t *addr_out)
Definition: nodelist.c:1542
Header file for networkstatus.c.
#define LD_BUG
Definition: log.h:86
const uint8_t * build_state_get_exit_rsa_id(cpath_build_state_t *state)
void * smartlist_choose(const smartlist_t *sl)
Definition: crypto_rand.c:590
STATIC void entry_guard_restriction_free_(entry_guard_restriction_t *rst)
Definition: entrynodes.c:2340
#define EPSILON
const char * entry_guard_get_rsa_id_digest(const entry_guard_t *guard)
Definition: entrynodes.c:327
STATIC int get_nonprimary_guard_connect_timeout(void)
Definition: entrynodes.c:516
routerset_t * ExcludeNodes
Definition: or_options_st.h:81
int smartlist_split_string(smartlist_t *sl, const char *str, const char *sep, int flags, int max)
STATIC entry_guard_t * sample_reachable_filtered_entry_guards(guard_selection_t *gs, const entry_guard_restriction_t *rst, unsigned flags)
Definition: entrynodes.c:1721
double use_successes
Definition: entrynodes.h:62