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