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