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