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