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