dirvote: Handling adding vote and signature if module is disabled
[tor.git] / src / or / entrynodes.c
blob96e6ccaaceb88e2e7748ba7ea197cb3ad1fd39ea
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-2017, The Tor Project, Inc. */
5 /* See LICENSE for licensing information */
7 /**
8 * \file entrynodes.c
9 * \brief Code to manage our fixed first nodes for various functions.
11 * Entry nodes can be guards (for general use) or bridges (for censorship
12 * circumvention).
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.
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.
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.
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.
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.
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. We order the guards on this list by the order
51 * in which they became confirmed.
53 * And as a final group, we have an ordered list of PRIMARY GUARDS,
54 * whose elements are taken from the filtered set. We prefer
55 * confirmed guards to non-confirmed guards for this list, and place
56 * other restrictions on it. The primary guards are the ones that we
57 * connect to "when nothing is wrong" -- circuits through them can be used
58 * immediately.
60 * To build circuits, we take a primary guard if possible -- or a
61 * reachable filtered confirmed guard if no primary guard is possible --
62 * or a random reachable filtered guard otherwise. If the guard is
63 * primary, we can use the circuit immediately on success. Otherwise,
64 * the guard is now "pending" -- we won't use its circuit unless all
65 * of the circuits we're trying to build through better guards have
66 * definitely failed.
68 * While we're building circuits, we track a little "guard state" for
69 * each circuit. We use this to keep track of whether the circuit is
70 * one that we can use as soon as it's done, or whether it's one that
71 * we should keep around to see if we can do better. In the latter case,
72 * a periodic call to entry_guards_upgrade_waiting_circuits() will
73 * eventually upgrade it.
74 **/
75 /* DOCDOC -- expand this.
77 * Information invariants:
79 * [x] whenever a guard becomes unreachable, clear its usable_filtered flag.
81 * [x] Whenever a guard becomes reachable or maybe-reachable, if its filtered
82 * flag is set, set its usable_filtered flag.
84 * [x] Whenever we get a new consensus, call update_from_consensus(). (LATER.)
86 * [x] Whenever the configuration changes in a relevant way, update the
87 * filtered/usable flags. (LATER.)
89 * [x] Whenever we add a guard to the sample, make sure its filtered/usable
90 * flags are set as possible.
92 * [x] Whenever we remove a guard from the sample, remove it from the primary
93 * and confirmed lists.
95 * [x] When we make a guard confirmed, update the primary list.
97 * [x] When we make a guard filtered or unfiltered, update the primary list.
99 * [x] When we are about to pick a guard, make sure that the primary list is
100 * full.
102 * [x] Before calling sample_reachable_filtered_entry_guards(), make sure
103 * that the filtered, primary, and confirmed flags are up-to-date.
105 * [x] Call entry_guard_consider_retry every time we are about to check
106 * is_usable_filtered or is_reachable, and every time we set
107 * is_filtered to 1.
109 * [x] Call entry_guards_changed_for_guard_selection() whenever we update
110 * a persistent field.
113 #define ENTRYNODES_PRIVATE
115 #include "or.h"
116 #include "channel.h"
117 #include "bridges.h"
118 #include "circpathbias.h"
119 #include "circuitbuild.h"
120 #include "circuitlist.h"
121 #include "circuitstats.h"
122 #include "config.h"
123 #include "confparse.h"
124 #include "connection.h"
125 #include "control.h"
126 #include "directory.h"
127 #include "entrynodes.h"
128 #include "main.h"
129 #include "microdesc.h"
130 #include "networkstatus.h"
131 #include "nodelist.h"
132 #include "policies.h"
133 #include "router.h"
134 #include "routerlist.h"
135 #include "routerparse.h"
136 #include "routerset.h"
137 #include "transports.h"
138 #include "statefile.h"
140 /** A list of existing guard selection contexts. */
141 static smartlist_t *guard_contexts = NULL;
142 /** The currently enabled guard selection context. */
143 static guard_selection_t *curr_guard_context = NULL;
145 /** A value of 1 means that at least one context has changed,
146 * and those changes need to be flushed to disk. */
147 static int entry_guards_dirty = 0;
149 static void entry_guard_set_filtered_flags(const or_options_t *options,
150 guard_selection_t *gs,
151 entry_guard_t *guard);
152 static void pathbias_check_use_success_count(entry_guard_t *guard);
153 static void pathbias_check_close_success_count(entry_guard_t *guard);
154 static int node_is_possible_guard(const node_t *node);
155 static int node_passes_guard_filter(const or_options_t *options,
156 const node_t *node);
157 static entry_guard_t *entry_guard_add_to_sample_impl(guard_selection_t *gs,
158 const uint8_t *rsa_id_digest,
159 const char *nickname,
160 const tor_addr_port_t *bridge_addrport);
161 static entry_guard_t *get_sampled_guard_by_bridge_addr(guard_selection_t *gs,
162 const tor_addr_port_t *addrport);
163 static int entry_guard_obeys_restriction(const entry_guard_t *guard,
164 const entry_guard_restriction_t *rst);
166 /** Return 0 if we should apply guardfraction information found in the
167 * consensus. A specific consensus can be specified with the
168 * <b>ns</b> argument, if NULL the most recent one will be picked.*/
170 should_apply_guardfraction(const networkstatus_t *ns)
172 /* We need to check the corresponding torrc option and the consensus
173 * parameter if we need to. */
174 const or_options_t *options = get_options();
176 /* If UseGuardFraction is 'auto' then check the same-named consensus
177 * parameter. If the consensus parameter is not present, default to
178 * "off". */
179 if (options->UseGuardFraction == -1) {
180 return networkstatus_get_param(ns, "UseGuardFraction",
181 0, /* default to "off" */
182 0, 1);
185 return options->UseGuardFraction;
188 /** Return true iff we know a preferred descriptor for <b>guard</b> */
189 static int
190 guard_has_descriptor(const entry_guard_t *guard)
192 const node_t *node = node_get_by_id(guard->identity);
193 if (!node)
194 return 0;
195 return node_has_preferred_descriptor(node, 1);
199 * Try to determine the correct type for a selection named "name",
200 * if <b>type</b> is GS_TYPE_INFER.
202 STATIC guard_selection_type_t
203 guard_selection_infer_type(guard_selection_type_t type,
204 const char *name)
206 if (type == GS_TYPE_INFER) {
207 if (!strcmp(name, "bridges"))
208 type = GS_TYPE_BRIDGE;
209 else if (!strcmp(name, "restricted"))
210 type = GS_TYPE_RESTRICTED;
211 else
212 type = GS_TYPE_NORMAL;
214 return type;
218 * Allocate and return a new guard_selection_t, with the name <b>name</b>.
220 STATIC guard_selection_t *
221 guard_selection_new(const char *name,
222 guard_selection_type_t type)
224 guard_selection_t *gs;
226 type = guard_selection_infer_type(type, name);
228 gs = tor_malloc_zero(sizeof(*gs));
229 gs->name = tor_strdup(name);
230 gs->type = type;
231 gs->sampled_entry_guards = smartlist_new();
232 gs->confirmed_entry_guards = smartlist_new();
233 gs->primary_entry_guards = smartlist_new();
235 return gs;
239 * Return the guard selection called <b>name</b>. If there is none, and
240 * <b>create_if_absent</b> is true, then create and return it. If there
241 * is none, and <b>create_if_absent</b> is false, then return NULL.
243 STATIC guard_selection_t *
244 get_guard_selection_by_name(const char *name,
245 guard_selection_type_t type,
246 int create_if_absent)
248 if (!guard_contexts) {
249 guard_contexts = smartlist_new();
251 SMARTLIST_FOREACH_BEGIN(guard_contexts, guard_selection_t *, gs) {
252 if (!strcmp(gs->name, name))
253 return gs;
254 } SMARTLIST_FOREACH_END(gs);
256 if (! create_if_absent)
257 return NULL;
259 log_debug(LD_GUARD, "Creating a guard selection called %s", name);
260 guard_selection_t *new_selection = guard_selection_new(name, type);
261 smartlist_add(guard_contexts, new_selection);
263 return new_selection;
267 * Allocate the first guard context that we're planning to use,
268 * and make it the current context.
270 static void
271 create_initial_guard_context(void)
273 tor_assert(! curr_guard_context);
274 if (!guard_contexts) {
275 guard_contexts = smartlist_new();
277 guard_selection_type_t type = GS_TYPE_INFER;
278 const char *name = choose_guard_selection(
279 get_options(),
280 networkstatus_get_live_consensus(approx_time()),
281 NULL,
282 &type);
283 tor_assert(name); // "name" can only be NULL if we had an old name.
284 tor_assert(type != GS_TYPE_INFER);
285 log_notice(LD_GUARD, "Starting with guard context \"%s\"", name);
286 curr_guard_context = get_guard_selection_by_name(name, type, 1);
289 /** Get current default guard_selection_t, creating it if necessary */
290 guard_selection_t *
291 get_guard_selection_info(void)
293 if (!curr_guard_context) {
294 create_initial_guard_context();
297 return curr_guard_context;
300 /** Return a statically allocated human-readable description of <b>guard</b>
302 const char *
303 entry_guard_describe(const entry_guard_t *guard)
305 static char buf[256];
306 tor_snprintf(buf, sizeof(buf),
307 "%s ($%s)",
308 strlen(guard->nickname) ? guard->nickname : "[bridge]",
309 hex_str(guard->identity, DIGEST_LEN));
310 return buf;
313 /** Return <b>guard</b>'s 20-byte RSA identity digest */
314 const char *
315 entry_guard_get_rsa_id_digest(const entry_guard_t *guard)
317 return guard->identity;
320 /** Return the pathbias state associated with <b>guard</b>. */
321 guard_pathbias_t *
322 entry_guard_get_pathbias_state(entry_guard_t *guard)
324 return &guard->pb;
327 HANDLE_IMPL(entry_guard, entry_guard_t, ATTR_UNUSED STATIC)
329 /** Return an interval betweeen 'now' and 'max_backdate' seconds in the past,
330 * chosen uniformly at random. We use this before recording persistent
331 * dates, so that we aren't leaking exactly when we recorded it.
333 MOCK_IMPL(STATIC time_t,
334 randomize_time,(time_t now, time_t max_backdate))
336 tor_assert(max_backdate > 0);
338 time_t earliest = now - max_backdate;
339 time_t latest = now;
340 if (earliest <= 0)
341 earliest = 1;
342 if (latest <= earliest)
343 latest = earliest + 1;
345 return crypto_rand_time_range(earliest, latest);
349 * @name parameters for networkstatus algorithm
351 * These parameters are taken from the consensus; some are overrideable in
352 * the torrc.
354 /**@{*/
356 * We never let our sampled guard set grow larger than this fraction
357 * of the guards on the network.
359 STATIC double
360 get_max_sample_threshold(void)
362 int32_t pct =
363 networkstatus_get_param(NULL, "guard-max-sample-threshold-percent",
364 DFLT_MAX_SAMPLE_THRESHOLD_PERCENT,
365 1, 100);
366 return pct / 100.0;
369 * We never let our sampled guard set grow larger than this number.
371 STATIC int
372 get_max_sample_size_absolute(void)
374 return (int) networkstatus_get_param(NULL, "guard-max-sample-size",
375 DFLT_MAX_SAMPLE_SIZE,
376 1, INT32_MAX);
379 * We always try to make our sample contain at least this many guards.
381 STATIC int
382 get_min_filtered_sample_size(void)
384 return networkstatus_get_param(NULL, "guard-min-filtered-sample-size",
385 DFLT_MIN_FILTERED_SAMPLE_SIZE,
386 1, INT32_MAX);
389 * If a guard is unlisted for this many days in a row, we remove it.
391 STATIC int
392 get_remove_unlisted_guards_after_days(void)
394 return networkstatus_get_param(NULL,
395 "guard-remove-unlisted-guards-after-days",
396 DFLT_REMOVE_UNLISTED_GUARDS_AFTER_DAYS,
397 1, 365*10);
400 * We remove unconfirmed guards from the sample after this many days,
401 * regardless of whether they are listed or unlisted.
403 STATIC int
404 get_guard_lifetime(void)
406 if (get_options()->GuardLifetime >= 86400)
407 return get_options()->GuardLifetime;
408 int32_t days;
409 days = networkstatus_get_param(NULL,
410 "guard-lifetime-days",
411 DFLT_GUARD_LIFETIME_DAYS, 1, 365*10);
412 return days * 86400;
415 * We remove confirmed guards from the sample if they were sampled
416 * GUARD_LIFETIME_DAYS ago and confirmed this many days ago.
418 STATIC int
419 get_guard_confirmed_min_lifetime(void)
421 if (get_options()->GuardLifetime >= 86400)
422 return get_options()->GuardLifetime;
423 int32_t days;
424 days = networkstatus_get_param(NULL, "guard-confirmed-min-lifetime-days",
425 DFLT_GUARD_CONFIRMED_MIN_LIFETIME_DAYS,
426 1, 365*10);
427 return days * 86400;
430 * How many guards do we try to keep on our primary guard list?
432 STATIC int
433 get_n_primary_guards(void)
435 const int n = get_options()->NumEntryGuards;
436 const int n_dir = get_options()->NumDirectoryGuards;
437 if (n > 5) {
438 return MAX(n_dir, n + n / 2);
439 } else if (n >= 1) {
440 return MAX(n_dir, n * 2);
443 return networkstatus_get_param(NULL,
444 "guard-n-primary-guards",
445 DFLT_N_PRIMARY_GUARDS, 1, INT32_MAX);
448 * Return the number of the live primary guards we should look at when
449 * making a circuit.
451 STATIC int
452 get_n_primary_guards_to_use(guard_usage_t usage)
454 int configured;
455 const char *param_name;
456 int param_default;
457 if (usage == GUARD_USAGE_DIRGUARD) {
458 configured = get_options()->NumDirectoryGuards;
459 param_name = "guard-n-primary-dir-guards-to-use";
460 param_default = DFLT_N_PRIMARY_DIR_GUARDS_TO_USE;
461 } else {
462 configured = get_options()->NumEntryGuards;
463 param_name = "guard-n-primary-guards-to-use";
464 param_default = DFLT_N_PRIMARY_GUARDS_TO_USE;
466 if (configured >= 1) {
467 return configured;
469 return networkstatus_get_param(NULL,
470 param_name, param_default, 1, INT32_MAX);
473 * If we haven't successfully built or used a circuit in this long, then
474 * consider that the internet is probably down.
476 STATIC int
477 get_internet_likely_down_interval(void)
479 return networkstatus_get_param(NULL, "guard-internet-likely-down-interval",
480 DFLT_INTERNET_LIKELY_DOWN_INTERVAL,
481 1, INT32_MAX);
484 * If we're trying to connect to a nonprimary guard for at least this
485 * many seconds, and we haven't gotten the connection to work, we will treat
486 * lower-priority guards as usable.
488 STATIC int
489 get_nonprimary_guard_connect_timeout(void)
491 return networkstatus_get_param(NULL,
492 "guard-nonprimary-guard-connect-timeout",
493 DFLT_NONPRIMARY_GUARD_CONNECT_TIMEOUT,
494 1, INT32_MAX);
497 * If a circuit has been sitting around in 'waiting for better guard' state
498 * for at least this long, we'll expire it.
500 STATIC int
501 get_nonprimary_guard_idle_timeout(void)
503 return networkstatus_get_param(NULL,
504 "guard-nonprimary-guard-idle-timeout",
505 DFLT_NONPRIMARY_GUARD_IDLE_TIMEOUT,
506 1, INT32_MAX);
509 * If our configuration retains fewer than this fraction of guards from the
510 * torrc, we are in a restricted setting.
512 STATIC double
513 get_meaningful_restriction_threshold(void)
515 int32_t pct = networkstatus_get_param(NULL,
516 "guard-meaningful-restriction-percent",
517 DFLT_MEANINGFUL_RESTRICTION_PERCENT,
518 1, INT32_MAX);
519 return pct / 100.0;
522 * If our configuration retains fewer than this fraction of guards from the
523 * torrc, we are in an extremely restricted setting, and should warn.
525 STATIC double
526 get_extreme_restriction_threshold(void)
528 int32_t pct = networkstatus_get_param(NULL,
529 "guard-extreme-restriction-percent",
530 DFLT_EXTREME_RESTRICTION_PERCENT,
531 1, INT32_MAX);
532 return pct / 100.0;
535 /* Mark <b>guard</b> as maybe reachable again. */
536 static void
537 mark_guard_maybe_reachable(entry_guard_t *guard)
539 if (guard->is_reachable != GUARD_REACHABLE_NO) {
540 return;
543 /* Note that we do not clear failing_since: this guard is now only
544 * _maybe-reachable_. */
545 guard->is_reachable = GUARD_REACHABLE_MAYBE;
546 if (guard->is_filtered_guard)
547 guard->is_usable_filtered_guard = 1;
551 * Called when the network comes up after having seemed to be down for
552 * a while: Mark the primary guards as maybe-reachable so that we'll
553 * try them again.
555 STATIC void
556 mark_primary_guards_maybe_reachable(guard_selection_t *gs)
558 tor_assert(gs);
560 if (!gs->primary_guards_up_to_date)
561 entry_guards_update_primary(gs);
563 SMARTLIST_FOREACH_BEGIN(gs->primary_entry_guards, entry_guard_t *, guard) {
564 mark_guard_maybe_reachable(guard);
565 } SMARTLIST_FOREACH_END(guard);
568 /* Called when we exhaust all guards in our sampled set: Marks all guards as
569 maybe-reachable so that we 'll try them again. */
570 static void
571 mark_all_guards_maybe_reachable(guard_selection_t *gs)
573 tor_assert(gs);
575 SMARTLIST_FOREACH_BEGIN(gs->sampled_entry_guards, entry_guard_t *, guard) {
576 mark_guard_maybe_reachable(guard);
577 } SMARTLIST_FOREACH_END(guard);
580 /**@}*/
583 * Given our options and our list of nodes, return the name of the
584 * guard selection that we should use. Return NULL for "use the
585 * same selection you were using before.
587 STATIC const char *
588 choose_guard_selection(const or_options_t *options,
589 const networkstatus_t *live_ns,
590 const guard_selection_t *old_selection,
591 guard_selection_type_t *type_out)
593 tor_assert(options);
594 tor_assert(type_out);
596 if (options->UseBridges) {
597 *type_out = GS_TYPE_BRIDGE;
598 return "bridges";
601 if (! live_ns) {
602 /* without a networkstatus, we can't tell any more than that. */
603 *type_out = GS_TYPE_NORMAL;
604 return "default";
607 const smartlist_t *nodes = nodelist_get_list();
608 int n_guards = 0, n_passing_filter = 0;
609 SMARTLIST_FOREACH_BEGIN(nodes, const node_t *, node) {
610 if (node_is_possible_guard(node)) {
611 ++n_guards;
612 if (node_passes_guard_filter(options, node)) {
613 ++n_passing_filter;
616 } SMARTLIST_FOREACH_END(node);
618 /* We use separate 'high' and 'low' thresholds here to prevent flapping
619 * back and forth */
620 const int meaningful_threshold_high =
621 (int)(n_guards * get_meaningful_restriction_threshold() * 1.05);
622 const int meaningful_threshold_mid =
623 (int)(n_guards * get_meaningful_restriction_threshold());
624 const int meaningful_threshold_low =
625 (int)(n_guards * get_meaningful_restriction_threshold() * .95);
626 const int extreme_threshold =
627 (int)(n_guards * get_extreme_restriction_threshold());
630 If we have no previous selection, then we're "restricted" iff we are
631 below the meaningful restriction threshold. That's easy enough.
633 But if we _do_ have a previous selection, we make it a little
634 "sticky": we only move from "restricted" to "default" when we find
635 that we're above the threshold plus 5%, and we only move from
636 "default" to "restricted" when we're below the threshold minus 5%.
637 That should prevent us from flapping back and forth if we happen to
638 be hovering very close to the default.
640 The extreme threshold is for warning only.
643 static int have_warned_extreme_threshold = 0;
644 if (n_guards &&
645 n_passing_filter < extreme_threshold &&
646 ! have_warned_extreme_threshold) {
647 have_warned_extreme_threshold = 1;
648 const double exclude_frac =
649 (n_guards - n_passing_filter) / (double)n_guards;
650 log_warn(LD_GUARD, "Your configuration excludes %d%% of all possible "
651 "guards. That's likely to make you stand out from the "
652 "rest of the world.", (int)(exclude_frac * 100));
655 /* Easy case: no previous selection. Just check if we are in restricted or
656 normal guard selection. */
657 if (old_selection == NULL) {
658 if (n_passing_filter >= meaningful_threshold_mid) {
659 *type_out = GS_TYPE_NORMAL;
660 return "default";
661 } else {
662 *type_out = GS_TYPE_RESTRICTED;
663 return "restricted";
667 /* Trickier case: we do have a previous guard selection context. */
668 tor_assert(old_selection);
670 /* Use high and low thresholds to decide guard selection, and if we fall in
671 the middle then keep the current guard selection context. */
672 if (n_passing_filter >= meaningful_threshold_high) {
673 *type_out = GS_TYPE_NORMAL;
674 return "default";
675 } else if (n_passing_filter < meaningful_threshold_low) {
676 *type_out = GS_TYPE_RESTRICTED;
677 return "restricted";
678 } else {
679 /* we are in the middle: maintain previous guard selection */
680 *type_out = old_selection->type;
681 return old_selection->name;
686 * Check whether we should switch from our current guard selection to a
687 * different one. If so, switch and return 1. Return 0 otherwise.
689 * On a 1 return, the caller should mark all currently live circuits unusable
690 * for new streams, by calling circuit_mark_all_unused_circs() and
691 * circuit_mark_all_dirty_circs_as_unusable().
694 update_guard_selection_choice(const or_options_t *options)
696 if (!curr_guard_context) {
697 create_initial_guard_context();
698 return 1;
701 guard_selection_type_t type = GS_TYPE_INFER;
702 const char *new_name = choose_guard_selection(
703 options,
704 networkstatus_get_live_consensus(approx_time()),
705 curr_guard_context,
706 &type);
707 tor_assert(new_name);
708 tor_assert(type != GS_TYPE_INFER);
710 const char *cur_name = curr_guard_context->name;
711 if (! strcmp(cur_name, new_name)) {
712 log_debug(LD_GUARD,
713 "Staying with guard context \"%s\" (no change)", new_name);
714 return 0; // No change
717 log_notice(LD_GUARD, "Switching to guard context \"%s\" (was using \"%s\")",
718 new_name, cur_name);
719 guard_selection_t *new_guard_context;
720 new_guard_context = get_guard_selection_by_name(new_name, type, 1);
721 tor_assert(new_guard_context);
722 tor_assert(new_guard_context != curr_guard_context);
723 curr_guard_context = new_guard_context;
725 return 1;
729 * Return true iff <b>node</b> has all the flags needed for us to consider it
730 * a possible guard when sampling guards.
732 static int
733 node_is_possible_guard(const node_t *node)
735 /* The "GUARDS" set is all nodes in the nodelist for which this predicate
736 * holds. */
738 tor_assert(node);
739 return (node->is_possible_guard &&
740 node->is_stable &&
741 node->is_fast &&
742 node->is_valid &&
743 node_is_dir(node) &&
744 !router_digest_is_me(node->identity));
748 * Return the sampled guard with the RSA identity digest <b>rsa_id</b>, or
749 * NULL if we don't have one. */
750 STATIC entry_guard_t *
751 get_sampled_guard_with_id(guard_selection_t *gs,
752 const uint8_t *rsa_id)
754 tor_assert(gs);
755 tor_assert(rsa_id);
756 SMARTLIST_FOREACH_BEGIN(gs->sampled_entry_guards, entry_guard_t *, guard) {
757 if (tor_memeq(guard->identity, rsa_id, DIGEST_LEN))
758 return guard;
759 } SMARTLIST_FOREACH_END(guard);
760 return NULL;
763 /** If <b>gs</b> contains a sampled entry guard matching <b>bridge</b>,
764 * return that guard. Otherwise return NULL. */
765 static entry_guard_t *
766 get_sampled_guard_for_bridge(guard_selection_t *gs,
767 const bridge_info_t *bridge)
769 const uint8_t *id = bridge_get_rsa_id_digest(bridge);
770 const tor_addr_port_t *addrport = bridge_get_addr_port(bridge);
771 entry_guard_t *guard;
772 if (BUG(!addrport))
773 return NULL; // LCOV_EXCL_LINE
774 guard = get_sampled_guard_by_bridge_addr(gs, addrport);
775 if (! guard || (id && tor_memneq(id, guard->identity, DIGEST_LEN)))
776 return NULL;
777 else
778 return guard;
781 /** If we know a bridge_info_t matching <b>guard</b>, return that
782 * bridge. Otherwise return NULL. */
783 static bridge_info_t *
784 get_bridge_info_for_guard(const entry_guard_t *guard)
786 const uint8_t *identity = NULL;
787 if (! tor_digest_is_zero(guard->identity)) {
788 identity = (const uint8_t *)guard->identity;
790 if (BUG(guard->bridge_addr == NULL))
791 return NULL;
793 return get_configured_bridge_by_exact_addr_port_digest(
794 &guard->bridge_addr->addr,
795 guard->bridge_addr->port,
796 (const char*)identity);
800 * Return true iff we have a sampled guard with the RSA identity digest
801 * <b>rsa_id</b>. */
802 static inline int
803 have_sampled_guard_with_id(guard_selection_t *gs, const uint8_t *rsa_id)
805 return get_sampled_guard_with_id(gs, rsa_id) != NULL;
809 * Allocate a new entry_guard_t object for <b>node</b>, add it to the
810 * sampled entry guards in <b>gs</b>, and return it. <b>node</b> must
811 * not currently be a sampled guard in <b>gs</b>.
813 STATIC entry_guard_t *
814 entry_guard_add_to_sample(guard_selection_t *gs,
815 const node_t *node)
817 log_info(LD_GUARD, "Adding %s to the entry guard sample set.",
818 node_describe(node));
820 /* make sure that the guard is not already sampled. */
821 if (BUG(have_sampled_guard_with_id(gs, (const uint8_t*)node->identity)))
822 return NULL; // LCOV_EXCL_LINE
824 return entry_guard_add_to_sample_impl(gs,
825 (const uint8_t*)node->identity,
826 node_get_nickname(node),
827 NULL);
831 * Backend: adds a new sampled guard to <b>gs</b>, with given identity,
832 * nickname, and ORPort. rsa_id_digest and bridge_addrport are optional, but
833 * we need one of them. nickname is optional. The caller is responsible for
834 * maintaining the size limit of the SAMPLED_GUARDS set.
836 static entry_guard_t *
837 entry_guard_add_to_sample_impl(guard_selection_t *gs,
838 const uint8_t *rsa_id_digest,
839 const char *nickname,
840 const tor_addr_port_t *bridge_addrport)
842 const int GUARD_LIFETIME = get_guard_lifetime();
843 tor_assert(gs);
845 // XXXX #20827 take ed25519 identity here too.
847 /* Make sure we can actually identify the guard. */
848 if (BUG(!rsa_id_digest && !bridge_addrport))
849 return NULL; // LCOV_EXCL_LINE
851 entry_guard_t *guard = tor_malloc_zero(sizeof(entry_guard_t));
853 /* persistent fields */
854 guard->is_persistent = (rsa_id_digest != NULL);
855 guard->selection_name = tor_strdup(gs->name);
856 if (rsa_id_digest)
857 memcpy(guard->identity, rsa_id_digest, DIGEST_LEN);
858 if (nickname)
859 strlcpy(guard->nickname, nickname, sizeof(guard->nickname));
860 guard->sampled_on_date = randomize_time(approx_time(), GUARD_LIFETIME/10);
861 tor_free(guard->sampled_by_version);
862 guard->sampled_by_version = tor_strdup(VERSION);
863 guard->currently_listed = 1;
864 guard->confirmed_idx = -1;
866 /* non-persistent fields */
867 guard->is_reachable = GUARD_REACHABLE_MAYBE;
868 if (bridge_addrport)
869 guard->bridge_addr = tor_memdup(bridge_addrport, sizeof(*bridge_addrport));
871 smartlist_add(gs->sampled_entry_guards, guard);
872 guard->in_selection = gs;
873 entry_guard_set_filtered_flags(get_options(), gs, guard);
874 entry_guards_changed_for_guard_selection(gs);
875 return guard;
879 * Add an entry guard to the "bridges" guard selection sample, with
880 * information taken from <b>bridge</b>. Return that entry guard.
882 static entry_guard_t *
883 entry_guard_add_bridge_to_sample(guard_selection_t *gs,
884 const bridge_info_t *bridge)
886 const uint8_t *id_digest = bridge_get_rsa_id_digest(bridge);
887 const tor_addr_port_t *addrport = bridge_get_addr_port(bridge);
889 tor_assert(addrport);
891 /* make sure that the guard is not already sampled. */
892 if (BUG(get_sampled_guard_for_bridge(gs, bridge)))
893 return NULL; // LCOV_EXCL_LINE
895 return entry_guard_add_to_sample_impl(gs, id_digest, NULL, addrport);
899 * Return the entry_guard_t in <b>gs</b> whose address is <b>addrport</b>,
900 * or NULL if none exists.
902 static entry_guard_t *
903 get_sampled_guard_by_bridge_addr(guard_selection_t *gs,
904 const tor_addr_port_t *addrport)
906 if (! gs)
907 return NULL;
908 if (BUG(!addrport))
909 return NULL;
910 SMARTLIST_FOREACH_BEGIN(gs->sampled_entry_guards, entry_guard_t *, g) {
911 if (g->bridge_addr && tor_addr_port_eq(addrport, g->bridge_addr))
912 return g;
913 } SMARTLIST_FOREACH_END(g);
914 return NULL;
917 /** Update the guard subsystem's knowledge of the identity of the bridge
918 * at <b>addrport</b>. Idempotent.
920 void
921 entry_guard_learned_bridge_identity(const tor_addr_port_t *addrport,
922 const uint8_t *rsa_id_digest)
924 guard_selection_t *gs = get_guard_selection_by_name("bridges",
925 GS_TYPE_BRIDGE,
927 if (!gs)
928 return;
930 entry_guard_t *g = get_sampled_guard_by_bridge_addr(gs, addrport);
931 if (!g)
932 return;
934 int make_persistent = 0;
936 if (tor_digest_is_zero(g->identity)) {
937 memcpy(g->identity, rsa_id_digest, DIGEST_LEN);
938 make_persistent = 1;
939 } else if (tor_memeq(g->identity, rsa_id_digest, DIGEST_LEN)) {
940 /* Nothing to see here; we learned something we already knew. */
941 if (BUG(! g->is_persistent))
942 make_persistent = 1;
943 } else {
944 char old_id[HEX_DIGEST_LEN+1];
945 base16_encode(old_id, sizeof(old_id), g->identity, sizeof(g->identity));
946 log_warn(LD_BUG, "We 'learned' an identity %s for a bridge at %s:%d, but "
947 "we already knew a different one (%s). Ignoring the new info as "
948 "possibly bogus.",
949 hex_str((const char *)rsa_id_digest, DIGEST_LEN),
950 fmt_and_decorate_addr(&addrport->addr), addrport->port,
951 old_id);
952 return; // redundant, but let's be clear: we're not making this persistent.
955 if (make_persistent) {
956 g->is_persistent = 1;
957 entry_guards_changed_for_guard_selection(gs);
962 * Return the number of sampled guards in <b>gs</b> that are "filtered"
963 * (that is, we're willing to connect to them) and that are "usable"
964 * (that is, either "reachable" or "maybe reachable").
966 * If a restriction is provided in <b>rst</b>, do not count any guards that
967 * violate it.
969 STATIC int
970 num_reachable_filtered_guards(const guard_selection_t *gs,
971 const entry_guard_restriction_t *rst)
973 int n_reachable_filtered_guards = 0;
974 SMARTLIST_FOREACH_BEGIN(gs->sampled_entry_guards, entry_guard_t *, guard) {
975 entry_guard_consider_retry(guard);
976 if (! entry_guard_obeys_restriction(guard, rst))
977 continue;
978 if (guard->is_usable_filtered_guard)
979 ++n_reachable_filtered_guards;
980 } SMARTLIST_FOREACH_END(guard);
981 return n_reachable_filtered_guards;
984 /** Return the actual maximum size for the sample in <b>gs</b>,
985 * given that we know about <b>n_guards</b> total. */
986 static int
987 get_max_sample_size(guard_selection_t *gs,
988 int n_guards)
990 const int using_bridges = (gs->type == GS_TYPE_BRIDGE);
991 const int min_sample = get_min_filtered_sample_size();
993 /* If we are in bridge mode, expand our sample set as needed without worrying
994 * about max size. We should respect the user's wishes to use many bridges if
995 * that's what they have specified in their configuration file. */
996 if (using_bridges)
997 return INT_MAX;
999 const int max_sample_by_pct = (int)(n_guards * get_max_sample_threshold());
1000 const int max_sample_absolute = get_max_sample_size_absolute();
1001 const int max_sample = MIN(max_sample_by_pct, max_sample_absolute);
1002 if (max_sample < min_sample)
1003 return min_sample;
1004 else
1005 return max_sample;
1009 * Return a smartlist of the all the guards that are not currently
1010 * members of the sample (GUARDS - SAMPLED_GUARDS). The elements of
1011 * this list are node_t pointers in the non-bridge case, and
1012 * bridge_info_t pointers in the bridge case. Set *<b>n_guards_out/b>
1013 * to the number of guards that we found in GUARDS, including those
1014 * that were already sampled.
1016 static smartlist_t *
1017 get_eligible_guards(const or_options_t *options,
1018 guard_selection_t *gs,
1019 int *n_guards_out)
1021 /* Construct eligible_guards as GUARDS - SAMPLED_GUARDS */
1022 smartlist_t *eligible_guards = smartlist_new();
1023 int n_guards = 0; // total size of "GUARDS"
1025 if (gs->type == GS_TYPE_BRIDGE) {
1026 const smartlist_t *bridges = bridge_list_get();
1027 SMARTLIST_FOREACH_BEGIN(bridges, bridge_info_t *, bridge) {
1028 ++n_guards;
1029 if (NULL != get_sampled_guard_for_bridge(gs, bridge)) {
1030 continue;
1032 smartlist_add(eligible_guards, bridge);
1033 } SMARTLIST_FOREACH_END(bridge);
1034 } else {
1035 const smartlist_t *nodes = nodelist_get_list();
1036 const int n_sampled = smartlist_len(gs->sampled_entry_guards);
1038 /* Build a bloom filter of our current guards: let's keep this O(N). */
1039 digestset_t *sampled_guard_ids = digestset_new(n_sampled);
1040 SMARTLIST_FOREACH_BEGIN(gs->sampled_entry_guards, const entry_guard_t *,
1041 guard) {
1042 digestset_add(sampled_guard_ids, guard->identity);
1043 } SMARTLIST_FOREACH_END(guard);
1045 SMARTLIST_FOREACH_BEGIN(nodes, const node_t *, node) {
1046 if (! node_is_possible_guard(node))
1047 continue;
1048 if (gs->type == GS_TYPE_RESTRICTED) {
1049 /* In restricted mode, we apply the filter BEFORE sampling, so
1050 * that we are sampling from the nodes that we might actually
1051 * select. If we sampled first, we might wind up with a sample
1052 * that didn't include any EntryNodes at all. */
1053 if (! node_passes_guard_filter(options, node))
1054 continue;
1056 ++n_guards;
1057 if (digestset_contains(sampled_guard_ids, node->identity))
1058 continue;
1059 smartlist_add(eligible_guards, (node_t*)node);
1060 } SMARTLIST_FOREACH_END(node);
1062 /* Now we can free that bloom filter. */
1063 digestset_free(sampled_guard_ids);
1066 *n_guards_out = n_guards;
1067 return eligible_guards;
1070 /** Helper: given a smartlist of either bridge_info_t (if gs->type is
1071 * GS_TYPE_BRIDGE) or node_t (otherwise), pick one that can be a guard,
1072 * add it as a guard, remove it from the list, and return a new
1073 * entry_guard_t. Return NULL on failure. */
1074 static entry_guard_t *
1075 select_and_add_guard_item_for_sample(guard_selection_t *gs,
1076 smartlist_t *eligible_guards)
1078 entry_guard_t *added_guard;
1079 if (gs->type == GS_TYPE_BRIDGE) {
1080 const bridge_info_t *bridge = smartlist_choose(eligible_guards);
1081 if (BUG(!bridge))
1082 return NULL; // LCOV_EXCL_LINE
1083 smartlist_remove(eligible_guards, bridge);
1084 added_guard = entry_guard_add_bridge_to_sample(gs, bridge);
1085 } else {
1086 const node_t *node =
1087 node_sl_choose_by_bandwidth(eligible_guards, WEIGHT_FOR_GUARD);
1088 if (BUG(!node))
1089 return NULL; // LCOV_EXCL_LINE
1090 smartlist_remove(eligible_guards, node);
1091 added_guard = entry_guard_add_to_sample(gs, node);
1094 return added_guard;
1098 * Return true iff we need a consensus to update our guards, but we don't
1099 * have one. (We can return 0 here either if the consensus is _not_ missing,
1100 * or if we don't need a consensus because we're using bridges.)
1102 static int
1103 live_consensus_is_missing(const guard_selection_t *gs)
1105 tor_assert(gs);
1106 if (gs->type == GS_TYPE_BRIDGE) {
1107 /* We don't update bridges from the consensus; they aren't there. */
1108 return 0;
1110 return networkstatus_get_live_consensus(approx_time()) == NULL;
1114 * Add new guards to the sampled guards in <b>gs</b> until there are
1115 * enough usable filtered guards, but never grow the sample beyond its
1116 * maximum size. Return the last guard added, or NULL if none were
1117 * added.
1119 STATIC entry_guard_t *
1120 entry_guards_expand_sample(guard_selection_t *gs)
1122 tor_assert(gs);
1123 const or_options_t *options = get_options();
1125 if (live_consensus_is_missing(gs)) {
1126 log_info(LD_GUARD, "Not expanding the sample guard set; we have "
1127 "no live consensus.");
1128 return NULL;
1131 int n_sampled = smartlist_len(gs->sampled_entry_guards);
1132 entry_guard_t *added_guard = NULL;
1133 int n_usable_filtered_guards = num_reachable_filtered_guards(gs, NULL);
1134 int n_guards = 0;
1135 smartlist_t *eligible_guards = get_eligible_guards(options, gs, &n_guards);
1137 const int max_sample = get_max_sample_size(gs, n_guards);
1138 const int min_filtered_sample = get_min_filtered_sample_size();
1140 log_info(LD_GUARD, "Expanding the sample guard set. We have %d guards "
1141 "in the sample, and %d eligible guards to extend it with.",
1142 n_sampled, smartlist_len(eligible_guards));
1144 while (n_usable_filtered_guards < min_filtered_sample) {
1145 /* Has our sample grown too large to expand? */
1146 if (n_sampled >= max_sample) {
1147 log_info(LD_GUARD, "Not expanding the guard sample any further; "
1148 "just hit the maximum sample threshold of %d",
1149 max_sample);
1150 goto done;
1153 /* Did we run out of guards? */
1154 if (smartlist_len(eligible_guards) == 0) {
1155 /* LCOV_EXCL_START
1156 As long as MAX_SAMPLE_THRESHOLD makes can't be adjusted to
1157 allow all guards to be sampled, this can't be reached.
1159 log_info(LD_GUARD, "Not expanding the guard sample any further; "
1160 "just ran out of eligible guards");
1161 goto done;
1162 /* LCOV_EXCL_STOP */
1165 /* Otherwise we can add at least one new guard. */
1166 added_guard = select_and_add_guard_item_for_sample(gs, eligible_guards);
1167 if (!added_guard)
1168 goto done; // LCOV_EXCL_LINE -- only fails on BUG.
1170 ++n_sampled;
1172 if (added_guard->is_usable_filtered_guard)
1173 ++n_usable_filtered_guards;
1176 done:
1177 smartlist_free(eligible_guards);
1178 return added_guard;
1182 * Helper: <b>guard</b> has just been removed from the sampled guards:
1183 * also remove it from primary and confirmed. */
1184 static void
1185 remove_guard_from_confirmed_and_primary_lists(guard_selection_t *gs,
1186 entry_guard_t *guard)
1188 if (guard->is_primary) {
1189 guard->is_primary = 0;
1190 smartlist_remove_keeporder(gs->primary_entry_guards, guard);
1191 } else {
1192 if (BUG(smartlist_contains(gs->primary_entry_guards, guard))) {
1193 smartlist_remove_keeporder(gs->primary_entry_guards, guard);
1197 if (guard->confirmed_idx >= 0) {
1198 smartlist_remove_keeporder(gs->confirmed_entry_guards, guard);
1199 guard->confirmed_idx = -1;
1200 guard->confirmed_on_date = 0;
1201 } else {
1202 if (BUG(smartlist_contains(gs->confirmed_entry_guards, guard))) {
1203 // LCOV_EXCL_START
1204 smartlist_remove_keeporder(gs->confirmed_entry_guards, guard);
1205 // LCOV_EXCL_STOP
1210 /** Return true iff <b>guard</b> is currently "listed" -- that is, it
1211 * appears in the consensus, or as a configured bridge (as
1212 * appropriate) */
1213 MOCK_IMPL(STATIC int,
1214 entry_guard_is_listed,(guard_selection_t *gs, const entry_guard_t *guard))
1216 if (gs->type == GS_TYPE_BRIDGE) {
1217 return NULL != get_bridge_info_for_guard(guard);
1218 } else {
1219 const node_t *node = node_get_by_id(guard->identity);
1221 return node && node_is_possible_guard(node);
1226 * Update the status of all sampled guards based on the arrival of a
1227 * new consensus networkstatus document. This will include marking
1228 * some guards as listed or unlisted, and removing expired guards. */
1229 STATIC void
1230 sampled_guards_update_from_consensus(guard_selection_t *gs)
1232 tor_assert(gs);
1233 const int REMOVE_UNLISTED_GUARDS_AFTER =
1234 (get_remove_unlisted_guards_after_days() * 86400);
1235 const int unlisted_since_slop = REMOVE_UNLISTED_GUARDS_AFTER / 5;
1237 // It's important to use only a live consensus here; we don't want to
1238 // make changes based on anything expired or old.
1239 if (live_consensus_is_missing(gs)) {
1240 log_info(LD_GUARD, "Not updating the sample guard set; we have "
1241 "no live consensus.");
1242 return;
1244 log_info(LD_GUARD, "Updating sampled guard status based on received "
1245 "consensus.");
1247 int n_changes = 0;
1249 /* First: Update listed/unlisted. */
1250 SMARTLIST_FOREACH_BEGIN(gs->sampled_entry_guards, entry_guard_t *, guard) {
1251 /* XXXX #20827 check ed ID too */
1252 const int is_listed = entry_guard_is_listed(gs, guard);
1254 if (is_listed && ! guard->currently_listed) {
1255 ++n_changes;
1256 guard->currently_listed = 1;
1257 guard->unlisted_since_date = 0;
1258 log_info(LD_GUARD, "Sampled guard %s is now listed again.",
1259 entry_guard_describe(guard));
1260 } else if (!is_listed && guard->currently_listed) {
1261 ++n_changes;
1262 guard->currently_listed = 0;
1263 guard->unlisted_since_date = randomize_time(approx_time(),
1264 unlisted_since_slop);
1265 log_info(LD_GUARD, "Sampled guard %s is now unlisted.",
1266 entry_guard_describe(guard));
1267 } else if (is_listed && guard->currently_listed) {
1268 log_debug(LD_GUARD, "Sampled guard %s is still listed.",
1269 entry_guard_describe(guard));
1270 } else {
1271 tor_assert(! is_listed && ! guard->currently_listed);
1272 log_debug(LD_GUARD, "Sampled guard %s is still unlisted.",
1273 entry_guard_describe(guard));
1276 /* Clean up unlisted_since_date, just in case. */
1277 if (guard->currently_listed && guard->unlisted_since_date) {
1278 ++n_changes;
1279 guard->unlisted_since_date = 0;
1280 log_warn(LD_BUG, "Sampled guard %s was listed, but with "
1281 "unlisted_since_date set. Fixing.",
1282 entry_guard_describe(guard));
1283 } else if (!guard->currently_listed && ! guard->unlisted_since_date) {
1284 ++n_changes;
1285 guard->unlisted_since_date = randomize_time(approx_time(),
1286 unlisted_since_slop);
1287 log_warn(LD_BUG, "Sampled guard %s was unlisted, but with "
1288 "unlisted_since_date unset. Fixing.",
1289 entry_guard_describe(guard));
1291 } SMARTLIST_FOREACH_END(guard);
1293 const time_t remove_if_unlisted_since =
1294 approx_time() - REMOVE_UNLISTED_GUARDS_AFTER;
1295 const time_t maybe_remove_if_sampled_before =
1296 approx_time() - get_guard_lifetime();
1297 const time_t remove_if_confirmed_before =
1298 approx_time() - get_guard_confirmed_min_lifetime();
1300 /* Then: remove the ones that have been junk for too long */
1301 SMARTLIST_FOREACH_BEGIN(gs->sampled_entry_guards, entry_guard_t *, guard) {
1302 int rmv = 0;
1304 if (guard->currently_listed == 0 &&
1305 guard->unlisted_since_date < remove_if_unlisted_since) {
1307 "We have a live consensus, and {IS_LISTED} is false, and
1308 {FIRST_UNLISTED_AT} is over {REMOVE_UNLISTED_GUARDS_AFTER}
1309 days in the past."
1311 log_info(LD_GUARD, "Removing sampled guard %s: it has been unlisted "
1312 "for over %d days", entry_guard_describe(guard),
1313 get_remove_unlisted_guards_after_days());
1314 rmv = 1;
1315 } else if (guard->sampled_on_date < maybe_remove_if_sampled_before) {
1316 /* We have a live consensus, and {ADDED_ON_DATE} is over
1317 {GUARD_LIFETIME} ago, *and* {CONFIRMED_ON_DATE} is either
1318 "never", or over {GUARD_CONFIRMED_MIN_LIFETIME} ago.
1320 if (guard->confirmed_on_date == 0) {
1321 rmv = 1;
1322 log_info(LD_GUARD, "Removing sampled guard %s: it was sampled "
1323 "over %d days ago, but never confirmed.",
1324 entry_guard_describe(guard),
1325 get_guard_lifetime() / 86400);
1326 } else if (guard->confirmed_on_date < remove_if_confirmed_before) {
1327 rmv = 1;
1328 log_info(LD_GUARD, "Removing sampled guard %s: it was sampled "
1329 "over %d days ago, and confirmed over %d days ago.",
1330 entry_guard_describe(guard),
1331 get_guard_lifetime() / 86400,
1332 get_guard_confirmed_min_lifetime() / 86400);
1336 if (rmv) {
1337 ++n_changes;
1338 SMARTLIST_DEL_CURRENT(gs->sampled_entry_guards, guard);
1339 remove_guard_from_confirmed_and_primary_lists(gs, guard);
1340 entry_guard_free(guard);
1342 } SMARTLIST_FOREACH_END(guard);
1344 if (n_changes) {
1345 gs->primary_guards_up_to_date = 0;
1346 entry_guards_update_filtered_sets(gs);
1347 /* We don't need to rebuild the confirmed list right here -- we may have
1348 * removed confirmed guards above, but we can't have added any new
1349 * confirmed guards.
1351 entry_guards_changed_for_guard_selection(gs);
1356 * Return true iff <b>node</b> is a Tor relay that we are configured to
1357 * be able to connect to. */
1358 static int
1359 node_passes_guard_filter(const or_options_t *options,
1360 const node_t *node)
1362 /* NOTE: Make sure that this function stays in sync with
1363 * options_transition_affects_entry_guards */
1364 if (routerset_contains_node(options->ExcludeNodes, node))
1365 return 0;
1367 if (options->EntryNodes &&
1368 !routerset_contains_node(options->EntryNodes, node))
1369 return 0;
1371 if (!fascist_firewall_allows_node(node, FIREWALL_OR_CONNECTION, 0))
1372 return 0;
1374 if (node_is_a_configured_bridge(node))
1375 return 0;
1377 return 1;
1380 /** Helper: Return true iff <b>bridge</b> passes our configuration
1381 * filter-- if it is a relay that we are configured to be able to
1382 * connect to. */
1383 static int
1384 bridge_passes_guard_filter(const or_options_t *options,
1385 const bridge_info_t *bridge)
1387 tor_assert(bridge);
1388 if (!bridge)
1389 return 0;
1391 if (routerset_contains_bridge(options->ExcludeNodes, bridge))
1392 return 0;
1394 /* Ignore entrynodes */
1395 const tor_addr_port_t *addrport = bridge_get_addr_port(bridge);
1397 if (!fascist_firewall_allows_address_addr(&addrport->addr,
1398 addrport->port,
1399 FIREWALL_OR_CONNECTION,
1400 0, 0))
1401 return 0;
1403 return 1;
1407 * Return true iff <b>guard</b> is a Tor relay that we are configured to
1408 * be able to connect to, and we haven't disabled it for omission from
1409 * the consensus or path bias issues. */
1410 static int
1411 entry_guard_passes_filter(const or_options_t *options, guard_selection_t *gs,
1412 entry_guard_t *guard)
1414 if (guard->currently_listed == 0)
1415 return 0;
1416 if (guard->pb.path_bias_disabled)
1417 return 0;
1419 if (gs->type == GS_TYPE_BRIDGE) {
1420 const bridge_info_t *bridge = get_bridge_info_for_guard(guard);
1421 if (bridge == NULL)
1422 return 0;
1423 return bridge_passes_guard_filter(options, bridge);
1424 } else {
1425 const node_t *node = node_get_by_id(guard->identity);
1426 if (node == NULL) {
1427 // This can happen when currently_listed is true, and we're not updating
1428 // it because we don't have a live consensus.
1429 return 0;
1432 return node_passes_guard_filter(options, node);
1436 /** Return true iff <b>guard</b> is in the same family as <b>node</b>.
1438 static int
1439 guard_in_node_family(const entry_guard_t *guard, const node_t *node)
1441 const node_t *guard_node = node_get_by_id(guard->identity);
1442 if (guard_node) {
1443 return nodes_in_same_family(guard_node, node);
1444 } else {
1445 /* If we don't have a node_t for the guard node, we might have
1446 * a bridge_info_t for it. So let's check to see whether the bridge
1447 * address matches has any family issues.
1449 * (Strictly speaking, I believe this check is unnecessary, since we only
1450 * use it to avoid the exit's family when building circuits, and we don't
1451 * build multihop circuits until we have a routerinfo_t for the
1452 * bridge... at which point, we'll also have a node_t for the
1453 * bridge. Nonetheless, it seems wise to include it, in case our
1454 * assumptions change down the road. -nickm.)
1456 if (get_options()->EnforceDistinctSubnets && guard->bridge_addr) {
1457 tor_addr_t node_addr;
1458 node_get_addr(node, &node_addr);
1459 if (addrs_in_same_network_family(&node_addr,
1460 &guard->bridge_addr->addr)) {
1461 return 1;
1464 return 0;
1468 /* Allocate and return a new exit guard restriction (where <b>exit_id</b> is of
1469 * size DIGEST_LEN) */
1470 STATIC entry_guard_restriction_t *
1471 guard_create_exit_restriction(const uint8_t *exit_id)
1473 entry_guard_restriction_t *rst = NULL;
1474 rst = tor_malloc_zero(sizeof(entry_guard_restriction_t));
1475 rst->type = RST_EXIT_NODE;
1476 memcpy(rst->exclude_id, exit_id, DIGEST_LEN);
1477 return rst;
1480 /** If we have fewer than this many possible usable guards, don't set
1481 * MD-availability-based restrictions: we might blacklist all of them. */
1482 #define MIN_GUARDS_FOR_MD_RESTRICTION 10
1484 /** Return true if we should set md dirserver restrictions. We might not want
1485 * to set those if our guard options are too restricted, since we don't want
1486 * to blacklist all of them. */
1487 static int
1488 should_set_md_dirserver_restriction(void)
1490 const guard_selection_t *gs = get_guard_selection_info();
1491 int num_usable_guards = num_reachable_filtered_guards(gs, NULL);
1493 /* Don't set restriction if too few reachable filtered guards. */
1494 if (num_usable_guards < MIN_GUARDS_FOR_MD_RESTRICTION) {
1495 log_info(LD_GUARD, "Not setting md restriction: only %d"
1496 " usable guards.", num_usable_guards);
1497 return 0;
1500 /* We have enough usable guards: set MD restriction */
1501 return 1;
1504 /** Allocate and return an outdated md guard restriction. Return NULL if no
1505 * such restriction is needed. */
1506 STATIC entry_guard_restriction_t *
1507 guard_create_dirserver_md_restriction(void)
1509 entry_guard_restriction_t *rst = NULL;
1511 if (!should_set_md_dirserver_restriction()) {
1512 log_debug(LD_GUARD, "Not setting md restriction: too few "
1513 "filtered guards.");
1514 return NULL;
1517 rst = tor_malloc_zero(sizeof(entry_guard_restriction_t));
1518 rst->type = RST_OUTDATED_MD_DIRSERVER;
1520 return rst;
1523 /* Return True if <b>guard</b> obeys the exit restriction <b>rst</b>. */
1524 static int
1525 guard_obeys_exit_restriction(const entry_guard_t *guard,
1526 const entry_guard_restriction_t *rst)
1528 tor_assert(rst->type == RST_EXIT_NODE);
1530 // Exclude the exit ID and all of its family.
1531 const node_t *node = node_get_by_id((const char*)rst->exclude_id);
1532 if (node && guard_in_node_family(guard, node))
1533 return 0;
1535 return tor_memneq(guard->identity, rst->exclude_id, DIGEST_LEN);
1538 /** Return True if <b>guard</b> should be used as a dirserver for fetching
1539 * microdescriptors. */
1540 static int
1541 guard_obeys_md_dirserver_restriction(const entry_guard_t *guard)
1543 /* If this guard is an outdated dirserver, don't use it. */
1544 if (microdesc_relay_is_outdated_dirserver(guard->identity)) {
1545 log_info(LD_GENERAL, "Skipping %s dirserver: outdated",
1546 hex_str(guard->identity, DIGEST_LEN));
1547 return 0;
1550 log_debug(LD_GENERAL, "%s dirserver obeys md restrictions",
1551 hex_str(guard->identity, DIGEST_LEN));
1553 return 1;
1557 * Return true iff <b>guard</b> obeys the restrictions defined in <b>rst</b>.
1558 * (If <b>rst</b> is NULL, there are no restrictions.)
1560 static int
1561 entry_guard_obeys_restriction(const entry_guard_t *guard,
1562 const entry_guard_restriction_t *rst)
1564 tor_assert(guard);
1565 if (! rst)
1566 return 1; // No restriction? No problem.
1568 if (rst->type == RST_EXIT_NODE) {
1569 return guard_obeys_exit_restriction(guard, rst);
1570 } else if (rst->type == RST_OUTDATED_MD_DIRSERVER) {
1571 return guard_obeys_md_dirserver_restriction(guard);
1574 tor_assert_nonfatal_unreached();
1575 return 0;
1579 * Update the <b>is_filtered_guard</b> and <b>is_usable_filtered_guard</b>
1580 * flags on <b>guard</b>. */
1581 void
1582 entry_guard_set_filtered_flags(const or_options_t *options,
1583 guard_selection_t *gs,
1584 entry_guard_t *guard)
1586 unsigned was_filtered = guard->is_filtered_guard;
1587 guard->is_filtered_guard = 0;
1588 guard->is_usable_filtered_guard = 0;
1590 if (entry_guard_passes_filter(options, gs, guard)) {
1591 guard->is_filtered_guard = 1;
1593 if (guard->is_reachable != GUARD_REACHABLE_NO)
1594 guard->is_usable_filtered_guard = 1;
1596 entry_guard_consider_retry(guard);
1598 log_debug(LD_GUARD, "Updated sampled guard %s: filtered=%d; "
1599 "reachable_filtered=%d.", entry_guard_describe(guard),
1600 guard->is_filtered_guard, guard->is_usable_filtered_guard);
1602 if (!bool_eq(was_filtered, guard->is_filtered_guard)) {
1603 /* This guard might now be primary or nonprimary. */
1604 gs->primary_guards_up_to_date = 0;
1609 * Update the <b>is_filtered_guard</b> and <b>is_usable_filtered_guard</b>
1610 * flag on every guard in <b>gs</b>. */
1611 STATIC void
1612 entry_guards_update_filtered_sets(guard_selection_t *gs)
1614 const or_options_t *options = get_options();
1616 SMARTLIST_FOREACH_BEGIN(gs->sampled_entry_guards, entry_guard_t *, guard) {
1617 entry_guard_set_filtered_flags(options, gs, guard);
1618 } SMARTLIST_FOREACH_END(guard);
1622 * Return a random guard from the reachable filtered sample guards
1623 * in <b>gs</b>, subject to the exclusion rules listed in <b>flags</b>.
1624 * Return NULL if no such guard can be found.
1626 * Make sure that the sample is big enough, and that all the filter flags
1627 * are set correctly, before calling this function.
1629 * If a restriction is provided in <b>rst</b>, do not return any guards that
1630 * violate it.
1632 STATIC entry_guard_t *
1633 sample_reachable_filtered_entry_guards(guard_selection_t *gs,
1634 const entry_guard_restriction_t *rst,
1635 unsigned flags)
1637 tor_assert(gs);
1638 entry_guard_t *result = NULL;
1639 const unsigned exclude_confirmed = flags & SAMPLE_EXCLUDE_CONFIRMED;
1640 const unsigned exclude_primary = flags & SAMPLE_EXCLUDE_PRIMARY;
1641 const unsigned exclude_pending = flags & SAMPLE_EXCLUDE_PENDING;
1642 const unsigned no_update_primary = flags & SAMPLE_NO_UPDATE_PRIMARY;
1643 const unsigned need_descriptor = flags & SAMPLE_EXCLUDE_NO_DESCRIPTOR;
1645 SMARTLIST_FOREACH_BEGIN(gs->sampled_entry_guards, entry_guard_t *, guard) {
1646 entry_guard_consider_retry(guard);
1647 } SMARTLIST_FOREACH_END(guard);
1649 const int n_reachable_filtered = num_reachable_filtered_guards(gs, rst);
1651 log_info(LD_GUARD, "Trying to sample a reachable guard: We know of %d "
1652 "in the USABLE_FILTERED set.", n_reachable_filtered);
1654 const int min_filtered_sample = get_min_filtered_sample_size();
1655 if (n_reachable_filtered < min_filtered_sample) {
1656 log_info(LD_GUARD, " (That isn't enough. Trying to expand the sample.)");
1657 entry_guards_expand_sample(gs);
1660 if (exclude_primary && !gs->primary_guards_up_to_date && !no_update_primary)
1661 entry_guards_update_primary(gs);
1663 /* Build the set of reachable filtered guards. */
1664 smartlist_t *reachable_filtered_sample = smartlist_new();
1665 SMARTLIST_FOREACH_BEGIN(gs->sampled_entry_guards, entry_guard_t *, guard) {
1666 entry_guard_consider_retry(guard);// redundant, but cheap.
1667 if (! entry_guard_obeys_restriction(guard, rst))
1668 continue;
1669 if (! guard->is_usable_filtered_guard)
1670 continue;
1671 if (exclude_confirmed && guard->confirmed_idx >= 0)
1672 continue;
1673 if (exclude_primary && guard->is_primary)
1674 continue;
1675 if (exclude_pending && guard->is_pending)
1676 continue;
1677 if (need_descriptor && !guard_has_descriptor(guard))
1678 continue;
1679 smartlist_add(reachable_filtered_sample, guard);
1680 } SMARTLIST_FOREACH_END(guard);
1682 log_info(LD_GUARD, " (After filters [%x], we have %d guards to consider.)",
1683 flags, smartlist_len(reachable_filtered_sample));
1685 if (smartlist_len(reachable_filtered_sample)) {
1686 result = smartlist_choose(reachable_filtered_sample);
1687 log_info(LD_GUARD, " (Selected %s.)",
1688 result ? entry_guard_describe(result) : "<null>");
1690 smartlist_free(reachable_filtered_sample);
1692 return result;
1696 * Helper: compare two entry_guard_t by their confirmed_idx values.
1697 * Used to sort the confirmed list.
1699 static int
1700 compare_guards_by_confirmed_idx(const void **a_, const void **b_)
1702 const entry_guard_t *a = *a_, *b = *b_;
1703 if (a->confirmed_idx < b->confirmed_idx)
1704 return -1;
1705 else if (a->confirmed_idx > b->confirmed_idx)
1706 return 1;
1707 else
1708 return 0;
1712 * Find the confirmed guards from among the sampled guards in <b>gs</b>,
1713 * and put them in confirmed_entry_guards in the correct
1714 * order. Recalculate their indices.
1716 STATIC void
1717 entry_guards_update_confirmed(guard_selection_t *gs)
1719 smartlist_clear(gs->confirmed_entry_guards);
1720 SMARTLIST_FOREACH_BEGIN(gs->sampled_entry_guards, entry_guard_t *, guard) {
1721 if (guard->confirmed_idx >= 0)
1722 smartlist_add(gs->confirmed_entry_guards, guard);
1723 } SMARTLIST_FOREACH_END(guard);
1725 smartlist_sort(gs->confirmed_entry_guards, compare_guards_by_confirmed_idx);
1727 int any_changed = 0;
1728 SMARTLIST_FOREACH_BEGIN(gs->confirmed_entry_guards, entry_guard_t *, guard) {
1729 if (guard->confirmed_idx != guard_sl_idx) {
1730 any_changed = 1;
1731 guard->confirmed_idx = guard_sl_idx;
1733 } SMARTLIST_FOREACH_END(guard);
1735 gs->next_confirmed_idx = smartlist_len(gs->confirmed_entry_guards);
1737 if (any_changed) {
1738 entry_guards_changed_for_guard_selection(gs);
1743 * Mark <b>guard</b> as a confirmed guard -- that is, one that we have
1744 * connected to, and intend to use again.
1746 STATIC void
1747 make_guard_confirmed(guard_selection_t *gs, entry_guard_t *guard)
1749 if (BUG(guard->confirmed_on_date && guard->confirmed_idx >= 0))
1750 return; // LCOV_EXCL_LINE
1752 if (BUG(smartlist_contains(gs->confirmed_entry_guards, guard)))
1753 return; // LCOV_EXCL_LINE
1755 const int GUARD_LIFETIME = get_guard_lifetime();
1756 guard->confirmed_on_date = randomize_time(approx_time(), GUARD_LIFETIME/10);
1758 log_info(LD_GUARD, "Marking %s as a confirmed guard (index %d)",
1759 entry_guard_describe(guard),
1760 gs->next_confirmed_idx);
1762 guard->confirmed_idx = gs->next_confirmed_idx++;
1763 smartlist_add(gs->confirmed_entry_guards, guard);
1765 // This confirmed guard might kick something else out of the primary
1766 // guards.
1767 gs->primary_guards_up_to_date = 0;
1769 entry_guards_changed_for_guard_selection(gs);
1773 * Recalculate the list of primary guards (the ones we'd prefer to use) from
1774 * the filtered sample and the confirmed list.
1776 STATIC void
1777 entry_guards_update_primary(guard_selection_t *gs)
1779 tor_assert(gs);
1781 // prevent recursion. Recursion is potentially very bad here.
1782 static int running = 0;
1783 tor_assert(!running);
1784 running = 1;
1786 const int N_PRIMARY_GUARDS = get_n_primary_guards();
1788 smartlist_t *new_primary_guards = smartlist_new();
1789 smartlist_t *old_primary_guards = smartlist_new();
1790 smartlist_add_all(old_primary_guards, gs->primary_entry_guards);
1792 /* Set this flag now, to prevent the calls below from recursing. */
1793 gs->primary_guards_up_to_date = 1;
1795 /* First, can we fill it up with confirmed guards? */
1796 SMARTLIST_FOREACH_BEGIN(gs->confirmed_entry_guards, entry_guard_t *, guard) {
1797 if (smartlist_len(new_primary_guards) >= N_PRIMARY_GUARDS)
1798 break;
1799 if (! guard->is_filtered_guard)
1800 continue;
1801 guard->is_primary = 1;
1802 smartlist_add(new_primary_guards, guard);
1803 } SMARTLIST_FOREACH_END(guard);
1805 /* Can we keep any older primary guards? First remove all the ones
1806 * that we already kept. */
1807 SMARTLIST_FOREACH_BEGIN(old_primary_guards, entry_guard_t *, guard) {
1808 if (smartlist_contains(new_primary_guards, guard)) {
1809 SMARTLIST_DEL_CURRENT_KEEPORDER(old_primary_guards, guard);
1811 } SMARTLIST_FOREACH_END(guard);
1813 /* Now add any that are still good. */
1814 SMARTLIST_FOREACH_BEGIN(old_primary_guards, entry_guard_t *, guard) {
1815 if (smartlist_len(new_primary_guards) >= N_PRIMARY_GUARDS)
1816 break;
1817 if (! guard->is_filtered_guard)
1818 continue;
1819 guard->is_primary = 1;
1820 smartlist_add(new_primary_guards, guard);
1821 SMARTLIST_DEL_CURRENT_KEEPORDER(old_primary_guards, guard);
1822 } SMARTLIST_FOREACH_END(guard);
1824 /* Mark the remaining previous primary guards as non-primary */
1825 SMARTLIST_FOREACH_BEGIN(old_primary_guards, entry_guard_t *, guard) {
1826 guard->is_primary = 0;
1827 } SMARTLIST_FOREACH_END(guard);
1829 /* Finally, fill out the list with sampled guards. */
1830 while (smartlist_len(new_primary_guards) < N_PRIMARY_GUARDS) {
1831 entry_guard_t *guard = sample_reachable_filtered_entry_guards(gs, NULL,
1832 SAMPLE_EXCLUDE_CONFIRMED|
1833 SAMPLE_EXCLUDE_PRIMARY|
1834 SAMPLE_NO_UPDATE_PRIMARY);
1835 if (!guard)
1836 break;
1837 guard->is_primary = 1;
1838 smartlist_add(new_primary_guards, guard);
1841 #if 1
1842 /* Debugging. */
1843 SMARTLIST_FOREACH(gs->sampled_entry_guards, entry_guard_t *, guard, {
1844 tor_assert_nonfatal(
1845 bool_eq(guard->is_primary,
1846 smartlist_contains(new_primary_guards, guard)));
1848 #endif /* 1 */
1850 int any_change = 0;
1851 if (smartlist_len(gs->primary_entry_guards) !=
1852 smartlist_len(new_primary_guards)) {
1853 any_change = 1;
1854 } else {
1855 SMARTLIST_FOREACH_BEGIN(gs->primary_entry_guards, entry_guard_t *, g) {
1856 if (g != smartlist_get(new_primary_guards, g_sl_idx)) {
1857 any_change = 1;
1859 } SMARTLIST_FOREACH_END(g);
1862 if (any_change) {
1863 log_info(LD_GUARD, "Primary entry guards have changed. "
1864 "New primary guard list is: ");
1865 int n = smartlist_len(new_primary_guards);
1866 SMARTLIST_FOREACH_BEGIN(new_primary_guards, entry_guard_t *, g) {
1867 log_info(LD_GUARD, " %d/%d: %s%s%s",
1868 g_sl_idx+1, n, entry_guard_describe(g),
1869 g->confirmed_idx >= 0 ? " (confirmed)" : "",
1870 g->is_filtered_guard ? "" : " (excluded by filter)");
1871 } SMARTLIST_FOREACH_END(g);
1874 smartlist_free(old_primary_guards);
1875 smartlist_free(gs->primary_entry_guards);
1876 gs->primary_entry_guards = new_primary_guards;
1877 gs->primary_guards_up_to_date = 1;
1878 running = 0;
1882 * Return the number of seconds after the last attempt at which we should
1883 * retry a guard that has been failing since <b>failing_since</b>.
1885 static int
1886 get_retry_schedule(time_t failing_since, time_t now,
1887 int is_primary)
1889 const unsigned SIX_HOURS = 6 * 3600;
1890 const unsigned FOUR_DAYS = 4 * 86400;
1891 const unsigned SEVEN_DAYS = 7 * 86400;
1893 time_t tdiff;
1894 if (now > failing_since) {
1895 tdiff = now - failing_since;
1896 } else {
1897 tdiff = 0;
1900 const struct {
1901 time_t maximum; int primary_delay; int nonprimary_delay;
1902 } delays[] = {
1903 { SIX_HOURS, 10*60, 1*60*60 },
1904 { FOUR_DAYS, 90*60, 4*60*60 },
1905 { SEVEN_DAYS, 4*60*60, 18*60*60 },
1906 { TIME_MAX, 9*60*60, 36*60*60 }
1909 unsigned i;
1910 for (i = 0; i < ARRAY_LENGTH(delays); ++i) {
1911 if (tdiff <= delays[i].maximum) {
1912 return is_primary ? delays[i].primary_delay : delays[i].nonprimary_delay;
1915 /* LCOV_EXCL_START -- can't reach, since delays ends with TIME_MAX. */
1916 tor_assert_nonfatal_unreached();
1917 return 36*60*60;
1918 /* LCOV_EXCL_STOP */
1922 * If <b>guard</b> is unreachable, consider whether enough time has passed
1923 * to consider it maybe-reachable again.
1925 STATIC void
1926 entry_guard_consider_retry(entry_guard_t *guard)
1928 if (guard->is_reachable != GUARD_REACHABLE_NO)
1929 return; /* No retry needed. */
1931 const time_t now = approx_time();
1932 const int delay =
1933 get_retry_schedule(guard->failing_since, now, guard->is_primary);
1934 const time_t last_attempt = guard->last_tried_to_connect;
1936 if (BUG(last_attempt == 0) ||
1937 now >= last_attempt + delay) {
1938 /* We should mark this retriable. */
1939 char tbuf[ISO_TIME_LEN+1];
1940 format_local_iso_time(tbuf, last_attempt);
1941 log_info(LD_GUARD, "Marked %s%sguard %s for possible retry, since we "
1942 "haven't tried to use it since %s.",
1943 guard->is_primary?"primary ":"",
1944 guard->confirmed_idx>=0?"confirmed ":"",
1945 entry_guard_describe(guard),
1946 tbuf);
1948 guard->is_reachable = GUARD_REACHABLE_MAYBE;
1949 if (guard->is_filtered_guard)
1950 guard->is_usable_filtered_guard = 1;
1954 /** Tell the entry guards subsystem that we have confirmed that as of
1955 * just now, we're on the internet. */
1956 void
1957 entry_guards_note_internet_connectivity(guard_selection_t *gs)
1959 gs->last_time_on_internet = approx_time();
1963 * Get a guard for use with a circuit. Prefer to pick a running primary
1964 * guard; then a non-pending running filtered confirmed guard; then a
1965 * non-pending runnable filtered guard. Update the
1966 * <b>last_tried_to_connect</b> time and the <b>is_pending</b> fields of the
1967 * guard as appropriate. Set <b>state_out</b> to the new guard-state
1968 * of the circuit.
1970 STATIC entry_guard_t *
1971 select_entry_guard_for_circuit(guard_selection_t *gs,
1972 guard_usage_t usage,
1973 const entry_guard_restriction_t *rst,
1974 unsigned *state_out)
1976 const int need_descriptor = (usage == GUARD_USAGE_TRAFFIC);
1977 tor_assert(gs);
1978 tor_assert(state_out);
1980 if (!gs->primary_guards_up_to_date)
1981 entry_guards_update_primary(gs);
1983 int num_entry_guards = get_n_primary_guards_to_use(usage);
1984 smartlist_t *usable_primary_guards = smartlist_new();
1986 /* "If any entry in PRIMARY_GUARDS has {is_reachable} status of
1987 <maybe> or <yes>, return the first such guard." */
1988 SMARTLIST_FOREACH_BEGIN(gs->primary_entry_guards, entry_guard_t *, guard) {
1989 entry_guard_consider_retry(guard);
1990 if (! entry_guard_obeys_restriction(guard, rst))
1991 continue;
1992 if (guard->is_reachable != GUARD_REACHABLE_NO) {
1993 if (need_descriptor && !guard_has_descriptor(guard)) {
1994 continue;
1996 *state_out = GUARD_CIRC_STATE_USABLE_ON_COMPLETION;
1997 guard->last_tried_to_connect = approx_time();
1998 smartlist_add(usable_primary_guards, guard);
1999 if (smartlist_len(usable_primary_guards) >= num_entry_guards)
2000 break;
2002 } SMARTLIST_FOREACH_END(guard);
2004 if (smartlist_len(usable_primary_guards)) {
2005 entry_guard_t *guard = smartlist_choose(usable_primary_guards);
2006 smartlist_free(usable_primary_guards);
2007 log_info(LD_GUARD, "Selected primary guard %s for circuit.",
2008 entry_guard_describe(guard));
2009 return guard;
2011 smartlist_free(usable_primary_guards);
2013 /* "Otherwise, if the ordered intersection of {CONFIRMED_GUARDS}
2014 and {USABLE_FILTERED_GUARDS} is nonempty, return the first
2015 entry in that intersection that has {is_pending} set to
2016 false." */
2017 SMARTLIST_FOREACH_BEGIN(gs->confirmed_entry_guards, entry_guard_t *, guard) {
2018 if (guard->is_primary)
2019 continue; /* we already considered this one. */
2020 if (! entry_guard_obeys_restriction(guard, rst))
2021 continue;
2022 entry_guard_consider_retry(guard);
2023 if (guard->is_usable_filtered_guard && ! guard->is_pending) {
2024 if (need_descriptor && !guard_has_descriptor(guard))
2025 continue; /* not a bug */
2026 guard->is_pending = 1;
2027 guard->last_tried_to_connect = approx_time();
2028 *state_out = GUARD_CIRC_STATE_USABLE_IF_NO_BETTER_GUARD;
2029 log_info(LD_GUARD, "No primary guards available. Selected confirmed "
2030 "guard %s for circuit. Will try other guards before using "
2031 "this circuit.",
2032 entry_guard_describe(guard));
2033 return guard;
2035 } SMARTLIST_FOREACH_END(guard);
2037 /* "Otherwise, if there is no such entry, select a member at
2038 random from {USABLE_FILTERED_GUARDS}." */
2040 entry_guard_t *guard;
2041 unsigned flags = 0;
2042 if (need_descriptor)
2043 flags |= SAMPLE_EXCLUDE_NO_DESCRIPTOR;
2044 guard = sample_reachable_filtered_entry_guards(gs,
2045 rst,
2046 SAMPLE_EXCLUDE_CONFIRMED |
2047 SAMPLE_EXCLUDE_PRIMARY |
2048 SAMPLE_EXCLUDE_PENDING |
2049 flags);
2050 if (guard == NULL) {
2051 log_info(LD_GUARD, "Absolutely no sampled guards were available. "
2052 "Marking all guards for retry and starting from top again.");
2053 mark_all_guards_maybe_reachable(gs);
2054 return NULL;
2056 guard->is_pending = 1;
2057 guard->last_tried_to_connect = approx_time();
2058 *state_out = GUARD_CIRC_STATE_USABLE_IF_NO_BETTER_GUARD;
2059 log_info(LD_GUARD, "No primary or confirmed guards available. Selected "
2060 "random guard %s for circuit. Will try other guards before "
2061 "using this circuit.",
2062 entry_guard_describe(guard));
2063 return guard;
2068 * Note that we failed to connect to or build circuits through <b>guard</b>.
2069 * Use with a guard returned by select_entry_guard_for_circuit().
2071 STATIC void
2072 entry_guards_note_guard_failure(guard_selection_t *gs,
2073 entry_guard_t *guard)
2075 tor_assert(gs);
2077 guard->is_reachable = GUARD_REACHABLE_NO;
2078 guard->is_usable_filtered_guard = 0;
2080 guard->is_pending = 0;
2081 if (guard->failing_since == 0)
2082 guard->failing_since = approx_time();
2084 log_info(LD_GUARD, "Recorded failure for %s%sguard %s",
2085 guard->is_primary?"primary ":"",
2086 guard->confirmed_idx>=0?"confirmed ":"",
2087 entry_guard_describe(guard));
2091 * Note that we successfully connected to, and built a circuit through
2092 * <b>guard</b>. Given the old guard-state of the circuit in <b>old_state</b>,
2093 * return the new guard-state of the circuit.
2095 * Be aware: the circuit is only usable when its guard-state becomes
2096 * GUARD_CIRC_STATE_COMPLETE.
2098 STATIC unsigned
2099 entry_guards_note_guard_success(guard_selection_t *gs,
2100 entry_guard_t *guard,
2101 unsigned old_state)
2103 tor_assert(gs);
2105 /* Save this, since we're about to overwrite it. */
2106 const time_t last_time_on_internet = gs->last_time_on_internet;
2107 gs->last_time_on_internet = approx_time();
2109 guard->is_reachable = GUARD_REACHABLE_YES;
2110 guard->failing_since = 0;
2111 guard->is_pending = 0;
2112 if (guard->is_filtered_guard)
2113 guard->is_usable_filtered_guard = 1;
2115 if (guard->confirmed_idx < 0) {
2116 make_guard_confirmed(gs, guard);
2117 if (!gs->primary_guards_up_to_date)
2118 entry_guards_update_primary(gs);
2121 unsigned new_state;
2122 switch (old_state) {
2123 case GUARD_CIRC_STATE_COMPLETE:
2124 case GUARD_CIRC_STATE_USABLE_ON_COMPLETION:
2125 new_state = GUARD_CIRC_STATE_COMPLETE;
2126 break;
2127 default:
2128 tor_assert_nonfatal_unreached();
2129 /* Fall through. */
2130 case GUARD_CIRC_STATE_USABLE_IF_NO_BETTER_GUARD:
2131 if (guard->is_primary) {
2132 /* XXXX #20832 -- I don't actually like this logic. It seems to make
2133 * us a little more susceptible to evil-ISP attacks. The mitigations
2134 * I'm thinking of, however, aren't local to this point, so I'll leave
2135 * it alone. */
2136 /* This guard may have become primary by virtue of being confirmed.
2137 * If so, the circuit for it is now complete.
2139 new_state = GUARD_CIRC_STATE_COMPLETE;
2140 } else {
2141 new_state = GUARD_CIRC_STATE_WAITING_FOR_BETTER_GUARD;
2143 break;
2146 if (! guard->is_primary) {
2147 if (last_time_on_internet + get_internet_likely_down_interval()
2148 < approx_time()) {
2149 mark_primary_guards_maybe_reachable(gs);
2153 log_info(LD_GUARD, "Recorded success for %s%sguard %s",
2154 guard->is_primary?"primary ":"",
2155 guard->confirmed_idx>=0?"confirmed ":"",
2156 entry_guard_describe(guard));
2158 return new_state;
2162 * Helper: Return true iff <b>a</b> has higher priority than <b>b</b>.
2164 STATIC int
2165 entry_guard_has_higher_priority(entry_guard_t *a, entry_guard_t *b)
2167 tor_assert(a && b);
2168 if (a == b)
2169 return 0;
2171 /* Confirmed is always better than unconfirmed; lower index better
2172 than higher */
2173 if (a->confirmed_idx < 0) {
2174 if (b->confirmed_idx >= 0)
2175 return 0;
2176 } else {
2177 if (b->confirmed_idx < 0)
2178 return 1;
2180 /* Lower confirmed_idx is better than higher. */
2181 return (a->confirmed_idx < b->confirmed_idx);
2184 /* If we reach this point, both are unconfirmed. If one is pending, it
2185 * has higher priority. */
2186 if (a->is_pending) {
2187 if (! b->is_pending)
2188 return 1;
2190 /* Both are pending: earlier last_tried_connect wins. */
2191 return a->last_tried_to_connect < b->last_tried_to_connect;
2192 } else {
2193 if (b->is_pending)
2194 return 0;
2196 /* Neither is pending: priorities are equal. */
2197 return 0;
2201 /** Release all storage held in <b>restriction</b> */
2202 STATIC void
2203 entry_guard_restriction_free_(entry_guard_restriction_t *rst)
2205 tor_free(rst);
2209 * Release all storage held in <b>state</b>.
2211 void
2212 circuit_guard_state_free_(circuit_guard_state_t *state)
2214 if (!state)
2215 return;
2216 entry_guard_restriction_free(state->restrictions);
2217 entry_guard_handle_free(state->guard);
2218 tor_free(state);
2221 /** Allocate and return a new circuit_guard_state_t to track the result
2222 * of using <b>guard</b> for a given operation. */
2223 MOCK_IMPL(STATIC circuit_guard_state_t *,
2224 circuit_guard_state_new,(entry_guard_t *guard, unsigned state,
2225 entry_guard_restriction_t *rst))
2227 circuit_guard_state_t *result;
2229 result = tor_malloc_zero(sizeof(circuit_guard_state_t));
2230 result->guard = entry_guard_handle_new(guard);
2231 result->state = state;
2232 result->state_set_at = approx_time();
2233 result->restrictions = rst;
2235 return result;
2239 * Pick a suitable entry guard for a circuit in, and place that guard
2240 * in *<b>chosen_node_out</b>. Set *<b>guard_state_out</b> to an opaque
2241 * state object that will record whether the circuit is ready to be used
2242 * or not. Return 0 on success; on failure, return -1.
2244 * If a restriction is provided in <b>rst</b>, do not return any guards that
2245 * violate it, and remember that restriction in <b>guard_state_out</b> for
2246 * later use. (Takes ownership of the <b>rst</b> object.)
2249 entry_guard_pick_for_circuit(guard_selection_t *gs,
2250 guard_usage_t usage,
2251 entry_guard_restriction_t *rst,
2252 const node_t **chosen_node_out,
2253 circuit_guard_state_t **guard_state_out)
2255 tor_assert(gs);
2256 tor_assert(chosen_node_out);
2257 tor_assert(guard_state_out);
2258 *chosen_node_out = NULL;
2259 *guard_state_out = NULL;
2261 unsigned state = 0;
2262 entry_guard_t *guard =
2263 select_entry_guard_for_circuit(gs, usage, rst, &state);
2264 if (! guard)
2265 goto fail;
2266 if (BUG(state == 0))
2267 goto fail;
2268 const node_t *node = node_get_by_id(guard->identity);
2269 // XXXX #20827 check Ed ID.
2270 if (! node)
2271 goto fail;
2272 if (BUG(usage != GUARD_USAGE_DIRGUARD &&
2273 !node_has_preferred_descriptor(node, 1)))
2274 goto fail;
2276 *chosen_node_out = node;
2277 *guard_state_out = circuit_guard_state_new(guard, state, rst);
2279 return 0;
2280 fail:
2281 entry_guard_restriction_free(rst);
2282 return -1;
2286 * Called by the circuit building module when a circuit has succeeded: informs
2287 * the guards code that the guard in *<b>guard_state_p</b> is working, and
2288 * advances the state of the guard module. On a GUARD_USABLE_NEVER return
2289 * value, the circuit is broken and should not be used. On a GUARD_USABLE_NOW
2290 * return value, the circuit is ready to use. On a GUARD_MAYBE_USABLE_LATER
2291 * return value, the circuit should not be used until we find out whether
2292 * preferred guards will work for us.
2294 guard_usable_t
2295 entry_guard_succeeded(circuit_guard_state_t **guard_state_p)
2297 if (BUG(*guard_state_p == NULL))
2298 return GUARD_USABLE_NEVER;
2300 entry_guard_t *guard = entry_guard_handle_get((*guard_state_p)->guard);
2301 if (! guard || BUG(guard->in_selection == NULL))
2302 return GUARD_USABLE_NEVER;
2304 unsigned newstate =
2305 entry_guards_note_guard_success(guard->in_selection, guard,
2306 (*guard_state_p)->state);
2308 (*guard_state_p)->state = newstate;
2309 (*guard_state_p)->state_set_at = approx_time();
2311 if (newstate == GUARD_CIRC_STATE_COMPLETE) {
2312 return GUARD_USABLE_NOW;
2313 } else {
2314 return GUARD_MAYBE_USABLE_LATER;
2318 /** Cancel the selection of *<b>guard_state_p</b> without declaring
2319 * success or failure. It is safe to call this function if success or
2320 * failure _has_ already been declared. */
2321 void
2322 entry_guard_cancel(circuit_guard_state_t **guard_state_p)
2324 if (BUG(*guard_state_p == NULL))
2325 return;
2326 entry_guard_t *guard = entry_guard_handle_get((*guard_state_p)->guard);
2327 if (! guard)
2328 return;
2330 /* XXXX prop271 -- last_tried_to_connect_at will be erroneous here, but this
2331 * function will only get called in "bug" cases anyway. */
2332 guard->is_pending = 0;
2333 circuit_guard_state_free(*guard_state_p);
2334 *guard_state_p = NULL;
2338 * Called by the circuit building module when a circuit has failed:
2339 * informs the guards code that the guard in *<b>guard_state_p</b> is
2340 * not working, and advances the state of the guard module.
2342 void
2343 entry_guard_failed(circuit_guard_state_t **guard_state_p)
2345 if (BUG(*guard_state_p == NULL))
2346 return;
2348 entry_guard_t *guard = entry_guard_handle_get((*guard_state_p)->guard);
2349 if (! guard || BUG(guard->in_selection == NULL))
2350 return;
2352 entry_guards_note_guard_failure(guard->in_selection, guard);
2354 (*guard_state_p)->state = GUARD_CIRC_STATE_DEAD;
2355 (*guard_state_p)->state_set_at = approx_time();
2359 * Run the entry_guard_failed() function on every circuit that is
2360 * pending on <b>chan</b>.
2362 void
2363 entry_guard_chan_failed(channel_t *chan)
2365 if (!chan)
2366 return;
2368 smartlist_t *pending = smartlist_new();
2369 circuit_get_all_pending_on_channel(pending, chan);
2370 SMARTLIST_FOREACH_BEGIN(pending, circuit_t *, circ) {
2371 if (!CIRCUIT_IS_ORIGIN(circ))
2372 continue;
2374 origin_circuit_t *origin_circ = TO_ORIGIN_CIRCUIT(circ);
2375 if (origin_circ->guard_state) {
2376 /* We might have no guard state if we didn't use a guard on this
2377 * circuit (eg it's for a fallback directory). */
2378 entry_guard_failed(&origin_circ->guard_state);
2380 } SMARTLIST_FOREACH_END(circ);
2381 smartlist_free(pending);
2385 * Return true iff every primary guard in <b>gs</b> is believed to
2386 * be unreachable.
2388 STATIC int
2389 entry_guards_all_primary_guards_are_down(guard_selection_t *gs)
2391 tor_assert(gs);
2392 if (!gs->primary_guards_up_to_date)
2393 entry_guards_update_primary(gs);
2394 SMARTLIST_FOREACH_BEGIN(gs->primary_entry_guards, entry_guard_t *, guard) {
2395 entry_guard_consider_retry(guard);
2396 if (guard->is_reachable != GUARD_REACHABLE_NO)
2397 return 0;
2398 } SMARTLIST_FOREACH_END(guard);
2399 return 1;
2402 /** Wrapper for entry_guard_has_higher_priority that compares the
2403 * guard-priorities of a pair of circuits. Return 1 if <b>a</b> has higher
2404 * priority than <b>b</b>.
2406 * If a restriction is provided in <b>rst</b>, then do not consider
2407 * <b>a</b> to have higher priority if it violates the restriction.
2409 static int
2410 circ_state_has_higher_priority(origin_circuit_t *a,
2411 const entry_guard_restriction_t *rst,
2412 origin_circuit_t *b)
2414 circuit_guard_state_t *state_a = origin_circuit_get_guard_state(a);
2415 circuit_guard_state_t *state_b = origin_circuit_get_guard_state(b);
2417 tor_assert(state_a);
2418 tor_assert(state_b);
2420 entry_guard_t *guard_a = entry_guard_handle_get(state_a->guard);
2421 entry_guard_t *guard_b = entry_guard_handle_get(state_b->guard);
2423 if (! guard_a) {
2424 /* Unknown guard -- never higher priority. */
2425 return 0;
2426 } else if (! guard_b) {
2427 /* Known guard -- higher priority than any unknown guard. */
2428 return 1;
2429 } else if (! entry_guard_obeys_restriction(guard_a, rst)) {
2430 /* Restriction violated; guard_a cannot have higher priority. */
2431 return 0;
2432 } else {
2433 /* Both known -- compare.*/
2434 return entry_guard_has_higher_priority(guard_a, guard_b);
2439 * Look at all of the origin_circuit_t * objects in <b>all_circuits_in</b>,
2440 * and see if any of them that were previously not ready to use for
2441 * guard-related reasons are now ready to use. Place those circuits
2442 * in <b>newly_complete_out</b>, and mark them COMPLETE.
2444 * Return 1 if we upgraded any circuits, and 0 otherwise.
2447 entry_guards_upgrade_waiting_circuits(guard_selection_t *gs,
2448 const smartlist_t *all_circuits_in,
2449 smartlist_t *newly_complete_out)
2451 tor_assert(gs);
2452 tor_assert(all_circuits_in);
2453 tor_assert(newly_complete_out);
2455 if (! entry_guards_all_primary_guards_are_down(gs)) {
2456 /* We only upgrade a waiting circuit if the primary guards are all
2457 * down. */
2458 log_debug(LD_GUARD, "Considered upgrading guard-stalled circuits, "
2459 "but not all primary guards were definitely down.");
2460 return 0;
2463 int n_waiting = 0;
2464 int n_complete = 0;
2465 int n_complete_blocking = 0;
2466 origin_circuit_t *best_waiting_circuit = NULL;
2467 smartlist_t *all_circuits = smartlist_new();
2468 SMARTLIST_FOREACH_BEGIN(all_circuits_in, origin_circuit_t *, circ) {
2469 // We filter out circuits that aren't ours, or which we can't
2470 // reason about.
2471 circuit_guard_state_t *state = origin_circuit_get_guard_state(circ);
2472 if (state == NULL)
2473 continue;
2474 entry_guard_t *guard = entry_guard_handle_get(state->guard);
2475 if (!guard || guard->in_selection != gs)
2476 continue;
2478 smartlist_add(all_circuits, circ);
2479 } SMARTLIST_FOREACH_END(circ);
2481 SMARTLIST_FOREACH_BEGIN(all_circuits, origin_circuit_t *, circ) {
2482 circuit_guard_state_t *state = origin_circuit_get_guard_state(circ);
2483 if (BUG(state == NULL))
2484 continue;
2486 if (state->state == GUARD_CIRC_STATE_WAITING_FOR_BETTER_GUARD) {
2487 ++n_waiting;
2488 if (! best_waiting_circuit ||
2489 circ_state_has_higher_priority(circ, NULL, best_waiting_circuit)) {
2490 best_waiting_circuit = circ;
2493 } SMARTLIST_FOREACH_END(circ);
2495 if (! best_waiting_circuit) {
2496 log_debug(LD_GUARD, "Considered upgrading guard-stalled circuits, "
2497 "but didn't find any.");
2498 goto no_change;
2501 /* We'll need to keep track of what restrictions were used when picking this
2502 * circuit, so that we don't allow any circuit without those restrictions to
2503 * block it. */
2504 const entry_guard_restriction_t *rst_on_best_waiting =
2505 origin_circuit_get_guard_state(best_waiting_circuit)->restrictions;
2507 /* First look at the complete circuits: Do any block this circuit? */
2508 SMARTLIST_FOREACH_BEGIN(all_circuits, origin_circuit_t *, circ) {
2509 /* "C2 "blocks" C1 if:
2510 * C2 obeys all the restrictions that C1 had to obey, AND
2511 * C2 has higher priority than C1, AND
2512 * Either C2 is <complete>, or C2 is <waiting_for_better_guard>,
2513 or C2 has been <usable_if_no_better_guard> for no more than
2514 {NONPRIMARY_GUARD_CONNECT_TIMEOUT} seconds."
2516 circuit_guard_state_t *state = origin_circuit_get_guard_state(circ);
2517 if BUG((state == NULL))
2518 continue;
2519 if (state->state != GUARD_CIRC_STATE_COMPLETE)
2520 continue;
2521 ++n_complete;
2522 if (circ_state_has_higher_priority(circ, rst_on_best_waiting,
2523 best_waiting_circuit))
2524 ++n_complete_blocking;
2525 } SMARTLIST_FOREACH_END(circ);
2527 if (n_complete_blocking) {
2528 log_debug(LD_GUARD, "Considered upgrading guard-stalled circuits: found "
2529 "%d complete and %d guard-stalled. At least one complete "
2530 "circuit had higher priority, so not upgrading.",
2531 n_complete, n_waiting);
2532 goto no_change;
2535 /* " * If any circuit C1 is <waiting_for_better_guard>, AND:
2536 * All primary guards have reachable status of <no>.
2537 * There is no circuit C2 that "blocks" C1.
2538 Then, upgrade C1 to <complete>.""
2540 int n_blockers_found = 0;
2541 const time_t state_set_at_cutoff =
2542 approx_time() - get_nonprimary_guard_connect_timeout();
2543 SMARTLIST_FOREACH_BEGIN(all_circuits, origin_circuit_t *, circ) {
2544 circuit_guard_state_t *state = origin_circuit_get_guard_state(circ);
2545 if (BUG(state == NULL))
2546 continue;
2547 if (state->state != GUARD_CIRC_STATE_USABLE_IF_NO_BETTER_GUARD)
2548 continue;
2549 if (state->state_set_at <= state_set_at_cutoff)
2550 continue;
2551 if (circ_state_has_higher_priority(circ, rst_on_best_waiting,
2552 best_waiting_circuit))
2553 ++n_blockers_found;
2554 } SMARTLIST_FOREACH_END(circ);
2556 if (n_blockers_found) {
2557 log_debug(LD_GUARD, "Considered upgrading guard-stalled circuits: found "
2558 "%d guard-stalled, but %d pending circuit(s) had higher "
2559 "guard priority, so not upgrading.",
2560 n_waiting, n_blockers_found);
2561 goto no_change;
2564 /* Okay. We have a best waiting circuit, and we aren't waiting for
2565 anything better. Add all circuits with that priority to the
2566 list, and call them COMPLETE. */
2567 int n_succeeded = 0;
2568 SMARTLIST_FOREACH_BEGIN(all_circuits, origin_circuit_t *, circ) {
2569 circuit_guard_state_t *state = origin_circuit_get_guard_state(circ);
2570 if (BUG(state == NULL))
2571 continue;
2572 if (circ != best_waiting_circuit && rst_on_best_waiting) {
2573 /* Can't upgrade other circ with same priority as best; might
2574 be blocked. */
2575 continue;
2577 if (state->state != GUARD_CIRC_STATE_WAITING_FOR_BETTER_GUARD)
2578 continue;
2579 if (circ_state_has_higher_priority(best_waiting_circuit, NULL, circ))
2580 continue;
2582 state->state = GUARD_CIRC_STATE_COMPLETE;
2583 state->state_set_at = approx_time();
2584 smartlist_add(newly_complete_out, circ);
2585 ++n_succeeded;
2586 } SMARTLIST_FOREACH_END(circ);
2588 log_info(LD_GUARD, "Considered upgrading guard-stalled circuits: found "
2589 "%d guard-stalled, %d complete. %d of the guard-stalled "
2590 "circuit(s) had high enough priority to upgrade.",
2591 n_waiting, n_complete, n_succeeded);
2593 tor_assert_nonfatal(n_succeeded >= 1);
2594 smartlist_free(all_circuits);
2595 return 1;
2597 no_change:
2598 smartlist_free(all_circuits);
2599 return 0;
2603 * Return true iff the circuit whose state is <b>guard_state</b> should
2604 * expire.
2607 entry_guard_state_should_expire(circuit_guard_state_t *guard_state)
2609 if (guard_state == NULL)
2610 return 0;
2611 const time_t expire_if_waiting_since =
2612 approx_time() - get_nonprimary_guard_idle_timeout();
2613 return (guard_state->state == GUARD_CIRC_STATE_WAITING_FOR_BETTER_GUARD
2614 && guard_state->state_set_at < expire_if_waiting_since);
2618 * Update all derived pieces of the guard selection state in <b>gs</b>.
2619 * Return true iff we should stop using all previously generated circuits.
2622 entry_guards_update_all(guard_selection_t *gs)
2624 sampled_guards_update_from_consensus(gs);
2625 entry_guards_update_filtered_sets(gs);
2626 entry_guards_update_confirmed(gs);
2627 entry_guards_update_primary(gs);
2628 return 0;
2632 * Return a newly allocated string for encoding the persistent parts of
2633 * <b>guard</b> to the state file.
2635 STATIC char *
2636 entry_guard_encode_for_state(entry_guard_t *guard)
2639 * The meta-format we use is K=V K=V K=V... where K can be any
2640 * characters excepts space and =, and V can be any characters except
2641 * space. The order of entries is not allowed to matter.
2642 * Unrecognized K=V entries are persisted; recognized but erroneous
2643 * entries are corrected.
2646 smartlist_t *result = smartlist_new();
2647 char tbuf[ISO_TIME_LEN+1];
2649 tor_assert(guard);
2651 smartlist_add_asprintf(result, "in=%s", guard->selection_name);
2652 smartlist_add_asprintf(result, "rsa_id=%s",
2653 hex_str(guard->identity, DIGEST_LEN));
2654 if (guard->bridge_addr) {
2655 smartlist_add_asprintf(result, "bridge_addr=%s:%d",
2656 fmt_and_decorate_addr(&guard->bridge_addr->addr),
2657 guard->bridge_addr->port);
2659 if (strlen(guard->nickname) && is_legal_nickname(guard->nickname)) {
2660 smartlist_add_asprintf(result, "nickname=%s", guard->nickname);
2663 format_iso_time_nospace(tbuf, guard->sampled_on_date);
2664 smartlist_add_asprintf(result, "sampled_on=%s", tbuf);
2666 if (guard->sampled_by_version) {
2667 smartlist_add_asprintf(result, "sampled_by=%s",
2668 guard->sampled_by_version);
2671 if (guard->unlisted_since_date > 0) {
2672 format_iso_time_nospace(tbuf, guard->unlisted_since_date);
2673 smartlist_add_asprintf(result, "unlisted_since=%s", tbuf);
2676 smartlist_add_asprintf(result, "listed=%d",
2677 (int)guard->currently_listed);
2679 if (guard->confirmed_idx >= 0) {
2680 format_iso_time_nospace(tbuf, guard->confirmed_on_date);
2681 smartlist_add_asprintf(result, "confirmed_on=%s", tbuf);
2683 smartlist_add_asprintf(result, "confirmed_idx=%d", guard->confirmed_idx);
2686 const double EPSILON = 1.0e-6;
2688 /* Make a copy of the pathbias object, since we will want to update
2689 some of them */
2690 guard_pathbias_t *pb = tor_memdup(&guard->pb, sizeof(*pb));
2691 pb->use_successes = pathbias_get_use_success_count(guard);
2692 pb->successful_circuits_closed = pathbias_get_close_success_count(guard);
2694 #define PB_FIELD(field) do { \
2695 if (pb->field >= EPSILON) { \
2696 smartlist_add_asprintf(result, "pb_" #field "=%f", pb->field); \
2698 } while (0)
2699 PB_FIELD(use_attempts);
2700 PB_FIELD(use_successes);
2701 PB_FIELD(circ_attempts);
2702 PB_FIELD(circ_successes);
2703 PB_FIELD(successful_circuits_closed);
2704 PB_FIELD(collapsed_circuits);
2705 PB_FIELD(unusable_circuits);
2706 PB_FIELD(timeouts);
2707 tor_free(pb);
2708 #undef PB_FIELD
2710 if (guard->extra_state_fields)
2711 smartlist_add_strdup(result, guard->extra_state_fields);
2713 char *joined = smartlist_join_strings(result, " ", 0, NULL);
2714 SMARTLIST_FOREACH(result, char *, cp, tor_free(cp));
2715 smartlist_free(result);
2717 return joined;
2721 * Given a string generated by entry_guard_encode_for_state(), parse it
2722 * (if possible) and return an entry_guard_t object for it. Return NULL
2723 * on complete failure.
2725 STATIC entry_guard_t *
2726 entry_guard_parse_from_state(const char *s)
2728 /* Unrecognized entries get put in here. */
2729 smartlist_t *extra = smartlist_new();
2731 /* These fields get parsed from the string. */
2732 char *in = NULL;
2733 char *rsa_id = NULL;
2734 char *nickname = NULL;
2735 char *sampled_on = NULL;
2736 char *sampled_by = NULL;
2737 char *unlisted_since = NULL;
2738 char *listed = NULL;
2739 char *confirmed_on = NULL;
2740 char *confirmed_idx = NULL;
2741 char *bridge_addr = NULL;
2743 // pathbias
2744 char *pb_use_attempts = NULL;
2745 char *pb_use_successes = NULL;
2746 char *pb_circ_attempts = NULL;
2747 char *pb_circ_successes = NULL;
2748 char *pb_successful_circuits_closed = NULL;
2749 char *pb_collapsed_circuits = NULL;
2750 char *pb_unusable_circuits = NULL;
2751 char *pb_timeouts = NULL;
2753 /* Split up the entries. Put the ones we know about in strings and the
2754 * rest in "extra". */
2756 smartlist_t *entries = smartlist_new();
2758 strmap_t *vals = strmap_new(); // Maps keyword to location
2759 #define FIELD(f) \
2760 strmap_set(vals, #f, &f);
2761 FIELD(in);
2762 FIELD(rsa_id);
2763 FIELD(nickname);
2764 FIELD(sampled_on);
2765 FIELD(sampled_by);
2766 FIELD(unlisted_since);
2767 FIELD(listed);
2768 FIELD(confirmed_on);
2769 FIELD(confirmed_idx);
2770 FIELD(bridge_addr);
2771 FIELD(pb_use_attempts);
2772 FIELD(pb_use_successes);
2773 FIELD(pb_circ_attempts);
2774 FIELD(pb_circ_successes);
2775 FIELD(pb_successful_circuits_closed);
2776 FIELD(pb_collapsed_circuits);
2777 FIELD(pb_unusable_circuits);
2778 FIELD(pb_timeouts);
2779 #undef FIELD
2781 smartlist_split_string(entries, s, " ",
2782 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
2784 SMARTLIST_FOREACH_BEGIN(entries, char *, entry) {
2785 const char *eq = strchr(entry, '=');
2786 if (!eq) {
2787 smartlist_add(extra, entry);
2788 continue;
2790 char *key = tor_strndup(entry, eq-entry);
2791 char **target = strmap_get(vals, key);
2792 if (target == NULL || *target != NULL) {
2793 /* unrecognized or already set */
2794 smartlist_add(extra, entry);
2795 tor_free(key);
2796 continue;
2799 *target = tor_strdup(eq+1);
2800 tor_free(key);
2801 tor_free(entry);
2802 } SMARTLIST_FOREACH_END(entry);
2804 smartlist_free(entries);
2805 strmap_free(vals, NULL);
2808 entry_guard_t *guard = tor_malloc_zero(sizeof(entry_guard_t));
2809 guard->is_persistent = 1;
2811 if (in == NULL) {
2812 log_warn(LD_CIRC, "Guard missing 'in' field");
2813 goto err;
2816 guard->selection_name = in;
2817 in = NULL;
2819 if (rsa_id == NULL) {
2820 log_warn(LD_CIRC, "Guard missing RSA ID field");
2821 goto err;
2824 /* Process the identity and nickname. */
2825 if (base16_decode(guard->identity, sizeof(guard->identity),
2826 rsa_id, strlen(rsa_id)) != DIGEST_LEN) {
2827 log_warn(LD_CIRC, "Unable to decode guard identity %s", escaped(rsa_id));
2828 goto err;
2831 if (nickname) {
2832 strlcpy(guard->nickname, nickname, sizeof(guard->nickname));
2833 } else {
2834 guard->nickname[0]='$';
2835 base16_encode(guard->nickname+1, sizeof(guard->nickname)-1,
2836 guard->identity, DIGEST_LEN);
2839 if (bridge_addr) {
2840 tor_addr_port_t res;
2841 memset(&res, 0, sizeof(res));
2842 int r = tor_addr_port_parse(LOG_WARN, bridge_addr,
2843 &res.addr, &res.port, -1);
2844 if (r == 0)
2845 guard->bridge_addr = tor_memdup(&res, sizeof(res));
2846 /* On error, we already warned. */
2849 /* Process the various time fields. */
2851 #define HANDLE_TIME(field) do { \
2852 if (field) { \
2853 int r = parse_iso_time_nospace(field, &field ## _time); \
2854 if (r < 0) { \
2855 log_warn(LD_CIRC, "Unable to parse %s %s from guard", \
2856 #field, escaped(field)); \
2857 field##_time = -1; \
2860 } while (0)
2862 time_t sampled_on_time = 0;
2863 time_t unlisted_since_time = 0;
2864 time_t confirmed_on_time = 0;
2866 HANDLE_TIME(sampled_on);
2867 HANDLE_TIME(unlisted_since);
2868 HANDLE_TIME(confirmed_on);
2870 if (sampled_on_time <= 0)
2871 sampled_on_time = approx_time();
2872 if (unlisted_since_time < 0)
2873 unlisted_since_time = 0;
2874 if (confirmed_on_time < 0)
2875 confirmed_on_time = 0;
2877 #undef HANDLE_TIME
2879 guard->sampled_on_date = sampled_on_time;
2880 guard->unlisted_since_date = unlisted_since_time;
2881 guard->confirmed_on_date = confirmed_on_time;
2883 /* Take sampled_by_version verbatim. */
2884 guard->sampled_by_version = sampled_by;
2885 sampled_by = NULL; /* prevent free */
2887 /* Listed is a boolean */
2888 if (listed && strcmp(listed, "0"))
2889 guard->currently_listed = 1;
2891 /* The index is a nonnegative integer. */
2892 guard->confirmed_idx = -1;
2893 if (confirmed_idx) {
2894 int ok=1;
2895 long idx = tor_parse_long(confirmed_idx, 10, 0, INT_MAX, &ok, NULL);
2896 if (! ok) {
2897 log_warn(LD_GUARD, "Guard has invalid confirmed_idx %s",
2898 escaped(confirmed_idx));
2899 } else {
2900 guard->confirmed_idx = (int)idx;
2904 /* Anything we didn't recognize gets crammed together */
2905 if (smartlist_len(extra) > 0) {
2906 guard->extra_state_fields = smartlist_join_strings(extra, " ", 0, NULL);
2909 /* initialize non-persistent fields */
2910 guard->is_reachable = GUARD_REACHABLE_MAYBE;
2912 #define PB_FIELD(field) \
2913 do { \
2914 if (pb_ ## field) { \
2915 int ok = 1; \
2916 double r = tor_parse_double(pb_ ## field, 0.0, 1e9, &ok, NULL); \
2917 if (! ok) { \
2918 log_warn(LD_CIRC, "Guard has invalid pb_%s %s", \
2919 #field, pb_ ## field); \
2920 } else { \
2921 guard->pb.field = r; \
2924 } while (0)
2925 PB_FIELD(use_attempts);
2926 PB_FIELD(use_successes);
2927 PB_FIELD(circ_attempts);
2928 PB_FIELD(circ_successes);
2929 PB_FIELD(successful_circuits_closed);
2930 PB_FIELD(collapsed_circuits);
2931 PB_FIELD(unusable_circuits);
2932 PB_FIELD(timeouts);
2933 #undef PB_FIELD
2935 pathbias_check_use_success_count(guard);
2936 pathbias_check_close_success_count(guard);
2938 /* We update everything on this guard later, after we've parsed
2939 * everything. */
2941 goto done;
2943 err:
2944 // only consider it an error if the guard state was totally unparseable.
2945 entry_guard_free(guard);
2946 guard = NULL;
2948 done:
2949 tor_free(in);
2950 tor_free(rsa_id);
2951 tor_free(nickname);
2952 tor_free(sampled_on);
2953 tor_free(sampled_by);
2954 tor_free(unlisted_since);
2955 tor_free(listed);
2956 tor_free(confirmed_on);
2957 tor_free(confirmed_idx);
2958 tor_free(bridge_addr);
2959 tor_free(pb_use_attempts);
2960 tor_free(pb_use_successes);
2961 tor_free(pb_circ_attempts);
2962 tor_free(pb_circ_successes);
2963 tor_free(pb_successful_circuits_closed);
2964 tor_free(pb_collapsed_circuits);
2965 tor_free(pb_unusable_circuits);
2966 tor_free(pb_timeouts);
2968 SMARTLIST_FOREACH(extra, char *, cp, tor_free(cp));
2969 smartlist_free(extra);
2971 return guard;
2975 * Replace the Guards entries in <b>state</b> with a list of all our sampled
2976 * guards.
2978 static void
2979 entry_guards_update_guards_in_state(or_state_t *state)
2981 if (!guard_contexts)
2982 return;
2983 config_line_t *lines = NULL;
2984 config_line_t **nextline = &lines;
2986 SMARTLIST_FOREACH_BEGIN(guard_contexts, guard_selection_t *, gs) {
2987 SMARTLIST_FOREACH_BEGIN(gs->sampled_entry_guards, entry_guard_t *, guard) {
2988 if (guard->is_persistent == 0)
2989 continue;
2990 *nextline = tor_malloc_zero(sizeof(config_line_t));
2991 (*nextline)->key = tor_strdup("Guard");
2992 (*nextline)->value = entry_guard_encode_for_state(guard);
2993 nextline = &(*nextline)->next;
2994 } SMARTLIST_FOREACH_END(guard);
2995 } SMARTLIST_FOREACH_END(gs);
2997 config_free_lines(state->Guard);
2998 state->Guard = lines;
3002 * Replace our sampled guards from the Guards entries in <b>state</b>. Return 0
3003 * on success, -1 on failure. (If <b>set</b> is true, replace nothing -- only
3004 * check whether replacing would work.)
3006 static int
3007 entry_guards_load_guards_from_state(or_state_t *state, int set)
3009 const config_line_t *line = state->Guard;
3010 int n_errors = 0;
3012 if (!guard_contexts)
3013 guard_contexts = smartlist_new();
3015 /* Wipe all our existing guard info. (we shouldn't have any, but
3016 * let's be safe.) */
3017 if (set) {
3018 SMARTLIST_FOREACH_BEGIN(guard_contexts, guard_selection_t *, gs) {
3019 guard_selection_free(gs);
3020 if (curr_guard_context == gs)
3021 curr_guard_context = NULL;
3022 SMARTLIST_DEL_CURRENT(guard_contexts, gs);
3023 } SMARTLIST_FOREACH_END(gs);
3026 for ( ; line != NULL; line = line->next) {
3027 entry_guard_t *guard = entry_guard_parse_from_state(line->value);
3028 if (guard == NULL) {
3029 ++n_errors;
3030 continue;
3032 tor_assert(guard->selection_name);
3033 if (!strcmp(guard->selection_name, "legacy")) {
3034 ++n_errors;
3035 entry_guard_free(guard);
3036 continue;
3039 if (set) {
3040 guard_selection_t *gs;
3041 gs = get_guard_selection_by_name(guard->selection_name,
3042 GS_TYPE_INFER, 1);
3043 tor_assert(gs);
3044 smartlist_add(gs->sampled_entry_guards, guard);
3045 guard->in_selection = gs;
3046 } else {
3047 entry_guard_free(guard);
3051 if (set) {
3052 SMARTLIST_FOREACH_BEGIN(guard_contexts, guard_selection_t *, gs) {
3053 entry_guards_update_all(gs);
3054 } SMARTLIST_FOREACH_END(gs);
3056 return n_errors ? -1 : 0;
3059 /** If <b>digest</b> matches the identity of any node in the
3060 * entry_guards list for the provided guard selection state,
3061 return that node. Else return NULL. */
3062 entry_guard_t *
3063 entry_guard_get_by_id_digest_for_guard_selection(guard_selection_t *gs,
3064 const char *digest)
3066 return get_sampled_guard_with_id(gs, (const uint8_t*)digest);
3069 /** Return the node_t associated with a single entry_guard_t. May
3070 * return NULL if the guard is not currently in the consensus. */
3071 const node_t *
3072 entry_guard_find_node(const entry_guard_t *guard)
3074 tor_assert(guard);
3075 return node_get_by_id(guard->identity);
3078 /** If <b>digest</b> matches the identity of any node in the
3079 * entry_guards list for the default guard selection state,
3080 return that node. Else return NULL. */
3081 entry_guard_t *
3082 entry_guard_get_by_id_digest(const char *digest)
3084 return entry_guard_get_by_id_digest_for_guard_selection(
3085 get_guard_selection_info(), digest);
3088 /** We are about to connect to bridge with identity <b>digest</b> to fetch its
3089 * descriptor. Create a new guard state for this connection and return it. */
3090 circuit_guard_state_t *
3091 get_guard_state_for_bridge_desc_fetch(const char *digest)
3093 circuit_guard_state_t *guard_state = NULL;
3094 entry_guard_t *guard = NULL;
3096 guard = entry_guard_get_by_id_digest_for_guard_selection(
3097 get_guard_selection_info(), digest);
3098 if (!guard) {
3099 return NULL;
3102 /* Update the guard last_tried_to_connect time since it's checked by the
3103 * guard susbsystem. */
3104 guard->last_tried_to_connect = approx_time();
3106 /* Create the guard state */
3107 guard_state = circuit_guard_state_new(guard,
3108 GUARD_CIRC_STATE_USABLE_ON_COMPLETION,
3109 NULL);
3111 return guard_state;
3114 /** Release all storage held by <b>e</b>. */
3115 STATIC void
3116 entry_guard_free_(entry_guard_t *e)
3118 if (!e)
3119 return;
3120 entry_guard_handles_clear(e);
3121 tor_free(e->sampled_by_version);
3122 tor_free(e->extra_state_fields);
3123 tor_free(e->selection_name);
3124 tor_free(e->bridge_addr);
3125 tor_free(e);
3128 /** Return 0 if we're fine adding arbitrary routers out of the
3129 * directory to our entry guard list, or return 1 if we have a
3130 * list already and we must stick to it.
3133 entry_list_is_constrained(const or_options_t *options)
3135 // XXXX #21425 look at the current selection.
3136 if (options->EntryNodes)
3137 return 1;
3138 if (options->UseBridges)
3139 return 1;
3140 return 0;
3143 /** Return the number of bridges that have descriptors that are marked with
3144 * purpose 'bridge' and are running. If use_maybe_reachable is
3145 * true, include bridges that might be reachable in the count.
3146 * Otherwise, if it is false, only include bridges that have recently been
3147 * found running in the count.
3149 * We use this function to decide if we're ready to start building
3150 * circuits through our bridges, or if we need to wait until the
3151 * directory "server/authority" requests finish. */
3152 MOCK_IMPL(int,
3153 num_bridges_usable,(int use_maybe_reachable))
3155 int n_options = 0;
3157 if (BUG(!get_options()->UseBridges)) {
3158 return 0;
3160 guard_selection_t *gs = get_guard_selection_info();
3161 if (BUG(gs->type != GS_TYPE_BRIDGE)) {
3162 return 0;
3165 SMARTLIST_FOREACH_BEGIN(gs->sampled_entry_guards, entry_guard_t *, guard) {
3166 /* Definitely not usable */
3167 if (guard->is_reachable == GUARD_REACHABLE_NO)
3168 continue;
3169 /* If we want to be really sure the bridges will work, skip maybes */
3170 if (!use_maybe_reachable && guard->is_reachable == GUARD_REACHABLE_MAYBE)
3171 continue;
3172 if (tor_digest_is_zero(guard->identity))
3173 continue;
3174 const node_t *node = node_get_by_id(guard->identity);
3175 if (node && node->ri)
3176 ++n_options;
3177 } SMARTLIST_FOREACH_END(guard);
3179 return n_options;
3182 /** Check the pathbias use success count of <b>node</b> and disable it if it
3183 * goes over our thresholds. */
3184 static void
3185 pathbias_check_use_success_count(entry_guard_t *node)
3187 const or_options_t *options = get_options();
3188 const double EPSILON = 1.0e-9;
3190 /* Note: We rely on the < comparison here to allow us to set a 0
3191 * rate and disable the feature entirely. If refactoring, don't
3192 * change to <= */
3193 if (node->pb.use_attempts > EPSILON &&
3194 pathbias_get_use_success_count(node)/node->pb.use_attempts
3195 < pathbias_get_extreme_use_rate(options) &&
3196 pathbias_get_dropguards(options)) {
3197 node->pb.path_bias_disabled = 1;
3198 log_info(LD_GENERAL,
3199 "Path use bias is too high (%f/%f); disabling node %s",
3200 node->pb.circ_successes, node->pb.circ_attempts,
3201 node->nickname);
3205 /** Check the pathbias close count of <b>node</b> and disable it if it goes
3206 * over our thresholds. */
3207 static void
3208 pathbias_check_close_success_count(entry_guard_t *node)
3210 const or_options_t *options = get_options();
3211 const double EPSILON = 1.0e-9;
3213 /* Note: We rely on the < comparison here to allow us to set a 0
3214 * rate and disable the feature entirely. If refactoring, don't
3215 * change to <= */
3216 if (node->pb.circ_attempts > EPSILON &&
3217 pathbias_get_close_success_count(node)/node->pb.circ_attempts
3218 < pathbias_get_extreme_rate(options) &&
3219 pathbias_get_dropguards(options)) {
3220 node->pb.path_bias_disabled = 1;
3221 log_info(LD_GENERAL,
3222 "Path bias is too high (%f/%f); disabling node %s",
3223 node->pb.circ_successes, node->pb.circ_attempts,
3224 node->nickname);
3228 /** Parse <b>state</b> and learn about the entry guards it describes.
3229 * If <b>set</b> is true, and there are no errors, replace the guard
3230 * list in the default guard selection context with what we find.
3231 * On success, return 0. On failure, alloc into *<b>msg</b> a string
3232 * describing the error, and return -1.
3235 entry_guards_parse_state(or_state_t *state, int set, char **msg)
3237 entry_guards_dirty = 0;
3238 int r1 = entry_guards_load_guards_from_state(state, set);
3239 entry_guards_dirty = 0;
3241 if (r1 < 0) {
3242 if (msg && *msg == NULL) {
3243 *msg = tor_strdup("parsing error");
3245 return -1;
3247 return 0;
3250 /** How long will we let a change in our guard nodes stay un-saved
3251 * when we are trying to avoid disk writes? */
3252 #define SLOW_GUARD_STATE_FLUSH_TIME 600
3253 /** How long will we let a change in our guard nodes stay un-saved
3254 * when we are not trying to avoid disk writes? */
3255 #define FAST_GUARD_STATE_FLUSH_TIME 30
3257 /** Our list of entry guards has changed for a particular guard selection
3258 * context, or some element of one of our entry guards has changed for one.
3259 * Write the changes to disk within the next few minutes.
3261 void
3262 entry_guards_changed_for_guard_selection(guard_selection_t *gs)
3264 time_t when;
3266 tor_assert(gs != NULL);
3268 entry_guards_dirty = 1;
3270 if (get_options()->AvoidDiskWrites)
3271 when = time(NULL) + SLOW_GUARD_STATE_FLUSH_TIME;
3272 else
3273 when = time(NULL) + FAST_GUARD_STATE_FLUSH_TIME;
3275 /* or_state_save() will call entry_guards_update_state() and
3276 entry_guards_update_guards_in_state()
3278 or_state_mark_dirty(get_or_state(), when);
3281 /** Our list of entry guards has changed for the default guard selection
3282 * context, or some element of one of our entry guards has changed. Write
3283 * the changes to disk within the next few minutes.
3285 void
3286 entry_guards_changed(void)
3288 entry_guards_changed_for_guard_selection(get_guard_selection_info());
3291 /** If the entry guard info has not changed, do nothing and return.
3292 * Otherwise, free the EntryGuards piece of <b>state</b> and create
3293 * a new one out of the global entry_guards list, and then mark
3294 * <b>state</b> dirty so it will get saved to disk.
3296 void
3297 entry_guards_update_state(or_state_t *state)
3299 entry_guards_dirty = 0;
3301 // Handles all guard info.
3302 entry_guards_update_guards_in_state(state);
3304 entry_guards_dirty = 0;
3306 if (!get_options()->AvoidDiskWrites)
3307 or_state_mark_dirty(get_or_state(), 0);
3308 entry_guards_dirty = 0;
3311 /** Return true iff the circuit's guard can succeed that is can be used. */
3313 entry_guard_could_succeed(const circuit_guard_state_t *guard_state)
3315 if (!guard_state) {
3316 return 0;
3319 entry_guard_t *guard = entry_guard_handle_get(guard_state->guard);
3320 if (!guard || BUG(guard->in_selection == NULL)) {
3321 return 0;
3324 return 1;
3328 * Format a single entry guard in the format expected by the controller.
3329 * Return a newly allocated string.
3331 STATIC char *
3332 getinfo_helper_format_single_entry_guard(const entry_guard_t *e)
3334 const char *status = NULL;
3335 time_t when = 0;
3336 const node_t *node;
3337 char tbuf[ISO_TIME_LEN+1];
3338 char nbuf[MAX_VERBOSE_NICKNAME_LEN+1];
3340 /* This is going to be a bit tricky, since the status
3341 * codes weren't really intended for prop271 guards.
3343 * XXXX use a more appropriate format for exporting this information
3345 if (e->confirmed_idx < 0) {
3346 status = "never-connected";
3347 } else if (! e->currently_listed) {
3348 when = e->unlisted_since_date;
3349 status = "unusable";
3350 } else if (! e->is_filtered_guard) {
3351 status = "unusable";
3352 } else if (e->is_reachable == GUARD_REACHABLE_NO) {
3353 when = e->failing_since;
3354 status = "down";
3355 } else {
3356 status = "up";
3359 node = entry_guard_find_node(e);
3360 if (node) {
3361 node_get_verbose_nickname(node, nbuf);
3362 } else {
3363 nbuf[0] = '$';
3364 base16_encode(nbuf+1, sizeof(nbuf)-1, e->identity, DIGEST_LEN);
3365 /* e->nickname field is not very reliable if we don't know about
3366 * this router any longer; don't include it. */
3369 char *result = NULL;
3370 if (when) {
3371 format_iso_time(tbuf, when);
3372 tor_asprintf(&result, "%s %s %s\n", nbuf, status, tbuf);
3373 } else {
3374 tor_asprintf(&result, "%s %s\n", nbuf, status);
3376 return result;
3379 /** If <b>question</b> is the string "entry-guards", then dump
3380 * to *<b>answer</b> a newly allocated string describing all of
3381 * the nodes in the global entry_guards list. See control-spec.txt
3382 * for details.
3383 * For backward compatibility, we also handle the string "helper-nodes".
3385 * XXX this should be totally redesigned after prop 271 too, and that's
3386 * going to take some control spec work.
3387 * */
3389 getinfo_helper_entry_guards(control_connection_t *conn,
3390 const char *question, char **answer,
3391 const char **errmsg)
3393 guard_selection_t *gs = get_guard_selection_info();
3395 tor_assert(gs != NULL);
3397 (void) conn;
3398 (void) errmsg;
3400 if (!strcmp(question,"entry-guards") ||
3401 !strcmp(question,"helper-nodes")) {
3402 const smartlist_t *guards;
3403 guards = gs->sampled_entry_guards;
3405 smartlist_t *sl = smartlist_new();
3407 SMARTLIST_FOREACH_BEGIN(guards, const entry_guard_t *, e) {
3408 char *cp = getinfo_helper_format_single_entry_guard(e);
3409 smartlist_add(sl, cp);
3410 } SMARTLIST_FOREACH_END(e);
3411 *answer = smartlist_join_strings(sl, "", 0, NULL);
3412 SMARTLIST_FOREACH(sl, char *, c, tor_free(c));
3413 smartlist_free(sl);
3415 return 0;
3418 /* Given the original bandwidth of a guard and its guardfraction,
3419 * calculate how much bandwidth the guard should have as a guard and
3420 * as a non-guard.
3422 * Quoting from proposal236:
3424 * Let Wpf denote the weight from the 'bandwidth-weights' line a
3425 * client would apply to N for position p if it had the guard
3426 * flag, Wpn the weight if it did not have the guard flag, and B the
3427 * measured bandwidth of N in the consensus. Then instead of choosing
3428 * N for position p proportionally to Wpf*B or Wpn*B, clients should
3429 * choose N proportionally to F*Wpf*B + (1-F)*Wpn*B.
3431 * This function fills the <b>guardfraction_bw</b> structure. It sets
3432 * <b>guard_bw</b> to F*B and <b>non_guard_bw</b> to (1-F)*B.
3434 void
3435 guard_get_guardfraction_bandwidth(guardfraction_bandwidth_t *guardfraction_bw,
3436 int orig_bandwidth,
3437 uint32_t guardfraction_percentage)
3439 double guardfraction_fraction;
3441 /* Turn the percentage into a fraction. */
3442 tor_assert(guardfraction_percentage <= 100);
3443 guardfraction_fraction = guardfraction_percentage / 100.0;
3445 long guard_bw = tor_lround(guardfraction_fraction * orig_bandwidth);
3446 tor_assert(guard_bw <= INT_MAX);
3448 guardfraction_bw->guard_bw = (int) guard_bw;
3450 guardfraction_bw->non_guard_bw = orig_bandwidth - (int) guard_bw;
3453 /** Helper: Update the status of all entry guards, in whatever algorithm
3454 * is used. Return true if we should stop using all previously generated
3455 * circuits, by calling circuit_mark_all_unused_circs() and
3456 * circuit_mark_all_dirty_circs_as_unusable().
3459 guards_update_all(void)
3461 int mark_circuits = 0;
3462 if (update_guard_selection_choice(get_options()))
3463 mark_circuits = 1;
3465 tor_assert(curr_guard_context);
3467 if (entry_guards_update_all(curr_guard_context))
3468 mark_circuits = 1;
3470 return mark_circuits;
3473 /** Helper: pick a guard for a circuit, with whatever algorithm is
3474 used. */
3475 const node_t *
3476 guards_choose_guard(cpath_build_state_t *state,
3477 circuit_guard_state_t **guard_state_out)
3479 const node_t *r = NULL;
3480 const uint8_t *exit_id = NULL;
3481 entry_guard_restriction_t *rst = NULL;
3482 if (state && (exit_id = build_state_get_exit_rsa_id(state))) {
3483 /* We're building to a targeted exit node, so that node can't be
3484 * chosen as our guard for this circuit. Remember that fact in a
3485 * restriction. */
3486 rst = guard_create_exit_restriction(exit_id);
3487 tor_assert(rst);
3489 if (entry_guard_pick_for_circuit(get_guard_selection_info(),
3490 GUARD_USAGE_TRAFFIC,
3491 rst,
3493 guard_state_out) < 0) {
3494 tor_assert(r == NULL);
3496 return r;
3499 /** Remove all currently listed entry guards for a given guard selection
3500 * context. This frees and replaces <b>gs</b>, so don't use <b>gs</b>
3501 * after calling this function. */
3502 void
3503 remove_all_entry_guards_for_guard_selection(guard_selection_t *gs)
3505 // This function shouldn't exist. XXXX
3506 tor_assert(gs != NULL);
3507 char *old_name = tor_strdup(gs->name);
3508 guard_selection_type_t old_type = gs->type;
3510 SMARTLIST_FOREACH(gs->sampled_entry_guards, entry_guard_t *, entry, {
3511 control_event_guard(entry->nickname, entry->identity, "DROPPED");
3514 if (gs == curr_guard_context) {
3515 curr_guard_context = NULL;
3518 smartlist_remove(guard_contexts, gs);
3519 guard_selection_free(gs);
3521 gs = get_guard_selection_by_name(old_name, old_type, 1);
3522 entry_guards_changed_for_guard_selection(gs);
3523 tor_free(old_name);
3526 /** Remove all currently listed entry guards, so new ones will be chosen.
3528 * XXXX This function shouldn't exist -- it's meant to support the DROPGUARDS
3529 * command, which is deprecated.
3531 void
3532 remove_all_entry_guards(void)
3534 remove_all_entry_guards_for_guard_selection(get_guard_selection_info());
3537 /** Helper: pick a directory guard, with whatever algorithm is used. */
3538 const node_t *
3539 guards_choose_dirguard(uint8_t dir_purpose,
3540 circuit_guard_state_t **guard_state_out)
3542 const node_t *r = NULL;
3543 entry_guard_restriction_t *rst = NULL;
3545 /* If we are fetching microdescs, don't query outdated dirservers. */
3546 if (dir_purpose == DIR_PURPOSE_FETCH_MICRODESC) {
3547 rst = guard_create_dirserver_md_restriction();
3550 if (entry_guard_pick_for_circuit(get_guard_selection_info(),
3551 GUARD_USAGE_DIRGUARD,
3552 rst,
3554 guard_state_out) < 0) {
3555 tor_assert(r == NULL);
3557 return r;
3561 * If we're running with a constrained guard set, then maybe mark our guards
3562 * usable. Return 1 if we do; 0 if we don't.
3565 guards_retry_optimistic(const or_options_t *options)
3567 if (! entry_list_is_constrained(options))
3568 return 0;
3570 mark_primary_guards_maybe_reachable(get_guard_selection_info());
3572 return 1;
3576 * Check if we are missing any crucial dirinfo for the guard subsystem to
3577 * work. Return NULL if everything went well, otherwise return a newly
3578 * allocated string with an informative error message. In the latter case, use
3579 * the genreal descriptor information <b>using_mds</b>, <b>num_present</b> and
3580 * <b>num_usable</b> to improve the error message. */
3581 char *
3582 guard_selection_get_err_str_if_dir_info_missing(guard_selection_t *gs,
3583 int using_mds,
3584 int num_present, int num_usable)
3586 if (!gs->primary_guards_up_to_date)
3587 entry_guards_update_primary(gs);
3589 char *ret_str = NULL;
3590 int n_missing_descriptors = 0;
3591 int n_considered = 0;
3592 int num_primary_to_check;
3594 /* We want to check for the descriptor of at least the first two primary
3595 * guards in our list, since these are the guards that we typically use for
3596 * circuits. */
3597 num_primary_to_check = get_n_primary_guards_to_use(GUARD_USAGE_TRAFFIC);
3598 num_primary_to_check++;
3600 SMARTLIST_FOREACH_BEGIN(gs->primary_entry_guards, entry_guard_t *, guard) {
3601 entry_guard_consider_retry(guard);
3602 if (guard->is_reachable == GUARD_REACHABLE_NO)
3603 continue;
3604 n_considered++;
3605 if (!guard_has_descriptor(guard))
3606 n_missing_descriptors++;
3607 if (n_considered >= num_primary_to_check)
3608 break;
3609 } SMARTLIST_FOREACH_END(guard);
3611 /* If we are not missing any descriptors, return NULL. */
3612 if (!n_missing_descriptors) {
3613 return NULL;
3616 /* otherwise return a helpful error string */
3617 tor_asprintf(&ret_str, "We're missing descriptors for %d/%d of our "
3618 "primary entry guards (total %sdescriptors: %d/%d).",
3619 n_missing_descriptors, num_primary_to_check,
3620 using_mds?"micro":"", num_present, num_usable);
3622 return ret_str;
3625 /** As guard_selection_have_enough_dir_info_to_build_circuits, but uses
3626 * the default guard selection. */
3627 char *
3628 entry_guards_get_err_str_if_dir_info_missing(int using_mds,
3629 int num_present, int num_usable)
3631 return guard_selection_get_err_str_if_dir_info_missing(
3632 get_guard_selection_info(),
3633 using_mds,
3634 num_present, num_usable);
3637 /** Free one guard selection context */
3638 STATIC void
3639 guard_selection_free_(guard_selection_t *gs)
3641 if (!gs) return;
3643 tor_free(gs->name);
3645 if (gs->sampled_entry_guards) {
3646 SMARTLIST_FOREACH(gs->sampled_entry_guards, entry_guard_t *, e,
3647 entry_guard_free(e));
3648 smartlist_free(gs->sampled_entry_guards);
3649 gs->sampled_entry_guards = NULL;
3652 smartlist_free(gs->confirmed_entry_guards);
3653 smartlist_free(gs->primary_entry_guards);
3655 tor_free(gs);
3658 /** Release all storage held by the list of entry guards and related
3659 * memory structs. */
3660 void
3661 entry_guards_free_all(void)
3663 /* Null out the default */
3664 curr_guard_context = NULL;
3665 /* Free all the guard contexts */
3666 if (guard_contexts != NULL) {
3667 SMARTLIST_FOREACH_BEGIN(guard_contexts, guard_selection_t *, gs) {
3668 guard_selection_free(gs);
3669 } SMARTLIST_FOREACH_END(gs);
3670 smartlist_free(guard_contexts);
3671 guard_contexts = NULL;
3673 circuit_build_times_free_timeouts(get_circuit_build_times_mutable());