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 */
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
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
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
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
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.
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
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
109 * [x] Call entry_guards_changed_for_guard_selection() whenever we update
110 * a persistent field.
113 #define ENTRYNODES_PRIVATE
118 #include "circpathbias.h"
119 #include "circuitbuild.h"
120 #include "circuitlist.h"
121 #include "circuitstats.h"
123 #include "confparse.h"
124 #include "connection.h"
126 #include "directory.h"
127 #include "entrynodes.h"
129 #include "microdesc.h"
130 #include "networkstatus.h"
131 #include "nodelist.h"
132 #include "policies.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
,
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
179 if (options
->UseGuardFraction
== -1) {
180 return networkstatus_get_param(ns
, "UseGuardFraction",
181 0, /* default to "off" */
185 return options
->UseGuardFraction
;
188 /** Return true iff we know a descriptor for <b>guard</b> */
190 guard_has_descriptor(const entry_guard_t
*guard
)
192 const node_t
*node
= node_get_by_id(guard
->identity
);
195 return node_has_descriptor(node
);
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
,
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
;
212 type
= GS_TYPE_NORMAL
;
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
);
231 gs
->sampled_entry_guards
= smartlist_new();
232 gs
->confirmed_entry_guards
= smartlist_new();
233 gs
->primary_entry_guards
= smartlist_new();
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
))
254 } SMARTLIST_FOREACH_END(gs
);
256 if (! create_if_absent
)
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.
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(
280 networkstatus_get_live_consensus(approx_time()),
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 */
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>
303 entry_guard_describe(const entry_guard_t
*guard
)
305 static char buf
[256];
306 tor_snprintf(buf
, sizeof(buf
),
308 strlen(guard
->nickname
) ? guard
->nickname
: "[bridge]",
309 hex_str(guard
->identity
, DIGEST_LEN
));
313 /** Return <b>guard</b>'s 20-byte RSA identity digest */
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>. */
322 entry_guard_get_pathbias_state(entry_guard_t
*guard
)
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
;
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
356 * We never let our sampled guard set grow larger than this fraction
357 * of the guards on the network.
360 get_max_sample_threshold(void)
363 networkstatus_get_param(NULL
, "guard-max-sample-threshold-percent",
364 DFLT_MAX_SAMPLE_THRESHOLD_PERCENT
,
369 * We never let our sampled guard set grow larger than this number.
372 get_max_sample_size_absolute(void)
374 return (int) networkstatus_get_param(NULL
, "guard-max-sample-size",
375 DFLT_MAX_SAMPLE_SIZE
,
379 * We always try to make our sample contain at least this many guards.
382 get_min_filtered_sample_size(void)
384 return networkstatus_get_param(NULL
, "guard-min-filtered-sample-size",
385 DFLT_MIN_FILTERED_SAMPLE_SIZE
,
389 * If a guard is unlisted for this many days in a row, we remove it.
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
,
400 * We remove unconfirmed guards from the sample after this many days,
401 * regardless of whether they are listed or unlisted.
404 get_guard_lifetime(void)
406 if (get_options()->GuardLifetime
>= 86400)
407 return get_options()->GuardLifetime
;
409 days
= networkstatus_get_param(NULL
,
410 "guard-lifetime-days",
411 DFLT_GUARD_LIFETIME_DAYS
, 1, 365*10);
415 * We remove confirmed guards from the sample if they were sampled
416 * GUARD_LIFETIME_DAYS ago and confirmed this many days ago.
419 get_guard_confirmed_min_lifetime(void)
421 if (get_options()->GuardLifetime
>= 86400)
422 return get_options()->GuardLifetime
;
424 days
= networkstatus_get_param(NULL
, "guard-confirmed-min-lifetime-days",
425 DFLT_GUARD_CONFIRMED_MIN_LIFETIME_DAYS
,
430 * How many guards do we try to keep on our primary guard list?
433 get_n_primary_guards(void)
435 const int n
= get_options()->NumEntryGuards
;
436 const int n_dir
= get_options()->NumDirectoryGuards
;
438 return MAX(n_dir
, n
+ n
/ 2);
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
452 get_n_primary_guards_to_use(guard_usage_t usage
)
455 const char *param_name
;
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
;
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) {
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.
477 get_internet_likely_down_interval(void)
479 return networkstatus_get_param(NULL
, "guard-internet-likely-down-interval",
480 DFLT_INTERNET_LIKELY_DOWN_INTERVAL
,
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.
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
,
497 * If a circuit has been sitting around in 'waiting for better guard' state
498 * for at least this long, we'll expire it.
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
,
509 * If our configuration retains fewer than this fraction of guards from the
510 * torrc, we are in a restricted setting.
513 get_meaningful_restriction_threshold(void)
515 int32_t pct
= networkstatus_get_param(NULL
,
516 "guard-meaningful-restriction-percent",
517 DFLT_MEANINGFUL_RESTRICTION_PERCENT
,
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.
526 get_extreme_restriction_threshold(void)
528 int32_t pct
= networkstatus_get_param(NULL
,
529 "guard-extreme-restriction-percent",
530 DFLT_EXTREME_RESTRICTION_PERCENT
,
535 /* Mark <b>guard</b> as maybe reachable again. */
537 mark_guard_maybe_reachable(entry_guard_t
*guard
)
539 if (guard
->is_reachable
!= GUARD_REACHABLE_NO
) {
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
556 mark_primary_guards_maybe_reachable(guard_selection_t
*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. */
571 mark_all_guards_maybe_reachable(guard_selection_t
*gs
)
575 SMARTLIST_FOREACH_BEGIN(gs
->sampled_entry_guards
, entry_guard_t
*, guard
) {
576 mark_guard_maybe_reachable(guard
);
577 } SMARTLIST_FOREACH_END(guard
);
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.
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
)
594 tor_assert(type_out
);
596 if (options
->UseBridges
) {
597 *type_out
= GS_TYPE_BRIDGE
;
602 /* without a networkstatus, we can't tell any more than that. */
603 *type_out
= GS_TYPE_NORMAL
;
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
)) {
612 if (node_passes_guard_filter(options
, node
)) {
616 } SMARTLIST_FOREACH_END(node
);
618 /* We use separate 'high' and 'low' thresholds here to prevent flapping
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;
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
;
662 *type_out
= GS_TYPE_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
;
675 } else if (n_passing_filter
< meaningful_threshold_low
) {
676 *type_out
= GS_TYPE_RESTRICTED
;
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();
701 guard_selection_type_t type
= GS_TYPE_INFER
;
702 const char *new_name
= choose_guard_selection(
704 networkstatus_get_live_consensus(approx_time()),
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
)) {
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\")",
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
;
729 * Return true iff <b>node</b> has all the flags needed for us to consider it
730 * a possible guard when sampling guards.
733 node_is_possible_guard(const node_t
*node
)
735 /* The "GUARDS" set is all nodes in the nodelist for which this predicate
739 return (node
->is_possible_guard
&&
747 * Return the sampled guard with the RSA identity digest <b>rsa_id</b>, or
748 * NULL if we don't have one. */
749 STATIC entry_guard_t
*
750 get_sampled_guard_with_id(guard_selection_t
*gs
,
751 const uint8_t *rsa_id
)
755 SMARTLIST_FOREACH_BEGIN(gs
->sampled_entry_guards
, entry_guard_t
*, guard
) {
756 if (tor_memeq(guard
->identity
, rsa_id
, DIGEST_LEN
))
758 } SMARTLIST_FOREACH_END(guard
);
762 /** If <b>gs</b> contains a sampled entry guard matching <b>bridge</b>,
763 * return that guard. Otherwise return NULL. */
764 static entry_guard_t
*
765 get_sampled_guard_for_bridge(guard_selection_t
*gs
,
766 const bridge_info_t
*bridge
)
768 const uint8_t *id
= bridge_get_rsa_id_digest(bridge
);
769 const tor_addr_port_t
*addrport
= bridge_get_addr_port(bridge
);
770 entry_guard_t
*guard
;
772 return NULL
; // LCOV_EXCL_LINE
773 guard
= get_sampled_guard_by_bridge_addr(gs
, addrport
);
774 if (! guard
|| (id
&& tor_memneq(id
, guard
->identity
, DIGEST_LEN
)))
780 /** If we know a bridge_info_t matching <b>guard</b>, return that
781 * bridge. Otherwise return NULL. */
782 static bridge_info_t
*
783 get_bridge_info_for_guard(const entry_guard_t
*guard
)
785 const uint8_t *identity
= NULL
;
786 if (! tor_digest_is_zero(guard
->identity
)) {
787 identity
= (const uint8_t *)guard
->identity
;
789 if (BUG(guard
->bridge_addr
== NULL
))
792 return get_configured_bridge_by_exact_addr_port_digest(
793 &guard
->bridge_addr
->addr
,
794 guard
->bridge_addr
->port
,
795 (const char*)identity
);
799 * Return true iff we have a sampled guard with the RSA identity digest
802 have_sampled_guard_with_id(guard_selection_t
*gs
, const uint8_t *rsa_id
)
804 return get_sampled_guard_with_id(gs
, rsa_id
) != NULL
;
808 * Allocate a new entry_guard_t object for <b>node</b>, add it to the
809 * sampled entry guards in <b>gs</b>, and return it. <b>node</b> must
810 * not currently be a sampled guard in <b>gs</b>.
812 STATIC entry_guard_t
*
813 entry_guard_add_to_sample(guard_selection_t
*gs
,
816 log_info(LD_GUARD
, "Adding %s to the entry guard sample set.",
817 node_describe(node
));
819 /* make sure that the guard is not already sampled. */
820 if (BUG(have_sampled_guard_with_id(gs
, (const uint8_t*)node
->identity
)))
821 return NULL
; // LCOV_EXCL_LINE
823 return entry_guard_add_to_sample_impl(gs
,
824 (const uint8_t*)node
->identity
,
825 node_get_nickname(node
),
830 * Backend: adds a new sampled guard to <b>gs</b>, with given identity,
831 * nickname, and ORPort. rsa_id_digest and bridge_addrport are optional, but
832 * we need one of them. nickname is optional. The caller is responsible for
833 * maintaining the size limit of the SAMPLED_GUARDS set.
835 static entry_guard_t
*
836 entry_guard_add_to_sample_impl(guard_selection_t
*gs
,
837 const uint8_t *rsa_id_digest
,
838 const char *nickname
,
839 const tor_addr_port_t
*bridge_addrport
)
841 const int GUARD_LIFETIME
= get_guard_lifetime();
844 // XXXX #20827 take ed25519 identity here too.
846 /* Make sure we can actually identify the guard. */
847 if (BUG(!rsa_id_digest
&& !bridge_addrport
))
848 return NULL
; // LCOV_EXCL_LINE
850 entry_guard_t
*guard
= tor_malloc_zero(sizeof(entry_guard_t
));
852 /* persistent fields */
853 guard
->is_persistent
= (rsa_id_digest
!= NULL
);
854 guard
->selection_name
= tor_strdup(gs
->name
);
856 memcpy(guard
->identity
, rsa_id_digest
, DIGEST_LEN
);
858 strlcpy(guard
->nickname
, nickname
, sizeof(guard
->nickname
));
859 guard
->sampled_on_date
= randomize_time(approx_time(), GUARD_LIFETIME
/10);
860 tor_free(guard
->sampled_by_version
);
861 guard
->sampled_by_version
= tor_strdup(VERSION
);
862 guard
->currently_listed
= 1;
863 guard
->confirmed_idx
= -1;
865 /* non-persistent fields */
866 guard
->is_reachable
= GUARD_REACHABLE_MAYBE
;
868 guard
->bridge_addr
= tor_memdup(bridge_addrport
, sizeof(*bridge_addrport
));
870 smartlist_add(gs
->sampled_entry_guards
, guard
);
871 guard
->in_selection
= gs
;
872 entry_guard_set_filtered_flags(get_options(), gs
, guard
);
873 entry_guards_changed_for_guard_selection(gs
);
878 * Add an entry guard to the "bridges" guard selection sample, with
879 * information taken from <b>bridge</b>. Return that entry guard.
881 static entry_guard_t
*
882 entry_guard_add_bridge_to_sample(guard_selection_t
*gs
,
883 const bridge_info_t
*bridge
)
885 const uint8_t *id_digest
= bridge_get_rsa_id_digest(bridge
);
886 const tor_addr_port_t
*addrport
= bridge_get_addr_port(bridge
);
888 tor_assert(addrport
);
890 /* make sure that the guard is not already sampled. */
891 if (BUG(get_sampled_guard_for_bridge(gs
, bridge
)))
892 return NULL
; // LCOV_EXCL_LINE
894 return entry_guard_add_to_sample_impl(gs
, id_digest
, NULL
, addrport
);
898 * Return the entry_guard_t in <b>gs</b> whose address is <b>addrport</b>,
899 * or NULL if none exists.
901 static entry_guard_t
*
902 get_sampled_guard_by_bridge_addr(guard_selection_t
*gs
,
903 const tor_addr_port_t
*addrport
)
909 SMARTLIST_FOREACH_BEGIN(gs
->sampled_entry_guards
, entry_guard_t
*, g
) {
910 if (g
->bridge_addr
&& tor_addr_port_eq(addrport
, g
->bridge_addr
))
912 } SMARTLIST_FOREACH_END(g
);
916 /** Update the guard subsystem's knowledge of the identity of the bridge
917 * at <b>addrport</b>. Idempotent.
920 entry_guard_learned_bridge_identity(const tor_addr_port_t
*addrport
,
921 const uint8_t *rsa_id_digest
)
923 guard_selection_t
*gs
= get_guard_selection_by_name("bridges",
929 entry_guard_t
*g
= get_sampled_guard_by_bridge_addr(gs
, addrport
);
933 int make_persistent
= 0;
935 if (tor_digest_is_zero(g
->identity
)) {
936 memcpy(g
->identity
, rsa_id_digest
, DIGEST_LEN
);
938 } else if (tor_memeq(g
->identity
, rsa_id_digest
, DIGEST_LEN
)) {
939 /* Nothing to see here; we learned something we already knew. */
940 if (BUG(! g
->is_persistent
))
943 char old_id
[HEX_DIGEST_LEN
+1];
944 base16_encode(old_id
, sizeof(old_id
), g
->identity
, sizeof(g
->identity
));
945 log_warn(LD_BUG
, "We 'learned' an identity %s for a bridge at %s:%d, but "
946 "we already knew a different one (%s). Ignoring the new info as "
948 hex_str((const char *)rsa_id_digest
, DIGEST_LEN
),
949 fmt_and_decorate_addr(&addrport
->addr
), addrport
->port
,
951 return; // redundant, but let's be clear: we're not making this persistent.
954 if (make_persistent
) {
955 g
->is_persistent
= 1;
956 entry_guards_changed_for_guard_selection(gs
);
961 * Return the number of sampled guards in <b>gs</b> that are "filtered"
962 * (that is, we're willing to connect to them) and that are "usable"
963 * (that is, either "reachable" or "maybe reachable").
965 * If a restriction is provided in <b>rst</b>, do not count any guards that
969 num_reachable_filtered_guards(const guard_selection_t
*gs
,
970 const entry_guard_restriction_t
*rst
)
972 int n_reachable_filtered_guards
= 0;
973 SMARTLIST_FOREACH_BEGIN(gs
->sampled_entry_guards
, entry_guard_t
*, guard
) {
974 entry_guard_consider_retry(guard
);
975 if (! entry_guard_obeys_restriction(guard
, rst
))
977 if (guard
->is_usable_filtered_guard
)
978 ++n_reachable_filtered_guards
;
979 } SMARTLIST_FOREACH_END(guard
);
980 return n_reachable_filtered_guards
;
983 /** Return the actual maximum size for the sample in <b>gs</b>,
984 * given that we know about <b>n_guards</b> total. */
986 get_max_sample_size(guard_selection_t
*gs
,
989 const int using_bridges
= (gs
->type
== GS_TYPE_BRIDGE
);
990 const int min_sample
= get_min_filtered_sample_size();
992 /* If we are in bridge mode, expand our sample set as needed without worrying
993 * about max size. We should respect the user's wishes to use many bridges if
994 * that's what they have specified in their configuration file. */
998 const int max_sample_by_pct
= (int)(n_guards
* get_max_sample_threshold());
999 const int max_sample_absolute
= get_max_sample_size_absolute();
1000 const int max_sample
= MIN(max_sample_by_pct
, max_sample_absolute
);
1001 if (max_sample
< min_sample
)
1008 * Return a smartlist of the all the guards that are not currently
1009 * members of the sample (GUARDS - SAMPLED_GUARDS). The elements of
1010 * this list are node_t pointers in the non-bridge case, and
1011 * bridge_info_t pointers in the bridge case. Set *<b>n_guards_out/b>
1012 * to the number of guards that we found in GUARDS, including those
1013 * that were already sampled.
1015 static smartlist_t
*
1016 get_eligible_guards(const or_options_t
*options
,
1017 guard_selection_t
*gs
,
1020 /* Construct eligible_guards as GUARDS - SAMPLED_GUARDS */
1021 smartlist_t
*eligible_guards
= smartlist_new();
1022 int n_guards
= 0; // total size of "GUARDS"
1024 if (gs
->type
== GS_TYPE_BRIDGE
) {
1025 const smartlist_t
*bridges
= bridge_list_get();
1026 SMARTLIST_FOREACH_BEGIN(bridges
, bridge_info_t
*, bridge
) {
1028 if (NULL
!= get_sampled_guard_for_bridge(gs
, bridge
)) {
1031 smartlist_add(eligible_guards
, bridge
);
1032 } SMARTLIST_FOREACH_END(bridge
);
1034 const smartlist_t
*nodes
= nodelist_get_list();
1035 const int n_sampled
= smartlist_len(gs
->sampled_entry_guards
);
1037 /* Build a bloom filter of our current guards: let's keep this O(N). */
1038 digestset_t
*sampled_guard_ids
= digestset_new(n_sampled
);
1039 SMARTLIST_FOREACH_BEGIN(gs
->sampled_entry_guards
, const entry_guard_t
*,
1041 digestset_add(sampled_guard_ids
, guard
->identity
);
1042 } SMARTLIST_FOREACH_END(guard
);
1044 SMARTLIST_FOREACH_BEGIN(nodes
, const node_t
*, node
) {
1045 if (! node_is_possible_guard(node
))
1047 if (gs
->type
== GS_TYPE_RESTRICTED
) {
1048 /* In restricted mode, we apply the filter BEFORE sampling, so
1049 * that we are sampling from the nodes that we might actually
1050 * select. If we sampled first, we might wind up with a sample
1051 * that didn't include any EntryNodes at all. */
1052 if (! node_passes_guard_filter(options
, node
))
1056 if (digestset_contains(sampled_guard_ids
, node
->identity
))
1058 smartlist_add(eligible_guards
, (node_t
*)node
);
1059 } SMARTLIST_FOREACH_END(node
);
1061 /* Now we can free that bloom filter. */
1062 digestset_free(sampled_guard_ids
);
1065 *n_guards_out
= n_guards
;
1066 return eligible_guards
;
1069 /** Helper: given a smartlist of either bridge_info_t (if gs->type is
1070 * GS_TYPE_BRIDGE) or node_t (otherwise), pick one that can be a guard,
1071 * add it as a guard, remove it from the list, and return a new
1072 * entry_guard_t. Return NULL on failure. */
1073 static entry_guard_t
*
1074 select_and_add_guard_item_for_sample(guard_selection_t
*gs
,
1075 smartlist_t
*eligible_guards
)
1077 entry_guard_t
*added_guard
;
1078 if (gs
->type
== GS_TYPE_BRIDGE
) {
1079 const bridge_info_t
*bridge
= smartlist_choose(eligible_guards
);
1081 return NULL
; // LCOV_EXCL_LINE
1082 smartlist_remove(eligible_guards
, bridge
);
1083 added_guard
= entry_guard_add_bridge_to_sample(gs
, bridge
);
1085 const node_t
*node
=
1086 node_sl_choose_by_bandwidth(eligible_guards
, WEIGHT_FOR_GUARD
);
1088 return NULL
; // LCOV_EXCL_LINE
1089 smartlist_remove(eligible_guards
, node
);
1090 added_guard
= entry_guard_add_to_sample(gs
, node
);
1096 /** Return true iff we need a consensus to maintain our */
1098 live_consensus_is_missing(const guard_selection_t
*gs
)
1101 if (gs
->type
== GS_TYPE_BRIDGE
) {
1102 /* We don't update bridges from the consensus; they aren't there. */
1105 return networkstatus_get_live_consensus(approx_time()) == NULL
;
1109 * Add new guards to the sampled guards in <b>gs</b> until there are
1110 * enough usable filtered guards, but never grow the sample beyond its
1111 * maximum size. Return the last guard added, or NULL if none were
1114 STATIC entry_guard_t
*
1115 entry_guards_expand_sample(guard_selection_t
*gs
)
1118 const or_options_t
*options
= get_options();
1120 if (live_consensus_is_missing(gs
)) {
1121 log_info(LD_GUARD
, "Not expanding the sample guard set; we have "
1122 "no live consensus.");
1126 int n_sampled
= smartlist_len(gs
->sampled_entry_guards
);
1127 entry_guard_t
*added_guard
= NULL
;
1128 int n_usable_filtered_guards
= num_reachable_filtered_guards(gs
, NULL
);
1130 smartlist_t
*eligible_guards
= get_eligible_guards(options
, gs
, &n_guards
);
1132 const int max_sample
= get_max_sample_size(gs
, n_guards
);
1133 const int min_filtered_sample
= get_min_filtered_sample_size();
1135 log_info(LD_GUARD
, "Expanding the sample guard set. We have %d guards "
1136 "in the sample, and %d eligible guards to extend it with.",
1137 n_sampled
, smartlist_len(eligible_guards
));
1139 while (n_usable_filtered_guards
< min_filtered_sample
) {
1140 /* Has our sample grown too large to expand? */
1141 if (n_sampled
>= max_sample
) {
1142 log_info(LD_GUARD
, "Not expanding the guard sample any further; "
1143 "just hit the maximum sample threshold of %d",
1148 /* Did we run out of guards? */
1149 if (smartlist_len(eligible_guards
) == 0) {
1151 As long as MAX_SAMPLE_THRESHOLD makes can't be adjusted to
1152 allow all guards to be sampled, this can't be reached.
1154 log_info(LD_GUARD
, "Not expanding the guard sample any further; "
1155 "just ran out of eligible guards");
1157 /* LCOV_EXCL_STOP */
1160 /* Otherwise we can add at least one new guard. */
1161 added_guard
= select_and_add_guard_item_for_sample(gs
, eligible_guards
);
1163 goto done
; // LCOV_EXCL_LINE -- only fails on BUG.
1167 if (added_guard
->is_usable_filtered_guard
)
1168 ++n_usable_filtered_guards
;
1172 smartlist_free(eligible_guards
);
1177 * Helper: <b>guard</b> has just been removed from the sampled guards:
1178 * also remove it from primary and confirmed. */
1180 remove_guard_from_confirmed_and_primary_lists(guard_selection_t
*gs
,
1181 entry_guard_t
*guard
)
1183 if (guard
->is_primary
) {
1184 guard
->is_primary
= 0;
1185 smartlist_remove_keeporder(gs
->primary_entry_guards
, guard
);
1187 if (BUG(smartlist_contains(gs
->primary_entry_guards
, guard
))) {
1188 smartlist_remove_keeporder(gs
->primary_entry_guards
, guard
);
1192 if (guard
->confirmed_idx
>= 0) {
1193 smartlist_remove_keeporder(gs
->confirmed_entry_guards
, guard
);
1194 guard
->confirmed_idx
= -1;
1195 guard
->confirmed_on_date
= 0;
1197 if (BUG(smartlist_contains(gs
->confirmed_entry_guards
, guard
))) {
1199 smartlist_remove_keeporder(gs
->confirmed_entry_guards
, guard
);
1205 /** Return true iff <b>guard</b> is currently "listed" -- that is, it
1206 * appears in the consensus, or as a configured bridge (as
1208 MOCK_IMPL(STATIC
int,
1209 entry_guard_is_listed
,(guard_selection_t
*gs
, const entry_guard_t
*guard
))
1211 if (gs
->type
== GS_TYPE_BRIDGE
) {
1212 return NULL
!= get_bridge_info_for_guard(guard
);
1214 const node_t
*node
= node_get_by_id(guard
->identity
);
1216 return node
&& node_is_possible_guard(node
);
1221 * Update the status of all sampled guards based on the arrival of a
1222 * new consensus networkstatus document. This will include marking
1223 * some guards as listed or unlisted, and removing expired guards. */
1225 sampled_guards_update_from_consensus(guard_selection_t
*gs
)
1228 const int REMOVE_UNLISTED_GUARDS_AFTER
=
1229 (get_remove_unlisted_guards_after_days() * 86400);
1230 const int unlisted_since_slop
= REMOVE_UNLISTED_GUARDS_AFTER
/ 5;
1232 // It's important to use only a live consensus here; we don't want to
1233 // make changes based on anything expired or old.
1234 if (live_consensus_is_missing(gs
)) {
1235 log_info(LD_GUARD
, "Not updating the sample guard set; we have "
1236 "no live consensus.");
1239 log_info(LD_GUARD
, "Updating sampled guard status based on received "
1244 /* First: Update listed/unlisted. */
1245 SMARTLIST_FOREACH_BEGIN(gs
->sampled_entry_guards
, entry_guard_t
*, guard
) {
1246 /* XXXX #20827 check ed ID too */
1247 const int is_listed
= entry_guard_is_listed(gs
, guard
);
1249 if (is_listed
&& ! guard
->currently_listed
) {
1251 guard
->currently_listed
= 1;
1252 guard
->unlisted_since_date
= 0;
1253 log_info(LD_GUARD
, "Sampled guard %s is now listed again.",
1254 entry_guard_describe(guard
));
1255 } else if (!is_listed
&& guard
->currently_listed
) {
1257 guard
->currently_listed
= 0;
1258 guard
->unlisted_since_date
= randomize_time(approx_time(),
1259 unlisted_since_slop
);
1260 log_info(LD_GUARD
, "Sampled guard %s is now unlisted.",
1261 entry_guard_describe(guard
));
1262 } else if (is_listed
&& guard
->currently_listed
) {
1263 log_debug(LD_GUARD
, "Sampled guard %s is still listed.",
1264 entry_guard_describe(guard
));
1266 tor_assert(! is_listed
&& ! guard
->currently_listed
);
1267 log_debug(LD_GUARD
, "Sampled guard %s is still unlisted.",
1268 entry_guard_describe(guard
));
1271 /* Clean up unlisted_since_date, just in case. */
1272 if (guard
->currently_listed
&& guard
->unlisted_since_date
) {
1274 guard
->unlisted_since_date
= 0;
1275 log_warn(LD_BUG
, "Sampled guard %s was listed, but with "
1276 "unlisted_since_date set. Fixing.",
1277 entry_guard_describe(guard
));
1278 } else if (!guard
->currently_listed
&& ! guard
->unlisted_since_date
) {
1280 guard
->unlisted_since_date
= randomize_time(approx_time(),
1281 unlisted_since_slop
);
1282 log_warn(LD_BUG
, "Sampled guard %s was unlisted, but with "
1283 "unlisted_since_date unset. Fixing.",
1284 entry_guard_describe(guard
));
1286 } SMARTLIST_FOREACH_END(guard
);
1288 const time_t remove_if_unlisted_since
=
1289 approx_time() - REMOVE_UNLISTED_GUARDS_AFTER
;
1290 const time_t maybe_remove_if_sampled_before
=
1291 approx_time() - get_guard_lifetime();
1292 const time_t remove_if_confirmed_before
=
1293 approx_time() - get_guard_confirmed_min_lifetime();
1295 /* Then: remove the ones that have been junk for too long */
1296 SMARTLIST_FOREACH_BEGIN(gs
->sampled_entry_guards
, entry_guard_t
*, guard
) {
1299 if (guard
->currently_listed
== 0 &&
1300 guard
->unlisted_since_date
< remove_if_unlisted_since
) {
1302 "We have a live consensus, and {IS_LISTED} is false, and
1303 {FIRST_UNLISTED_AT} is over {REMOVE_UNLISTED_GUARDS_AFTER}
1306 log_info(LD_GUARD
, "Removing sampled guard %s: it has been unlisted "
1307 "for over %d days", entry_guard_describe(guard
),
1308 get_remove_unlisted_guards_after_days());
1310 } else if (guard
->sampled_on_date
< maybe_remove_if_sampled_before
) {
1311 /* We have a live consensus, and {ADDED_ON_DATE} is over
1312 {GUARD_LIFETIME} ago, *and* {CONFIRMED_ON_DATE} is either
1313 "never", or over {GUARD_CONFIRMED_MIN_LIFETIME} ago.
1315 if (guard
->confirmed_on_date
== 0) {
1317 log_info(LD_GUARD
, "Removing sampled guard %s: it was sampled "
1318 "over %d days ago, but never confirmed.",
1319 entry_guard_describe(guard
),
1320 get_guard_lifetime() / 86400);
1321 } else if (guard
->confirmed_on_date
< remove_if_confirmed_before
) {
1323 log_info(LD_GUARD
, "Removing sampled guard %s: it was sampled "
1324 "over %d days ago, and confirmed over %d days ago.",
1325 entry_guard_describe(guard
),
1326 get_guard_lifetime() / 86400,
1327 get_guard_confirmed_min_lifetime() / 86400);
1333 SMARTLIST_DEL_CURRENT(gs
->sampled_entry_guards
, guard
);
1334 remove_guard_from_confirmed_and_primary_lists(gs
, guard
);
1335 entry_guard_free(guard
);
1337 } SMARTLIST_FOREACH_END(guard
);
1340 gs
->primary_guards_up_to_date
= 0;
1341 entry_guards_update_filtered_sets(gs
);
1342 /* We don't need to rebuild the confirmed list right here -- we may have
1343 * removed confirmed guards above, but we can't have added any new
1346 entry_guards_changed_for_guard_selection(gs
);
1351 * Return true iff <b>node</b> is a Tor relay that we are configured to
1352 * be able to connect to. */
1354 node_passes_guard_filter(const or_options_t
*options
,
1357 /* NOTE: Make sure that this function stays in sync with
1358 * options_transition_affects_entry_guards */
1359 if (routerset_contains_node(options
->ExcludeNodes
, node
))
1362 if (options
->EntryNodes
&&
1363 !routerset_contains_node(options
->EntryNodes
, node
))
1366 if (!fascist_firewall_allows_node(node
, FIREWALL_OR_CONNECTION
, 0))
1369 if (node_is_a_configured_bridge(node
))
1375 /** Helper: Return true iff <b>bridge</b> passes our configuration
1376 * filter-- if it is a relay that we are configured to be able to
1379 bridge_passes_guard_filter(const or_options_t
*options
,
1380 const bridge_info_t
*bridge
)
1386 if (routerset_contains_bridge(options
->ExcludeNodes
, bridge
))
1389 /* Ignore entrynodes */
1390 const tor_addr_port_t
*addrport
= bridge_get_addr_port(bridge
);
1392 if (!fascist_firewall_allows_address_addr(&addrport
->addr
,
1394 FIREWALL_OR_CONNECTION
,
1402 * Return true iff <b>guard</b> is a Tor relay that we are configured to
1403 * be able to connect to, and we haven't disabled it for omission from
1404 * the consensus or path bias issues. */
1406 entry_guard_passes_filter(const or_options_t
*options
, guard_selection_t
*gs
,
1407 entry_guard_t
*guard
)
1409 if (guard
->currently_listed
== 0)
1411 if (guard
->pb
.path_bias_disabled
)
1414 if (gs
->type
== GS_TYPE_BRIDGE
) {
1415 const bridge_info_t
*bridge
= get_bridge_info_for_guard(guard
);
1418 return bridge_passes_guard_filter(options
, bridge
);
1420 const node_t
*node
= node_get_by_id(guard
->identity
);
1422 // This can happen when currently_listed is true, and we're not updating
1423 // it because we don't have a live consensus.
1427 return node_passes_guard_filter(options
, node
);
1431 /** Return true iff <b>guard</b> is in the same family as <b>node</b>.
1434 guard_in_node_family(const entry_guard_t
*guard
, const node_t
*node
)
1436 const node_t
*guard_node
= node_get_by_id(guard
->identity
);
1438 return nodes_in_same_family(guard_node
, node
);
1440 /* If we don't have a node_t for the guard node, we might have
1441 * a bridge_info_t for it. So let's check to see whether the bridge
1442 * address matches has any family issues.
1444 * (Strictly speaking, I believe this check is unnecessary, since we only
1445 * use it to avoid the exit's family when building circuits, and we don't
1446 * build multihop circuits until we have a routerinfo_t for the
1447 * bridge... at which point, we'll also have a node_t for the
1448 * bridge. Nonetheless, it seems wise to include it, in case our
1449 * assumptions change down the road. -nickm.)
1451 if (get_options()->EnforceDistinctSubnets
&& guard
->bridge_addr
) {
1452 tor_addr_t node_addr
;
1453 node_get_addr(node
, &node_addr
);
1454 if (addrs_in_same_network_family(&node_addr
,
1455 &guard
->bridge_addr
->addr
)) {
1463 /* Allocate and return a new exit guard restriction (where <b>exit_id</b> is of
1464 * size DIGEST_LEN) */
1465 STATIC entry_guard_restriction_t
*
1466 guard_create_exit_restriction(const uint8_t *exit_id
)
1468 entry_guard_restriction_t
*rst
= NULL
;
1469 rst
= tor_malloc_zero(sizeof(entry_guard_restriction_t
));
1470 rst
->type
= RST_EXIT_NODE
;
1471 memcpy(rst
->exclude_id
, exit_id
, DIGEST_LEN
);
1475 /** If we have fewer than this many possible usable guards, don't set
1476 * MD-availability-based restrictions: we might blacklist all of them. */
1477 #define MIN_GUARDS_FOR_MD_RESTRICTION 10
1479 /** Return true if we should set md dirserver restrictions. We might not want
1480 * to set those if our guard options are too restricted, since we don't want
1481 * to blacklist all of them. */
1483 should_set_md_dirserver_restriction(void)
1485 const guard_selection_t
*gs
= get_guard_selection_info();
1486 int num_usable_guards
= num_reachable_filtered_guards(gs
, NULL
);
1488 /* Don't set restriction if too few reachable filtered guards. */
1489 if (num_usable_guards
< MIN_GUARDS_FOR_MD_RESTRICTION
) {
1490 log_info(LD_GUARD
, "Not setting md restriction: only %d"
1491 " usable guards.", num_usable_guards
);
1495 /* We have enough usable guards: set MD restriction */
1499 /** Allocate and return an outdated md guard restriction. Return NULL if no
1500 * such restriction is needed. */
1501 STATIC entry_guard_restriction_t
*
1502 guard_create_dirserver_md_restriction(void)
1504 entry_guard_restriction_t
*rst
= NULL
;
1506 if (!should_set_md_dirserver_restriction()) {
1507 log_debug(LD_GUARD
, "Not setting md restriction: too few "
1508 "filtered guards.");
1512 rst
= tor_malloc_zero(sizeof(entry_guard_restriction_t
));
1513 rst
->type
= RST_OUTDATED_MD_DIRSERVER
;
1518 /* Return True if <b>guard</b> obeys the exit restriction <b>rst</b>. */
1520 guard_obeys_exit_restriction(const entry_guard_t
*guard
,
1521 const entry_guard_restriction_t
*rst
)
1523 tor_assert(rst
->type
== RST_EXIT_NODE
);
1525 // Exclude the exit ID and all of its family.
1526 const node_t
*node
= node_get_by_id((const char*)rst
->exclude_id
);
1527 if (node
&& guard_in_node_family(guard
, node
))
1530 return tor_memneq(guard
->identity
, rst
->exclude_id
, DIGEST_LEN
);
1533 /** Return True if <b>guard</b> should be used as a dirserver for fetching
1534 * microdescriptors. */
1536 guard_obeys_md_dirserver_restriction(const entry_guard_t
*guard
)
1538 /* If this guard is an outdated dirserver, don't use it. */
1539 if (microdesc_relay_is_outdated_dirserver(guard
->identity
)) {
1540 log_info(LD_GENERAL
, "Skipping %s dirserver: outdated",
1541 hex_str(guard
->identity
, DIGEST_LEN
));
1545 log_debug(LD_GENERAL
, "%s dirserver obeys md restrictions",
1546 hex_str(guard
->identity
, DIGEST_LEN
));
1552 * Return true iff <b>guard</b> obeys the restrictions defined in <b>rst</b>.
1553 * (If <b>rst</b> is NULL, there are no restrictions.)
1556 entry_guard_obeys_restriction(const entry_guard_t
*guard
,
1557 const entry_guard_restriction_t
*rst
)
1561 return 1; // No restriction? No problem.
1563 if (rst
->type
== RST_EXIT_NODE
) {
1564 return guard_obeys_exit_restriction(guard
, rst
);
1565 } else if (rst
->type
== RST_OUTDATED_MD_DIRSERVER
) {
1566 return guard_obeys_md_dirserver_restriction(guard
);
1569 tor_assert_nonfatal_unreached();
1574 * Update the <b>is_filtered_guard</b> and <b>is_usable_filtered_guard</b>
1575 * flags on <b>guard</b>. */
1577 entry_guard_set_filtered_flags(const or_options_t
*options
,
1578 guard_selection_t
*gs
,
1579 entry_guard_t
*guard
)
1581 unsigned was_filtered
= guard
->is_filtered_guard
;
1582 guard
->is_filtered_guard
= 0;
1583 guard
->is_usable_filtered_guard
= 0;
1585 if (entry_guard_passes_filter(options
, gs
, guard
)) {
1586 guard
->is_filtered_guard
= 1;
1588 if (guard
->is_reachable
!= GUARD_REACHABLE_NO
)
1589 guard
->is_usable_filtered_guard
= 1;
1591 entry_guard_consider_retry(guard
);
1593 log_debug(LD_GUARD
, "Updated sampled guard %s: filtered=%d; "
1594 "reachable_filtered=%d.", entry_guard_describe(guard
),
1595 guard
->is_filtered_guard
, guard
->is_usable_filtered_guard
);
1597 if (!bool_eq(was_filtered
, guard
->is_filtered_guard
)) {
1598 /* This guard might now be primary or nonprimary. */
1599 gs
->primary_guards_up_to_date
= 0;
1604 * Update the <b>is_filtered_guard</b> and <b>is_usable_filtered_guard</b>
1605 * flag on every guard in <b>gs</b>. */
1607 entry_guards_update_filtered_sets(guard_selection_t
*gs
)
1609 const or_options_t
*options
= get_options();
1611 SMARTLIST_FOREACH_BEGIN(gs
->sampled_entry_guards
, entry_guard_t
*, guard
) {
1612 entry_guard_set_filtered_flags(options
, gs
, guard
);
1613 } SMARTLIST_FOREACH_END(guard
);
1617 * Return a random guard from the reachable filtered sample guards
1618 * in <b>gs</b>, subject to the exclusion rules listed in <b>flags</b>.
1619 * Return NULL if no such guard can be found.
1621 * Make sure that the sample is big enough, and that all the filter flags
1622 * are set correctly, before calling this function.
1624 * If a restriction is provided in <b>rst</b>, do not return any guards that
1627 STATIC entry_guard_t
*
1628 sample_reachable_filtered_entry_guards(guard_selection_t
*gs
,
1629 const entry_guard_restriction_t
*rst
,
1633 entry_guard_t
*result
= NULL
;
1634 const unsigned exclude_confirmed
= flags
& SAMPLE_EXCLUDE_CONFIRMED
;
1635 const unsigned exclude_primary
= flags
& SAMPLE_EXCLUDE_PRIMARY
;
1636 const unsigned exclude_pending
= flags
& SAMPLE_EXCLUDE_PENDING
;
1637 const unsigned no_update_primary
= flags
& SAMPLE_NO_UPDATE_PRIMARY
;
1638 const unsigned need_descriptor
= flags
& SAMPLE_EXCLUDE_NO_DESCRIPTOR
;
1640 SMARTLIST_FOREACH_BEGIN(gs
->sampled_entry_guards
, entry_guard_t
*, guard
) {
1641 entry_guard_consider_retry(guard
);
1642 } SMARTLIST_FOREACH_END(guard
);
1644 const int n_reachable_filtered
= num_reachable_filtered_guards(gs
, rst
);
1646 log_info(LD_GUARD
, "Trying to sample a reachable guard: We know of %d "
1647 "in the USABLE_FILTERED set.", n_reachable_filtered
);
1649 const int min_filtered_sample
= get_min_filtered_sample_size();
1650 if (n_reachable_filtered
< min_filtered_sample
) {
1651 log_info(LD_GUARD
, " (That isn't enough. Trying to expand the sample.)");
1652 entry_guards_expand_sample(gs
);
1655 if (exclude_primary
&& !gs
->primary_guards_up_to_date
&& !no_update_primary
)
1656 entry_guards_update_primary(gs
);
1658 /* Build the set of reachable filtered guards. */
1659 smartlist_t
*reachable_filtered_sample
= smartlist_new();
1660 SMARTLIST_FOREACH_BEGIN(gs
->sampled_entry_guards
, entry_guard_t
*, guard
) {
1661 entry_guard_consider_retry(guard
);// redundant, but cheap.
1662 if (! entry_guard_obeys_restriction(guard
, rst
))
1664 if (! guard
->is_usable_filtered_guard
)
1666 if (exclude_confirmed
&& guard
->confirmed_idx
>= 0)
1668 if (exclude_primary
&& guard
->is_primary
)
1670 if (exclude_pending
&& guard
->is_pending
)
1672 if (need_descriptor
&& !guard_has_descriptor(guard
))
1674 smartlist_add(reachable_filtered_sample
, guard
);
1675 } SMARTLIST_FOREACH_END(guard
);
1677 log_info(LD_GUARD
, " (After filters [%x], we have %d guards to consider.)",
1678 flags
, smartlist_len(reachable_filtered_sample
));
1680 if (smartlist_len(reachable_filtered_sample
)) {
1681 result
= smartlist_choose(reachable_filtered_sample
);
1682 log_info(LD_GUARD
, " (Selected %s.)",
1683 result
? entry_guard_describe(result
) : "<null>");
1685 smartlist_free(reachable_filtered_sample
);
1691 * Helper: compare two entry_guard_t by their confirmed_idx values.
1692 * Used to sort the confirmed list.
1695 compare_guards_by_confirmed_idx(const void **a_
, const void **b_
)
1697 const entry_guard_t
*a
= *a_
, *b
= *b_
;
1698 if (a
->confirmed_idx
< b
->confirmed_idx
)
1700 else if (a
->confirmed_idx
> b
->confirmed_idx
)
1707 * Find the confirmed guards from among the sampled guards in <b>gs</b>,
1708 * and put them in confirmed_entry_guards in the correct
1709 * order. Recalculate their indices.
1712 entry_guards_update_confirmed(guard_selection_t
*gs
)
1714 smartlist_clear(gs
->confirmed_entry_guards
);
1715 SMARTLIST_FOREACH_BEGIN(gs
->sampled_entry_guards
, entry_guard_t
*, guard
) {
1716 if (guard
->confirmed_idx
>= 0)
1717 smartlist_add(gs
->confirmed_entry_guards
, guard
);
1718 } SMARTLIST_FOREACH_END(guard
);
1720 smartlist_sort(gs
->confirmed_entry_guards
, compare_guards_by_confirmed_idx
);
1722 int any_changed
= 0;
1723 SMARTLIST_FOREACH_BEGIN(gs
->confirmed_entry_guards
, entry_guard_t
*, guard
) {
1724 if (guard
->confirmed_idx
!= guard_sl_idx
) {
1726 guard
->confirmed_idx
= guard_sl_idx
;
1728 } SMARTLIST_FOREACH_END(guard
);
1730 gs
->next_confirmed_idx
= smartlist_len(gs
->confirmed_entry_guards
);
1733 entry_guards_changed_for_guard_selection(gs
);
1738 * Mark <b>guard</b> as a confirmed guard -- that is, one that we have
1739 * connected to, and intend to use again.
1742 make_guard_confirmed(guard_selection_t
*gs
, entry_guard_t
*guard
)
1744 if (BUG(guard
->confirmed_on_date
&& guard
->confirmed_idx
>= 0))
1745 return; // LCOV_EXCL_LINE
1747 if (BUG(smartlist_contains(gs
->confirmed_entry_guards
, guard
)))
1748 return; // LCOV_EXCL_LINE
1750 const int GUARD_LIFETIME
= get_guard_lifetime();
1751 guard
->confirmed_on_date
= randomize_time(approx_time(), GUARD_LIFETIME
/10);
1753 log_info(LD_GUARD
, "Marking %s as a confirmed guard (index %d)",
1754 entry_guard_describe(guard
),
1755 gs
->next_confirmed_idx
);
1757 guard
->confirmed_idx
= gs
->next_confirmed_idx
++;
1758 smartlist_add(gs
->confirmed_entry_guards
, guard
);
1760 // This confirmed guard might kick something else out of the primary
1762 gs
->primary_guards_up_to_date
= 0;
1764 entry_guards_changed_for_guard_selection(gs
);
1768 * Recalculate the list of primary guards (the ones we'd prefer to use) from
1769 * the filtered sample and the confirmed list.
1772 entry_guards_update_primary(guard_selection_t
*gs
)
1776 // prevent recursion. Recursion is potentially very bad here.
1777 static int running
= 0;
1778 tor_assert(!running
);
1781 const int N_PRIMARY_GUARDS
= get_n_primary_guards();
1783 smartlist_t
*new_primary_guards
= smartlist_new();
1784 smartlist_t
*old_primary_guards
= smartlist_new();
1785 smartlist_add_all(old_primary_guards
, gs
->primary_entry_guards
);
1787 /* Set this flag now, to prevent the calls below from recursing. */
1788 gs
->primary_guards_up_to_date
= 1;
1790 /* First, can we fill it up with confirmed guards? */
1791 SMARTLIST_FOREACH_BEGIN(gs
->confirmed_entry_guards
, entry_guard_t
*, guard
) {
1792 if (smartlist_len(new_primary_guards
) >= N_PRIMARY_GUARDS
)
1794 if (! guard
->is_filtered_guard
)
1796 guard
->is_primary
= 1;
1797 smartlist_add(new_primary_guards
, guard
);
1798 } SMARTLIST_FOREACH_END(guard
);
1800 /* Can we keep any older primary guards? First remove all the ones
1801 * that we already kept. */
1802 SMARTLIST_FOREACH_BEGIN(old_primary_guards
, entry_guard_t
*, guard
) {
1803 if (smartlist_contains(new_primary_guards
, guard
)) {
1804 SMARTLIST_DEL_CURRENT_KEEPORDER(old_primary_guards
, guard
);
1806 } SMARTLIST_FOREACH_END(guard
);
1808 /* Now add any that are still good. */
1809 SMARTLIST_FOREACH_BEGIN(old_primary_guards
, entry_guard_t
*, guard
) {
1810 if (smartlist_len(new_primary_guards
) >= N_PRIMARY_GUARDS
)
1812 if (! guard
->is_filtered_guard
)
1814 guard
->is_primary
= 1;
1815 smartlist_add(new_primary_guards
, guard
);
1816 SMARTLIST_DEL_CURRENT_KEEPORDER(old_primary_guards
, guard
);
1817 } SMARTLIST_FOREACH_END(guard
);
1819 /* Mark the remaining previous primary guards as non-primary */
1820 SMARTLIST_FOREACH_BEGIN(old_primary_guards
, entry_guard_t
*, guard
) {
1821 guard
->is_primary
= 0;
1822 } SMARTLIST_FOREACH_END(guard
);
1824 /* Finally, fill out the list with sampled guards. */
1825 while (smartlist_len(new_primary_guards
) < N_PRIMARY_GUARDS
) {
1826 entry_guard_t
*guard
= sample_reachable_filtered_entry_guards(gs
, NULL
,
1827 SAMPLE_EXCLUDE_CONFIRMED
|
1828 SAMPLE_EXCLUDE_PRIMARY
|
1829 SAMPLE_NO_UPDATE_PRIMARY
);
1832 guard
->is_primary
= 1;
1833 smartlist_add(new_primary_guards
, guard
);
1838 SMARTLIST_FOREACH(gs
->sampled_entry_guards
, entry_guard_t
*, guard
, {
1839 tor_assert_nonfatal(
1840 bool_eq(guard
->is_primary
,
1841 smartlist_contains(new_primary_guards
, guard
)));
1846 if (smartlist_len(gs
->primary_entry_guards
) !=
1847 smartlist_len(new_primary_guards
)) {
1850 SMARTLIST_FOREACH_BEGIN(gs
->primary_entry_guards
, entry_guard_t
*, g
) {
1851 if (g
!= smartlist_get(new_primary_guards
, g_sl_idx
)) {
1854 } SMARTLIST_FOREACH_END(g
);
1858 log_info(LD_GUARD
, "Primary entry guards have changed. "
1859 "New primary guard list is: ");
1860 int n
= smartlist_len(new_primary_guards
);
1861 SMARTLIST_FOREACH_BEGIN(new_primary_guards
, entry_guard_t
*, g
) {
1862 log_info(LD_GUARD
, " %d/%d: %s%s%s",
1863 g_sl_idx
+1, n
, entry_guard_describe(g
),
1864 g
->confirmed_idx
>= 0 ? " (confirmed)" : "",
1865 g
->is_filtered_guard
? "" : " (excluded by filter)");
1866 } SMARTLIST_FOREACH_END(g
);
1869 smartlist_free(old_primary_guards
);
1870 smartlist_free(gs
->primary_entry_guards
);
1871 gs
->primary_entry_guards
= new_primary_guards
;
1872 gs
->primary_guards_up_to_date
= 1;
1877 * Return the number of seconds after the last attempt at which we should
1878 * retry a guard that has been failing since <b>failing_since</b>.
1881 get_retry_schedule(time_t failing_since
, time_t now
,
1884 const unsigned SIX_HOURS
= 6 * 3600;
1885 const unsigned FOUR_DAYS
= 4 * 86400;
1886 const unsigned SEVEN_DAYS
= 7 * 86400;
1889 if (now
> failing_since
) {
1890 tdiff
= now
- failing_since
;
1896 time_t maximum
; int primary_delay
; int nonprimary_delay
;
1898 { SIX_HOURS
, 10*60, 1*60*60 },
1899 { FOUR_DAYS
, 90*60, 4*60*60 },
1900 { SEVEN_DAYS
, 4*60*60, 18*60*60 },
1901 { TIME_MAX
, 9*60*60, 36*60*60 }
1905 for (i
= 0; i
< ARRAY_LENGTH(delays
); ++i
) {
1906 if (tdiff
<= delays
[i
].maximum
) {
1907 return is_primary
? delays
[i
].primary_delay
: delays
[i
].nonprimary_delay
;
1910 /* LCOV_EXCL_START -- can't reach, since delays ends with TIME_MAX. */
1911 tor_assert_nonfatal_unreached();
1913 /* LCOV_EXCL_STOP */
1917 * If <b>guard</b> is unreachable, consider whether enough time has passed
1918 * to consider it maybe-reachable again.
1921 entry_guard_consider_retry(entry_guard_t
*guard
)
1923 if (guard
->is_reachable
!= GUARD_REACHABLE_NO
)
1924 return; /* No retry needed. */
1926 const time_t now
= approx_time();
1928 get_retry_schedule(guard
->failing_since
, now
, guard
->is_primary
);
1929 const time_t last_attempt
= guard
->last_tried_to_connect
;
1931 if (BUG(last_attempt
== 0) ||
1932 now
>= last_attempt
+ delay
) {
1933 /* We should mark this retriable. */
1934 char tbuf
[ISO_TIME_LEN
+1];
1935 format_local_iso_time(tbuf
, last_attempt
);
1936 log_info(LD_GUARD
, "Marked %s%sguard %s for possible retry, since we "
1937 "haven't tried to use it since %s.",
1938 guard
->is_primary
?"primary ":"",
1939 guard
->confirmed_idx
>=0?"confirmed ":"",
1940 entry_guard_describe(guard
),
1943 guard
->is_reachable
= GUARD_REACHABLE_MAYBE
;
1944 if (guard
->is_filtered_guard
)
1945 guard
->is_usable_filtered_guard
= 1;
1949 /** Tell the entry guards subsystem that we have confirmed that as of
1950 * just now, we're on the internet. */
1952 entry_guards_note_internet_connectivity(guard_selection_t
*gs
)
1954 gs
->last_time_on_internet
= approx_time();
1958 * Get a guard for use with a circuit. Prefer to pick a running primary
1959 * guard; then a non-pending running filtered confirmed guard; then a
1960 * non-pending runnable filtered guard. Update the
1961 * <b>last_tried_to_connect</b> time and the <b>is_pending</b> fields of the
1962 * guard as appropriate. Set <b>state_out</b> to the new guard-state
1965 STATIC entry_guard_t
*
1966 select_entry_guard_for_circuit(guard_selection_t
*gs
,
1967 guard_usage_t usage
,
1968 const entry_guard_restriction_t
*rst
,
1969 unsigned *state_out
)
1971 const int need_descriptor
= (usage
== GUARD_USAGE_TRAFFIC
);
1973 tor_assert(state_out
);
1975 if (!gs
->primary_guards_up_to_date
)
1976 entry_guards_update_primary(gs
);
1978 int num_entry_guards
= get_n_primary_guards_to_use(usage
);
1979 smartlist_t
*usable_primary_guards
= smartlist_new();
1981 /* "If any entry in PRIMARY_GUARDS has {is_reachable} status of
1982 <maybe> or <yes>, return the first such guard." */
1983 SMARTLIST_FOREACH_BEGIN(gs
->primary_entry_guards
, entry_guard_t
*, guard
) {
1984 entry_guard_consider_retry(guard
);
1985 if (! entry_guard_obeys_restriction(guard
, rst
))
1987 if (guard
->is_reachable
!= GUARD_REACHABLE_NO
) {
1988 if (need_descriptor
&& !guard_has_descriptor(guard
)) {
1991 *state_out
= GUARD_CIRC_STATE_USABLE_ON_COMPLETION
;
1992 guard
->last_tried_to_connect
= approx_time();
1993 smartlist_add(usable_primary_guards
, guard
);
1994 if (smartlist_len(usable_primary_guards
) >= num_entry_guards
)
1997 } SMARTLIST_FOREACH_END(guard
);
1999 if (smartlist_len(usable_primary_guards
)) {
2000 entry_guard_t
*guard
= smartlist_choose(usable_primary_guards
);
2001 smartlist_free(usable_primary_guards
);
2002 log_info(LD_GUARD
, "Selected primary guard %s for circuit.",
2003 entry_guard_describe(guard
));
2006 smartlist_free(usable_primary_guards
);
2008 /* "Otherwise, if the ordered intersection of {CONFIRMED_GUARDS}
2009 and {USABLE_FILTERED_GUARDS} is nonempty, return the first
2010 entry in that intersection that has {is_pending} set to
2012 SMARTLIST_FOREACH_BEGIN(gs
->confirmed_entry_guards
, entry_guard_t
*, guard
) {
2013 if (guard
->is_primary
)
2014 continue; /* we already considered this one. */
2015 if (! entry_guard_obeys_restriction(guard
, rst
))
2017 entry_guard_consider_retry(guard
);
2018 if (guard
->is_usable_filtered_guard
&& ! guard
->is_pending
) {
2019 if (need_descriptor
&& !guard_has_descriptor(guard
))
2020 continue; /* not a bug */
2021 guard
->is_pending
= 1;
2022 guard
->last_tried_to_connect
= approx_time();
2023 *state_out
= GUARD_CIRC_STATE_USABLE_IF_NO_BETTER_GUARD
;
2024 log_info(LD_GUARD
, "No primary guards available. Selected confirmed "
2025 "guard %s for circuit. Will try other guards before using "
2027 entry_guard_describe(guard
));
2030 } SMARTLIST_FOREACH_END(guard
);
2032 /* "Otherwise, if there is no such entry, select a member at
2033 random from {USABLE_FILTERED_GUARDS}." */
2035 entry_guard_t
*guard
;
2037 if (need_descriptor
)
2038 flags
|= SAMPLE_EXCLUDE_NO_DESCRIPTOR
;
2039 guard
= sample_reachable_filtered_entry_guards(gs
,
2041 SAMPLE_EXCLUDE_CONFIRMED
|
2042 SAMPLE_EXCLUDE_PRIMARY
|
2043 SAMPLE_EXCLUDE_PENDING
|
2045 if (guard
== NULL
) {
2046 log_info(LD_GUARD
, "Absolutely no sampled guards were available. "
2047 "Marking all guards for retry and starting from top again.");
2048 mark_all_guards_maybe_reachable(gs
);
2051 guard
->is_pending
= 1;
2052 guard
->last_tried_to_connect
= approx_time();
2053 *state_out
= GUARD_CIRC_STATE_USABLE_IF_NO_BETTER_GUARD
;
2054 log_info(LD_GUARD
, "No primary or confirmed guards available. Selected "
2055 "random guard %s for circuit. Will try other guards before "
2056 "using this circuit.",
2057 entry_guard_describe(guard
));
2063 * Note that we failed to connect to or build circuits through <b>guard</b>.
2064 * Use with a guard returned by select_entry_guard_for_circuit().
2067 entry_guards_note_guard_failure(guard_selection_t
*gs
,
2068 entry_guard_t
*guard
)
2072 guard
->is_reachable
= GUARD_REACHABLE_NO
;
2073 guard
->is_usable_filtered_guard
= 0;
2075 guard
->is_pending
= 0;
2076 if (guard
->failing_since
== 0)
2077 guard
->failing_since
= approx_time();
2079 log_info(LD_GUARD
, "Recorded failure for %s%sguard %s",
2080 guard
->is_primary
?"primary ":"",
2081 guard
->confirmed_idx
>=0?"confirmed ":"",
2082 entry_guard_describe(guard
));
2086 * Note that we successfully connected to, and built a circuit through
2087 * <b>guard</b>. Given the old guard-state of the circuit in <b>old_state</b>,
2088 * return the new guard-state of the circuit.
2090 * Be aware: the circuit is only usable when its guard-state becomes
2091 * GUARD_CIRC_STATE_COMPLETE.
2094 entry_guards_note_guard_success(guard_selection_t
*gs
,
2095 entry_guard_t
*guard
,
2100 /* Save this, since we're about to overwrite it. */
2101 const time_t last_time_on_internet
= gs
->last_time_on_internet
;
2102 gs
->last_time_on_internet
= approx_time();
2104 guard
->is_reachable
= GUARD_REACHABLE_YES
;
2105 guard
->failing_since
= 0;
2106 guard
->is_pending
= 0;
2107 if (guard
->is_filtered_guard
)
2108 guard
->is_usable_filtered_guard
= 1;
2110 if (guard
->confirmed_idx
< 0) {
2111 make_guard_confirmed(gs
, guard
);
2112 if (!gs
->primary_guards_up_to_date
)
2113 entry_guards_update_primary(gs
);
2117 switch (old_state
) {
2118 case GUARD_CIRC_STATE_COMPLETE
:
2119 case GUARD_CIRC_STATE_USABLE_ON_COMPLETION
:
2120 new_state
= GUARD_CIRC_STATE_COMPLETE
;
2123 tor_assert_nonfatal_unreached();
2125 case GUARD_CIRC_STATE_USABLE_IF_NO_BETTER_GUARD
:
2126 if (guard
->is_primary
) {
2127 /* XXXX #20832 -- I don't actually like this logic. It seems to make
2128 * us a little more susceptible to evil-ISP attacks. The mitigations
2129 * I'm thinking of, however, aren't local to this point, so I'll leave
2131 /* This guard may have become primary by virtue of being confirmed.
2132 * If so, the circuit for it is now complete.
2134 new_state
= GUARD_CIRC_STATE_COMPLETE
;
2136 new_state
= GUARD_CIRC_STATE_WAITING_FOR_BETTER_GUARD
;
2141 if (! guard
->is_primary
) {
2142 if (last_time_on_internet
+ get_internet_likely_down_interval()
2144 mark_primary_guards_maybe_reachable(gs
);
2148 log_info(LD_GUARD
, "Recorded success for %s%sguard %s",
2149 guard
->is_primary
?"primary ":"",
2150 guard
->confirmed_idx
>=0?"confirmed ":"",
2151 entry_guard_describe(guard
));
2157 * Helper: Return true iff <b>a</b> has higher priority than <b>b</b>.
2160 entry_guard_has_higher_priority(entry_guard_t
*a
, entry_guard_t
*b
)
2166 /* Confirmed is always better than unconfirmed; lower index better
2168 if (a
->confirmed_idx
< 0) {
2169 if (b
->confirmed_idx
>= 0)
2172 if (b
->confirmed_idx
< 0)
2175 /* Lower confirmed_idx is better than higher. */
2176 return (a
->confirmed_idx
< b
->confirmed_idx
);
2179 /* If we reach this point, both are unconfirmed. If one is pending, it
2180 * has higher priority. */
2181 if (a
->is_pending
) {
2182 if (! b
->is_pending
)
2185 /* Both are pending: earlier last_tried_connect wins. */
2186 return a
->last_tried_to_connect
< b
->last_tried_to_connect
;
2191 /* Neither is pending: priorities are equal. */
2196 /** Release all storage held in <b>restriction</b> */
2198 entry_guard_restriction_free(entry_guard_restriction_t
*rst
)
2204 * Release all storage held in <b>state</b>.
2207 circuit_guard_state_free(circuit_guard_state_t
*state
)
2211 entry_guard_restriction_free(state
->restrictions
);
2212 entry_guard_handle_free(state
->guard
);
2216 /** Allocate and return a new circuit_guard_state_t to track the result
2217 * of using <b>guard</b> for a given operation. */
2218 static circuit_guard_state_t
*
2219 circuit_guard_state_new(entry_guard_t
*guard
, unsigned state
,
2220 entry_guard_restriction_t
*rst
)
2222 circuit_guard_state_t
*result
;
2224 result
= tor_malloc_zero(sizeof(circuit_guard_state_t
));
2225 result
->guard
= entry_guard_handle_new(guard
);
2226 result
->state
= state
;
2227 result
->state_set_at
= approx_time();
2228 result
->restrictions
= rst
;
2234 * Pick a suitable entry guard for a circuit in, and place that guard
2235 * in *<b>chosen_node_out</b>. Set *<b>guard_state_out</b> to an opaque
2236 * state object that will record whether the circuit is ready to be used
2237 * or not. Return 0 on success; on failure, return -1.
2239 * If a restriction is provided in <b>rst</b>, do not return any guards that
2240 * violate it, and remember that restriction in <b>guard_state_out</b> for
2241 * later use. (Takes ownership of the <b>rst</b> object.)
2244 entry_guard_pick_for_circuit(guard_selection_t
*gs
,
2245 guard_usage_t usage
,
2246 entry_guard_restriction_t
*rst
,
2247 const node_t
**chosen_node_out
,
2248 circuit_guard_state_t
**guard_state_out
)
2251 tor_assert(chosen_node_out
);
2252 tor_assert(guard_state_out
);
2253 *chosen_node_out
= NULL
;
2254 *guard_state_out
= NULL
;
2257 entry_guard_t
*guard
=
2258 select_entry_guard_for_circuit(gs
, usage
, rst
, &state
);
2261 if (BUG(state
== 0))
2263 const node_t
*node
= node_get_by_id(guard
->identity
);
2264 // XXXX #20827 check Ed ID.
2267 if (BUG(usage
!= GUARD_USAGE_DIRGUARD
&& !node_has_descriptor(node
)))
2270 *chosen_node_out
= node
;
2271 *guard_state_out
= circuit_guard_state_new(guard
, state
, rst
);
2275 entry_guard_restriction_free(rst
);
2280 * Called by the circuit building module when a circuit has succeeded: informs
2281 * the guards code that the guard in *<b>guard_state_p</b> is working, and
2282 * advances the state of the guard module. On a GUARD_USABLE_NEVER return
2283 * value, the circuit is broken and should not be used. On a GUARD_USABLE_NOW
2284 * return value, the circuit is ready to use. On a GUARD_MAYBE_USABLE_LATER
2285 * return value, the circuit should not be used until we find out whether
2286 * preferred guards will work for us.
2289 entry_guard_succeeded(circuit_guard_state_t
**guard_state_p
)
2291 if (BUG(*guard_state_p
== NULL
))
2292 return GUARD_USABLE_NEVER
;
2294 entry_guard_t
*guard
= entry_guard_handle_get((*guard_state_p
)->guard
);
2295 if (! guard
|| BUG(guard
->in_selection
== NULL
))
2296 return GUARD_USABLE_NEVER
;
2299 entry_guards_note_guard_success(guard
->in_selection
, guard
,
2300 (*guard_state_p
)->state
);
2302 (*guard_state_p
)->state
= newstate
;
2303 (*guard_state_p
)->state_set_at
= approx_time();
2305 if (newstate
== GUARD_CIRC_STATE_COMPLETE
) {
2306 return GUARD_USABLE_NOW
;
2308 return GUARD_MAYBE_USABLE_LATER
;
2312 /** Cancel the selection of *<b>guard_state_p</b> without declaring
2313 * success or failure. It is safe to call this function if success or
2314 * failure _has_ already been declared. */
2316 entry_guard_cancel(circuit_guard_state_t
**guard_state_p
)
2318 if (BUG(*guard_state_p
== NULL
))
2320 entry_guard_t
*guard
= entry_guard_handle_get((*guard_state_p
)->guard
);
2324 /* XXXX prop271 -- last_tried_to_connect_at will be erroneous here, but this
2325 * function will only get called in "bug" cases anyway. */
2326 guard
->is_pending
= 0;
2327 circuit_guard_state_free(*guard_state_p
);
2328 *guard_state_p
= NULL
;
2332 * Called by the circuit building module when a circuit has succeeded:
2333 * informs the guards code that the guard in *<b>guard_state_p</b> is
2334 * not working, and advances the state of the guard module.
2337 entry_guard_failed(circuit_guard_state_t
**guard_state_p
)
2339 if (BUG(*guard_state_p
== NULL
))
2342 entry_guard_t
*guard
= entry_guard_handle_get((*guard_state_p
)->guard
);
2343 if (! guard
|| BUG(guard
->in_selection
== NULL
))
2346 entry_guards_note_guard_failure(guard
->in_selection
, guard
);
2348 (*guard_state_p
)->state
= GUARD_CIRC_STATE_DEAD
;
2349 (*guard_state_p
)->state_set_at
= approx_time();
2353 * Run the entry_guard_failed() function on every circuit that is
2354 * pending on <b>chan</b>.
2357 entry_guard_chan_failed(channel_t
*chan
)
2362 smartlist_t
*pending
= smartlist_new();
2363 circuit_get_all_pending_on_channel(pending
, chan
);
2364 SMARTLIST_FOREACH_BEGIN(pending
, circuit_t
*, circ
) {
2365 if (!CIRCUIT_IS_ORIGIN(circ
))
2368 origin_circuit_t
*origin_circ
= TO_ORIGIN_CIRCUIT(circ
);
2369 if (origin_circ
->guard_state
) {
2370 /* We might have no guard state if we didn't use a guard on this
2371 * circuit (eg it's for a fallback directory). */
2372 entry_guard_failed(&origin_circ
->guard_state
);
2374 } SMARTLIST_FOREACH_END(circ
);
2375 smartlist_free(pending
);
2379 * Return true iff every primary guard in <b>gs</b> is believed to
2383 entry_guards_all_primary_guards_are_down(guard_selection_t
*gs
)
2386 if (!gs
->primary_guards_up_to_date
)
2387 entry_guards_update_primary(gs
);
2388 SMARTLIST_FOREACH_BEGIN(gs
->primary_entry_guards
, entry_guard_t
*, guard
) {
2389 entry_guard_consider_retry(guard
);
2390 if (guard
->is_reachable
!= GUARD_REACHABLE_NO
)
2392 } SMARTLIST_FOREACH_END(guard
);
2396 /** Wrapper for entry_guard_has_higher_priority that compares the
2397 * guard-priorities of a pair of circuits. Return 1 if <b>a</b> has higher
2398 * priority than <b>b</b>.
2400 * If a restriction is provided in <b>rst</b>, then do not consider
2401 * <b>a</b> to have higher priority if it violates the restriction.
2404 circ_state_has_higher_priority(origin_circuit_t
*a
,
2405 const entry_guard_restriction_t
*rst
,
2406 origin_circuit_t
*b
)
2408 circuit_guard_state_t
*state_a
= origin_circuit_get_guard_state(a
);
2409 circuit_guard_state_t
*state_b
= origin_circuit_get_guard_state(b
);
2411 tor_assert(state_a
);
2412 tor_assert(state_b
);
2414 entry_guard_t
*guard_a
= entry_guard_handle_get(state_a
->guard
);
2415 entry_guard_t
*guard_b
= entry_guard_handle_get(state_b
->guard
);
2418 /* Unknown guard -- never higher priority. */
2420 } else if (! guard_b
) {
2421 /* Known guard -- higher priority than any unknown guard. */
2423 } else if (! entry_guard_obeys_restriction(guard_a
, rst
)) {
2424 /* Restriction violated; guard_a cannot have higher priority. */
2427 /* Both known -- compare.*/
2428 return entry_guard_has_higher_priority(guard_a
, guard_b
);
2433 * Look at all of the origin_circuit_t * objects in <b>all_circuits_in</b>,
2434 * and see if any of them that were previously not ready to use for
2435 * guard-related reasons are now ready to use. Place those circuits
2436 * in <b>newly_complete_out</b>, and mark them COMPLETE.
2438 * Return 1 if we upgraded any circuits, and 0 otherwise.
2441 entry_guards_upgrade_waiting_circuits(guard_selection_t
*gs
,
2442 const smartlist_t
*all_circuits_in
,
2443 smartlist_t
*newly_complete_out
)
2446 tor_assert(all_circuits_in
);
2447 tor_assert(newly_complete_out
);
2449 if (! entry_guards_all_primary_guards_are_down(gs
)) {
2450 /* We only upgrade a waiting circuit if the primary guards are all
2452 log_debug(LD_GUARD
, "Considered upgrading guard-stalled circuits, "
2453 "but not all primary guards were definitely down.");
2459 int n_complete_blocking
= 0;
2460 origin_circuit_t
*best_waiting_circuit
= NULL
;
2461 smartlist_t
*all_circuits
= smartlist_new();
2462 SMARTLIST_FOREACH_BEGIN(all_circuits_in
, origin_circuit_t
*, circ
) {
2463 // We filter out circuits that aren't ours, or which we can't
2465 circuit_guard_state_t
*state
= origin_circuit_get_guard_state(circ
);
2468 entry_guard_t
*guard
= entry_guard_handle_get(state
->guard
);
2469 if (!guard
|| guard
->in_selection
!= gs
)
2472 smartlist_add(all_circuits
, circ
);
2473 } SMARTLIST_FOREACH_END(circ
);
2475 SMARTLIST_FOREACH_BEGIN(all_circuits
, origin_circuit_t
*, circ
) {
2476 circuit_guard_state_t
*state
= origin_circuit_get_guard_state(circ
);
2477 if (BUG(state
== NULL
))
2480 if (state
->state
== GUARD_CIRC_STATE_WAITING_FOR_BETTER_GUARD
) {
2482 if (! best_waiting_circuit
||
2483 circ_state_has_higher_priority(circ
, NULL
, best_waiting_circuit
)) {
2484 best_waiting_circuit
= circ
;
2487 } SMARTLIST_FOREACH_END(circ
);
2489 if (! best_waiting_circuit
) {
2490 log_debug(LD_GUARD
, "Considered upgrading guard-stalled circuits, "
2491 "but didn't find any.");
2495 /* We'll need to keep track of what restrictions were used when picking this
2496 * circuit, so that we don't allow any circuit without those restrictions to
2498 const entry_guard_restriction_t
*rst_on_best_waiting
=
2499 origin_circuit_get_guard_state(best_waiting_circuit
)->restrictions
;
2501 /* First look at the complete circuits: Do any block this circuit? */
2502 SMARTLIST_FOREACH_BEGIN(all_circuits
, origin_circuit_t
*, circ
) {
2503 /* "C2 "blocks" C1 if:
2504 * C2 obeys all the restrictions that C1 had to obey, AND
2505 * C2 has higher priority than C1, AND
2506 * Either C2 is <complete>, or C2 is <waiting_for_better_guard>,
2507 or C2 has been <usable_if_no_better_guard> for no more than
2508 {NONPRIMARY_GUARD_CONNECT_TIMEOUT} seconds."
2510 circuit_guard_state_t
*state
= origin_circuit_get_guard_state(circ
);
2511 if BUG((state
== NULL
))
2513 if (state
->state
!= GUARD_CIRC_STATE_COMPLETE
)
2516 if (circ_state_has_higher_priority(circ
, rst_on_best_waiting
,
2517 best_waiting_circuit
))
2518 ++n_complete_blocking
;
2519 } SMARTLIST_FOREACH_END(circ
);
2521 if (n_complete_blocking
) {
2522 log_debug(LD_GUARD
, "Considered upgrading guard-stalled circuits: found "
2523 "%d complete and %d guard-stalled. At least one complete "
2524 "circuit had higher priority, so not upgrading.",
2525 n_complete
, n_waiting
);
2529 /* " * If any circuit C1 is <waiting_for_better_guard>, AND:
2530 * All primary guards have reachable status of <no>.
2531 * There is no circuit C2 that "blocks" C1.
2532 Then, upgrade C1 to <complete>.""
2534 int n_blockers_found
= 0;
2535 const time_t state_set_at_cutoff
=
2536 approx_time() - get_nonprimary_guard_connect_timeout();
2537 SMARTLIST_FOREACH_BEGIN(all_circuits
, origin_circuit_t
*, circ
) {
2538 circuit_guard_state_t
*state
= origin_circuit_get_guard_state(circ
);
2539 if (BUG(state
== NULL
))
2541 if (state
->state
!= GUARD_CIRC_STATE_USABLE_IF_NO_BETTER_GUARD
)
2543 if (state
->state_set_at
<= state_set_at_cutoff
)
2545 if (circ_state_has_higher_priority(circ
, rst_on_best_waiting
,
2546 best_waiting_circuit
))
2548 } SMARTLIST_FOREACH_END(circ
);
2550 if (n_blockers_found
) {
2551 log_debug(LD_GUARD
, "Considered upgrading guard-stalled circuits: found "
2552 "%d guard-stalled, but %d pending circuit(s) had higher "
2553 "guard priority, so not upgrading.",
2554 n_waiting
, n_blockers_found
);
2558 /* Okay. We have a best waiting circuit, and we aren't waiting for
2559 anything better. Add all circuits with that priority to the
2560 list, and call them COMPLETE. */
2561 int n_succeeded
= 0;
2562 SMARTLIST_FOREACH_BEGIN(all_circuits
, origin_circuit_t
*, circ
) {
2563 circuit_guard_state_t
*state
= origin_circuit_get_guard_state(circ
);
2564 if (BUG(state
== NULL
))
2566 if (circ
!= best_waiting_circuit
&& rst_on_best_waiting
) {
2567 /* Can't upgrade other circ with same priority as best; might
2571 if (state
->state
!= GUARD_CIRC_STATE_WAITING_FOR_BETTER_GUARD
)
2573 if (circ_state_has_higher_priority(best_waiting_circuit
, NULL
, circ
))
2576 state
->state
= GUARD_CIRC_STATE_COMPLETE
;
2577 state
->state_set_at
= approx_time();
2578 smartlist_add(newly_complete_out
, circ
);
2580 } SMARTLIST_FOREACH_END(circ
);
2582 log_info(LD_GUARD
, "Considered upgrading guard-stalled circuits: found "
2583 "%d guard-stalled, %d complete. %d of the guard-stalled "
2584 "circuit(s) had high enough priority to upgrade.",
2585 n_waiting
, n_complete
, n_succeeded
);
2587 tor_assert_nonfatal(n_succeeded
>= 1);
2588 smartlist_free(all_circuits
);
2592 smartlist_free(all_circuits
);
2597 * Return true iff the circuit whose state is <b>guard_state</b> should
2601 entry_guard_state_should_expire(circuit_guard_state_t
*guard_state
)
2603 if (guard_state
== NULL
)
2605 const time_t expire_if_waiting_since
=
2606 approx_time() - get_nonprimary_guard_idle_timeout();
2607 return (guard_state
->state
== GUARD_CIRC_STATE_WAITING_FOR_BETTER_GUARD
2608 && guard_state
->state_set_at
< expire_if_waiting_since
);
2612 * Update all derived pieces of the guard selection state in <b>gs</b>.
2613 * Return true iff we should stop using all previously generated circuits.
2616 entry_guards_update_all(guard_selection_t
*gs
)
2618 sampled_guards_update_from_consensus(gs
);
2619 entry_guards_update_filtered_sets(gs
);
2620 entry_guards_update_confirmed(gs
);
2621 entry_guards_update_primary(gs
);
2626 * Return a newly allocated string for encoding the persistent parts of
2627 * <b>guard</b> to the state file.
2630 entry_guard_encode_for_state(entry_guard_t
*guard
)
2633 * The meta-format we use is K=V K=V K=V... where K can be any
2634 * characters excepts space and =, and V can be any characters except
2635 * space. The order of entries is not allowed to matter.
2636 * Unrecognized K=V entries are persisted; recognized but erroneous
2637 * entries are corrected.
2640 smartlist_t
*result
= smartlist_new();
2641 char tbuf
[ISO_TIME_LEN
+1];
2645 smartlist_add_asprintf(result
, "in=%s", guard
->selection_name
);
2646 smartlist_add_asprintf(result
, "rsa_id=%s",
2647 hex_str(guard
->identity
, DIGEST_LEN
));
2648 if (guard
->bridge_addr
) {
2649 smartlist_add_asprintf(result
, "bridge_addr=%s:%d",
2650 fmt_and_decorate_addr(&guard
->bridge_addr
->addr
),
2651 guard
->bridge_addr
->port
);
2653 if (strlen(guard
->nickname
) && is_legal_nickname(guard
->nickname
)) {
2654 smartlist_add_asprintf(result
, "nickname=%s", guard
->nickname
);
2657 format_iso_time_nospace(tbuf
, guard
->sampled_on_date
);
2658 smartlist_add_asprintf(result
, "sampled_on=%s", tbuf
);
2660 if (guard
->sampled_by_version
) {
2661 smartlist_add_asprintf(result
, "sampled_by=%s",
2662 guard
->sampled_by_version
);
2665 if (guard
->unlisted_since_date
> 0) {
2666 format_iso_time_nospace(tbuf
, guard
->unlisted_since_date
);
2667 smartlist_add_asprintf(result
, "unlisted_since=%s", tbuf
);
2670 smartlist_add_asprintf(result
, "listed=%d",
2671 (int)guard
->currently_listed
);
2673 if (guard
->confirmed_idx
>= 0) {
2674 format_iso_time_nospace(tbuf
, guard
->confirmed_on_date
);
2675 smartlist_add_asprintf(result
, "confirmed_on=%s", tbuf
);
2677 smartlist_add_asprintf(result
, "confirmed_idx=%d", guard
->confirmed_idx
);
2680 const double EPSILON
= 1.0e-6;
2682 /* Make a copy of the pathbias object, since we will want to update
2684 guard_pathbias_t
*pb
= tor_memdup(&guard
->pb
, sizeof(*pb
));
2685 pb
->use_successes
= pathbias_get_use_success_count(guard
);
2686 pb
->successful_circuits_closed
= pathbias_get_close_success_count(guard
);
2688 #define PB_FIELD(field) do { \
2689 if (pb->field >= EPSILON) { \
2690 smartlist_add_asprintf(result, "pb_" #field "=%f", pb->field); \
2693 PB_FIELD(use_attempts
);
2694 PB_FIELD(use_successes
);
2695 PB_FIELD(circ_attempts
);
2696 PB_FIELD(circ_successes
);
2697 PB_FIELD(successful_circuits_closed
);
2698 PB_FIELD(collapsed_circuits
);
2699 PB_FIELD(unusable_circuits
);
2704 if (guard
->extra_state_fields
)
2705 smartlist_add_strdup(result
, guard
->extra_state_fields
);
2707 char *joined
= smartlist_join_strings(result
, " ", 0, NULL
);
2708 SMARTLIST_FOREACH(result
, char *, cp
, tor_free(cp
));
2709 smartlist_free(result
);
2715 * Given a string generated by entry_guard_encode_for_state(), parse it
2716 * (if possible) and return an entry_guard_t object for it. Return NULL
2717 * on complete failure.
2719 STATIC entry_guard_t
*
2720 entry_guard_parse_from_state(const char *s
)
2722 /* Unrecognized entries get put in here. */
2723 smartlist_t
*extra
= smartlist_new();
2725 /* These fields get parsed from the string. */
2727 char *rsa_id
= NULL
;
2728 char *nickname
= NULL
;
2729 char *sampled_on
= NULL
;
2730 char *sampled_by
= NULL
;
2731 char *unlisted_since
= NULL
;
2732 char *listed
= NULL
;
2733 char *confirmed_on
= NULL
;
2734 char *confirmed_idx
= NULL
;
2735 char *bridge_addr
= NULL
;
2738 char *pb_use_attempts
= NULL
;
2739 char *pb_use_successes
= NULL
;
2740 char *pb_circ_attempts
= NULL
;
2741 char *pb_circ_successes
= NULL
;
2742 char *pb_successful_circuits_closed
= NULL
;
2743 char *pb_collapsed_circuits
= NULL
;
2744 char *pb_unusable_circuits
= NULL
;
2745 char *pb_timeouts
= NULL
;
2747 /* Split up the entries. Put the ones we know about in strings and the
2748 * rest in "extra". */
2750 smartlist_t
*entries
= smartlist_new();
2752 strmap_t
*vals
= strmap_new(); // Maps keyword to location
2754 strmap_set(vals, #f, &f);
2760 FIELD(unlisted_since
);
2762 FIELD(confirmed_on
);
2763 FIELD(confirmed_idx
);
2765 FIELD(pb_use_attempts
);
2766 FIELD(pb_use_successes
);
2767 FIELD(pb_circ_attempts
);
2768 FIELD(pb_circ_successes
);
2769 FIELD(pb_successful_circuits_closed
);
2770 FIELD(pb_collapsed_circuits
);
2771 FIELD(pb_unusable_circuits
);
2775 smartlist_split_string(entries
, s
, " ",
2776 SPLIT_SKIP_SPACE
|SPLIT_IGNORE_BLANK
, 0);
2778 SMARTLIST_FOREACH_BEGIN(entries
, char *, entry
) {
2779 const char *eq
= strchr(entry
, '=');
2781 smartlist_add(extra
, entry
);
2784 char *key
= tor_strndup(entry
, eq
-entry
);
2785 char **target
= strmap_get(vals
, key
);
2786 if (target
== NULL
|| *target
!= NULL
) {
2787 /* unrecognized or already set */
2788 smartlist_add(extra
, entry
);
2793 *target
= tor_strdup(eq
+1);
2796 } SMARTLIST_FOREACH_END(entry
);
2798 smartlist_free(entries
);
2799 strmap_free(vals
, NULL
);
2802 entry_guard_t
*guard
= tor_malloc_zero(sizeof(entry_guard_t
));
2803 guard
->is_persistent
= 1;
2806 log_warn(LD_CIRC
, "Guard missing 'in' field");
2810 guard
->selection_name
= in
;
2813 if (rsa_id
== NULL
) {
2814 log_warn(LD_CIRC
, "Guard missing RSA ID field");
2818 /* Process the identity and nickname. */
2819 if (base16_decode(guard
->identity
, sizeof(guard
->identity
),
2820 rsa_id
, strlen(rsa_id
)) != DIGEST_LEN
) {
2821 log_warn(LD_CIRC
, "Unable to decode guard identity %s", escaped(rsa_id
));
2826 strlcpy(guard
->nickname
, nickname
, sizeof(guard
->nickname
));
2828 guard
->nickname
[0]='$';
2829 base16_encode(guard
->nickname
+1, sizeof(guard
->nickname
)-1,
2830 guard
->identity
, DIGEST_LEN
);
2834 tor_addr_port_t res
;
2835 memset(&res
, 0, sizeof(res
));
2836 int r
= tor_addr_port_parse(LOG_WARN
, bridge_addr
,
2837 &res
.addr
, &res
.port
, -1);
2839 guard
->bridge_addr
= tor_memdup(&res
, sizeof(res
));
2840 /* On error, we already warned. */
2843 /* Process the various time fields. */
2845 #define HANDLE_TIME(field) do { \
2847 int r = parse_iso_time_nospace(field, &field ## _time); \
2849 log_warn(LD_CIRC, "Unable to parse %s %s from guard", \
2850 #field, escaped(field)); \
2851 field##_time = -1; \
2856 time_t sampled_on_time
= 0;
2857 time_t unlisted_since_time
= 0;
2858 time_t confirmed_on_time
= 0;
2860 HANDLE_TIME(sampled_on
);
2861 HANDLE_TIME(unlisted_since
);
2862 HANDLE_TIME(confirmed_on
);
2864 if (sampled_on_time
<= 0)
2865 sampled_on_time
= approx_time();
2866 if (unlisted_since_time
< 0)
2867 unlisted_since_time
= 0;
2868 if (confirmed_on_time
< 0)
2869 confirmed_on_time
= 0;
2873 guard
->sampled_on_date
= sampled_on_time
;
2874 guard
->unlisted_since_date
= unlisted_since_time
;
2875 guard
->confirmed_on_date
= confirmed_on_time
;
2877 /* Take sampled_by_version verbatim. */
2878 guard
->sampled_by_version
= sampled_by
;
2879 sampled_by
= NULL
; /* prevent free */
2881 /* Listed is a boolean */
2882 if (listed
&& strcmp(listed
, "0"))
2883 guard
->currently_listed
= 1;
2885 /* The index is a nonnegative integer. */
2886 guard
->confirmed_idx
= -1;
2887 if (confirmed_idx
) {
2889 long idx
= tor_parse_long(confirmed_idx
, 10, 0, INT_MAX
, &ok
, NULL
);
2891 log_warn(LD_GUARD
, "Guard has invalid confirmed_idx %s",
2892 escaped(confirmed_idx
));
2894 guard
->confirmed_idx
= (int)idx
;
2898 /* Anything we didn't recognize gets crammed together */
2899 if (smartlist_len(extra
) > 0) {
2900 guard
->extra_state_fields
= smartlist_join_strings(extra
, " ", 0, NULL
);
2903 /* initialize non-persistent fields */
2904 guard
->is_reachable
= GUARD_REACHABLE_MAYBE
;
2906 #define PB_FIELD(field) \
2908 if (pb_ ## field) { \
2910 double r = tor_parse_double(pb_ ## field, 0.0, 1e9, &ok, NULL); \
2912 log_warn(LD_CIRC, "Guard has invalid pb_%s %s", \
2913 #field, pb_ ## field); \
2915 guard->pb.field = r; \
2919 PB_FIELD(use_attempts
);
2920 PB_FIELD(use_successes
);
2921 PB_FIELD(circ_attempts
);
2922 PB_FIELD(circ_successes
);
2923 PB_FIELD(successful_circuits_closed
);
2924 PB_FIELD(collapsed_circuits
);
2925 PB_FIELD(unusable_circuits
);
2929 pathbias_check_use_success_count(guard
);
2930 pathbias_check_close_success_count(guard
);
2932 /* We update everything on this guard later, after we've parsed
2938 // only consider it an error if the guard state was totally unparseable.
2939 entry_guard_free(guard
);
2946 tor_free(sampled_on
);
2947 tor_free(sampled_by
);
2948 tor_free(unlisted_since
);
2950 tor_free(confirmed_on
);
2951 tor_free(confirmed_idx
);
2952 tor_free(bridge_addr
);
2953 tor_free(pb_use_attempts
);
2954 tor_free(pb_use_successes
);
2955 tor_free(pb_circ_attempts
);
2956 tor_free(pb_circ_successes
);
2957 tor_free(pb_successful_circuits_closed
);
2958 tor_free(pb_collapsed_circuits
);
2959 tor_free(pb_unusable_circuits
);
2960 tor_free(pb_timeouts
);
2962 SMARTLIST_FOREACH(extra
, char *, cp
, tor_free(cp
));
2963 smartlist_free(extra
);
2969 * Replace the Guards entries in <b>state</b> with a list of all our sampled
2973 entry_guards_update_guards_in_state(or_state_t
*state
)
2975 if (!guard_contexts
)
2977 config_line_t
*lines
= NULL
;
2978 config_line_t
**nextline
= &lines
;
2980 SMARTLIST_FOREACH_BEGIN(guard_contexts
, guard_selection_t
*, gs
) {
2981 SMARTLIST_FOREACH_BEGIN(gs
->sampled_entry_guards
, entry_guard_t
*, guard
) {
2982 if (guard
->is_persistent
== 0)
2984 *nextline
= tor_malloc_zero(sizeof(config_line_t
));
2985 (*nextline
)->key
= tor_strdup("Guard");
2986 (*nextline
)->value
= entry_guard_encode_for_state(guard
);
2987 nextline
= &(*nextline
)->next
;
2988 } SMARTLIST_FOREACH_END(guard
);
2989 } SMARTLIST_FOREACH_END(gs
);
2991 config_free_lines(state
->Guard
);
2992 state
->Guard
= lines
;
2996 * Replace our sampled guards from the Guards entries in <b>state</b>. Return 0
2997 * on success, -1 on failure. (If <b>set</b> is true, replace nothing -- only
2998 * check whether replacing would work.)
3001 entry_guards_load_guards_from_state(or_state_t
*state
, int set
)
3003 const config_line_t
*line
= state
->Guard
;
3006 if (!guard_contexts
)
3007 guard_contexts
= smartlist_new();
3009 /* Wipe all our existing guard info. (we shouldn't have any, but
3010 * let's be safe.) */
3012 SMARTLIST_FOREACH_BEGIN(guard_contexts
, guard_selection_t
*, gs
) {
3013 guard_selection_free(gs
);
3014 if (curr_guard_context
== gs
)
3015 curr_guard_context
= NULL
;
3016 SMARTLIST_DEL_CURRENT(guard_contexts
, gs
);
3017 } SMARTLIST_FOREACH_END(gs
);
3020 for ( ; line
!= NULL
; line
= line
->next
) {
3021 entry_guard_t
*guard
= entry_guard_parse_from_state(line
->value
);
3022 if (guard
== NULL
) {
3026 tor_assert(guard
->selection_name
);
3027 if (!strcmp(guard
->selection_name
, "legacy")) {
3029 entry_guard_free(guard
);
3034 guard_selection_t
*gs
;
3035 gs
= get_guard_selection_by_name(guard
->selection_name
,
3038 smartlist_add(gs
->sampled_entry_guards
, guard
);
3039 guard
->in_selection
= gs
;
3041 entry_guard_free(guard
);
3046 SMARTLIST_FOREACH_BEGIN(guard_contexts
, guard_selection_t
*, gs
) {
3047 entry_guards_update_all(gs
);
3048 } SMARTLIST_FOREACH_END(gs
);
3050 return n_errors
? -1 : 0;
3053 /** If <b>digest</b> matches the identity of any node in the
3054 * entry_guards list for the provided guard selection state,
3055 return that node. Else return NULL. */
3057 entry_guard_get_by_id_digest_for_guard_selection(guard_selection_t
*gs
,
3060 return get_sampled_guard_with_id(gs
, (const uint8_t*)digest
);
3063 /** Return the node_t associated with a single entry_guard_t. May
3064 * return NULL if the guard is not currently in the consensus. */
3066 entry_guard_find_node(const entry_guard_t
*guard
)
3069 return node_get_by_id(guard
->identity
);
3072 /** If <b>digest</b> matches the identity of any node in the
3073 * entry_guards list for the default guard selection state,
3074 return that node. Else return NULL. */
3076 entry_guard_get_by_id_digest(const char *digest
)
3078 return entry_guard_get_by_id_digest_for_guard_selection(
3079 get_guard_selection_info(), digest
);
3082 /** We are about to connect to bridge with identity <b>digest</b> to fetch its
3083 * descriptor. Create a new guard state for this connection and return it. */
3084 circuit_guard_state_t
*
3085 get_guard_state_for_bridge_desc_fetch(const char *digest
)
3087 circuit_guard_state_t
*guard_state
= NULL
;
3088 entry_guard_t
*guard
= NULL
;
3090 guard
= entry_guard_get_by_id_digest_for_guard_selection(
3091 get_guard_selection_info(), digest
);
3096 /* Update the guard last_tried_to_connect time since it's checked by the
3097 * guard susbsystem. */
3098 guard
->last_tried_to_connect
= approx_time();
3100 /* Create the guard state */
3101 guard_state
= circuit_guard_state_new(guard
,
3102 GUARD_CIRC_STATE_USABLE_ON_COMPLETION
,
3108 /** Release all storage held by <b>e</b>. */
3110 entry_guard_free(entry_guard_t
*e
)
3114 entry_guard_handles_clear(e
);
3115 tor_free(e
->sampled_by_version
);
3116 tor_free(e
->extra_state_fields
);
3117 tor_free(e
->selection_name
);
3118 tor_free(e
->bridge_addr
);
3122 /** Return 0 if we're fine adding arbitrary routers out of the
3123 * directory to our entry guard list, or return 1 if we have a
3124 * list already and we must stick to it.
3127 entry_list_is_constrained(const or_options_t
*options
)
3129 // XXXX #21425 look at the current selection.
3130 if (options
->EntryNodes
)
3132 if (options
->UseBridges
)
3137 /** Return the number of bridges that have descriptors that are marked with
3138 * purpose 'bridge' and are running.
3140 * We use this function to decide if we're ready to start building
3141 * circuits through our bridges, or if we need to wait until the
3142 * directory "server/authority" requests finish. */
3144 num_bridges_usable
,(void))
3148 if (BUG(!get_options()->UseBridges
)) {
3151 guard_selection_t
*gs
= get_guard_selection_info();
3152 if (BUG(gs
->type
!= GS_TYPE_BRIDGE
)) {
3156 SMARTLIST_FOREACH_BEGIN(gs
->sampled_entry_guards
, entry_guard_t
*, guard
) {
3157 if (guard
->is_reachable
== GUARD_REACHABLE_NO
)
3159 if (tor_digest_is_zero(guard
->identity
))
3161 const node_t
*node
= node_get_by_id(guard
->identity
);
3162 if (node
&& node
->ri
)
3164 } SMARTLIST_FOREACH_END(guard
);
3169 /** Check the pathbias use success count of <b>node</b> and disable it if it
3170 * goes over our thresholds. */
3172 pathbias_check_use_success_count(entry_guard_t
*node
)
3174 const or_options_t
*options
= get_options();
3175 const double EPSILON
= 1.0e-9;
3177 /* Note: We rely on the < comparison here to allow us to set a 0
3178 * rate and disable the feature entirely. If refactoring, don't
3180 if (node
->pb
.use_attempts
> EPSILON
&&
3181 pathbias_get_use_success_count(node
)/node
->pb
.use_attempts
3182 < pathbias_get_extreme_use_rate(options
) &&
3183 pathbias_get_dropguards(options
)) {
3184 node
->pb
.path_bias_disabled
= 1;
3185 log_info(LD_GENERAL
,
3186 "Path use bias is too high (%f/%f); disabling node %s",
3187 node
->pb
.circ_successes
, node
->pb
.circ_attempts
,
3192 /** Check the pathbias close count of <b>node</b> and disable it if it goes
3193 * over our thresholds. */
3195 pathbias_check_close_success_count(entry_guard_t
*node
)
3197 const or_options_t
*options
= get_options();
3198 const double EPSILON
= 1.0e-9;
3200 /* Note: We rely on the < comparison here to allow us to set a 0
3201 * rate and disable the feature entirely. If refactoring, don't
3203 if (node
->pb
.circ_attempts
> EPSILON
&&
3204 pathbias_get_close_success_count(node
)/node
->pb
.circ_attempts
3205 < pathbias_get_extreme_rate(options
) &&
3206 pathbias_get_dropguards(options
)) {
3207 node
->pb
.path_bias_disabled
= 1;
3208 log_info(LD_GENERAL
,
3209 "Path bias is too high (%f/%f); disabling node %s",
3210 node
->pb
.circ_successes
, node
->pb
.circ_attempts
,
3215 /** Parse <b>state</b> and learn about the entry guards it describes.
3216 * If <b>set</b> is true, and there are no errors, replace the guard
3217 * list in the default guard selection context with what we find.
3218 * On success, return 0. On failure, alloc into *<b>msg</b> a string
3219 * describing the error, and return -1.
3222 entry_guards_parse_state(or_state_t
*state
, int set
, char **msg
)
3224 entry_guards_dirty
= 0;
3225 int r1
= entry_guards_load_guards_from_state(state
, set
);
3226 entry_guards_dirty
= 0;
3229 if (msg
&& *msg
== NULL
) {
3230 *msg
= tor_strdup("parsing error");
3237 /** How long will we let a change in our guard nodes stay un-saved
3238 * when we are trying to avoid disk writes? */
3239 #define SLOW_GUARD_STATE_FLUSH_TIME 600
3240 /** How long will we let a change in our guard nodes stay un-saved
3241 * when we are not trying to avoid disk writes? */
3242 #define FAST_GUARD_STATE_FLUSH_TIME 30
3244 /** Our list of entry guards has changed for a particular guard selection
3245 * context, or some element of one of our entry guards has changed for one.
3246 * Write the changes to disk within the next few minutes.
3249 entry_guards_changed_for_guard_selection(guard_selection_t
*gs
)
3253 tor_assert(gs
!= NULL
);
3255 entry_guards_dirty
= 1;
3257 if (get_options()->AvoidDiskWrites
)
3258 when
= time(NULL
) + SLOW_GUARD_STATE_FLUSH_TIME
;
3260 when
= time(NULL
) + FAST_GUARD_STATE_FLUSH_TIME
;
3262 /* or_state_save() will call entry_guards_update_state() and
3263 entry_guards_update_guards_in_state()
3265 or_state_mark_dirty(get_or_state(), when
);
3268 /** Our list of entry guards has changed for the default guard selection
3269 * context, or some element of one of our entry guards has changed. Write
3270 * the changes to disk within the next few minutes.
3273 entry_guards_changed(void)
3275 entry_guards_changed_for_guard_selection(get_guard_selection_info());
3278 /** If the entry guard info has not changed, do nothing and return.
3279 * Otherwise, free the EntryGuards piece of <b>state</b> and create
3280 * a new one out of the global entry_guards list, and then mark
3281 * <b>state</b> dirty so it will get saved to disk.
3284 entry_guards_update_state(or_state_t
*state
)
3286 entry_guards_dirty
= 0;
3288 // Handles all guard info.
3289 entry_guards_update_guards_in_state(state
);
3291 entry_guards_dirty
= 0;
3293 if (!get_options()->AvoidDiskWrites
)
3294 or_state_mark_dirty(get_or_state(), 0);
3295 entry_guards_dirty
= 0;
3299 * Format a single entry guard in the format expected by the controller.
3300 * Return a newly allocated string.
3303 getinfo_helper_format_single_entry_guard(const entry_guard_t
*e
)
3305 const char *status
= NULL
;
3308 char tbuf
[ISO_TIME_LEN
+1];
3309 char nbuf
[MAX_VERBOSE_NICKNAME_LEN
+1];
3311 /* This is going to be a bit tricky, since the status
3312 * codes weren't really intended for prop271 guards.
3314 * XXXX use a more appropriate format for exporting this information
3316 if (e
->confirmed_idx
< 0) {
3317 status
= "never-connected";
3318 } else if (! e
->currently_listed
) {
3319 when
= e
->unlisted_since_date
;
3320 status
= "unusable";
3321 } else if (! e
->is_filtered_guard
) {
3322 status
= "unusable";
3323 } else if (e
->is_reachable
== GUARD_REACHABLE_NO
) {
3324 when
= e
->failing_since
;
3330 node
= entry_guard_find_node(e
);
3332 node_get_verbose_nickname(node
, nbuf
);
3335 base16_encode(nbuf
+1, sizeof(nbuf
)-1, e
->identity
, DIGEST_LEN
);
3336 /* e->nickname field is not very reliable if we don't know about
3337 * this router any longer; don't include it. */
3340 char *result
= NULL
;
3342 format_iso_time(tbuf
, when
);
3343 tor_asprintf(&result
, "%s %s %s\n", nbuf
, status
, tbuf
);
3345 tor_asprintf(&result
, "%s %s\n", nbuf
, status
);
3350 /** If <b>question</b> is the string "entry-guards", then dump
3351 * to *<b>answer</b> a newly allocated string describing all of
3352 * the nodes in the global entry_guards list. See control-spec.txt
3354 * For backward compatibility, we also handle the string "helper-nodes".
3356 * XXX this should be totally redesigned after prop 271 too, and that's
3357 * going to take some control spec work.
3360 getinfo_helper_entry_guards(control_connection_t
*conn
,
3361 const char *question
, char **answer
,
3362 const char **errmsg
)
3364 guard_selection_t
*gs
= get_guard_selection_info();
3366 tor_assert(gs
!= NULL
);
3371 if (!strcmp(question
,"entry-guards") ||
3372 !strcmp(question
,"helper-nodes")) {
3373 const smartlist_t
*guards
;
3374 guards
= gs
->sampled_entry_guards
;
3376 smartlist_t
*sl
= smartlist_new();
3378 SMARTLIST_FOREACH_BEGIN(guards
, const entry_guard_t
*, e
) {
3379 char *cp
= getinfo_helper_format_single_entry_guard(e
);
3380 smartlist_add(sl
, cp
);
3381 } SMARTLIST_FOREACH_END(e
);
3382 *answer
= smartlist_join_strings(sl
, "", 0, NULL
);
3383 SMARTLIST_FOREACH(sl
, char *, c
, tor_free(c
));
3389 /* Given the original bandwidth of a guard and its guardfraction,
3390 * calculate how much bandwidth the guard should have as a guard and
3393 * Quoting from proposal236:
3395 * Let Wpf denote the weight from the 'bandwidth-weights' line a
3396 * client would apply to N for position p if it had the guard
3397 * flag, Wpn the weight if it did not have the guard flag, and B the
3398 * measured bandwidth of N in the consensus. Then instead of choosing
3399 * N for position p proportionally to Wpf*B or Wpn*B, clients should
3400 * choose N proportionally to F*Wpf*B + (1-F)*Wpn*B.
3402 * This function fills the <b>guardfraction_bw</b> structure. It sets
3403 * <b>guard_bw</b> to F*B and <b>non_guard_bw</b> to (1-F)*B.
3406 guard_get_guardfraction_bandwidth(guardfraction_bandwidth_t
*guardfraction_bw
,
3408 uint32_t guardfraction_percentage
)
3410 double guardfraction_fraction
;
3412 /* Turn the percentage into a fraction. */
3413 tor_assert(guardfraction_percentage
<= 100);
3414 guardfraction_fraction
= guardfraction_percentage
/ 100.0;
3416 long guard_bw
= tor_lround(guardfraction_fraction
* orig_bandwidth
);
3417 tor_assert(guard_bw
<= INT_MAX
);
3419 guardfraction_bw
->guard_bw
= (int) guard_bw
;
3421 guardfraction_bw
->non_guard_bw
= orig_bandwidth
- (int) guard_bw
;
3424 /** Helper: Update the status of all entry guards, in whatever algorithm
3425 * is used. Return true if we should stop using all previously generated
3426 * circuits, by calling circuit_mark_all_unused_circs() and
3427 * circuit_mark_all_dirty_circs_as_unusable().
3430 guards_update_all(void)
3432 int mark_circuits
= 0;
3433 if (update_guard_selection_choice(get_options()))
3436 tor_assert(curr_guard_context
);
3438 if (entry_guards_update_all(curr_guard_context
))
3441 return mark_circuits
;
3444 /** Helper: pick a guard for a circuit, with whatever algorithm is
3447 guards_choose_guard(cpath_build_state_t
*state
,
3448 circuit_guard_state_t
**guard_state_out
)
3450 const node_t
*r
= NULL
;
3451 const uint8_t *exit_id
= NULL
;
3452 entry_guard_restriction_t
*rst
= NULL
;
3453 if (state
&& (exit_id
= build_state_get_exit_rsa_id(state
))) {
3454 /* We're building to a targeted exit node, so that node can't be
3455 * chosen as our guard for this circuit. Remember that fact in a
3457 rst
= guard_create_exit_restriction(exit_id
);
3460 if (entry_guard_pick_for_circuit(get_guard_selection_info(),
3461 GUARD_USAGE_TRAFFIC
,
3464 guard_state_out
) < 0) {
3465 tor_assert(r
== NULL
);
3470 /** Remove all currently listed entry guards for a given guard selection
3471 * context. This frees and replaces <b>gs</b>, so don't use <b>gs</b>
3472 * after calling this function. */
3474 remove_all_entry_guards_for_guard_selection(guard_selection_t
*gs
)
3476 // This function shouldn't exist. XXXX
3477 tor_assert(gs
!= NULL
);
3478 char *old_name
= tor_strdup(gs
->name
);
3479 guard_selection_type_t old_type
= gs
->type
;
3481 SMARTLIST_FOREACH(gs
->sampled_entry_guards
, entry_guard_t
*, entry
, {
3482 control_event_guard(entry
->nickname
, entry
->identity
, "DROPPED");
3485 if (gs
== curr_guard_context
) {
3486 curr_guard_context
= NULL
;
3489 smartlist_remove(guard_contexts
, gs
);
3490 guard_selection_free(gs
);
3492 gs
= get_guard_selection_by_name(old_name
, old_type
, 1);
3493 entry_guards_changed_for_guard_selection(gs
);
3497 /** Remove all currently listed entry guards, so new ones will be chosen.
3499 * XXXX This function shouldn't exist -- it's meant to support the DROPGUARDS
3500 * command, which is deprecated.
3503 remove_all_entry_guards(void)
3505 remove_all_entry_guards_for_guard_selection(get_guard_selection_info());
3508 /** Helper: pick a directory guard, with whatever algorithm is used. */
3510 guards_choose_dirguard(uint8_t dir_purpose
,
3511 circuit_guard_state_t
**guard_state_out
)
3513 const node_t
*r
= NULL
;
3514 entry_guard_restriction_t
*rst
= NULL
;
3516 /* If we are fetching microdescs, don't query outdated dirservers. */
3517 if (dir_purpose
== DIR_PURPOSE_FETCH_MICRODESC
) {
3518 rst
= guard_create_dirserver_md_restriction();
3521 if (entry_guard_pick_for_circuit(get_guard_selection_info(),
3522 GUARD_USAGE_DIRGUARD
,
3525 guard_state_out
) < 0) {
3526 tor_assert(r
== NULL
);
3532 * If we're running with a constrained guard set, then maybe mark our guards
3533 * usable. Return 1 if we do; 0 if we don't.
3536 guards_retry_optimistic(const or_options_t
*options
)
3538 if (! entry_list_is_constrained(options
))
3541 mark_primary_guards_maybe_reachable(get_guard_selection_info());
3547 * Check if we are missing any crucial dirinfo for the guard subsystem to
3548 * work. Return NULL if everything went well, otherwise return a newly
3549 * allocated string with an informative error message. In the latter case, use
3550 * the genreal descriptor information <b>using_mds</b>, <b>num_present</b> and
3551 * <b>num_usable</b> to improve the error message. */
3553 guard_selection_get_err_str_if_dir_info_missing(guard_selection_t
*gs
,
3555 int num_present
, int num_usable
)
3557 if (!gs
->primary_guards_up_to_date
)
3558 entry_guards_update_primary(gs
);
3560 char *ret_str
= NULL
;
3561 int n_missing_descriptors
= 0;
3562 int n_considered
= 0;
3563 int num_primary_to_check
;
3565 /* We want to check for the descriptor of at least the first two primary
3566 * guards in our list, since these are the guards that we typically use for
3568 num_primary_to_check
= get_n_primary_guards_to_use(GUARD_USAGE_TRAFFIC
);
3569 num_primary_to_check
++;
3571 SMARTLIST_FOREACH_BEGIN(gs
->primary_entry_guards
, entry_guard_t
*, guard
) {
3572 entry_guard_consider_retry(guard
);
3573 if (guard
->is_reachable
== GUARD_REACHABLE_NO
)
3576 if (!guard_has_descriptor(guard
))
3577 n_missing_descriptors
++;
3578 if (n_considered
>= num_primary_to_check
)
3580 } SMARTLIST_FOREACH_END(guard
);
3582 /* If we are not missing any descriptors, return NULL. */
3583 if (!n_missing_descriptors
) {
3587 /* otherwise return a helpful error string */
3588 tor_asprintf(&ret_str
, "We're missing descriptors for %d/%d of our "
3589 "primary entry guards (total %sdescriptors: %d/%d).",
3590 n_missing_descriptors
, num_primary_to_check
,
3591 using_mds
?"micro":"", num_present
, num_usable
);
3596 /** As guard_selection_have_enough_dir_info_to_build_circuits, but uses
3597 * the default guard selection. */
3599 entry_guards_get_err_str_if_dir_info_missing(int using_mds
,
3600 int num_present
, int num_usable
)
3602 return guard_selection_get_err_str_if_dir_info_missing(
3603 get_guard_selection_info(),
3605 num_present
, num_usable
);
3608 /** Free one guard selection context */
3610 guard_selection_free(guard_selection_t
*gs
)
3616 if (gs
->sampled_entry_guards
) {
3617 SMARTLIST_FOREACH(gs
->sampled_entry_guards
, entry_guard_t
*, e
,
3618 entry_guard_free(e
));
3619 smartlist_free(gs
->sampled_entry_guards
);
3620 gs
->sampled_entry_guards
= NULL
;
3623 smartlist_free(gs
->confirmed_entry_guards
);
3624 smartlist_free(gs
->primary_entry_guards
);
3629 /** Release all storage held by the list of entry guards and related
3630 * memory structs. */
3632 entry_guards_free_all(void)
3634 /* Null out the default */
3635 curr_guard_context
= NULL
;
3636 /* Free all the guard contexts */
3637 if (guard_contexts
!= NULL
) {
3638 SMARTLIST_FOREACH_BEGIN(guard_contexts
, guard_selection_t
*, gs
) {
3639 guard_selection_free(gs
);
3640 } SMARTLIST_FOREACH_END(gs
);
3641 smartlist_free(guard_contexts
);
3642 guard_contexts
= NULL
;
3644 circuit_build_times_free_timeouts(get_circuit_build_times_mutable());