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-2016, 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 * XXXX prop271 This module is in flux, since I'm currently in the middle of
15 * implementation proposal 271. The module documentation here will describe
16 * the new algorithm and data structures; the old ones should get removed as
17 * proposal 271 is completed.
19 * In general, we use entry guards to prevent traffic-sampling attacks:
20 * if we chose every circuit independently, an adversary controlling
21 * some fraction of paths on the network would observe a sample of every
22 * user's traffic. Using guards gives users a chance of not being
25 * The current entry guard selection code is designed to try to avoid
26 * _ever_ trying every guard on the network, to try to stick to guards
27 * that we've used before, to handle hostile/broken networks, and
28 * to behave sanely when the network goes up and down.
30 * Our algorithm works as follows: First, we maintain a SAMPLE of guards
31 * we've seen in the networkstatus consensus. We maintain this sample
32 * over time, and store it persistently; it is chosen without reference
33 * to our configuration or firewall rules. Guards remain in the sample
34 * as they enter and leave the consensus. We expand this sample as
35 * needed, up to a maximum size.
37 * As a subset of the sample, we maintain a FILTERED SET of the guards
38 * that we would be willing to use if we could connect to them. The
39 * filter removes all the guards that we're excluding because they're
40 * bridges (or not bridges), because we have restrictive firewall rules,
41 * because of ExcludeNodes, because we of path bias restrictions,
42 * because they're absent from the network at present, and so on.
44 * As a subset of the filtered set, we keep a REACHABLE FILTERED SET
45 * (also called a "usable filtered set") of those guards that we call
46 * "reachable" or "maybe reachable". A guard is reachable if we've
47 * connected to it more recently than we've failed. A guard is "maybe
48 * reachable" if we have never tried to connect to it, or if we
49 * failed to connect to it so long ago that we no longer think our
50 * failure means it's down.
52 * As a persistent ordered list whose elements are taken from the
53 * sampled set, we track a CONFIRMED GUARDS LIST. A guard becomes
54 * confirmed when we successfully build a circuit through it, and decide
55 * to use that circuit. We order the guards on this list by the order
56 * in which they became confirmed.
58 * And as a final group, we have an ordered list of PRIMARY GUARDS,
59 * whose elements are taken from the filtered set. We prefer
60 * confirmed guards to non-confirmed guards for this list, and place
61 * other restrictions on it. The primary guards are the ones that we
62 * connect to "when nothing is wrong" -- circuits through them can be used
65 * To build circuits, we take a primary guard if possible -- or a
66 * reachable filtered confirmed guard if no primary guard is possible --
67 * or a random reachable filtered guard otherwise. If the guard is
68 * primary, we can use the circuit immediately on success. Otherwise,
69 * the guard is now "pending" -- we won't use its circuit unless all
70 * of the circuits we're trying to build through better guards have
73 * While we're building circuits, we track a little "guard state" for
74 * each circuit. We use this to keep track of whether the circuit is
75 * one that we can use as soon as its done, or whether it's one that
76 * we should keep around to see if we can do better. In the latter case,
77 * a periodic call to entry_guards_upgrade_waiting_circuits() will
78 * eventually upgrade it.
80 /* DOCDOC -- expand this.
82 * Information invariants:
84 * [x] whenever a guard becomes unreachable, clear its usable_filtered flag.
86 * [x] Whenever a guard becomes reachable or maybe-reachable, if its filtered
87 * flag is set, set its usable_filtered flag.
89 * [x] Whenever we get a new consensus, call update_from_consensus(). (LATER.)
91 * [x] Whenever the configuration changes in a relevant way, update the
92 * filtered/usable flags. (LATER.)
94 * [x] Whenever we add a guard to the sample, make sure its filtered/usable
95 * flags are set as possible.
97 * [x] Whenever we remove a guard from the sample, remove it from the primary
98 * and confirmed lists.
100 * [x] When we make a guard confirmed, update the primary list.
102 * [x] When we make a guard filtered or unfiltered, update the primary list.
104 * [x] When we are about to pick a guard, make sure that the primary list is
107 * [x] Before calling sample_reachable_filtered_entry_guards(), make sure
108 * that the filtered, primary, and confirmed flags are up-to-date.
110 * [x] Call entry_guard_consider_retry every time we are about to check
111 * is_usable_filtered or is_reachable, and every time we set
114 * [x] Call entry_guards_changed_for_guard_selection() whenever we update
115 * a persistent field.
118 #define ENTRYNODES_PRIVATE
122 #include "circpathbias.h"
123 #include "circuitbuild.h"
124 #include "circuitlist.h"
125 #include "circuitstats.h"
127 #include "confparse.h"
128 #include "connection.h"
129 #include "connection_or.h"
131 #include "directory.h"
132 #include "entrynodes.h"
134 #include "microdesc.h"
135 #include "networkstatus.h"
136 #include "nodelist.h"
137 #include "policies.h"
139 #include "routerlist.h"
140 #include "routerparse.h"
141 #include "routerset.h"
142 #include "transports.h"
143 #include "statefile.h"
145 static smartlist_t
*guard_contexts
= NULL
;
146 static guard_selection_t
*curr_guard_context
= NULL
;
148 /** A value of 1 means that at least one context has changed,
149 * and those changes need to be flushed to disk. */
150 static int entry_guards_dirty
= 0;
152 static const node_t
*choose_random_entry_impl(guard_selection_t
*gs
,
153 cpath_build_state_t
*state
,
155 dirinfo_type_t dirtype
,
157 static void entry_guard_set_filtered_flags(const or_options_t
*options
,
158 guard_selection_t
*gs
,
159 entry_guard_t
*guard
);
160 static void pathbias_check_use_success_count(entry_guard_t
*guard
);
161 static void pathbias_check_close_success_count(entry_guard_t
*guard
);
162 static int node_is_possible_guard(const node_t
*node
);
163 static int node_passes_guard_filter(const or_options_t
*options
,
165 static entry_guard_t
*entry_guard_add_to_sample_impl(guard_selection_t
*gs
,
166 const uint8_t *rsa_id_digest
,
167 const char *nickname
,
168 const tor_addr_port_t
*bridge_addrport
);
169 static entry_guard_t
*get_sampled_guard_by_bridge_addr(guard_selection_t
*gs
,
170 const tor_addr_port_t
*addrport
);
171 static int entry_guard_obeys_restriction(const entry_guard_t
*guard
,
172 const entry_guard_restriction_t
*rst
);
174 /** Return 0 if we should apply guardfraction information found in the
175 * consensus. A specific consensus can be specified with the
176 * <b>ns</b> argument, if NULL the most recent one will be picked.*/
178 should_apply_guardfraction(const networkstatus_t
*ns
)
180 /* We need to check the corresponding torrc option and the consensus
181 * parameter if we need to. */
182 const or_options_t
*options
= get_options();
184 /* If UseGuardFraction is 'auto' then check the same-named consensus
185 * parameter. If the consensus parameter is not present, default to
187 if (options
->UseGuardFraction
== -1) {
188 return networkstatus_get_param(ns
, "UseGuardFraction",
189 0, /* default to "off" */
193 return options
->UseGuardFraction
;
197 * Allocate and return a new guard_selection_t, with the name <b>name</b>.
199 STATIC guard_selection_t
*
200 guard_selection_new(const char *name
,
201 guard_selection_type_t type
)
203 guard_selection_t
*gs
;
205 if (type
== GS_TYPE_INFER
) {
206 if (!strcmp(name
, "legacy"))
207 type
= GS_TYPE_LEGACY
;
208 else if (!strcmp(name
, "bridges"))
209 type
= GS_TYPE_BRIDGE
;
210 else if (!strcmp(name
, "restricted"))
211 type
= GS_TYPE_RESTRICTED
;
213 type
= GS_TYPE_NORMAL
;
216 gs
= tor_malloc_zero(sizeof(*gs
));
217 gs
->name
= tor_strdup(name
);
219 gs
->chosen_entry_guards
= smartlist_new();
220 gs
->sampled_entry_guards
= smartlist_new();
221 gs
->confirmed_entry_guards
= smartlist_new();
222 gs
->primary_entry_guards
= smartlist_new();
228 * Return the guard selection called <b>name</b>. If there is none, and
229 * <b>create_if_absent</b> is true, then create and return it. If there
230 * is none, and <b>create_if_absent</b> is false, then return NULL.
232 STATIC guard_selection_t
*
233 get_guard_selection_by_name(const char *name
,
234 guard_selection_type_t type
,
235 int create_if_absent
)
237 if (!guard_contexts
) {
238 guard_contexts
= smartlist_new();
240 SMARTLIST_FOREACH_BEGIN(guard_contexts
, guard_selection_t
*, gs
) {
241 if (!strcmp(gs
->name
, name
))
243 } SMARTLIST_FOREACH_END(gs
);
245 if (! create_if_absent
)
248 log_debug(LD_GUARD
, "Creating a guard selection called %s", name
);
249 guard_selection_t
*new_selection
= guard_selection_new(name
, type
);
250 smartlist_add(guard_contexts
, new_selection
);
252 return new_selection
;
256 * Allocate the first guard context that we're planning to use,
257 * and make it the current context.
260 create_initial_guard_context(void)
262 tor_assert(! curr_guard_context
);
263 if (!guard_contexts
) {
264 guard_contexts
= smartlist_new();
266 guard_selection_type_t type
= GS_TYPE_INFER
;
267 const char *name
= choose_guard_selection(
269 networkstatus_get_live_consensus(approx_time()),
272 tor_assert(name
); // "name" can only be NULL if we had an old name.
273 tor_assert(type
!= GS_TYPE_INFER
);
274 log_notice(LD_GUARD
, "Starting with guard context \"%s\"", name
);
275 curr_guard_context
= get_guard_selection_by_name(name
, type
, 1);
278 /** Get current default guard_selection_t, creating it if necessary */
280 get_guard_selection_info(void)
282 if (!curr_guard_context
) {
283 create_initial_guard_context();
286 return curr_guard_context
;
289 /** Return the list of entry guards for a guard_selection_t, creating it
292 get_entry_guards_for_guard_selection(guard_selection_t
*gs
)
294 tor_assert(gs
!= NULL
);
295 tor_assert(gs
->chosen_entry_guards
!= NULL
);
297 return gs
->chosen_entry_guards
;
300 /** Return the list of entry guards for the default guard_selection_t,
301 * creating it if necessary. */
303 get_entry_guards(void)
305 return get_entry_guards_for_guard_selection(get_guard_selection_info());
308 /** Helper: mark an entry guard as not usable. */
310 entry_guard_mark_bad(entry_guard_t
*guard
)
312 guard
->bad_since
= approx_time();
313 entry_guards_changed();
316 /** Return a statically allocated human-readable description of <b>guard</b>
319 entry_guard_describe(const entry_guard_t
*guard
)
321 static char buf
[256];
322 tor_snprintf(buf
, sizeof(buf
),
324 guard
->nickname
, hex_str(guard
->identity
, DIGEST_LEN
));
328 /** Return <b>guard</b>'s 20-byte RSA identity digest */
330 entry_guard_get_rsa_id_digest(const entry_guard_t
*guard
)
332 return guard
->identity
;
335 /** Return the pathbias state associated with <b>guard</b>. */
337 entry_guard_get_pathbias_state(entry_guard_t
*guard
)
342 HANDLE_IMPL(entry_guard
, entry_guard_t
, ATTR_UNUSED STATIC
)
344 /** Return an interval betweeen 'now' and 'max_backdate' seconds in the past,
345 * chosen uniformly at random. We use this before recording persistent
346 * dates, so that we aren't leaking exactly when we recorded it.
348 MOCK_IMPL(STATIC
time_t,
349 randomize_time
,(time_t now
, time_t max_backdate
))
351 tor_assert(max_backdate
> 0);
353 time_t earliest
= now
- max_backdate
;
357 if (latest
<= earliest
)
358 latest
= earliest
+ 1;
360 return crypto_rand_time_range(earliest
, latest
);
364 * @name parameters for networkstatus algorithm
366 * These parameters are taken from the consensus; some are overrideable in
371 * We never let our sampled guard set grow larger than this fraction
372 * of the guards on the network.
375 get_max_sample_threshold(void)
378 networkstatus_get_param(NULL
, "guard-max-sample-threshold-percent",
379 DFLT_MAX_SAMPLE_THRESHOLD_PERCENT
,
384 * We always try to make our sample contain at least this many guards.
386 * XXXX prop271 spec deviation There was a MIN_SAMPLE_THRESHOLD in the
387 * proposal, but I removed it in favor of MIN_FILTERED_SAMPLE_SIZE. -NM
390 get_min_filtered_sample_size(void)
392 return networkstatus_get_param(NULL
, "guard-min-filtered-sample-size",
393 DFLT_MIN_FILTERED_SAMPLE_SIZE
,
397 * If a guard is unlisted for this many days in a row, we remove it.
400 get_remove_unlisted_guards_after_days(void)
402 return networkstatus_get_param(NULL
,
403 "guard-remove-unlisted-guards-after-days",
404 DFLT_REMOVE_UNLISTED_GUARDS_AFTER_DAYS
,
408 * We remove unconfirmed guards from the sample after this many days,
409 * regardless of whether they are listed or unlisted.
412 get_guard_lifetime_days(void)
414 return networkstatus_get_param(NULL
,
415 "guard-lifetime-days",
416 DFLT_GUARD_LIFETIME_DAYS
, 1, 365*10);
419 * We remove confirmed guards from the sample if they were sampled
420 * GUARD_LIFETIME_DAYS ago and confirmed this many days ago.
423 get_guard_confirmed_min_lifetime_days(void)
425 return networkstatus_get_param(NULL
, "guard-confirmed-min-lifetime-days",
426 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 return networkstatus_get_param(NULL
, "guard-n-primary-guards",
436 DFLT_N_PRIMARY_GUARDS
, 1, INT32_MAX
);
439 * If we haven't successfully built or used a circuit in this long, then
440 * consider that the internet is probably down.
443 get_internet_likely_down_interval(void)
445 return networkstatus_get_param(NULL
, "guard-internet-likely-down-interval",
446 DFLT_INTERNET_LIKELY_DOWN_INTERVAL
,
450 * If we're trying to connect to a nonprimary guard for at least this
451 * many seconds, and we haven't gotten the connection to work, we will treat
452 * lower-priority guards as usable.
455 get_nonprimary_guard_connect_timeout(void)
457 return networkstatus_get_param(NULL
,
458 "guard-nonprimary-guard-connect-timeout",
459 DFLT_NONPRIMARY_GUARD_CONNECT_TIMEOUT
,
463 * If a circuit has been sitting around in 'waiting for better guard' state
464 * for at least this long, we'll expire it.
467 get_nonprimary_guard_idle_timeout(void)
469 return networkstatus_get_param(NULL
,
470 "guard-nonprimary-guard-idle-timeout",
471 DFLT_NONPRIMARY_GUARD_IDLE_TIMEOUT
,
475 * If our configuration retains fewer than this fraction of guards from the
476 * torrc, we are in a restricted setting.
479 get_meaningful_restriction_threshold(void)
481 int32_t pct
= networkstatus_get_param(NULL
,
482 "guard-meaningful-restriction-percent",
483 DFLT_MEANINGFUL_RESTRICTION_PERCENT
,
488 * If our configuration retains fewer than this fraction of guards from the
489 * torrc, we are in an extremely restricted setting, and should warn.
492 get_extreme_restriction_threshold(void)
494 int32_t pct
= networkstatus_get_param(NULL
,
495 "guard-extreme-restriction-percent",
496 DFLT_EXTREME_RESTRICTION_PERCENT
,
503 * Given our options and our list of nodes, return the name of the
504 * guard selection that we should use. Return NULL for "use the
505 * same selection you were using before.
508 choose_guard_selection(const or_options_t
*options
,
509 const networkstatus_t
*live_ns
,
510 const char *old_selection
,
511 guard_selection_type_t
*type_out
)
514 tor_assert(type_out
);
515 if (options
->UseDeprecatedGuardAlgorithm
) {
516 *type_out
= GS_TYPE_LEGACY
;
520 if (options
->UseBridges
) {
521 *type_out
= GS_TYPE_BRIDGE
;
526 /* without a networkstatus, we can't tell any more than that. */
527 *type_out
= GS_TYPE_NORMAL
;
531 const smartlist_t
*nodes
= nodelist_get_list();
532 int n_guards
= 0, n_passing_filter
= 0;
533 SMARTLIST_FOREACH_BEGIN(nodes
, const node_t
*, node
) {
534 if (node_is_possible_guard(node
)) {
536 if (node_passes_guard_filter(options
, node
)) {
540 } SMARTLIST_FOREACH_END(node
);
542 /* XXXX prop271 spec deviation -- separate 'high' and 'low' thresholds
543 * to prevent flapping */
544 const int meaningful_threshold_high
=
545 (int)(n_guards
* get_meaningful_restriction_threshold() * 1.05);
546 const int meaningful_threshold_mid
=
547 (int)(n_guards
* get_meaningful_restriction_threshold());
548 const int meaningful_threshold_low
=
549 (int)(n_guards
* get_meaningful_restriction_threshold() * .95);
550 const int extreme_threshold
=
551 (int)(n_guards
* get_extreme_restriction_threshold());
554 If we have no previous selection, then we're "restricted" iff we are
555 below the meaningful restriction threshold. That's easy enough.
557 But if we _do_ have a previous selection, we make it a little
558 "sticky": we only move from "restricted" to "default" when we find
559 that we're above the threshold plus 5%, and we only move from
560 "default" to "restricted" when we're below the threshold minus 5%.
561 That should prevent us from flapping back and forth if we happen to
562 be hovering very close to the default.
564 The extreme threshold is for warning only.
567 static int have_warned_extreme_threshold
= 0;
568 if (n_passing_filter
< extreme_threshold
&&
569 ! have_warned_extreme_threshold
) {
570 have_warned_extreme_threshold
= 1;
571 const double exclude_frac
=
572 (n_guards
- n_passing_filter
) / (double)n_guards
;
573 log_warn(LD_GUARD
, "Your configuration excludes %d%% of all possible "
574 "guards. That's likely to make you stand out from the "
575 "rest of the world.", (int)(exclude_frac
* 100));
578 /* Easy case: no previous selection */
579 if (old_selection
== NULL
) {
580 if (n_passing_filter
>= meaningful_threshold_mid
) {
581 *type_out
= GS_TYPE_NORMAL
;
584 *type_out
= GS_TYPE_RESTRICTED
;
589 /* Trickier case: we do have a previous selection */
590 if (n_passing_filter
>= meaningful_threshold_high
) {
591 *type_out
= GS_TYPE_NORMAL
;
593 } else if (n_passing_filter
< meaningful_threshold_low
) {
594 *type_out
= GS_TYPE_RESTRICTED
;
602 * Check whether we should switch from our current guard selection to a
603 * different one. If so, switch and return 1. Return 0 otherwise.
605 * On a 1 return, the caller should mark all currently live circuits
606 * unusable for new streams.
609 update_guard_selection_choice(const or_options_t
*options
)
611 if (!curr_guard_context
) {
612 create_initial_guard_context();
616 const char *cur_name
= curr_guard_context
->name
;
617 guard_selection_type_t type
= GS_TYPE_INFER
;
618 const char *new_name
= choose_guard_selection(
620 networkstatus_get_live_consensus(approx_time()),
623 tor_assert(new_name
);
624 tor_assert(type
!= GS_TYPE_INFER
);
626 if (! strcmp(cur_name
, new_name
)) {
628 "Staying with guard context \"%s\" (no change)", new_name
);
629 return 0; // No change
632 log_notice(LD_GUARD
, "Switching to guard context \"%s\" (was using \"%s\")",
634 guard_selection_t
*new_guard_context
;
635 new_guard_context
= get_guard_selection_by_name(new_name
, type
, 1);
636 tor_assert(new_guard_context
);
637 tor_assert(new_guard_context
!= curr_guard_context
);
638 curr_guard_context
= new_guard_context
;
642 circuit_mark_all_unused_circs();
643 circuit_mark_all_dirty_circs_as_unusable();
650 * Return true iff <b>node</b> has all the flags needed for us to consider it
651 * a possible guard when sampling guards.
654 node_is_possible_guard(const node_t
*node
)
656 /* The "GUARDS" set is all nodes in the nodelist for which this predicate
659 /* XXXX -- prop271 spec deviation. We require node_is_dir() here. */
661 return (node
->is_possible_guard
&&
669 * Return the sampled guard with the RSA identity digest <b>rsa_id</b>, or
670 * NULL if we don't have one. */
671 STATIC entry_guard_t
*
672 get_sampled_guard_with_id(guard_selection_t
*gs
,
673 const uint8_t *rsa_id
)
677 SMARTLIST_FOREACH_BEGIN(gs
->sampled_entry_guards
, entry_guard_t
*, guard
) {
678 if (tor_memeq(guard
->identity
, rsa_id
, DIGEST_LEN
))
680 } SMARTLIST_FOREACH_END(guard
);
684 /** If <b>gs</b> contains a sampled entry guard matching <b>bridge</b>,
685 * return that guard. Otherwise return NULL. */
686 static entry_guard_t
*
687 get_sampled_guard_for_bridge(guard_selection_t
*gs
,
688 const bridge_info_t
*bridge
)
690 const uint8_t *id
= bridge_get_rsa_id_digest(bridge
);
691 const tor_addr_port_t
*addrport
= bridge_get_addr_port(bridge
);
692 entry_guard_t
*guard
;
694 guard
= get_sampled_guard_with_id(gs
, id
);
699 return NULL
; // LCOV_EXCL_LINE
700 guard
= get_sampled_guard_by_bridge_addr(gs
, addrport
);
701 if (! guard
|| (id
&& tor_memneq(id
, guard
->identity
, DIGEST_LEN
)))
707 /** If we know a bridge_info_t matching <b>guard</b>, return that
708 * bridge. Otherwise return NULL. */
709 static bridge_info_t
*
710 get_bridge_info_for_guard(const entry_guard_t
*guard
)
712 if (! tor_digest_is_zero(guard
->identity
)) {
713 bridge_info_t
*bridge
= find_bridge_by_digest(guard
->identity
);
717 if (BUG(guard
->bridge_addr
== NULL
))
719 return get_configured_bridge_by_addr_port_digest(&guard
->bridge_addr
->addr
,
720 guard
->bridge_addr
->port
,
725 * Return true iff we have a sampled guard with the RSA identity digest
728 have_sampled_guard_with_id(guard_selection_t
*gs
, const uint8_t *rsa_id
)
730 return get_sampled_guard_with_id(gs
, rsa_id
) != NULL
;
734 * Allocate a new entry_guard_t object for <b>node</b>, add it to the
735 * sampled entry guards in <b>gs</b>, and return it. <b>node</b> must
736 * not currently be a sampled guard in <b>gs</b>.
738 STATIC entry_guard_t
*
739 entry_guard_add_to_sample(guard_selection_t
*gs
,
742 log_info(LD_GUARD
, "Adding %s as to the entry guard sample set.",
743 node_describe(node
));
745 return entry_guard_add_to_sample_impl(gs
,
746 (const uint8_t*)node
->identity
,
747 node_get_nickname(node
),
752 * Backend: adds a new sampled guard to <b>gs</b>, with given identity,
753 * nickname, and ORPort. rsa_id_digest and bridge_addrport are
754 * optional, but we need one of them. nickname is optional.
756 static entry_guard_t
*
757 entry_guard_add_to_sample_impl(guard_selection_t
*gs
,
758 const uint8_t *rsa_id_digest
,
759 const char *nickname
,
760 const tor_addr_port_t
*bridge_addrport
)
762 const int GUARD_LIFETIME
= get_guard_lifetime_days() * 86400;
765 // XXXX prop271 take ed25519 identity here too.
767 /* make sure that the guard is not already sampled. */
768 if (rsa_id_digest
&& BUG(have_sampled_guard_with_id(gs
, rsa_id_digest
)))
769 return NULL
; // LCOV_EXCL_LINE
770 /* Make sure we can actually identify the guard. */
771 if (BUG(!rsa_id_digest
&& !bridge_addrport
))
772 return NULL
; // LCOV_EXCL_LINE
774 entry_guard_t
*guard
= tor_malloc_zero(sizeof(entry_guard_t
));
776 /* persistent fields */
777 guard
->is_persistent
= (rsa_id_digest
!= NULL
);
778 guard
->selection_name
= tor_strdup(gs
->name
);
780 memcpy(guard
->identity
, rsa_id_digest
, DIGEST_LEN
);
782 strlcpy(guard
->nickname
, nickname
, sizeof(guard
->nickname
));
783 guard
->sampled_on_date
= randomize_time(approx_time(), GUARD_LIFETIME
/10);
784 tor_free(guard
->sampled_by_version
);
785 guard
->sampled_by_version
= tor_strdup(VERSION
);
786 guard
->currently_listed
= 1;
787 guard
->confirmed_idx
= -1;
789 /* non-persistent fields */
790 guard
->is_reachable
= GUARD_REACHABLE_MAYBE
;
792 guard
->bridge_addr
= tor_memdup(bridge_addrport
, sizeof(*bridge_addrport
));
794 smartlist_add(gs
->sampled_entry_guards
, guard
);
795 guard
->in_selection
= gs
;
796 entry_guard_set_filtered_flags(get_options(), gs
, guard
);
797 entry_guards_changed_for_guard_selection(gs
);
802 * Add an entry guard to the "bridges" guard selection sample, with
803 * information taken from <b>bridge</b>. Return that entry guard.
805 static entry_guard_t
*
806 entry_guard_add_bridge_to_sample(guard_selection_t
*gs
,
807 const bridge_info_t
*bridge
)
809 const uint8_t *id_digest
= bridge_get_rsa_id_digest(bridge
);
810 const tor_addr_port_t
*addrport
= bridge_get_addr_port(bridge
);
812 tor_assert(addrport
);
814 return entry_guard_add_to_sample_impl(gs
, id_digest
, NULL
, addrport
);
818 * Return the entry_guard_t in <b>gs</b> whose address is <b>addrport</b>,
819 * or NULL if none exists.
821 static entry_guard_t
*
822 get_sampled_guard_by_bridge_addr(guard_selection_t
*gs
,
823 const tor_addr_port_t
*addrport
)
829 SMARTLIST_FOREACH_BEGIN(gs
->sampled_entry_guards
, entry_guard_t
*, g
) {
830 if (g
->bridge_addr
&& tor_addr_port_eq(addrport
, g
->bridge_addr
))
832 } SMARTLIST_FOREACH_END(g
);
836 /** Update the guard subsystem's knowledge of the identity of the bridge
837 * at <b>addrport</b>. Idempotent.
840 entry_guard_learned_bridge_identity(const tor_addr_port_t
*addrport
,
841 const uint8_t *rsa_id_digest
)
843 guard_selection_t
*gs
= get_guard_selection_by_name("bridges",
849 entry_guard_t
*g
= get_sampled_guard_by_bridge_addr(gs
, addrport
);
853 int make_persistent
= 0;
855 if (tor_digest_is_zero(g
->identity
)) {
856 memcpy(g
->identity
, rsa_id_digest
, DIGEST_LEN
);
858 } else if (tor_memeq(g
->identity
, rsa_id_digest
, DIGEST_LEN
)) {
859 /* Nothing to see here; we learned something we already knew. */
860 if (BUG(! g
->is_persistent
))
863 char old_id
[HEX_DIGEST_LEN
+1];
864 base16_encode(old_id
, sizeof(old_id
), g
->identity
, sizeof(g
->identity
));
865 log_warn(LD_BUG
, "We 'learned' an identity %s for a bridge at %s:%d, but "
866 "we already knew a different one (%s). Ignoring the new info as "
868 hex_str((const char *)rsa_id_digest
, DIGEST_LEN
),
869 fmt_and_decorate_addr(&addrport
->addr
), addrport
->port
,
871 return; // redundant, but let's be clear: we're not making this persistent.
874 if (make_persistent
) {
875 g
->is_persistent
= 1;
876 entry_guards_changed_for_guard_selection(gs
);
881 * Return the number of sampled guards in <b>gs</b> that are "filtered"
882 * (that is, we're willing to connect to them) and that are "usable"
883 * (that is, either "reachable" or "maybe reachable").
885 * If a restriction is provided in <b>rst</b>, do not count any guards that
889 num_reachable_filtered_guards(guard_selection_t
*gs
,
890 const entry_guard_restriction_t
*rst
)
892 int n_reachable_filtered_guards
= 0;
893 SMARTLIST_FOREACH_BEGIN(gs
->sampled_entry_guards
, entry_guard_t
*, guard
) {
894 entry_guard_consider_retry(guard
);
895 if (! entry_guard_obeys_restriction(guard
, rst
))
897 if (guard
->is_usable_filtered_guard
)
898 ++n_reachable_filtered_guards
;
899 } SMARTLIST_FOREACH_END(guard
);
900 return n_reachable_filtered_guards
;
903 /** Return the actual maximum size for the sample in <b>gs</b>,
904 * given that we know about <b>n_guards</b> total. */
906 get_max_sample_size(guard_selection_t
*gs
,
909 const int using_bridges
= (gs
->type
== GS_TYPE_BRIDGE
);
910 const int min_sample
= get_min_filtered_sample_size();
912 /* XXXX prop271 spec deviation with bridges, max_sample is "all of them" */
916 const int max_sample
= (int)(n_guards
* get_max_sample_threshold());
917 if (max_sample
< min_sample
) // XXXX prop271 spec deviation
924 * Return a smartlist of the all the guards that are not currently
925 * members of the sample (GUARDS - SAMPLED_GUARDS). The elements of
926 * this list are node_t pointers in the non-bridge case, and
927 * bridge_info_t pointers in the bridge case. Set *<b>n_guards_out/b>
928 * to the number of guards that we found in GUARDS, including those
929 * that were already sampled.
932 get_eligible_guards(guard_selection_t
*gs
,
935 /* Construct eligible_guards as GUARDS - SAMPLED_GUARDS */
936 smartlist_t
*eligible_guards
= smartlist_new();
937 int n_guards
= 0; // total size of "GUARDS"
939 if (gs
->type
== GS_TYPE_BRIDGE
) {
940 const smartlist_t
*bridges
= bridge_list_get();
941 SMARTLIST_FOREACH_BEGIN(bridges
, bridge_info_t
*, bridge
) {
943 if (NULL
!= get_sampled_guard_for_bridge(gs
, bridge
)) {
946 smartlist_add(eligible_guards
, bridge
);
947 } SMARTLIST_FOREACH_END(bridge
);
949 const smartlist_t
*nodes
= nodelist_get_list();
950 const int n_sampled
= smartlist_len(gs
->sampled_entry_guards
);
952 /* Build a bloom filter of our current guards: let's keep this O(N). */
953 digestset_t
*sampled_guard_ids
= digestset_new(n_sampled
);
954 SMARTLIST_FOREACH_BEGIN(gs
->sampled_entry_guards
, const entry_guard_t
*,
956 digestset_add(sampled_guard_ids
, guard
->identity
);
957 } SMARTLIST_FOREACH_END(guard
);
959 SMARTLIST_FOREACH_BEGIN(nodes
, const node_t
*, node
) {
960 if (! node_is_possible_guard(node
))
963 if (digestset_contains(sampled_guard_ids
, node
->identity
))
965 smartlist_add(eligible_guards
, (node_t
*)node
);
966 } SMARTLIST_FOREACH_END(node
);
968 /* Now we can free that bloom filter. */
969 digestset_free(sampled_guard_ids
);
972 *n_guards_out
= n_guards
;
973 return eligible_guards
;
976 /** Helper: given a smartlist of either bridge_info_t (if gs->type is
977 * GS_TYPE_BRIDGE) or node_t (otherwise), pick one that can be a guard,
978 * add it as a guard, remove it from the list, and return a new
979 * entry_guard_t. Return NULL on failure. */
980 static entry_guard_t
*
981 select_and_add_guard_item_for_sample(guard_selection_t
*gs
,
982 smartlist_t
*eligible_guards
)
984 entry_guard_t
*added_guard
;
985 if (gs
->type
== GS_TYPE_BRIDGE
) {
986 const bridge_info_t
*bridge
= smartlist_choose(eligible_guards
);
988 return NULL
; // LCOV_EXCL_LINE
989 smartlist_remove(eligible_guards
, bridge
);
990 added_guard
= entry_guard_add_bridge_to_sample(gs
, bridge
);
993 node_sl_choose_by_bandwidth(eligible_guards
, WEIGHT_FOR_GUARD
);
995 return NULL
; // LCOV_EXCL_LINE
996 smartlist_remove(eligible_guards
, node
);
997 added_guard
= entry_guard_add_to_sample(gs
, node
);
1004 * Add new guards to the sampled guards in <b>gs</b> until there are
1005 * enough usable filtered guards, but never grow the sample beyond its
1006 * maximum size. Return the last guard added, or NULL if none were
1009 STATIC entry_guard_t
*
1010 entry_guards_expand_sample(guard_selection_t
*gs
)
1013 int n_sampled
= smartlist_len(gs
->sampled_entry_guards
);
1014 entry_guard_t
*added_guard
= NULL
;
1015 int n_usable_filtered_guards
= num_reachable_filtered_guards(gs
, NULL
);
1017 smartlist_t
*eligible_guards
= get_eligible_guards(gs
, &n_guards
);
1019 const int max_sample
= get_max_sample_size(gs
, n_guards
);
1020 const int min_filtered_sample
= get_min_filtered_sample_size();
1022 log_info(LD_GUARD
, "Expanding the sample guard set. We have %d guards "
1023 "in the sample, and %d eligible guards to extend it with.",
1024 n_sampled
, smartlist_len(eligible_guards
));
1026 while (n_usable_filtered_guards
< min_filtered_sample
) {
1027 /* Has our sample grown too large to expand? */
1028 if (n_sampled
>= max_sample
) {
1029 log_info(LD_GUARD
, "Not expanding the guard sample any further; "
1030 "just hit the maximum sample threshold of %d",
1035 /* Did we run out of guards? */
1036 if (smartlist_len(eligible_guards
) == 0) {
1038 As long as MAX_SAMPLE_THRESHOLD makes can't be adjusted to
1039 allow all guards to be sampled, this can't be reached.
1041 log_info(LD_GUARD
, "Not expanding the guard sample any further; "
1042 "just ran out of eligible guards");
1044 /* LCOV_EXCL_STOP */
1047 /* Otherwise we can add at least one new guard. */
1048 added_guard
= select_and_add_guard_item_for_sample(gs
, eligible_guards
);
1050 goto done
; // LCOV_EXCL_LINE -- only fails on BUG.
1054 if (added_guard
->is_usable_filtered_guard
)
1055 ++n_usable_filtered_guards
;
1059 smartlist_free(eligible_guards
);
1064 * Helper: <b>guard</b> has just been removed from the sampled guards:
1065 * also remove it from primary and confirmed. */
1067 remove_guard_from_confirmed_and_primary_lists(guard_selection_t
*gs
,
1068 entry_guard_t
*guard
)
1070 if (guard
->is_primary
) {
1071 guard
->is_primary
= 0;
1072 smartlist_remove_keeporder(gs
->primary_entry_guards
, guard
);
1074 if (BUG(smartlist_contains(gs
->primary_entry_guards
, guard
))) {
1075 smartlist_remove_keeporder(gs
->primary_entry_guards
, guard
);
1079 if (guard
->confirmed_idx
>= 0) {
1080 entry_guard_t
*found_guard
= NULL
;
1081 if (guard
->confirmed_idx
< smartlist_len(gs
->confirmed_entry_guards
))
1082 found_guard
= smartlist_get(gs
->confirmed_entry_guards
,
1083 guard
->confirmed_idx
);
1084 if (BUG(guard
!= found_guard
)) {
1086 smartlist_remove_keeporder(gs
->confirmed_entry_guards
, guard
);
1089 smartlist_del_keeporder(gs
->confirmed_entry_guards
,
1090 guard
->confirmed_idx
);
1092 guard
->confirmed_idx
= -1;
1093 guard
->confirmed_on_date
= 0;
1095 if (BUG(smartlist_contains(gs
->confirmed_entry_guards
, guard
))) {
1097 smartlist_remove_keeporder(gs
->confirmed_entry_guards
, guard
);
1103 /** Return true iff <b>guard</b> is currently "listed" -- that is, it
1104 * appears in the consensus, or as a configured bridge (as
1107 entry_guard_is_listed(guard_selection_t
*gs
, const entry_guard_t
*guard
)
1109 if (gs
->type
== GS_TYPE_BRIDGE
) {
1110 return NULL
!= get_bridge_info_for_guard(guard
);
1112 const node_t
*node
= node_get_by_id(guard
->identity
);
1114 return node
&& node_is_possible_guard(node
);
1119 * Update the status of all sampled guards based on the arrival of a
1120 * new consensus networkstatus document. This will include marking
1121 * some guards as listed or unlisted, and removing expired guards. */
1123 sampled_guards_update_from_consensus(guard_selection_t
*gs
)
1125 /*XXXX prop271 consider splitting this function up. */
1127 const int REMOVE_UNLISTED_GUARDS_AFTER
=
1128 (get_remove_unlisted_guards_after_days() * 86400);
1129 const int unlisted_since_slop
= REMOVE_UNLISTED_GUARDS_AFTER
/ 5;
1131 // It's important to use only a live consensus here; we don't want to
1132 // make changes based on anything expired or old.
1133 if (gs
->type
!= GS_TYPE_BRIDGE
) {
1134 networkstatus_t
*ns
= networkstatus_get_live_consensus(approx_time());
1136 log_info(LD_GUARD
, "Updating sampled guard status based on received "
1139 if (! ns
|| ns
->valid_until
< approx_time()) {
1140 log_info(LD_GUARD
, "Hey, there wasn't a valid consensus. Ignoring");
1147 /* First: Update listed/unlisted. */
1148 SMARTLIST_FOREACH_BEGIN(gs
->sampled_entry_guards
, entry_guard_t
*, guard
) {
1149 /* XXXX prop271 check ed ID too */
1150 const int is_listed
= entry_guard_is_listed(gs
, guard
);
1152 if (is_listed
&& ! guard
->currently_listed
) {
1154 guard
->currently_listed
= 1;
1155 guard
->unlisted_since_date
= 0;
1156 log_info(LD_GUARD
, "Sampled guard %s is now listed again.",
1157 entry_guard_describe(guard
));
1158 } else if (!is_listed
&& guard
->currently_listed
) {
1160 guard
->currently_listed
= 0;
1161 guard
->unlisted_since_date
= randomize_time(approx_time(),
1162 unlisted_since_slop
);
1163 log_info(LD_GUARD
, "Sampled guard %s is now unlisted.",
1164 entry_guard_describe(guard
));
1165 } else if (is_listed
&& guard
->currently_listed
) {
1166 log_debug(LD_GUARD
, "Sampled guard %s is still listed.",
1167 entry_guard_describe(guard
));
1169 tor_assert(! is_listed
&& ! guard
->currently_listed
);
1170 log_debug(LD_GUARD
, "Sampled guard %s is still unlisted.",
1171 entry_guard_describe(guard
));
1174 /* Clean up unlisted_since_date, just in case. */
1175 if (guard
->currently_listed
&& guard
->unlisted_since_date
) {
1177 guard
->unlisted_since_date
= 0;
1178 log_warn(LD_BUG
, "Sampled guard %s was listed, but with "
1179 "unlisted_since_date set. Fixing.",
1180 entry_guard_describe(guard
));
1181 } else if (!guard
->currently_listed
&& ! guard
->unlisted_since_date
) {
1183 guard
->unlisted_since_date
= randomize_time(approx_time(),
1184 unlisted_since_slop
);
1185 log_warn(LD_BUG
, "Sampled guard %s was unlisted, but with "
1186 "unlisted_since_date unset. Fixing.",
1187 entry_guard_describe(guard
));
1189 } SMARTLIST_FOREACH_END(guard
);
1191 const time_t remove_if_unlisted_since
=
1192 approx_time() - REMOVE_UNLISTED_GUARDS_AFTER
;
1193 const time_t maybe_remove_if_sampled_before
=
1194 approx_time() - (get_guard_lifetime_days() * 86400);
1195 const time_t remove_if_confirmed_before
=
1196 approx_time() - (get_guard_confirmed_min_lifetime_days() * 86400);
1198 /* Then: remove the ones that have been junk for too long */
1199 SMARTLIST_FOREACH_BEGIN(gs
->sampled_entry_guards
, entry_guard_t
*, guard
) {
1202 if (guard
->currently_listed
== 0 &&
1203 guard
->unlisted_since_date
< remove_if_unlisted_since
) {
1205 "We have a live consensus, and {IS_LISTED} is false, and
1206 {FIRST_UNLISTED_AT} is over {REMOVE_UNLISTED_GUARDS_AFTER}
1209 log_info(LD_GUARD
, "Removing sampled guard %s: it has been unlisted "
1210 "for over %d days", entry_guard_describe(guard
),
1211 get_remove_unlisted_guards_after_days());
1213 } else if (guard
->sampled_on_date
< maybe_remove_if_sampled_before
) {
1214 /* We have a live consensus, and {ADDED_ON_DATE} is over
1215 {GUARD_LIFETIME} ago, *and* {CONFIRMED_ON_DATE} is either
1216 "never", or over {GUARD_CONFIRMED_MIN_LIFETIME} ago.
1218 if (guard
->confirmed_on_date
== 0) {
1220 log_info(LD_GUARD
, "Removing sampled guard %s: it was sampled "
1221 "over %d days ago, but never confirmed.",
1222 entry_guard_describe(guard
),
1223 get_guard_lifetime_days());
1224 } else if (guard
->confirmed_on_date
< remove_if_confirmed_before
) {
1226 log_info(LD_GUARD
, "Removing sampled guard %s: it was sampled "
1227 "over %d days ago, and confirmed over %d days ago.",
1228 entry_guard_describe(guard
),
1229 get_guard_lifetime_days(),
1230 get_guard_confirmed_min_lifetime_days());
1236 SMARTLIST_DEL_CURRENT(gs
->sampled_entry_guards
, guard
);
1237 remove_guard_from_confirmed_and_primary_lists(gs
, guard
);
1238 entry_guard_free(guard
);
1240 } SMARTLIST_FOREACH_END(guard
);
1243 gs
->primary_guards_up_to_date
= 0;
1244 entry_guards_update_filtered_sets(gs
);
1245 /* We don't need to rebuild the confirmed list right here -- we may have
1246 * removed confirmed guards above, but we can't have added any new
1249 entry_guards_changed_for_guard_selection(gs
);
1254 * Return true iff <b>node</b> is a Tor relay that we are configured to
1255 * be able to connect to. */
1257 node_passes_guard_filter(const or_options_t
*options
,
1260 /* NOTE: Make sure that this function stays in sync with
1261 * options_transition_affects_entry_guards */
1262 if (routerset_contains_node(options
->ExcludeNodes
, node
))
1265 /* XXXX -- prop271 spec deviation -- add entrynodes to spec. */
1266 if (options
->EntryNodes
&&
1267 !routerset_contains_node(options
->EntryNodes
, node
))
1270 if (!fascist_firewall_allows_node(node
, FIREWALL_OR_CONNECTION
, 0))
1273 if (node_is_a_configured_bridge(node
))
1279 /** Helper: Return true iff <b>bridge</b> passes our configuration
1280 * filter-- if it is a relay that we are configured to be able to
1283 bridge_passes_guard_filter(const or_options_t
*options
,
1284 const bridge_info_t
*bridge
)
1290 if (routerset_contains_bridge(options
->ExcludeNodes
, bridge
))
1293 /* Ignore entrynodes */
1294 const tor_addr_port_t
*addrport
= bridge_get_addr_port(bridge
);
1296 if (!fascist_firewall_allows_address_addr(&addrport
->addr
,
1298 FIREWALL_OR_CONNECTION
,
1306 * Return true iff <b>guard</b> is a Tor relay that we are configured to
1307 * be able to connect to, and we haven't disabled it for omission from
1308 * the consensus or path bias issues. */
1310 entry_guard_passes_filter(const or_options_t
*options
, guard_selection_t
*gs
,
1311 entry_guard_t
*guard
)
1313 if (guard
->currently_listed
== 0)
1315 if (guard
->pb
.path_bias_disabled
)
1318 if (gs
->type
== GS_TYPE_BRIDGE
) {
1319 const bridge_info_t
*bridge
= get_bridge_info_for_guard(guard
);
1322 return bridge_passes_guard_filter(options
, bridge
);
1324 const node_t
*node
= node_get_by_id(guard
->identity
);
1326 // This can happen when currently_listed is true, and we're not updating
1327 // it because we don't have a live consensus.
1331 return node_passes_guard_filter(options
, node
);
1336 * Return true iff <b>guard</b> obeys the restrictions defined in <b>rst</b>.
1337 * (If <b>rst</b> is NULL, there are no restrictions.)
1340 entry_guard_obeys_restriction(const entry_guard_t
*guard
,
1341 const entry_guard_restriction_t
*rst
)
1345 return 1; // No restriction? No problem.
1347 // Only one kind of restriction exists right now
1348 return tor_memneq(guard
->identity
, rst
->exclude_id
, DIGEST_LEN
);
1352 * Update the <b>is_filtered_guard</b> and <b>is_usable_filtered_guard</b>
1353 * flags on <b>guard</b>. */
1355 entry_guard_set_filtered_flags(const or_options_t
*options
,
1356 guard_selection_t
*gs
,
1357 entry_guard_t
*guard
)
1359 unsigned was_filtered
= guard
->is_filtered_guard
;
1360 guard
->is_filtered_guard
= 0;
1361 guard
->is_usable_filtered_guard
= 0;
1363 if (entry_guard_passes_filter(options
, gs
, guard
)) {
1364 guard
->is_filtered_guard
= 1;
1366 if (guard
->is_reachable
!= GUARD_REACHABLE_NO
)
1367 guard
->is_usable_filtered_guard
= 1;
1369 entry_guard_consider_retry(guard
);
1371 log_debug(LD_GUARD
, "Updated sampled guard %s: filtered=%d; "
1372 "reachable_filtered=%d.", entry_guard_describe(guard
),
1373 guard
->is_filtered_guard
, guard
->is_usable_filtered_guard
);
1375 if (!bool_eq(was_filtered
, guard
->is_filtered_guard
)) {
1376 /* This guard might now be primary or nonprimary. */
1377 gs
->primary_guards_up_to_date
= 0;
1382 * Update the <b>is_filtered_guard</b> and <b>is_usable_filtered_guard</b>
1383 * flag on every guard in <b>gs</b>. */
1385 entry_guards_update_filtered_sets(guard_selection_t
*gs
)
1387 const or_options_t
*options
= get_options();
1389 SMARTLIST_FOREACH_BEGIN(gs
->sampled_entry_guards
, entry_guard_t
*, guard
) {
1390 entry_guard_set_filtered_flags(options
, gs
, guard
);
1391 } SMARTLIST_FOREACH_END(guard
);
1395 * Return a random guard from the reachable filtered sample guards
1396 * in <b>gs</b>, subject to the exclusion rules listed in <b>flags</b>.
1397 * Return NULL if no such guard can be found.
1399 * Make sure that the sample is big enough, and that all the filter flags
1400 * are set correctly, before calling this function.
1402 * If a restriction is provided in <b>rst</b>, do not return any guards that
1405 STATIC entry_guard_t
*
1406 sample_reachable_filtered_entry_guards(guard_selection_t
*gs
,
1407 const entry_guard_restriction_t
*rst
,
1411 entry_guard_t
*result
= NULL
;
1412 const unsigned exclude_confirmed
= flags
& SAMPLE_EXCLUDE_CONFIRMED
;
1413 const unsigned exclude_primary
= flags
& SAMPLE_EXCLUDE_PRIMARY
;
1414 const unsigned exclude_pending
= flags
& SAMPLE_EXCLUDE_PENDING
;
1415 const unsigned no_update_primary
= flags
& SAMPLE_NO_UPDATE_PRIMARY
;
1417 SMARTLIST_FOREACH_BEGIN(gs
->sampled_entry_guards
, entry_guard_t
*, guard
) {
1418 entry_guard_consider_retry(guard
);
1419 } SMARTLIST_FOREACH_END(guard
);
1421 const int n_reachable_filtered
= num_reachable_filtered_guards(gs
, rst
);
1423 log_info(LD_GUARD
, "Trying to sample a reachable guard: We know of %d "
1424 "in the USABLE_FILTERED set.", n_reachable_filtered
);
1426 const int min_filtered_sample
= get_min_filtered_sample_size();
1427 if (n_reachable_filtered
< min_filtered_sample
) {
1428 log_info(LD_GUARD
, " (That isn't enough. Trying to expand the sample.)");
1429 entry_guards_expand_sample(gs
);
1432 if (exclude_primary
&& !gs
->primary_guards_up_to_date
&& !no_update_primary
)
1433 entry_guards_update_primary(gs
);
1435 /* Build the set of reachable filtered guards. */
1436 smartlist_t
*reachable_filtered_sample
= smartlist_new();
1437 SMARTLIST_FOREACH_BEGIN(gs
->sampled_entry_guards
, entry_guard_t
*, guard
) {
1438 entry_guard_consider_retry(guard
);// redundant, but cheap.
1439 if (! entry_guard_obeys_restriction(guard
, rst
))
1441 if (! guard
->is_usable_filtered_guard
)
1443 if (exclude_confirmed
&& guard
->confirmed_idx
>= 0)
1445 if (exclude_primary
&& guard
->is_primary
)
1447 if (exclude_pending
&& guard
->is_pending
)
1449 smartlist_add(reachable_filtered_sample
, guard
);
1450 } SMARTLIST_FOREACH_END(guard
);
1452 log_info(LD_GUARD
, " (After filters [%x], we have %d guards to consider.)",
1453 flags
, smartlist_len(reachable_filtered_sample
));
1455 if (smartlist_len(reachable_filtered_sample
)) {
1456 result
= smartlist_choose(reachable_filtered_sample
);
1457 log_info(LD_GUARD
, " (Selected %s.)",
1458 result
? entry_guard_describe(result
) : "<null>");
1460 smartlist_free(reachable_filtered_sample
);
1466 * Helper: compare two entry_guard_t by their confirmed_idx values.
1467 * Used to sort the confirmed list.
1470 compare_guards_by_confirmed_idx(const void **a_
, const void **b_
)
1472 const entry_guard_t
*a
= *a_
, *b
= *b_
;
1473 if (a
->confirmed_idx
< b
->confirmed_idx
)
1475 else if (a
->confirmed_idx
> b
->confirmed_idx
)
1482 * Find the confirmed guards from among the sampled guards in <b>gs</b>,
1483 * and put them in confirmed_entry_guards in the correct
1484 * order. Recalculate their indices.
1487 entry_guards_update_confirmed(guard_selection_t
*gs
)
1489 smartlist_clear(gs
->confirmed_entry_guards
);
1490 SMARTLIST_FOREACH_BEGIN(gs
->sampled_entry_guards
, entry_guard_t
*, guard
) {
1491 if (guard
->confirmed_idx
>= 0)
1492 smartlist_add(gs
->confirmed_entry_guards
, guard
);
1493 } SMARTLIST_FOREACH_END(guard
);
1495 smartlist_sort(gs
->confirmed_entry_guards
, compare_guards_by_confirmed_idx
);
1497 int any_changed
= 0;
1498 SMARTLIST_FOREACH_BEGIN(gs
->confirmed_entry_guards
, entry_guard_t
*, guard
) {
1499 if (guard
->confirmed_idx
!= guard_sl_idx
) {
1501 guard
->confirmed_idx
= guard_sl_idx
;
1503 } SMARTLIST_FOREACH_END(guard
);
1505 gs
->next_confirmed_idx
= smartlist_len(gs
->confirmed_entry_guards
);
1508 entry_guards_changed_for_guard_selection(gs
);
1513 * Mark <b>guard</b> as a confirmed guard -- that is, one that we have
1514 * connected to, and intend to use again.
1517 make_guard_confirmed(guard_selection_t
*gs
, entry_guard_t
*guard
)
1519 if (BUG(guard
->confirmed_on_date
&& guard
->confirmed_idx
>= 0))
1520 return; // LCOV_EXCL_LINE
1522 if (BUG(smartlist_contains(gs
->confirmed_entry_guards
, guard
)))
1523 return; // LCOV_EXCL_LINE
1525 const int GUARD_LIFETIME
= get_guard_lifetime_days() * 86400;
1526 guard
->confirmed_on_date
= randomize_time(approx_time(), GUARD_LIFETIME
/10);
1528 log_info(LD_GUARD
, "Marking %s as a confirmed guard (index %d)",
1529 entry_guard_describe(guard
),
1530 gs
->next_confirmed_idx
);
1532 guard
->confirmed_idx
= gs
->next_confirmed_idx
++;
1533 smartlist_add(gs
->confirmed_entry_guards
, guard
);
1535 // This confirmed guard might kick something else out of the primary
1537 gs
->primary_guards_up_to_date
= 0;
1539 entry_guards_changed_for_guard_selection(gs
);
1543 * Recalculate the list of primary guards (the ones we'd prefer to use) from
1544 * the filtered sample and the confirmed list.
1547 entry_guards_update_primary(guard_selection_t
*gs
)
1549 /*XXXX prop271 consider splitting this function up. */
1552 // prevent recursion. Recursion is potentially very bad here.
1553 static int running
= 0;
1554 tor_assert(!running
);
1557 const int N_PRIMARY_GUARDS
= get_n_primary_guards();
1559 smartlist_t
*new_primary_guards
= smartlist_new();
1560 smartlist_t
*old_primary_guards
= smartlist_new();
1561 smartlist_add_all(old_primary_guards
, gs
->primary_entry_guards
);
1563 /* Set this flag now, to prevent the calls below from recursing. */
1564 gs
->primary_guards_up_to_date
= 1;
1566 /* First, can we fill it up with confirmed guards? */
1567 SMARTLIST_FOREACH_BEGIN(gs
->confirmed_entry_guards
, entry_guard_t
*, guard
) {
1568 if (smartlist_len(new_primary_guards
) >= N_PRIMARY_GUARDS
)
1570 if (! guard
->is_filtered_guard
)
1572 guard
->is_primary
= 1;
1573 smartlist_add(new_primary_guards
, guard
);
1574 } SMARTLIST_FOREACH_END(guard
);
1576 /* Can we keep any older primary guards? First remove all the ones
1577 * that we already kept. */
1578 SMARTLIST_FOREACH_BEGIN(old_primary_guards
, entry_guard_t
*, guard
) {
1579 if (smartlist_contains(new_primary_guards
, guard
)) {
1580 SMARTLIST_DEL_CURRENT_KEEPORDER(old_primary_guards
, guard
);
1582 } SMARTLIST_FOREACH_END(guard
);
1584 /* Now add any that are still good. */
1585 SMARTLIST_FOREACH_BEGIN(old_primary_guards
, entry_guard_t
*, guard
) {
1586 if (smartlist_len(new_primary_guards
) >= N_PRIMARY_GUARDS
)
1588 if (! guard
->is_filtered_guard
)
1590 guard
->is_primary
= 1;
1591 smartlist_add(new_primary_guards
, guard
);
1592 SMARTLIST_DEL_CURRENT_KEEPORDER(old_primary_guards
, guard
);
1593 } SMARTLIST_FOREACH_END(guard
);
1595 /* Mark the remaining previous primary guards as non-primary */
1596 SMARTLIST_FOREACH_BEGIN(old_primary_guards
, entry_guard_t
*, guard
) {
1597 guard
->is_primary
= 0;
1598 } SMARTLIST_FOREACH_END(guard
);
1600 /* Finally, fill out the list with sampled guards. */
1601 while (smartlist_len(new_primary_guards
) < N_PRIMARY_GUARDS
) {
1602 entry_guard_t
*guard
= sample_reachable_filtered_entry_guards(gs
, NULL
,
1603 SAMPLE_EXCLUDE_CONFIRMED
|
1604 SAMPLE_EXCLUDE_PRIMARY
|
1605 SAMPLE_NO_UPDATE_PRIMARY
);
1608 guard
->is_primary
= 1;
1609 smartlist_add(new_primary_guards
, guard
);
1614 SMARTLIST_FOREACH(gs
->sampled_entry_guards
, entry_guard_t
*, guard
, {
1615 tor_assert_nonfatal(
1616 bool_eq(guard
->is_primary
,
1617 smartlist_contains(new_primary_guards
, guard
)));
1622 if (smartlist_len(gs
->primary_entry_guards
) !=
1623 smartlist_len(new_primary_guards
)) {
1626 SMARTLIST_FOREACH_BEGIN(gs
->primary_entry_guards
, entry_guard_t
*, g
) {
1627 if (g
!= smartlist_get(new_primary_guards
, g_sl_idx
)) {
1630 } SMARTLIST_FOREACH_END(g
);
1634 log_info(LD_GUARD
, "Primary entry guards have changed. "
1635 "New primary guard list is: ");
1636 int n
= smartlist_len(new_primary_guards
);
1637 SMARTLIST_FOREACH_BEGIN(new_primary_guards
, entry_guard_t
*, g
) {
1638 log_info(LD_GUARD
, " %d/%d: %s%s%s",
1639 g_sl_idx
+1, n
, entry_guard_describe(g
),
1640 g
->confirmed_idx
>= 0 ? " (confirmed)" : "",
1641 g
->is_filtered_guard
? "" : " (excluded by filter)");
1642 } SMARTLIST_FOREACH_END(g
);
1645 smartlist_free(old_primary_guards
);
1646 smartlist_free(gs
->primary_entry_guards
);
1647 gs
->primary_entry_guards
= new_primary_guards
;
1648 gs
->primary_guards_up_to_date
= 1;
1653 * Return the number of seconds after the last attempt at which we should
1654 * retry a guard that has been failing since <b>failing_since</b>.
1657 get_retry_schedule(time_t failing_since
, time_t now
,
1660 const unsigned SIX_HOURS
= 6 * 3600;
1661 const unsigned FOUR_DAYS
= 4 * 86400;
1662 const unsigned SEVEN_DAYS
= 7 * 86400;
1665 if (now
> failing_since
) {
1666 tdiff
= now
- failing_since
;
1672 time_t maximum
; int primary_delay
; int nonprimary_delay
;
1674 { SIX_HOURS
, 30*60, 1*60*60 },
1675 { FOUR_DAYS
, 2*60*60, 4*60*60 },
1676 { SEVEN_DAYS
, 4*60*60, 18*60*60 },
1677 { TIME_MAX
, 9*60*60, 36*60*60 }
1681 for (i
= 0; i
< ARRAY_LENGTH(delays
); ++i
) {
1682 if (tdiff
<= delays
[i
].maximum
) {
1683 return is_primary
? delays
[i
].primary_delay
: delays
[i
].nonprimary_delay
;
1686 /* LCOV_EXCL_START -- can't reach, since delays ends with TIME_MAX. */
1687 tor_assert_nonfatal_unreached();
1689 /* LCOV_EXCL_STOP */
1693 * If <b>guard</b> is unreachable, consider whether enough time has passed
1694 * to consider it maybe-reachable again.
1697 entry_guard_consider_retry(entry_guard_t
*guard
)
1699 if (guard
->is_reachable
!= GUARD_REACHABLE_NO
)
1700 return; /* No retry needed. */
1702 const time_t now
= approx_time();
1703 const unsigned delay
=
1704 get_retry_schedule(guard
->failing_since
, now
, guard
->is_primary
);
1705 const time_t last_attempt
= guard
->last_tried_to_connect
;
1707 if (BUG(last_attempt
== 0) ||
1708 now
>= last_attempt
+ delay
) {
1709 /* We should mark this retriable. */
1710 char tbuf
[ISO_TIME_LEN
+1];
1711 format_local_iso_time(tbuf
, last_attempt
);
1712 log_info(LD_GUARD
, "Marked %s%sguard %s for possible retry, since we "
1713 "haven't tried to use it since %s.",
1714 guard
->is_primary
?"primary ":"",
1715 guard
->confirmed_idx
>=0?"confirmed ":"",
1716 entry_guard_describe(guard
),
1719 guard
->is_reachable
= GUARD_REACHABLE_MAYBE
;
1720 if (guard
->is_filtered_guard
)
1721 guard
->is_usable_filtered_guard
= 1;
1725 /** Tell the entry guards subsystem that we have confirmed that as of
1726 * just now, we're on the internet. */
1728 entry_guards_note_internet_connectivity(guard_selection_t
*gs
)
1730 gs
->last_time_on_internet
= approx_time();
1734 * Get a guard for use with a circuit. Prefer to pick a running primary
1735 * guard; then a non-pending running filtered confirmed guard; then a
1736 * non-pending runnable filtered guard. Update the
1737 * <b>last_tried_to_connect</b> time and the <b>is_pending</b> fields of the
1738 * guard as appropriate. Set <b>state_out</b> to the new guard-state
1741 STATIC entry_guard_t
*
1742 select_entry_guard_for_circuit(guard_selection_t
*gs
,
1743 const entry_guard_restriction_t
*rst
,
1744 unsigned *state_out
)
1746 /*XXXX prop271 consider splitting this function up. */
1748 tor_assert(state_out
);
1750 if (!gs
->primary_guards_up_to_date
)
1751 entry_guards_update_primary(gs
);
1753 /* "If any entry in PRIMARY_GUARDS has {is_reachable} status of
1754 <maybe> or <yes>, return the first such guard." */
1755 SMARTLIST_FOREACH_BEGIN(gs
->primary_entry_guards
, entry_guard_t
*, guard
) {
1756 entry_guard_consider_retry(guard
);
1757 if (! entry_guard_obeys_restriction(guard
, rst
))
1759 if (guard
->is_reachable
!= GUARD_REACHABLE_NO
) {
1760 *state_out
= GUARD_CIRC_STATE_USABLE_ON_COMPLETION
;
1761 guard
->last_tried_to_connect
= approx_time();
1762 log_info(LD_GUARD
, "Selected primary guard %s for circuit.",
1763 entry_guard_describe(guard
));
1766 } SMARTLIST_FOREACH_END(guard
);
1768 /* "Otherwise, if the ordered intersection of {CONFIRMED_GUARDS}
1769 and {USABLE_FILTERED_GUARDS} is nonempty, return the first
1770 entry in that intersection that has {is_pending} set to
1772 SMARTLIST_FOREACH_BEGIN(gs
->confirmed_entry_guards
, entry_guard_t
*, guard
) {
1773 if (guard
->is_primary
)
1774 continue; /* we already considered this one. */
1775 if (! entry_guard_obeys_restriction(guard
, rst
))
1777 entry_guard_consider_retry(guard
);
1778 if (guard
->is_usable_filtered_guard
&& ! guard
->is_pending
) {
1779 guard
->is_pending
= 1;
1780 guard
->last_tried_to_connect
= approx_time();
1781 *state_out
= GUARD_CIRC_STATE_USABLE_IF_NO_BETTER_GUARD
;
1782 log_info(LD_GUARD
, "No primary guards available. Selected confirmed "
1783 "guard %s for circuit. Will try other guards before using "
1785 entry_guard_describe(guard
));
1788 } SMARTLIST_FOREACH_END(guard
);
1790 /* "Otherwise, if there is no such entry, select a member at
1791 random from {USABLE_FILTERED_GUARDS}." */
1793 entry_guard_t
*guard
;
1794 guard
= sample_reachable_filtered_entry_guards(gs
,
1796 SAMPLE_EXCLUDE_CONFIRMED
|
1797 SAMPLE_EXCLUDE_PRIMARY
|
1798 SAMPLE_EXCLUDE_PENDING
);
1799 if (guard
== NULL
) {
1800 log_info(LD_GUARD
, "Absolutely no sampled guards were available.");
1803 guard
->is_pending
= 1;
1804 guard
->last_tried_to_connect
= approx_time();
1805 *state_out
= GUARD_CIRC_STATE_USABLE_IF_NO_BETTER_GUARD
;
1806 log_info(LD_GUARD
, "No primary or confirmed guards available. Selected "
1807 "random guard %s for circuit. Will try other guards before "
1808 "using this circuit.",
1809 entry_guard_describe(guard
));
1815 * Note that we failed to connect to or build circuits through <b>guard</b>.
1816 * Use with a guard returned by select_entry_guard_for_circuit().
1819 entry_guards_note_guard_failure(guard_selection_t
*gs
,
1820 entry_guard_t
*guard
)
1824 guard
->is_reachable
= GUARD_REACHABLE_NO
;
1825 guard
->is_usable_filtered_guard
= 0;
1827 guard
->is_pending
= 0;
1828 if (guard
->failing_since
== 0)
1829 guard
->failing_since
= approx_time();
1831 log_info(LD_GUARD
, "Recorded failure for %s%sguard %s",
1832 guard
->is_primary
?"primary ":"",
1833 guard
->confirmed_idx
>=0?"confirmed ":"",
1834 entry_guard_describe(guard
));
1838 * Called when the network comes up after having seemed to be down for
1839 * a while: Mark the primary guards as maybe-reachable so that we'll
1843 mark_primary_guards_maybe_reachable(guard_selection_t
*gs
)
1845 if (!gs
->primary_guards_up_to_date
)
1846 entry_guards_update_primary(gs
);
1848 SMARTLIST_FOREACH_BEGIN(gs
->primary_entry_guards
, entry_guard_t
*, guard
) {
1849 if (guard
->is_reachable
!= GUARD_REACHABLE_NO
)
1852 /* Note that we do not clear failing_since: this guard is now only
1853 * _maybe-reachable_. */
1854 guard
->is_reachable
= GUARD_REACHABLE_MAYBE
;
1855 if (guard
->is_filtered_guard
)
1856 guard
->is_usable_filtered_guard
= 1;
1858 } SMARTLIST_FOREACH_END(guard
);
1862 * Note that we successfully connected to, and built a circuit through
1863 * <b>guard</b>. Given the old guard-state of the circuit in <b>old_state</b>,
1864 * return the new guard-state of the circuit.
1866 * Be aware: the circuit is only usable when its guard-state becomes
1867 * GUARD_CIRC_STATE_COMPLETE.
1870 entry_guards_note_guard_success(guard_selection_t
*gs
,
1871 entry_guard_t
*guard
,
1876 /* Save this, since we're about to overwrite it. */
1877 const time_t last_time_on_internet
= gs
->last_time_on_internet
;
1878 gs
->last_time_on_internet
= approx_time();
1880 guard
->is_reachable
= GUARD_REACHABLE_YES
;
1881 guard
->failing_since
= 0;
1882 guard
->is_pending
= 0;
1883 if (guard
->is_filtered_guard
)
1884 guard
->is_usable_filtered_guard
= 1;
1886 if (guard
->confirmed_idx
< 0) {
1887 make_guard_confirmed(gs
, guard
);
1888 if (!gs
->primary_guards_up_to_date
)
1889 entry_guards_update_primary(gs
);
1893 if (old_state
== GUARD_CIRC_STATE_USABLE_ON_COMPLETION
) {
1894 new_state
= GUARD_CIRC_STATE_COMPLETE
;
1896 tor_assert_nonfatal(
1897 old_state
== GUARD_CIRC_STATE_USABLE_IF_NO_BETTER_GUARD
);
1899 if (guard
->is_primary
) {
1900 /* XXXX prop271 -- I don't actually like this logic. It seems to make us
1901 * a little more susceptible to evil-ISP attacks. The mitigations I'm
1902 * thinking of, however, aren't local to this point, so I'll leave it
1904 /* This guard may have become primary by virtue of being confirmed.
1905 If so, the circuit for it is now complete.
1907 new_state
= GUARD_CIRC_STATE_COMPLETE
;
1909 new_state
= GUARD_CIRC_STATE_WAITING_FOR_BETTER_GUARD
;
1912 if (last_time_on_internet
+ get_internet_likely_down_interval()
1914 mark_primary_guards_maybe_reachable(gs
);
1918 log_info(LD_GUARD
, "Recorded success for %s%sguard %s",
1919 guard
->is_primary
?"primary ":"",
1920 guard
->confirmed_idx
>=0?"confirmed ":"",
1921 entry_guard_describe(guard
));
1927 * Helper: Return true iff <b>a</b> has higher priority than <b>b</b>.
1930 entry_guard_has_higher_priority(entry_guard_t
*a
, entry_guard_t
*b
)
1936 /* Confirmed is always better than unconfirmed; lower index better
1938 if (a
->confirmed_idx
< 0) {
1939 if (b
->confirmed_idx
>= 0)
1942 if (b
->confirmed_idx
< 0)
1945 /* Lower confirmed_idx is better than higher. */
1946 return (a
->confirmed_idx
< b
->confirmed_idx
);
1949 /* If we reach this point, both are unconfirmed. If one is pending, it
1950 * has higher priority. */
1951 if (a
->is_pending
) {
1952 if (! b
->is_pending
)
1955 /* Both are pending: earlier last_tried_connect wins. */
1956 return a
->last_tried_to_connect
< b
->last_tried_to_connect
;
1961 /* Neither is pending: priorities are equal. */
1962 return 0; // XXXX prop271 return a tristate instead?
1966 /** Release all storage held in <b>restriction</b> */
1968 entry_guard_restriction_free(entry_guard_restriction_t
*rst
)
1974 * Release all storage held in <b>state</b>.
1977 circuit_guard_state_free(circuit_guard_state_t
*state
)
1981 entry_guard_restriction_free(state
->restrictions
);
1982 entry_guard_handle_free(state
->guard
);
1987 * Pick a suitable entry guard for a circuit in, and place that guard
1988 * in *<b>chosen_node_out</b>. Set *<b>guard_state_out</b> to an opaque
1989 * state object that will record whether the circuit is ready to be used
1990 * or not. Return 0 on success; on failure, return -1.
1992 * If a restriction is provided in <b>rst</b>, do not return any guards that
1993 * violate it, and remember that restriction in <b>guard_state_out</b> for
1994 * later use. (Takes ownership of the <b>rst</b> object.)
1997 entry_guard_pick_for_circuit(guard_selection_t
*gs
,
1998 entry_guard_restriction_t
*rst
,
1999 const node_t
**chosen_node_out
,
2000 circuit_guard_state_t
**guard_state_out
)
2003 tor_assert(chosen_node_out
);
2004 tor_assert(guard_state_out
);
2005 *chosen_node_out
= NULL
;
2006 *guard_state_out
= NULL
;
2009 entry_guard_t
*guard
= select_entry_guard_for_circuit(gs
, rst
, &state
);
2012 if (BUG(state
== 0))
2014 const node_t
*node
= node_get_by_id(guard
->identity
);
2015 // XXXX prop271 check Ed ID.
2019 *chosen_node_out
= node
;
2020 *guard_state_out
= tor_malloc_zero(sizeof(circuit_guard_state_t
));
2021 (*guard_state_out
)->guard
= entry_guard_handle_new(guard
);
2022 (*guard_state_out
)->state
= state
;
2023 (*guard_state_out
)->state_set_at
= approx_time();
2024 (*guard_state_out
)->restrictions
= rst
;
2028 entry_guard_restriction_free(rst
);
2033 * Called by the circuit building module when a circuit has succeeded: informs
2034 * the guards code that the guard in *<b>guard_state_p</b> is working, and
2035 * advances the state of the guard module. On a GUARD_USABLE_NEVER return
2036 * value, the circuit is broken and should not be used. On a GUARD_USABLE_NOW
2037 * return value, the circuit is ready to use. On a GUARD_MAYBE_USABLE_LATER
2038 * return value, the circuit should not be used until we find out whether
2039 * preferred guards will work for us.
2042 entry_guard_succeeded(circuit_guard_state_t
**guard_state_p
)
2044 if (get_options()->UseDeprecatedGuardAlgorithm
)
2045 return GUARD_USABLE_NOW
;
2047 if (BUG(*guard_state_p
== NULL
))
2048 return GUARD_USABLE_NEVER
;
2050 entry_guard_t
*guard
= entry_guard_handle_get((*guard_state_p
)->guard
);
2051 if (! guard
|| BUG(guard
->in_selection
== NULL
))
2052 return GUARD_USABLE_NEVER
;
2055 entry_guards_note_guard_success(guard
->in_selection
, guard
,
2056 (*guard_state_p
)->state
);
2058 (*guard_state_p
)->state
= newstate
;
2059 (*guard_state_p
)->state_set_at
= approx_time();
2061 if (newstate
== GUARD_CIRC_STATE_COMPLETE
) {
2062 return GUARD_USABLE_NOW
;
2064 return GUARD_MAYBE_USABLE_LATER
;
2068 /** Cancel the selection of *<b>guard_state_p</b> without declaring
2069 * success or failure. It is safe to call this function if success or
2070 * failure _has_ already been declared. */
2072 entry_guard_cancel(circuit_guard_state_t
**guard_state_p
)
2074 if (get_options()->UseDeprecatedGuardAlgorithm
)
2076 if (BUG(*guard_state_p
== NULL
))
2078 entry_guard_t
*guard
= entry_guard_handle_get((*guard_state_p
)->guard
);
2082 /* XXXX prop271 -- last_tried_to_connect_at will be erroneous here, but this
2083 * function will only get called in "bug" cases anyway. */
2084 guard
->is_pending
= 0;
2085 circuit_guard_state_free(*guard_state_p
);
2086 *guard_state_p
= NULL
;
2090 * Called by the circuit building module when a circuit has succeeded:
2091 * informs the guards code that the guard in *<b>guard_state_p</b> is
2092 * not working, and advances the state of the guard module.
2095 entry_guard_failed(circuit_guard_state_t
**guard_state_p
)
2097 if (get_options()->UseDeprecatedGuardAlgorithm
)
2100 if (BUG(*guard_state_p
== NULL
))
2103 entry_guard_t
*guard
= entry_guard_handle_get((*guard_state_p
)->guard
);
2104 if (! guard
|| BUG(guard
->in_selection
== NULL
))
2107 entry_guards_note_guard_failure(guard
->in_selection
, guard
);
2109 (*guard_state_p
)->state
= GUARD_CIRC_STATE_DEAD
;
2110 (*guard_state_p
)->state_set_at
= approx_time();
2114 * Run the entry_guard_failed() function on every circuit that is
2115 * pending on <b>chan</b>.
2118 entry_guard_chan_failed(channel_t
*chan
)
2122 if (get_options()->UseDeprecatedGuardAlgorithm
)
2125 smartlist_t
*pending
= smartlist_new();
2126 circuit_get_all_pending_on_channel(pending
, chan
);
2127 SMARTLIST_FOREACH_BEGIN(pending
, circuit_t
*, circ
) {
2128 if (!CIRCUIT_IS_ORIGIN(circ
))
2131 origin_circuit_t
*origin_circ
= TO_ORIGIN_CIRCUIT(circ
);
2132 entry_guard_failed(&origin_circ
->guard_state
);
2133 } SMARTLIST_FOREACH_END(circ
);
2134 smartlist_free(pending
);
2138 * Return true iff every primary guard in <b>gs</b> is believed to
2142 entry_guards_all_primary_guards_are_down(guard_selection_t
*gs
)
2145 if (!gs
->primary_guards_up_to_date
)
2146 entry_guards_update_primary(gs
);
2147 SMARTLIST_FOREACH_BEGIN(gs
->primary_entry_guards
, entry_guard_t
*, guard
) {
2148 entry_guard_consider_retry(guard
);
2149 if (guard
->is_reachable
!= GUARD_REACHABLE_NO
)
2151 } SMARTLIST_FOREACH_END(guard
);
2155 /** Wrapper for entry_guard_has_higher_priority that compares the
2156 * guard-priorities of a pair of circuits.
2158 * If a restriction is provided in <b>rst</b>, then do not consider
2159 * <b>a</b> to have higher priority if it violates the restriction.
2162 circ_state_has_higher_priority(origin_circuit_t
*a
,
2163 const entry_guard_restriction_t
*rst
,
2164 origin_circuit_t
*b
)
2166 circuit_guard_state_t
*state_a
= origin_circuit_get_guard_state(a
);
2167 circuit_guard_state_t
*state_b
= origin_circuit_get_guard_state(b
);
2169 tor_assert(state_a
);
2170 tor_assert(state_b
);
2172 entry_guard_t
*guard_a
= entry_guard_handle_get(state_a
->guard
);
2173 entry_guard_t
*guard_b
= entry_guard_handle_get(state_b
->guard
);
2176 /* Unknown guard -- never higher priority. */
2178 } else if (! guard_b
) {
2179 /* Known guard -- higher priority than any unknown guard. */
2181 } else if (! entry_guard_obeys_restriction(guard_a
, rst
)) {
2182 /* Restriction violated; guard_a cannot have higher priority. */
2185 /* Both known -- compare.*/
2186 return entry_guard_has_higher_priority(guard_a
, guard_b
);
2191 * Look at all of the origin_circuit_t * objects in <b>all_circuits_in</b>,
2192 * and see if any of them that were previously not ready to use for
2193 * guard-related reasons are now ready to use. Place those circuits
2194 * in <b>newly_complete_out</b>, and mark them COMPLETE.
2196 * Return 1 if we upgraded any circuits, and 0 otherwise.
2199 entry_guards_upgrade_waiting_circuits(guard_selection_t
*gs
,
2200 const smartlist_t
*all_circuits_in
,
2201 smartlist_t
*newly_complete_out
)
2204 tor_assert(all_circuits_in
);
2205 tor_assert(newly_complete_out
);
2207 if (! entry_guards_all_primary_guards_are_down(gs
)) {
2208 /* We only upgrade a waiting circuit if the primary guards are all
2210 log_debug(LD_GUARD
, "Considered upgrading guard-stalled circuits, "
2211 "but not all primary guards were definitely down.");
2217 origin_circuit_t
*best_waiting_circuit
= NULL
;
2218 origin_circuit_t
*best_complete_circuit
= NULL
;
2219 smartlist_t
*all_circuits
= smartlist_new();
2220 SMARTLIST_FOREACH_BEGIN(all_circuits_in
, origin_circuit_t
*, circ
) {
2221 // We filter out circuits that aren't ours, or which we can't
2223 circuit_guard_state_t
*state
= origin_circuit_get_guard_state(circ
);
2226 entry_guard_t
*guard
= entry_guard_handle_get(state
->guard
);
2227 if (!guard
|| guard
->in_selection
!= gs
)
2230 smartlist_add(all_circuits
, circ
);
2231 } SMARTLIST_FOREACH_END(circ
);
2233 SMARTLIST_FOREACH_BEGIN(all_circuits
, origin_circuit_t
*, circ
) {
2234 circuit_guard_state_t
*state
= origin_circuit_get_guard_state(circ
);
2235 if BUG((state
== NULL
))
2238 if (state
->state
== GUARD_CIRC_STATE_WAITING_FOR_BETTER_GUARD
) {
2240 if (! best_waiting_circuit
||
2241 circ_state_has_higher_priority(circ
, NULL
, best_waiting_circuit
)) {
2242 best_waiting_circuit
= circ
;
2244 } else if (state
->state
== GUARD_CIRC_STATE_COMPLETE
) {
2246 if (! best_complete_circuit
||
2247 circ_state_has_higher_priority(circ
, NULL
, best_complete_circuit
)) {
2248 best_complete_circuit
= circ
;
2251 } SMARTLIST_FOREACH_END(circ
);
2253 if (! best_waiting_circuit
) {
2254 log_debug(LD_GUARD
, "Considered upgrading guard-stalled circuits, "
2255 "but didn't find any.");
2259 /* We'll need to keep track of what restrictions were used when picking this
2260 * circuit, so that we don't allow any circuit without those restrictions to
2262 const entry_guard_restriction_t
*rst_on_best_waiting
=
2263 origin_circuit_get_guard_state(best_waiting_circuit
)->restrictions
;
2265 if (best_complete_circuit
) {
2266 if (circ_state_has_higher_priority(best_complete_circuit
,
2267 rst_on_best_waiting
,
2268 best_waiting_circuit
)) {
2269 /* "If any circuit is <complete>, then do not use any
2270 <waiting_for_better_guard> or <usable_if_no_better_guard> circuits
2271 circuits whose guards have lower priority." */
2272 log_debug(LD_GUARD
, "Considered upgrading guard-stalled circuits: found "
2273 "%d complete and %d guard-stalled. At least one complete "
2274 "circuit had higher priority, so not upgrading.",
2275 n_complete
, n_waiting
);
2280 /* "If any circuit is <waiting_for_better_guard>, and every currently
2281 {is_pending} circuit whose guard has higher priority has been in
2282 state <usable_if_no_better_guard> for at least
2283 {NONPRIMARY_GUARD_CONNECT_TIMEOUT} seconds, and all primary guards
2284 have reachable status of <no>, then call that circuit <complete>."
2286 XXXX --- prop271 deviation. there's no such thing in the spec as
2287 an {is_pending circuit}; fix the spec.
2289 int n_blockers_found
= 0;
2290 const time_t state_set_at_cutoff
=
2291 approx_time() - get_nonprimary_guard_connect_timeout();
2292 SMARTLIST_FOREACH_BEGIN(all_circuits
, origin_circuit_t
*, circ
) {
2293 circuit_guard_state_t
*state
= origin_circuit_get_guard_state(circ
);
2294 if (BUG(state
== NULL
))
2296 if (state
->state
!= GUARD_CIRC_STATE_USABLE_IF_NO_BETTER_GUARD
)
2298 if (state
->state_set_at
<= state_set_at_cutoff
)
2300 if (circ_state_has_higher_priority(circ
, rst_on_best_waiting
,
2301 best_waiting_circuit
))
2303 } SMARTLIST_FOREACH_END(circ
);
2305 if (n_blockers_found
) {
2306 log_debug(LD_GUARD
, "Considered upgrading guard-stalled circuits: found "
2307 "%d guard-stalled, but %d pending circuit(s) had higher "
2308 "guard priority, so not upgrading.",
2309 n_waiting
, n_blockers_found
);
2313 /* Okay. We have a best waiting circuit, and we aren't waiting for
2314 anything better. Add all circuits with that priority to the
2315 list, and call them COMPLETE. */
2316 int n_succeeded
= 0;
2317 SMARTLIST_FOREACH_BEGIN(all_circuits
, origin_circuit_t
*, circ
) {
2318 circuit_guard_state_t
*state
= origin_circuit_get_guard_state(circ
);
2319 if (BUG(state
== NULL
))
2321 if (circ
!= best_waiting_circuit
&& rst_on_best_waiting
) {
2322 /* Can't upgrade other circ with same priority as best; might
2326 if (state
->state
!= GUARD_CIRC_STATE_WAITING_FOR_BETTER_GUARD
)
2328 if (circ_state_has_higher_priority(best_waiting_circuit
, NULL
, circ
))
2331 state
->state
= GUARD_CIRC_STATE_COMPLETE
;
2332 state
->state_set_at
= approx_time();
2333 smartlist_add(newly_complete_out
, circ
);
2335 } SMARTLIST_FOREACH_END(circ
);
2337 log_info(LD_GUARD
, "Considered upgrading guard-stalled circuits: found "
2338 "%d guard-stalled, %d complete. %d of the guard-stalled "
2339 "circuit(s) had high enough priority to upgrade.",
2340 n_waiting
, n_complete
, n_succeeded
);
2342 tor_assert_nonfatal(n_succeeded
>= 1);
2343 smartlist_free(all_circuits
);
2347 smartlist_free(all_circuits
);
2352 * Return true iff the circuit whose state is <b>guard_state</b> should
2356 entry_guard_state_should_expire(circuit_guard_state_t
*guard_state
)
2358 if (guard_state
== NULL
)
2360 const time_t expire_if_waiting_since
=
2361 approx_time() - get_nonprimary_guard_idle_timeout();
2362 return (guard_state
->state
== GUARD_CIRC_STATE_WAITING_FOR_BETTER_GUARD
2363 && guard_state
->state_set_at
< expire_if_waiting_since
);
2367 * Update all derived pieces of the guard selection state in <b>gs</b>.
2368 * Return true iff we should stop using all previously generated circuits.
2371 entry_guards_update_all(guard_selection_t
*gs
)
2373 sampled_guards_update_from_consensus(gs
);
2374 entry_guards_update_filtered_sets(gs
);
2375 entry_guards_update_confirmed(gs
);
2376 entry_guards_update_primary(gs
);
2381 * Return a newly allocated string for encoding the persistent parts of
2382 * <b>guard</b> to the state file.
2385 entry_guard_encode_for_state(entry_guard_t
*guard
)
2388 * The meta-format we use is K=V K=V K=V... where K can be any
2389 * characters excepts space and =, and V can be any characters except
2390 * space. The order of entries is not allowed to matter.
2391 * Unrecognized K=V entries are persisted; recognized but erroneous
2392 * entries are corrected.
2395 smartlist_t
*result
= smartlist_new();
2396 char tbuf
[ISO_TIME_LEN
+1];
2400 smartlist_add_asprintf(result
, "in=%s", guard
->selection_name
);
2401 smartlist_add_asprintf(result
, "rsa_id=%s",
2402 hex_str(guard
->identity
, DIGEST_LEN
));
2403 if (guard
->bridge_addr
) {
2404 smartlist_add_asprintf(result
, "bridge_addr=%s:%d",
2405 fmt_and_decorate_addr(&guard
->bridge_addr
->addr
),
2406 guard
->bridge_addr
->port
);
2408 if (strlen(guard
->nickname
)) {
2409 smartlist_add_asprintf(result
, "nickname=%s", guard
->nickname
);
2412 format_iso_time_nospace(tbuf
, guard
->sampled_on_date
);
2413 smartlist_add_asprintf(result
, "sampled_on=%s", tbuf
);
2415 if (guard
->sampled_by_version
) {
2416 smartlist_add_asprintf(result
, "sampled_by=%s",
2417 guard
->sampled_by_version
);
2420 if (guard
->unlisted_since_date
> 0) {
2421 format_iso_time_nospace(tbuf
, guard
->unlisted_since_date
);
2422 smartlist_add_asprintf(result
, "unlisted_since=%s", tbuf
);
2425 smartlist_add_asprintf(result
, "listed=%d",
2426 (int)guard
->currently_listed
);
2428 if (guard
->confirmed_idx
>= 0) {
2429 format_iso_time_nospace(tbuf
, guard
->confirmed_on_date
);
2430 smartlist_add_asprintf(result
, "confirmed_on=%s", tbuf
);
2432 smartlist_add_asprintf(result
, "confirmed_idx=%d", guard
->confirmed_idx
);
2435 const double EPSILON
= 1.0e-6;
2437 /* Make a copy of the pathbias object, since we will want to update
2439 guard_pathbias_t
*pb
= tor_memdup(&guard
->pb
, sizeof(*pb
));
2440 pb
->use_successes
= pathbias_get_use_success_count(guard
);
2441 pb
->successful_circuits_closed
= pathbias_get_close_success_count(guard
);
2443 #define PB_FIELD(field) do { \
2444 if (pb->field >= EPSILON) { \
2445 smartlist_add_asprintf(result, "pb_" #field "=%f", pb->field); \
2448 PB_FIELD(use_attempts
);
2449 PB_FIELD(use_successes
);
2450 PB_FIELD(circ_attempts
);
2451 PB_FIELD(circ_successes
);
2452 PB_FIELD(successful_circuits_closed
);
2453 PB_FIELD(collapsed_circuits
);
2454 PB_FIELD(unusable_circuits
);
2459 if (guard
->extra_state_fields
)
2460 smartlist_add_strdup(result
, guard
->extra_state_fields
);
2462 char *joined
= smartlist_join_strings(result
, " ", 0, NULL
);
2463 SMARTLIST_FOREACH(result
, char *, cp
, tor_free(cp
));
2464 smartlist_free(result
);
2470 * Given a string generated by entry_guard_encode_for_state(), parse it
2471 * (if possible) and return an entry_guard_t object for it. Return NULL
2472 * on complete failure.
2474 STATIC entry_guard_t
*
2475 entry_guard_parse_from_state(const char *s
)
2477 /* Unrecognized entries get put in here. */
2478 smartlist_t
*extra
= smartlist_new();
2480 /* These fields get parsed from the string. */
2482 char *rsa_id
= NULL
;
2483 char *nickname
= NULL
;
2484 char *sampled_on
= NULL
;
2485 char *sampled_by
= NULL
;
2486 char *unlisted_since
= NULL
;
2487 char *listed
= NULL
;
2488 char *confirmed_on
= NULL
;
2489 char *confirmed_idx
= NULL
;
2490 char *bridge_addr
= NULL
;
2493 char *pb_use_attempts
= NULL
;
2494 char *pb_use_successes
= NULL
;
2495 char *pb_circ_attempts
= NULL
;
2496 char *pb_circ_successes
= NULL
;
2497 char *pb_successful_circuits_closed
= NULL
;
2498 char *pb_collapsed_circuits
= NULL
;
2499 char *pb_unusable_circuits
= NULL
;
2500 char *pb_timeouts
= NULL
;
2502 /* Split up the entries. Put the ones we know about in strings and the
2503 * rest in "extra". */
2505 smartlist_t
*entries
= smartlist_new();
2507 strmap_t
*vals
= strmap_new(); // Maps keyword to location
2509 strmap_set(vals, #f, &f);
2515 FIELD(unlisted_since
);
2517 FIELD(confirmed_on
);
2518 FIELD(confirmed_idx
);
2520 FIELD(pb_use_attempts
);
2521 FIELD(pb_use_successes
);
2522 FIELD(pb_circ_attempts
);
2523 FIELD(pb_circ_successes
);
2524 FIELD(pb_successful_circuits_closed
);
2525 FIELD(pb_collapsed_circuits
);
2526 FIELD(pb_unusable_circuits
);
2530 smartlist_split_string(entries
, s
, " ",
2531 SPLIT_SKIP_SPACE
|SPLIT_IGNORE_BLANK
, 0);
2533 SMARTLIST_FOREACH_BEGIN(entries
, char *, entry
) {
2534 const char *eq
= strchr(entry
, '=');
2536 smartlist_add(extra
, entry
);
2539 char *key
= tor_strndup(entry
, eq
-entry
);
2540 char **target
= strmap_get(vals
, key
);
2541 if (target
== NULL
|| *target
!= NULL
) {
2542 /* unrecognized or already set */
2543 smartlist_add(extra
, entry
);
2548 *target
= tor_strdup(eq
+1);
2551 } SMARTLIST_FOREACH_END(entry
);
2553 smartlist_free(entries
);
2554 strmap_free(vals
, NULL
);
2557 entry_guard_t
*guard
= tor_malloc_zero(sizeof(entry_guard_t
));
2558 guard
->is_persistent
= 1;
2561 log_warn(LD_CIRC
, "Guard missing 'in' field");
2565 guard
->selection_name
= in
;
2568 if (rsa_id
== NULL
) {
2569 log_warn(LD_CIRC
, "Guard missing RSA ID field");
2573 /* Process the identity and nickname. */
2574 if (base16_decode(guard
->identity
, sizeof(guard
->identity
),
2575 rsa_id
, strlen(rsa_id
)) != DIGEST_LEN
) {
2576 log_warn(LD_CIRC
, "Unable to decode guard identity %s", escaped(rsa_id
));
2581 strlcpy(guard
->nickname
, nickname
, sizeof(guard
->nickname
));
2583 guard
->nickname
[0]='$';
2584 base16_encode(guard
->nickname
+1, sizeof(guard
->nickname
)-1,
2585 guard
->identity
, DIGEST_LEN
);
2589 tor_addr_port_t res
;
2590 memset(&res
, 0, sizeof(res
));
2591 int r
= tor_addr_port_parse(LOG_WARN
, bridge_addr
,
2592 &res
.addr
, &res
.port
, -1);
2594 guard
->bridge_addr
= tor_memdup(&res
, sizeof(res
));
2595 /* On error, we already warned. */
2598 /* Process the various time fields. */
2600 #define HANDLE_TIME(field) do { \
2602 int r = parse_iso_time_nospace(field, &field ## _time); \
2604 log_warn(LD_CIRC, "Unable to parse %s %s from guard", \
2605 #field, escaped(field)); \
2606 field##_time = -1; \
2611 time_t sampled_on_time
= 0;
2612 time_t unlisted_since_time
= 0;
2613 time_t confirmed_on_time
= 0;
2615 HANDLE_TIME(sampled_on
);
2616 HANDLE_TIME(unlisted_since
);
2617 HANDLE_TIME(confirmed_on
);
2619 if (sampled_on_time
<= 0)
2620 sampled_on_time
= approx_time();
2621 if (unlisted_since_time
< 0)
2622 unlisted_since_time
= 0;
2623 if (confirmed_on_time
< 0)
2624 confirmed_on_time
= 0;
2628 guard
->sampled_on_date
= sampled_on_time
;
2629 guard
->unlisted_since_date
= unlisted_since_time
;
2630 guard
->confirmed_on_date
= confirmed_on_time
;
2632 /* Take sampled_by_version verbatim. */
2633 guard
->sampled_by_version
= sampled_by
;
2634 sampled_by
= NULL
; /* prevent free */
2635 // XXXX -- prop271 spec deviation -- we do not require sampled_by_version
2637 /* Listed is a boolean */
2638 if (listed
&& strcmp(listed
, "0"))
2639 guard
->currently_listed
= 1;
2641 /* The index is a nonnegative integer. */
2642 guard
->confirmed_idx
= -1;
2643 if (confirmed_idx
) {
2645 long idx
= tor_parse_long(confirmed_idx
, 10, 0, INT_MAX
, &ok
, NULL
);
2647 log_warn(LD_GUARD
, "Guard has invalid confirmed_idx %s",
2648 escaped(confirmed_idx
));
2650 guard
->confirmed_idx
= (int)idx
;
2654 /* Anything we didn't recognize gets crammed together */
2655 if (smartlist_len(extra
) > 0) {
2656 guard
->extra_state_fields
= smartlist_join_strings(extra
, " ", 0, NULL
);
2659 /* initialize non-persistent fields */
2660 guard
->is_reachable
= GUARD_REACHABLE_MAYBE
;
2662 #define PB_FIELD(field) \
2664 if (pb_ ## field) { \
2666 double r = tor_parse_double(pb_ ## field, 0.0, 1e9, &ok, NULL); \
2668 log_warn(LD_CIRC, "Guard has invalid pb_%s %s", \
2669 #field, pb_ ## field); \
2671 guard->pb.field = r; \
2675 PB_FIELD(use_attempts
);
2676 PB_FIELD(use_successes
);
2677 PB_FIELD(circ_attempts
);
2678 PB_FIELD(circ_successes
);
2679 PB_FIELD(successful_circuits_closed
);
2680 PB_FIELD(collapsed_circuits
);
2681 PB_FIELD(unusable_circuits
);
2685 pathbias_check_use_success_count(guard
);
2686 pathbias_check_close_success_count(guard
);
2688 /* We update everything on this guard later, after we've parsed
2694 // only consider it an error if the guard state was totally unparseable.
2695 entry_guard_free(guard
);
2702 tor_free(sampled_on
);
2703 tor_free(sampled_by
);
2704 tor_free(unlisted_since
);
2706 tor_free(confirmed_on
);
2707 tor_free(confirmed_idx
);
2708 tor_free(bridge_addr
);
2709 tor_free(pb_use_attempts
);
2710 tor_free(pb_use_successes
);
2711 tor_free(pb_circ_attempts
);
2712 tor_free(pb_circ_successes
);
2713 tor_free(pb_successful_circuits_closed
);
2714 tor_free(pb_collapsed_circuits
);
2715 tor_free(pb_unusable_circuits
);
2716 tor_free(pb_timeouts
);
2718 SMARTLIST_FOREACH(extra
, char *, cp
, tor_free(cp
));
2719 smartlist_free(extra
);
2725 * Replace the Guards entries in <b>state</b> with a list of all our
2726 * non-legacy sampled guards.
2729 entry_guards_update_guards_in_state(or_state_t
*state
)
2731 if (!guard_contexts
)
2733 config_line_t
*lines
= NULL
;
2734 config_line_t
**nextline
= &lines
;
2736 SMARTLIST_FOREACH_BEGIN(guard_contexts
, guard_selection_t
*, gs
) {
2737 if (!strcmp(gs
->name
, "legacy"))
2738 continue; /* This is encoded differently. */
2739 SMARTLIST_FOREACH_BEGIN(gs
->sampled_entry_guards
, entry_guard_t
*, guard
) {
2740 if (guard
->is_persistent
== 0)
2742 *nextline
= tor_malloc_zero(sizeof(config_line_t
));
2743 (*nextline
)->key
= tor_strdup("Guard");
2744 (*nextline
)->value
= entry_guard_encode_for_state(guard
);
2745 nextline
= &(*nextline
)->next
;
2746 } SMARTLIST_FOREACH_END(guard
);
2747 } SMARTLIST_FOREACH_END(gs
);
2749 config_free_lines(state
->Guard
);
2750 state
->Guard
= lines
;
2754 * Replace our non-legacy sampled guards from the Guards entries in
2755 * <b>state</b>. Return 0 on success, -1 on failure. (If <b>set</b> is
2756 * true, replace nothing -- only check whether replacing would work.)
2759 entry_guards_load_guards_from_state(or_state_t
*state
, int set
)
2761 const config_line_t
*line
= state
->Guard
;
2764 if (!guard_contexts
)
2765 guard_contexts
= smartlist_new();
2767 /* Wipe all our existing guard info. (we shouldn't have any, but
2768 * let's be safe.) */
2770 SMARTLIST_FOREACH_BEGIN(guard_contexts
, guard_selection_t
*, gs
) {
2771 if (!strcmp(gs
->name
, "legacy"))
2773 guard_selection_free(gs
);
2774 if (curr_guard_context
== gs
)
2775 curr_guard_context
= NULL
;
2776 SMARTLIST_DEL_CURRENT(guard_contexts
, gs
);
2777 } SMARTLIST_FOREACH_END(gs
);
2780 for ( ; line
!= NULL
; line
= line
->next
) {
2781 entry_guard_t
*guard
= entry_guard_parse_from_state(line
->value
);
2782 if (guard
== NULL
) {
2786 tor_assert(guard
->selection_name
);
2787 if (!strcmp(guard
->selection_name
, "legacy")) {
2789 entry_guard_free(guard
);
2794 guard_selection_t
*gs
;
2795 gs
= get_guard_selection_by_name(guard
->selection_name
,
2798 smartlist_add(gs
->sampled_entry_guards
, guard
);
2799 guard
->in_selection
= gs
;
2801 entry_guard_free(guard
);
2806 SMARTLIST_FOREACH_BEGIN(guard_contexts
, guard_selection_t
*, gs
) {
2807 if (!strcmp(gs
->name
, "legacy"))
2809 entry_guards_update_all(gs
);
2810 } SMARTLIST_FOREACH_END(gs
);
2812 return n_errors
? -1 : 0;
2815 /* XXXXX ----------------------------------------------- */
2816 /* XXXXX prop271 ----- end of new-for-prop271 code ----- */
2817 /* XXXXX ----------------------------------------------- */
2820 * @name Constants for old (pre-prop271) guard selection algorithm.
2825 /* Default number of entry guards in the case where the NumEntryGuards
2826 * consensus parameter is not set */
2827 #define DEFAULT_N_GUARDS 1
2828 /* Minimum and maximum number of entry guards (in case the NumEntryGuards
2829 * consensus parameter is set). */
2830 #define MIN_N_GUARDS 1
2831 #define MAX_N_GUARDS 10
2832 /** Largest amount that we'll backdate chosen_on_date */
2833 #define CHOSEN_ON_DATE_SLOP (30*86400)
2834 /** How long (in seconds) do we allow an entry guard to be nonfunctional,
2835 * unlisted, excluded, or otherwise nonusable before we give up on it? */
2836 #define ENTRY_GUARD_REMOVE_AFTER (30*24*60*60)
2840 * @name Networkstatus parameters for old (pre-prop271) guard selection
2843 /** Choose how many entry guards or directory guards we'll use. If
2844 * <b>for_directory</b> is true, we return how many directory guards to
2845 * use; else we return how many entry guards to use. */
2847 decide_num_guards(const or_options_t
*options
, int for_directory
)
2849 if (for_directory
) {
2851 if (options
->NumDirectoryGuards
!= 0)
2852 return options
->NumDirectoryGuards
;
2853 answer
= networkstatus_get_param(NULL
, "NumDirectoryGuards", 0, 0, 10);
2854 if (answer
) /* non-zero means use the consensus value */
2858 if (options
->NumEntryGuards
)
2859 return options
->NumEntryGuards
;
2861 /* Use the value from the consensus, or 3 if no guidance. */
2862 return networkstatus_get_param(NULL
, "NumEntryGuards", DEFAULT_N_GUARDS
,
2863 MIN_N_GUARDS
, MAX_N_GUARDS
);
2866 /** Check whether the entry guard <b>e</b> is usable, given the directory
2867 * authorities' opinion about the router (stored in <b>ri</b>) and the user's
2868 * configuration (in <b>options</b>). Set <b>e</b>->bad_since
2869 * accordingly. Return true iff the entry guard's status changes.
2871 * If it's not usable, set *<b>reason</b> to a static string explaining why.
2874 entry_guard_set_status(entry_guard_t
*e
, const node_t
*node
,
2875 time_t now
, const or_options_t
*options
,
2876 const char **reason
)
2878 char buf
[HEX_DIGEST_LEN
+1];
2883 /* Do we want to mark this guard as bad? */
2885 *reason
= "unlisted";
2886 else if (!node
->is_running
)
2888 else if (options
->UseBridges
&& (!node
->ri
||
2889 node
->ri
->purpose
!= ROUTER_PURPOSE_BRIDGE
))
2890 *reason
= "not a bridge";
2891 else if (options
->UseBridges
&& !node_is_a_configured_bridge(node
))
2892 *reason
= "not a configured bridge";
2893 else if (!options
->UseBridges
&& !node
->is_possible_guard
&&
2894 !routerset_contains_node(options
->EntryNodes
,node
))
2895 *reason
= "not recommended as a guard";
2896 else if (routerset_contains_node(options
->ExcludeNodes
, node
))
2897 *reason
= "excluded";
2898 /* We only care about OR connection connectivity for entry guards. */
2899 else if (!fascist_firewall_allows_node(node
, FIREWALL_OR_CONNECTION
, 0))
2900 *reason
= "unreachable by config";
2901 else if (e
->pb
.path_bias_disabled
)
2902 *reason
= "path-biased";
2904 if (*reason
&& ! e
->bad_since
) {
2905 /* Router is newly bad. */
2906 base16_encode(buf
, sizeof(buf
), e
->identity
, DIGEST_LEN
);
2907 log_info(LD_CIRC
, "Entry guard %s (%s) is %s: marking as unusable.",
2908 e
->nickname
, buf
, *reason
);
2911 control_event_guard(e
->nickname
, e
->identity
, "BAD");
2913 } else if (!*reason
&& e
->bad_since
) {
2914 /* There's nothing wrong with the router any more. */
2915 base16_encode(buf
, sizeof(buf
), e
->identity
, DIGEST_LEN
);
2916 log_info(LD_CIRC
, "Entry guard %s (%s) is no longer unusable: "
2917 "marking as ok.", e
->nickname
, buf
);
2920 control_event_guard(e
->nickname
, e
->identity
, "GOOD");
2925 int is_dir
= node_is_dir(node
);
2926 if (options
->UseBridges
&& node_is_a_configured_bridge(node
))
2928 if (e
->is_dir_cache
!= is_dir
) {
2929 e
->is_dir_cache
= is_dir
;
2937 /** Return true iff enough time has passed since we last tried to connect
2938 * to the unreachable guard <b>e</b> that we're willing to try again. */
2940 entry_is_time_to_retry(const entry_guard_t
*e
, time_t now
)
2942 struct guard_retry_period_s
{
2943 time_t period_duration
;
2944 time_t interval_during_period
;
2947 struct guard_retry_period_s periods
[] = {
2948 { 6*60*60, 60*60 }, /* For first 6 hrs., retry hourly; */
2949 { 3*24*60*60, 4*60*60 }, /* Then retry every 4 hrs. until the
2951 { 7*24*60*60, 18*60*60 }, /* After 3 days, retry every 18 hours until
2953 { TIME_MAX
, 36*60*60 } /* After 1 week, retry every 36 hours. */
2956 time_t ith_deadline_for_retry
;
2957 time_t unreachable_for
;
2960 if (e
->last_attempted
< e
->unreachable_since
)
2963 unreachable_for
= now
- e
->unreachable_since
;
2965 for (i
= 0; i
< ARRAY_LENGTH(periods
); i
++) {
2966 if (unreachable_for
<= periods
[i
].period_duration
) {
2967 ith_deadline_for_retry
= e
->last_attempted
+
2968 periods
[i
].interval_during_period
;
2970 return (now
> ith_deadline_for_retry
);
2976 /** Return the node corresponding to <b>e</b>, if <b>e</b> is
2977 * working well enough that we are willing to use it as an entry
2978 * right now. (Else return NULL.) In particular, it must be
2979 * - Listed as either up or never yet contacted;
2980 * - Present in the routerlist;
2981 * - Listed as 'stable' or 'fast' by the current dirserver consensus,
2982 * if demanded by <b>need_uptime</b> or <b>need_capacity</b>
2983 * (unless it's a configured EntryNode);
2984 * - Allowed by our current ReachableORAddresses config option; and
2985 * - Currently thought to be reachable by us (unless <b>assume_reachable</b>
2988 * If the answer is no, set *<b>msg</b> to an explanation of why.
2990 * If need_descriptor is true, only return the node if we currently have
2991 * a descriptor (routerinfo or microdesc) for it.
2993 STATIC
const node_t
*
2994 entry_is_live(const entry_guard_t
*e
, entry_is_live_flags_t flags
,
2998 const or_options_t
*options
= get_options();
2999 int need_uptime
= (flags
& ENTRY_NEED_UPTIME
) != 0;
3000 int need_capacity
= (flags
& ENTRY_NEED_CAPACITY
) != 0;
3001 const int assume_reachable
= (flags
& ENTRY_ASSUME_REACHABLE
) != 0;
3002 const int need_descriptor
= (flags
& ENTRY_NEED_DESCRIPTOR
) != 0;
3006 if (e
->pb
.path_bias_disabled
) {
3007 *msg
= "path-biased";
3014 /* no good if it's unreachable, unless assume_unreachable or can_retry. */
3015 if (!assume_reachable
&& !e
->can_retry
&&
3016 e
->unreachable_since
&& !entry_is_time_to_retry(e
, time(NULL
))) {
3017 *msg
= "unreachable";
3020 node
= node_get_by_id(e
->identity
);
3022 *msg
= "no node info";
3025 if (need_descriptor
&& !node_has_descriptor(node
)) {
3026 *msg
= "no descriptor";
3029 if (get_options()->UseBridges
) {
3030 if (node_get_purpose(node
) != ROUTER_PURPOSE_BRIDGE
) {
3031 *msg
= "not a bridge";
3034 if (!node_is_a_configured_bridge(node
)) {
3035 *msg
= "not a configured bridge";
3038 } else { /* !get_options()->UseBridges */
3039 if (node_get_purpose(node
) != ROUTER_PURPOSE_GENERAL
) {
3040 *msg
= "not general-purpose";
3044 if (routerset_contains_node(options
->EntryNodes
, node
)) {
3045 /* they asked for it, they get it */
3046 need_uptime
= need_capacity
= 0;
3048 if (node_is_unreliable(node
, need_uptime
, need_capacity
, 0)) {
3049 *msg
= "not fast/stable";
3052 if (!fascist_firewall_allows_node(node
, FIREWALL_OR_CONNECTION
, 0)) {
3053 *msg
= "unreachable by config";
3059 /** Return the number of entry guards that we think are usable, in the
3060 * context of the given guard_selection_t */
3062 num_live_entry_guards_for_guard_selection(guard_selection_t
*gs
,
3068 tor_assert(gs
!= NULL
);
3070 /* Set the entry node attributes we are interested in. */
3071 entry_is_live_flags_t entry_flags
= ENTRY_NEED_CAPACITY
;
3072 if (!for_directory
) {
3073 entry_flags
|= ENTRY_NEED_DESCRIPTOR
;
3076 if (!(gs
->chosen_entry_guards
)) {
3080 SMARTLIST_FOREACH_BEGIN(gs
->chosen_entry_guards
, entry_guard_t
*, entry
) {
3081 if (for_directory
&& !entry
->is_dir_cache
)
3083 if (entry_is_live(entry
, entry_flags
, &msg
))
3085 } SMARTLIST_FOREACH_END(entry
);
3089 /** Return the number of entry guards that we think are usable, for the
3090 * default guard selection */
3092 num_live_entry_guards(int for_directory
)
3094 return num_live_entry_guards_for_guard_selection(
3095 get_guard_selection_info(), for_directory
);
3098 /** If <b>digest</b> matches the identity of any node in the
3099 * entry_guards list for the provided guard selection state,
3100 return that node. Else return NULL. */
3102 entry_guard_get_by_id_digest_for_guard_selection(guard_selection_t
*gs
,
3105 tor_assert(gs
!= NULL
);
3107 SMARTLIST_FOREACH(gs
->sampled_entry_guards
, entry_guard_t
*, entry
,
3108 if (tor_memeq(digest
, entry
->identity
, DIGEST_LEN
))
3112 SMARTLIST_FOREACH(gs
->chosen_entry_guards
, entry_guard_t
*, entry
,
3113 if (tor_memeq(digest
, entry
->identity
, DIGEST_LEN
))
3119 /** Return the node_t associated with a single entry_guard_t. May
3120 * return NULL if the guard is not currently in the consensus. */
3122 entry_guard_find_node(const entry_guard_t
*guard
)
3125 return node_get_by_id(guard
->identity
);
3128 /** If <b>digest</b> matches the identity of any node in the
3129 * entry_guards list for the default guard selection state,
3130 return that node. Else return NULL. */
3132 entry_guard_get_by_id_digest(const char *digest
)
3134 return entry_guard_get_by_id_digest_for_guard_selection(
3135 get_guard_selection_info(), digest
);
3138 /** Dump a description of our list of entry guards in the given guard
3139 * selection context to the log at level <b>severity</b>. */
3141 log_entry_guards_for_guard_selection(guard_selection_t
*gs
, int severity
)
3143 smartlist_t
*elements
= smartlist_new();
3147 * TODO this should probably log more info about prop-271 state too
3148 * when it's implemented.
3151 tor_assert(gs
!= NULL
);
3153 SMARTLIST_FOREACH_BEGIN(gs
->chosen_entry_guards
, entry_guard_t
*, e
)
3155 const char *msg
= NULL
;
3156 if (entry_is_live(e
, ENTRY_NEED_CAPACITY
, &msg
))
3157 smartlist_add_asprintf(elements
, "%s [%s] (up %s)",
3159 hex_str(e
->identity
, DIGEST_LEN
),
3160 e
->made_contact
? "made-contact" : "never-contacted");
3162 smartlist_add_asprintf(elements
, "%s [%s] (%s, %s)",
3164 hex_str(e
->identity
, DIGEST_LEN
),
3166 e
->made_contact
? "made-contact" : "never-contacted");
3168 SMARTLIST_FOREACH_END(e
);
3170 s
= smartlist_join_strings(elements
, ",", 0, NULL
);
3171 SMARTLIST_FOREACH(elements
, char*, cp
, tor_free(cp
));
3172 smartlist_free(elements
);
3173 log_fn(severity
,LD_CIRC
,"%s",s
);
3177 /** Called when one or more guards that we would previously have used for some
3178 * purpose are no longer in use because a higher-priority guard has become
3181 control_event_guard_deferred(void)
3183 /* XXXX We don't actually have a good way to figure out _how many_ entries
3184 * are live for some purpose. We need an entry_is_even_slightly_live()
3185 * function for this to work right. NumEntryGuards isn't reliable: if we
3186 * need guards with weird properties, we can have more than that number
3192 const or_options_t
*options
= get_options();
3195 SMARTLIST_FOREACH(entry_guards
, entry_guard_t
*, entry
,
3197 if (entry_is_live(entry
, 0, 1, 0, &msg
)) {
3198 if (n
++ == options
->NumEntryGuards
) {
3199 control_event_guard(entry
->nickname
, entry
->identity
, "DEFERRED");
3207 /** Add a new (preferably stable and fast) router to our chosen_entry_guards
3208 * list for the supplied guard selection. Return a pointer to the router if
3209 * we succeed, or NULL if we can't find any more suitable entries.
3211 * If <b>chosen</b> is defined, use that one, and if it's not
3212 * already in our entry_guards list, put it at the *beginning*.
3213 * Else, put the one we pick at the end of the list. */
3214 STATIC
const node_t
*
3215 add_an_entry_guard(guard_selection_t
*gs
,
3216 const node_t
*chosen
, int reset_status
, int prepend
,
3217 int for_discovery
, int for_directory
)
3220 entry_guard_t
*entry
;
3222 tor_assert(gs
!= NULL
);
3223 tor_assert(gs
->chosen_entry_guards
!= NULL
);
3227 entry
= entry_guard_get_by_id_digest_for_guard_selection(gs
,
3231 entry
->bad_since
= 0;
3232 entry
->can_retry
= 1;
3234 entry
->is_dir_cache
= node_is_dir(node
);
3235 if (get_options()->UseBridges
&& node_is_a_configured_bridge(node
))
3236 entry
->is_dir_cache
= 1;
3240 } else if (!for_directory
) {
3241 node
= choose_good_entry_server(CIRCUIT_PURPOSE_C_GENERAL
, NULL
, NULL
);
3245 const routerstatus_t
*rs
;
3246 rs
= router_pick_directory_server(MICRODESC_DIRINFO
|V3_DIRINFO
,
3250 node
= node_get_by_id(rs
->identity_digest
);
3254 if (entry_guard_get_by_id_digest_for_guard_selection(gs
, node
->identity
)
3256 log_info(LD_CIRC
, "I was about to add a duplicate entry guard.");
3257 /* This can happen if we choose a guard, then the node goes away, then
3261 entry
= tor_malloc_zero(sizeof(entry_guard_t
));
3262 entry
->is_persistent
= 1;
3263 log_info(LD_CIRC
, "Chose %s as new entry guard.",
3264 node_describe(node
));
3265 strlcpy(entry
->nickname
, node_get_nickname(node
), sizeof(entry
->nickname
));
3266 memcpy(entry
->identity
, node
->identity
, DIGEST_LEN
);
3267 entry
->is_dir_cache
= node_is_dir(node
);
3268 if (get_options()->UseBridges
&& node_is_a_configured_bridge(node
))
3269 entry
->is_dir_cache
= 1;
3271 /* Choose expiry time smudged over the past month. The goal here
3272 * is to a) spread out when Tor clients rotate their guards, so they
3273 * don't all select them on the same day, and b) avoid leaving a
3274 * precise timestamp in the state file about when we first picked
3275 * this guard. For details, see the Jan 2010 or-dev thread. */
3276 time_t now
= time(NULL
);
3277 entry
->chosen_on_date
= crypto_rand_time_range(now
- 3600*24*30, now
);
3278 entry
->chosen_by_version
= tor_strdup(VERSION
);
3280 /* Are we picking this guard because all of our current guards are
3281 * down so we need another one (for_discovery is 1), or because we
3282 * decided we need more variety in our guard list (for_discovery is 0)?
3284 * Currently we hack this behavior into place by setting "made_contact"
3285 * for guards of the latter variety, so we'll be willing to use any of
3286 * them right off the bat.
3289 entry
->made_contact
= 1;
3292 smartlist_insert(gs
->chosen_entry_guards
, 0, entry
);
3294 smartlist_add(gs
->chosen_entry_guards
, entry
);
3295 entry
->in_selection
= gs
;
3297 control_event_guard(entry
->nickname
, entry
->identity
, "NEW");
3298 control_event_guard_deferred();
3299 log_entry_guards_for_guard_selection(gs
, LOG_INFO
);
3304 /** Entry point for bridges.c to add a bridge as guard.
3306 * XXXX prop271 refactor, bridge.*/
3308 add_bridge_as_entry_guard(guard_selection_t
*gs
,
3309 const node_t
*chosen
)
3311 add_an_entry_guard(gs
, chosen
, 1, 1, 0, 0);
3315 * Return the minimum lifetime of working entry guard, in seconds,
3316 * as given in the consensus networkstatus. (Plus CHOSEN_ON_DATE_SLOP,
3317 * so that we can do the chosen_on_date randomization while achieving the
3318 * desired minimum lifetime.)
3321 guards_get_lifetime(void)
3323 const or_options_t
*options
= get_options();
3324 #define DFLT_GUARD_LIFETIME (86400 * 60) /* Two months. */
3325 #define MIN_GUARD_LIFETIME (86400 * 30) /* One months. */
3326 #define MAX_GUARD_LIFETIME (86400 * 1826) /* Five years. */
3328 if (options
->GuardLifetime
>= 1) {
3329 return CLAMP(MIN_GUARD_LIFETIME
,
3330 options
->GuardLifetime
,
3331 MAX_GUARD_LIFETIME
) + CHOSEN_ON_DATE_SLOP
;
3334 return networkstatus_get_param(NULL
, "GuardLifetime",
3335 DFLT_GUARD_LIFETIME
,
3337 MAX_GUARD_LIFETIME
) + CHOSEN_ON_DATE_SLOP
;
3340 /** If the use of entry guards is configured, choose more entry guards
3341 * until we have enough in the list. */
3343 pick_entry_guards(guard_selection_t
*gs
,
3344 const or_options_t
*options
,
3348 const int num_needed
= decide_num_guards(options
, for_directory
);
3350 tor_assert(gs
!= NULL
);
3351 tor_assert(gs
->chosen_entry_guards
!= NULL
);
3353 while (num_live_entry_guards_for_guard_selection(gs
, for_directory
)
3355 if (!add_an_entry_guard(gs
, NULL
, 0, 0, 0, for_directory
))
3361 entry_guards_changed_for_guard_selection(gs
);
3364 /** Release all storage held by <b>e</b>. */
3366 entry_guard_free(entry_guard_t
*e
)
3370 entry_guard_handles_clear(e
);
3371 tor_free(e
->chosen_by_version
);
3372 tor_free(e
->sampled_by_version
);
3373 tor_free(e
->extra_state_fields
);
3374 tor_free(e
->selection_name
);
3375 tor_free(e
->bridge_addr
);
3379 /** Remove from a guard selection context any entry guard which was selected
3380 * by an unknown version of Tor, or which was selected by a version of Tor
3381 * that's known to select entry guards badly, or which was selected more 2
3383 /* XXXX The "obsolete guards" and "chosen long ago guards" things should
3384 * probably be different functions. */
3386 remove_obsolete_entry_guards(guard_selection_t
*gs
, time_t now
)
3389 int32_t guard_lifetime
= guards_get_lifetime();
3391 tor_assert(gs
!= NULL
);
3392 if (!(gs
->chosen_entry_guards
)) goto done
;
3394 for (i
= 0; i
< smartlist_len(gs
->chosen_entry_guards
); ++i
) {
3395 entry_guard_t
*entry
= smartlist_get(gs
->chosen_entry_guards
, i
);
3396 const char *ver
= entry
->chosen_by_version
;
3397 const char *msg
= NULL
;
3399 int version_is_bad
= 0, date_is_bad
= 0;
3401 msg
= "does not say what version of Tor it was selected by";
3403 } else if (tor_version_parse(ver
, &v
)) {
3404 msg
= "does not seem to be from any recognized version of Tor";
3407 if (!version_is_bad
&& entry
->chosen_on_date
+ guard_lifetime
< now
) {
3408 /* It's been too long since the date listed in our state file. */
3409 msg
= "was selected several months ago";
3413 if (version_is_bad
|| date_is_bad
) { /* we need to drop it */
3414 char dbuf
[HEX_DIGEST_LEN
+1];
3416 base16_encode(dbuf
, sizeof(dbuf
), entry
->identity
, DIGEST_LEN
);
3417 log_fn(version_is_bad
? LOG_NOTICE
: LOG_INFO
, LD_CIRC
,
3418 "Entry guard '%s' (%s) %s. (Version=%s.) Replacing it.",
3419 entry
->nickname
, dbuf
, msg
, ver
?escaped(ver
):"none");
3420 control_event_guard(entry
->nickname
, entry
->identity
, "DROPPED");
3421 entry_guard_free(entry
);
3422 smartlist_del_keeporder(gs
->chosen_entry_guards
, i
--);
3423 log_entry_guards_for_guard_selection(gs
, LOG_INFO
);
3429 return changed
? 1 : 0;
3432 /** Remove all entry guards from this guard selection context that have
3433 * been down or unlisted for so long that we don't think they'll come up
3434 * again. Return 1 if we removed any, or 0 if we did nothing. */
3436 remove_dead_entry_guards(guard_selection_t
*gs
, time_t now
)
3438 char dbuf
[HEX_DIGEST_LEN
+1];
3439 char tbuf
[ISO_TIME_LEN
+1];
3443 tor_assert(gs
!= NULL
);
3444 if (!(gs
->chosen_entry_guards
)) goto done
;
3446 for (i
= 0; i
< smartlist_len(gs
->chosen_entry_guards
); ) {
3447 entry_guard_t
*entry
= smartlist_get(gs
->chosen_entry_guards
, i
);
3448 if (entry
->bad_since
&&
3449 ! entry
->pb
.path_bias_disabled
&&
3450 entry
->bad_since
+ ENTRY_GUARD_REMOVE_AFTER
< now
) {
3452 base16_encode(dbuf
, sizeof(dbuf
), entry
->identity
, DIGEST_LEN
);
3453 format_local_iso_time(tbuf
, entry
->bad_since
);
3454 log_info(LD_CIRC
, "Entry guard '%s' (%s) has been down or unlisted "
3455 "since %s local time; removing.",
3456 entry
->nickname
, dbuf
, tbuf
);
3457 control_event_guard(entry
->nickname
, entry
->identity
, "DROPPED");
3458 entry_guard_free(entry
);
3459 smartlist_del_keeporder(gs
->chosen_entry_guards
, i
);
3460 log_entry_guards_for_guard_selection(gs
, LOG_INFO
);
3467 return changed
? 1 : 0;
3470 /** Remove all currently listed entry guards for a given guard selection
3473 remove_all_entry_guards_for_guard_selection(guard_selection_t
*gs
)
3475 char dbuf
[HEX_DIGEST_LEN
+1];
3477 tor_assert(gs
!= NULL
);
3479 if (gs
->chosen_entry_guards
) {
3480 while (smartlist_len(gs
->chosen_entry_guards
)) {
3481 entry_guard_t
*entry
= smartlist_get(gs
->chosen_entry_guards
, 0);
3482 base16_encode(dbuf
, sizeof(dbuf
), entry
->identity
, DIGEST_LEN
);
3483 log_info(LD_CIRC
, "Entry guard '%s' (%s) has been dropped.",
3484 entry
->nickname
, dbuf
);
3485 control_event_guard(entry
->nickname
, entry
->identity
, "DROPPED");
3486 entry_guard_free(entry
);
3487 smartlist_del(gs
->chosen_entry_guards
, 0);
3491 log_entry_guards_for_guard_selection(gs
, LOG_INFO
);
3492 entry_guards_changed_for_guard_selection(gs
);
3495 /** Remove all currently listed entry guards. So new ones will be chosen. */
3497 remove_all_entry_guards(void)
3499 // XXXX prop271 this function shouldn't exist, in the new order.
3500 remove_all_entry_guards_for_guard_selection(get_guard_selection_info());
3503 /** A new directory or router-status has arrived; update the down/listed
3504 * status of the entry guards.
3506 * An entry is 'down' if the directory lists it as nonrunning.
3507 * An entry is 'unlisted' if the directory doesn't include it.
3509 * Don't call this on startup; only on a fresh download. Otherwise we'll
3510 * think that things are unlisted.
3513 entry_guards_compute_status_for_guard_selection(guard_selection_t
*gs
,
3514 const or_options_t
*options
,
3518 digestmap_t
*reasons
;
3520 if ((!gs
) || !(gs
->chosen_entry_guards
))
3523 if (!get_options()->UseDeprecatedGuardAlgorithm
)
3526 if (options
->EntryNodes
) /* reshuffle the entry guard list if needed */
3527 entry_nodes_should_be_added();
3529 reasons
= digestmap_new();
3530 SMARTLIST_FOREACH_BEGIN(gs
->chosen_entry_guards
, entry_guard_t
*, entry
)
3532 const node_t
*r
= node_get_by_id(entry
->identity
);
3533 const char *reason
= NULL
;
3534 if (entry_guard_set_status(entry
, r
, now
, options
, &reason
))
3537 if (entry
->bad_since
)
3540 digestmap_set(reasons
, entry
->identity
, (char*)reason
);
3542 SMARTLIST_FOREACH_END(entry
);
3544 if (remove_dead_entry_guards(gs
, now
))
3546 if (remove_obsolete_entry_guards(gs
, now
))
3550 SMARTLIST_FOREACH_BEGIN(gs
->chosen_entry_guards
, entry_guard_t
*,
3552 const char *reason
= digestmap_get(reasons
, entry
->identity
);
3553 const char *live_msg
= "";
3554 const node_t
*r
= entry_is_live(entry
, ENTRY_NEED_CAPACITY
, &live_msg
);
3555 log_info(LD_CIRC
, "Summary: Entry %s [%s] is %s, %s%s%s, and %s%s.",
3557 hex_str(entry
->identity
, DIGEST_LEN
),
3558 entry
->unreachable_since
? "unreachable" : "reachable",
3559 entry
->bad_since
? "unusable" : "usable",
3561 reason
? reason
: "",
3562 r
? "live" : "not live / ",
3564 } SMARTLIST_FOREACH_END(entry
);
3565 log_info(LD_CIRC
, " (%d/%d entry guards are usable/new)",
3566 num_live_entry_guards_for_guard_selection(gs
, 0),
3567 smartlist_len(gs
->chosen_entry_guards
));
3568 log_entry_guards_for_guard_selection(gs
, LOG_INFO
);
3569 entry_guards_changed_for_guard_selection(gs
);
3572 digestmap_free(reasons
, NULL
);
3575 /** A new directory or router-status has arrived; update the down/listed
3576 * status of the entry guards.
3578 * An entry is 'down' if the directory lists it as nonrunning.
3579 * An entry is 'unlisted' if the directory doesn't include it.
3581 * Don't call this on startup; only on a fresh download. Otherwise we'll
3582 * think that things are unlisted.
3585 entry_guards_compute_status(const or_options_t
*options
, time_t now
)
3587 entry_guards_compute_status_for_guard_selection(get_guard_selection_info(),
3591 /** Called when a connection to an OR with the identity digest <b>digest</b>
3592 * is established (<b>succeeded</b>==1) or has failed (<b>succeeded</b>==0).
3593 * If the OR is an entry, change that entry's up/down status.
3594 * Return 0 normally, or -1 if we want to tear down the new connection.
3596 * If <b>mark_relay_status</b>, also call router_set_status() on this
3599 /* XXX We could change succeeded and mark_relay_status into 'int flags'.
3600 * Too many boolean arguments is a recipe for confusion.
3603 entry_guard_register_connect_status_for_guard_selection(
3604 guard_selection_t
*gs
, const char *digest
, int succeeded
,
3605 int mark_relay_status
, time_t now
)
3608 int refuse_conn
= 0;
3609 int first_contact
= 0;
3610 entry_guard_t
*entry
= NULL
;
3612 char buf
[HEX_DIGEST_LEN
+1];
3614 if (!(gs
) || !(gs
->chosen_entry_guards
)) {
3618 if (! get_options()->UseDeprecatedGuardAlgorithm
) {
3622 SMARTLIST_FOREACH_BEGIN(gs
->chosen_entry_guards
, entry_guard_t
*, e
) {
3624 if (tor_memeq(e
->identity
, digest
, DIGEST_LEN
)) {
3629 } SMARTLIST_FOREACH_END(e
);
3634 base16_encode(buf
, sizeof(buf
), entry
->identity
, DIGEST_LEN
);
3637 if (entry
->unreachable_since
) {
3638 log_info(LD_CIRC
, "Entry guard '%s' (%s) is now reachable again. Good.",
3639 entry
->nickname
, buf
);
3640 entry
->can_retry
= 0;
3641 entry
->unreachable_since
= 0;
3642 entry
->last_attempted
= now
;
3643 control_event_guard(entry
->nickname
, entry
->identity
, "UP");
3646 if (!entry
->made_contact
) {
3647 entry
->made_contact
= 1;
3648 first_contact
= changed
= 1;
3650 } else { /* ! succeeded */
3651 if (!entry
->made_contact
) {
3652 /* We've never connected to this one. */
3654 "Connection to never-contacted entry guard '%s' (%s) failed. "
3655 "Removing from the list. %d/%d entry guards usable/new.",
3656 entry
->nickname
, buf
,
3657 num_live_entry_guards_for_guard_selection(gs
, 0) - 1,
3658 smartlist_len(gs
->chosen_entry_guards
)-1);
3659 control_event_guard(entry
->nickname
, entry
->identity
, "DROPPED");
3660 entry_guard_free(entry
);
3661 smartlist_del_keeporder(gs
->chosen_entry_guards
, idx
);
3662 log_entry_guards_for_guard_selection(gs
, LOG_INFO
);
3664 } else if (!entry
->unreachable_since
) {
3665 log_info(LD_CIRC
, "Unable to connect to entry guard '%s' (%s). "
3666 "Marking as unreachable.", entry
->nickname
, buf
);
3667 entry
->unreachable_since
= entry
->last_attempted
= now
;
3668 control_event_guard(entry
->nickname
, entry
->identity
, "DOWN");
3670 entry
->can_retry
= 0; /* We gave it an early chance; no good. */
3672 char tbuf
[ISO_TIME_LEN
+1];
3673 format_iso_time(tbuf
, entry
->unreachable_since
);
3674 log_debug(LD_CIRC
, "Failed to connect to unreachable entry guard "
3675 "'%s' (%s). It has been unreachable since %s.",
3676 entry
->nickname
, buf
, tbuf
);
3677 entry
->last_attempted
= now
;
3678 entry
->can_retry
= 0; /* We gave it an early chance; no good. */
3682 /* if the caller asked us to, also update the is_running flags for this
3684 if (mark_relay_status
)
3685 router_set_status(digest
, succeeded
);
3687 if (first_contact
) {
3688 /* We've just added a new long-term entry guard. Perhaps the network just
3689 * came back? We should give our earlier entries another try too,
3690 * and close this connection so we don't use it before we've given
3691 * the others a shot. */
3692 SMARTLIST_FOREACH_BEGIN(gs
->chosen_entry_guards
, entry_guard_t
*, e
) {
3695 if (e
->made_contact
) {
3697 const node_t
*r
= entry_is_live(e
,
3698 ENTRY_NEED_CAPACITY
| ENTRY_ASSUME_REACHABLE
,
3700 if (r
&& e
->unreachable_since
) {
3705 } SMARTLIST_FOREACH_END(e
);
3708 "Connected to new entry guard '%s' (%s). Marking earlier "
3709 "entry guards up. %d/%d entry guards usable/new.",
3710 entry
->nickname
, buf
,
3711 num_live_entry_guards_for_guard_selection(gs
, 0),
3712 smartlist_len(gs
->chosen_entry_guards
));
3713 log_entry_guards_for_guard_selection(gs
, LOG_INFO
);
3719 entry_guards_changed_for_guard_selection(gs
);
3720 return refuse_conn
? -1 : 0;
3723 /** Called when a connection to an OR with the identity digest <b>digest</b>
3724 * is established (<b>succeeded</b>==1) or has failed (<b>succeeded</b>==0).
3725 * If the OR is an entry, change that entry's up/down status in the default
3726 * guard selection context.
3727 * Return 0 normally, or -1 if we want to tear down the new connection.
3729 * If <b>mark_relay_status</b>, also call router_set_status() on this
3733 entry_guard_register_connect_status(const char *digest
, int succeeded
,
3734 int mark_relay_status
, time_t now
)
3736 return entry_guard_register_connect_status_for_guard_selection(
3737 get_guard_selection_info(), digest
, succeeded
, mark_relay_status
, now
);
3740 /** Called when the value of EntryNodes changes in our configuration. */
3742 entry_nodes_should_be_added_for_guard_selection(guard_selection_t
*gs
)
3744 tor_assert(gs
!= NULL
);
3746 log_info(LD_CIRC
, "EntryNodes config option set. Putting configured "
3747 "relays at the front of the entry guard list.");
3748 gs
->should_add_entry_nodes
= 1;
3751 /** Called when the value of EntryNodes changes in our configuration. */
3753 entry_nodes_should_be_added(void)
3755 entry_nodes_should_be_added_for_guard_selection(
3756 get_guard_selection_info());
3759 /** Adjust the entry guards list so that it only contains entries from
3760 * EntryNodes, adding new entries from EntryNodes to the list as needed. */
3762 entry_guards_set_from_config(guard_selection_t
*gs
,
3763 const or_options_t
*options
)
3765 smartlist_t
*entry_nodes
, *worse_entry_nodes
, *entry_fps
;
3766 smartlist_t
*old_entry_guards_on_list
, *old_entry_guards_not_on_list
;
3767 const int numentryguards
= decide_num_guards(options
, 0);
3769 tor_assert(gs
!= NULL
);
3770 tor_assert(gs
->chosen_entry_guards
!= NULL
);
3772 gs
->should_add_entry_nodes
= 0;
3774 if (!options
->EntryNodes
) {
3775 /* It's possible that a controller set EntryNodes, thus making
3776 * should_add_entry_nodes set, then cleared it again, all before the
3777 * call to choose_random_entry() that triggered us. If so, just return.
3783 char *string
= routerset_to_string(options
->EntryNodes
);
3784 log_info(LD_CIRC
,"Adding configured EntryNodes '%s'.", string
);
3788 entry_nodes
= smartlist_new();
3789 worse_entry_nodes
= smartlist_new();
3790 entry_fps
= smartlist_new();
3791 old_entry_guards_on_list
= smartlist_new();
3792 old_entry_guards_not_on_list
= smartlist_new();
3794 /* Split entry guards into those on the list and those not. */
3796 routerset_get_all_nodes(entry_nodes
, options
->EntryNodes
,
3797 options
->ExcludeNodes
, 0);
3798 SMARTLIST_FOREACH(entry_nodes
, const node_t
*,node
,
3799 smartlist_add(entry_fps
, (void*)node
->identity
));
3801 SMARTLIST_FOREACH(gs
->chosen_entry_guards
, entry_guard_t
*, e
, {
3802 if (smartlist_contains_digest(entry_fps
, e
->identity
))
3803 smartlist_add(old_entry_guards_on_list
, e
);
3805 smartlist_add(old_entry_guards_not_on_list
, e
);
3808 /* Remove all currently configured guard nodes, excluded nodes, unreachable
3809 * nodes, or non-Guard nodes from entry_nodes. */
3810 SMARTLIST_FOREACH_BEGIN(entry_nodes
, const node_t
*, node
) {
3811 if (entry_guard_get_by_id_digest_for_guard_selection(gs
,
3813 SMARTLIST_DEL_CURRENT(entry_nodes
, node
);
3815 } else if (routerset_contains_node(options
->ExcludeNodes
, node
)) {
3816 SMARTLIST_DEL_CURRENT(entry_nodes
, node
);
3818 } else if (!fascist_firewall_allows_node(node
, FIREWALL_OR_CONNECTION
,
3820 SMARTLIST_DEL_CURRENT(entry_nodes
, node
);
3822 } else if (! node
->is_possible_guard
) {
3823 smartlist_add(worse_entry_nodes
, (node_t
*)node
);
3824 SMARTLIST_DEL_CURRENT(entry_nodes
, node
);
3826 } SMARTLIST_FOREACH_END(node
);
3828 /* Now build the new entry_guards list. */
3829 smartlist_clear(gs
->chosen_entry_guards
);
3830 /* First, the previously configured guards that are in EntryNodes. */
3831 smartlist_add_all(gs
->chosen_entry_guards
, old_entry_guards_on_list
);
3832 /* Next, scramble the rest of EntryNodes, putting the guards first. */
3833 smartlist_shuffle(entry_nodes
);
3834 smartlist_shuffle(worse_entry_nodes
);
3835 smartlist_add_all(entry_nodes
, worse_entry_nodes
);
3837 /* Next, the rest of EntryNodes */
3838 SMARTLIST_FOREACH_BEGIN(entry_nodes
, const node_t
*, node
) {
3839 add_an_entry_guard(gs
, node
, 0, 0, 1, 0);
3840 if (smartlist_len(gs
->chosen_entry_guards
) > numentryguards
* 10)
3842 } SMARTLIST_FOREACH_END(node
);
3843 log_notice(LD_GENERAL
, "%d entries in guards",
3844 smartlist_len(gs
->chosen_entry_guards
));
3845 /* Finally, free the remaining previously configured guards that are not in
3847 SMARTLIST_FOREACH(old_entry_guards_not_on_list
, entry_guard_t
*, e
,
3848 entry_guard_free(e
));
3850 smartlist_free(entry_nodes
);
3851 smartlist_free(worse_entry_nodes
);
3852 smartlist_free(entry_fps
);
3853 smartlist_free(old_entry_guards_on_list
);
3854 smartlist_free(old_entry_guards_not_on_list
);
3855 entry_guards_changed_for_guard_selection(gs
);
3858 /** Return 0 if we're fine adding arbitrary routers out of the
3859 * directory to our entry guard list, or return 1 if we have a
3860 * list already and we must stick to it.
3863 entry_list_is_constrained(const or_options_t
*options
)
3865 if (options
->EntryNodes
)
3867 if (options
->UseBridges
)
3872 /** Pick a live (up and listed) entry guard from entry_guards. If
3873 * <b>state</b> is non-NULL, this is for a specific circuit --
3874 * make sure not to pick this circuit's exit or any node in the
3875 * exit's family. If <b>state</b> is NULL, we're looking for a random
3876 * guard (likely a bridge). If <b>dirinfo</b> is not NO_DIRINFO (zero),
3877 * then only select from nodes that know how to answer directory questions
3880 choose_random_entry(cpath_build_state_t
*state
)
3882 tor_assert(get_options()->UseDeprecatedGuardAlgorithm
);
3884 return choose_random_entry_impl(get_guard_selection_info(),
3885 state
, 0, NO_DIRINFO
, NULL
);
3888 /** Pick a live (up and listed) directory guard from entry_guards for
3889 * downloading information of type <b>type</b>. */
3891 choose_random_dirguard(dirinfo_type_t type
)
3893 tor_assert(get_options()->UseDeprecatedGuardAlgorithm
);
3895 return choose_random_entry_impl(get_guard_selection_info(),
3896 NULL
, 1, type
, NULL
);
3899 /** Return the number of bridges that have descriptors that are marked with
3900 * purpose 'bridge' and are running.
3903 num_bridges_usable(void)
3907 if (get_options()->UseDeprecatedGuardAlgorithm
) {
3909 tor_assert(get_options()->UseBridges
);
3910 (void) choose_random_entry_impl(get_guard_selection_info(),
3911 NULL
, 0, 0, &n_options
);
3913 /* XXXX prop271 Is this quite right? */
3914 tor_assert(get_options()->UseBridges
);
3915 guard_selection_t
*gs
= get_guard_selection_info();
3916 tor_assert(gs
->type
== GS_TYPE_BRIDGE
);
3918 SMARTLIST_FOREACH_BEGIN(gs
->sampled_entry_guards
, entry_guard_t
*, guard
) {
3919 if (guard
->is_reachable
== GUARD_REACHABLE_NO
)
3921 if (tor_digest_is_zero(guard
->identity
))
3923 const node_t
*node
= node_get_by_id(guard
->identity
);
3924 if (node
&& node
->ri
)
3926 } SMARTLIST_FOREACH_END(guard
);
3932 /** Filter <b>all_entry_guards</b> for usable entry guards and put them
3933 * in <b>live_entry_guards</b>. We filter based on whether the node is
3934 * currently alive, and on whether it satisfies the restrictions
3935 * imposed by the other arguments of this function.
3937 * We don't place more guards than NumEntryGuards in <b>live_entry_guards</b>.
3939 * If <b>chosen_exit</b> is set, it contains the exit node of this
3940 * circuit. Make sure to not use it or its family as an entry guard.
3942 * If <b>need_uptime</b> is set, we are looking for a stable entry guard.
3943 * if <b>need_capacity</b> is set, we are looking for a fast entry guard.
3945 * The rest of the arguments are the same as in choose_random_entry_impl().
3947 * Return 1 if we should choose a guard right away. Return 0 if we
3948 * should try to add more nodes to our list before deciding on a
3952 populate_live_entry_guards(smartlist_t
*live_entry_guards
,
3953 const smartlist_t
*all_entry_guards
,
3954 const node_t
*chosen_exit
,
3955 dirinfo_type_t dirinfo_type
,
3957 int need_uptime
, int need_capacity
)
3959 const or_options_t
*options
= get_options();
3960 const node_t
*node
= NULL
;
3961 const int num_needed
= decide_num_guards(options
, for_directory
);
3962 smartlist_t
*exit_family
= smartlist_new();
3964 entry_is_live_flags_t entry_flags
= 0;
3966 (void) dirinfo_type
;
3968 { /* Set the flags we want our entry node to have */
3970 entry_flags
|= ENTRY_NEED_UPTIME
;
3972 if (need_capacity
) {
3973 entry_flags
|= ENTRY_NEED_CAPACITY
;
3975 if (!for_directory
) {
3976 entry_flags
|= ENTRY_NEED_DESCRIPTOR
;
3980 tor_assert(all_entry_guards
);
3983 nodelist_add_node_and_family(exit_family
, chosen_exit
);
3986 SMARTLIST_FOREACH_BEGIN(all_entry_guards
, const entry_guard_t
*, entry
) {
3988 node
= entry_is_live(entry
, entry_flags
, &msg
);
3990 continue; /* down, no point */
3991 if (for_directory
) {
3992 if (!entry
->is_dir_cache
)
3993 continue; /* We need a directory and didn't get one. */
3995 if (node
== chosen_exit
)
3996 continue; /* don't pick the same node for entry and exit */
3997 if (smartlist_contains(exit_family
, node
))
3998 continue; /* avoid relays that are family members of our exit */
3999 smartlist_add(live_entry_guards
, (void*)node
);
4000 if (!entry
->made_contact
) {
4001 /* Always start with the first not-yet-contacted entry
4002 * guard. Otherwise we might add several new ones, pick
4003 * the second new one, and now we've expanded our entry
4004 * guard list without needing to. */
4008 if (smartlist_len(live_entry_guards
) >= num_needed
) {
4010 goto done
; /* We picked enough entry guards. Done! */
4012 } SMARTLIST_FOREACH_END(entry
);
4015 smartlist_free(exit_family
);
4020 /** Pick a node to be used as the entry guard of a circuit, relative to
4021 * a supplied guard selection context.
4023 * If <b>state</b> is set, it contains the information we know about
4024 * the upcoming circuit.
4026 * If <b>for_directory</b> is set, we are looking for a directory guard.
4028 * <b>dirinfo_type</b> contains the kind of directory information we
4029 * are looking for in our node, or NO_DIRINFO (zero) if we are not
4030 * looking for any particular directory information (when set to
4031 * NO_DIRINFO, the <b>dirinfo_type</b> filter is ignored).
4033 * If <b>n_options_out</b> is set, we set it to the number of
4034 * candidate guard nodes we had before picking a specific guard node.
4036 * On success, return the node that should be used as the entry guard
4037 * of the circuit. Return NULL if no such node could be found.
4039 * Helper for choose_random{entry,dirguard}.
4041 static const node_t
*
4042 choose_random_entry_impl(guard_selection_t
*gs
,
4043 cpath_build_state_t
*state
, int for_directory
,
4044 dirinfo_type_t dirinfo_type
, int *n_options_out
)
4046 const or_options_t
*options
= get_options();
4047 smartlist_t
*live_entry_guards
= smartlist_new();
4048 const node_t
*chosen_exit
=
4049 state
?build_state_get_exit_node(state
) : NULL
;
4050 const node_t
*node
= NULL
;
4051 int need_uptime
= state
? state
->need_uptime
: 0;
4052 int need_capacity
= state
? state
->need_capacity
: 0;
4053 int preferred_min
= 0;
4054 const int num_needed
= decide_num_guards(options
, for_directory
);
4057 tor_assert(gs
!= NULL
);
4058 tor_assert(gs
->chosen_entry_guards
!= NULL
);
4063 if (gs
->should_add_entry_nodes
)
4064 entry_guards_set_from_config(gs
, options
);
4066 if (!entry_list_is_constrained(options
) &&
4067 smartlist_len(gs
->chosen_entry_guards
) < num_needed
)
4068 pick_entry_guards(gs
, options
, for_directory
);
4071 smartlist_clear(live_entry_guards
);
4073 /* Populate the list of live entry guards so that we pick one of
4075 retval
= populate_live_entry_guards(live_entry_guards
,
4076 gs
->chosen_entry_guards
,
4080 need_uptime
, need_capacity
);
4082 if (retval
== 1) { /* We should choose a guard right now. */
4083 goto choose_and_finish
;
4086 if (entry_list_is_constrained(options
)) {
4087 /* If we prefer the entry nodes we've got, and we have at least
4088 * one choice, that's great. Use it. */
4091 /* Try to have at least 2 choices available. This way we don't
4092 * get stuck with a single live-but-crummy entry and just keep
4094 * (We might get 2 live-but-crummy entry guards, but so be it.) */
4098 if (smartlist_len(live_entry_guards
) < preferred_min
) {
4099 if (!entry_list_is_constrained(options
)) {
4100 /* still no? try adding a new entry then */
4101 /* XXX if guard doesn't imply fast and stable, then we need
4102 * to tell add_an_entry_guard below what we want, or it might
4103 * be a long time til we get it. -RD */
4104 node
= add_an_entry_guard(gs
, NULL
, 0, 0, 1, for_directory
);
4106 entry_guards_changed_for_guard_selection(gs
);
4107 /* XXX we start over here in case the new node we added shares
4108 * a family with our exit node. There's a chance that we'll just
4109 * load up on entry guards here, if the network we're using is
4110 * one big family. Perhaps we should teach add_an_entry_guard()
4111 * to understand nodes-to-avoid-if-possible? -RD */
4115 if (!node
&& need_uptime
) {
4116 need_uptime
= 0; /* try without that requirement */
4119 if (!node
&& need_capacity
) {
4120 /* still no? last attempt, try without requiring capacity */
4125 /* live_entry_guards may be empty below. Oh well, we tried. */
4129 if (entry_list_is_constrained(options
)) {
4130 /* We need to weight by bandwidth, because our bridges or entryguards
4131 * were not already selected proportional to their bandwidth. */
4132 node
= node_sl_choose_by_bandwidth(live_entry_guards
, WEIGHT_FOR_GUARD
);
4134 /* We choose uniformly at random here, because choose_good_entry_server()
4135 * already weights its choices by bandwidth, so we don't want to
4136 * *double*-weight our guard selection. */
4137 node
= smartlist_choose(live_entry_guards
);
4140 *n_options_out
= smartlist_len(live_entry_guards
);
4141 smartlist_free(live_entry_guards
);
4146 pathbias_check_use_success_count(entry_guard_t
*node
)
4148 const or_options_t
*options
= get_options();
4149 const double EPSILON
= 1.0e-9;
4151 /* Note: We rely on the < comparison here to allow us to set a 0
4152 * rate and disable the feature entirely. If refactoring, don't
4154 if (node
->pb
.use_attempts
> EPSILON
&&
4155 pathbias_get_use_success_count(node
)/node
->pb
.use_attempts
4156 < pathbias_get_extreme_use_rate(options
) &&
4157 pathbias_get_dropguards(options
)) {
4158 node
->pb
.path_bias_disabled
= 1;
4159 log_info(LD_GENERAL
,
4160 "Path use bias is too high (%f/%f); disabling node %s",
4161 node
->pb
.circ_successes
, node
->pb
.circ_attempts
,
4167 pathbias_check_close_success_count(entry_guard_t
*node
)
4169 const or_options_t
*options
= get_options();
4170 const double EPSILON
= 1.0e-9;
4172 /* Note: We rely on the < comparison here to allow us to set a 0
4173 * rate and disable the feature entirely. If refactoring, don't
4175 if (node
->pb
.circ_attempts
> EPSILON
&&
4176 pathbias_get_close_success_count(node
)/node
->pb
.circ_attempts
4177 < pathbias_get_extreme_rate(options
) &&
4178 pathbias_get_dropguards(options
)) {
4179 node
->pb
.path_bias_disabled
= 1;
4180 log_info(LD_GENERAL
,
4181 "Path bias is too high (%f/%f); disabling node %s",
4182 node
->pb
.circ_successes
, node
->pb
.circ_attempts
,
4187 /** Parse <b>state</b> and learn about the entry guards it describes.
4188 * If <b>set</b> is true, and there are no errors, replace the guard
4189 * list in the provided guard selection context with what we find.
4190 * On success, return 0. On failure, alloc into *<b>msg</b> a string
4191 * describing the error, and return -1.
4194 entry_guards_parse_state_for_guard_selection(
4195 guard_selection_t
*gs
,
4196 or_state_t
*state
, int set
, char **msg
)
4198 entry_guard_t
*node
= NULL
;
4199 smartlist_t
*new_entry_guards
= smartlist_new();
4200 config_line_t
*line
;
4201 time_t now
= time(NULL
);
4202 const char *state_version
= state
->TorVersion
;
4203 digestmap_t
*added_by
= digestmap_new();
4205 tor_assert(gs
!= NULL
);
4208 for (line
= state
->EntryGuards
; line
; line
= line
->next
) {
4209 if (!strcasecmp(line
->key
, "EntryGuard")) {
4210 smartlist_t
*args
= smartlist_new();
4211 node
= tor_malloc_zero(sizeof(entry_guard_t
));
4212 /* all entry guards on disk have been contacted */
4213 node
->made_contact
= 1;
4214 node
->is_persistent
= 1;
4215 smartlist_add(new_entry_guards
, node
);
4216 smartlist_split_string(args
, line
->value
, " ",
4217 SPLIT_SKIP_SPACE
|SPLIT_IGNORE_BLANK
, 0);
4218 if (smartlist_len(args
)<2) {
4219 *msg
= tor_strdup("Unable to parse entry nodes: "
4220 "Too few arguments to EntryGuard");
4221 } else if (!is_legal_nickname(smartlist_get(args
,0))) {
4222 *msg
= tor_strdup("Unable to parse entry nodes: "
4223 "Bad nickname for EntryGuard");
4225 strlcpy(node
->nickname
, smartlist_get(args
,0), MAX_NICKNAME_LEN
+1);
4226 if (base16_decode(node
->identity
, DIGEST_LEN
, smartlist_get(args
,1),
4227 strlen(smartlist_get(args
,1))) != DIGEST_LEN
) {
4228 *msg
= tor_strdup("Unable to parse entry nodes: "
4229 "Bad hex digest for EntryGuard");
4232 if (smartlist_len(args
) >= 3) {
4233 const char *is_cache
= smartlist_get(args
, 2);
4234 if (!strcasecmp(is_cache
, "DirCache")) {
4235 node
->is_dir_cache
= 1;
4236 } else if (!strcasecmp(is_cache
, "NoDirCache")) {
4237 node
->is_dir_cache
= 0;
4239 log_warn(LD_CONFIG
, "Bogus third argument to EntryGuard line: %s",
4243 SMARTLIST_FOREACH(args
, char*, cp
, tor_free(cp
));
4244 smartlist_free(args
);
4247 } else if (!strcasecmp(line
->key
, "EntryGuardDownSince") ||
4248 !strcasecmp(line
->key
, "EntryGuardUnlistedSince")) {
4250 time_t last_try
= 0;
4252 *msg
= tor_strdup("Unable to parse entry nodes: "
4253 "EntryGuardDownSince/UnlistedSince without EntryGuard");
4256 if (parse_iso_time_(line
->value
, &when
, 0, 0)<0) {
4257 *msg
= tor_strdup("Unable to parse entry nodes: "
4258 "Bad time in EntryGuardDownSince/UnlistedSince");
4262 /* It's a bad idea to believe info in the future: you can wind
4263 * up with timeouts that aren't allowed to happen for years. */
4266 if (strlen(line
->value
) >= ISO_TIME_LEN
+ISO_TIME_LEN
+1) {
4267 /* ignore failure */
4268 (void) parse_iso_time(line
->value
+ISO_TIME_LEN
+1, &last_try
);
4270 if (!strcasecmp(line
->key
, "EntryGuardDownSince")) {
4271 node
->unreachable_since
= when
;
4272 node
->last_attempted
= last_try
;
4274 node
->bad_since
= when
;
4276 } else if (!strcasecmp(line
->key
, "EntryGuardAddedBy")) {
4278 /* format is digest version date */
4279 if (strlen(line
->value
) < HEX_DIGEST_LEN
+1+1+1+ISO_TIME_LEN
) {
4280 log_warn(LD_BUG
, "EntryGuardAddedBy line is not long enough.");
4283 if (base16_decode(d
, sizeof(d
),
4284 line
->value
, HEX_DIGEST_LEN
) != sizeof(d
) ||
4285 line
->value
[HEX_DIGEST_LEN
] != ' ') {
4286 log_warn(LD_BUG
, "EntryGuardAddedBy line %s does not begin with "
4287 "hex digest", escaped(line
->value
));
4290 digestmap_set(added_by
, d
, tor_strdup(line
->value
+HEX_DIGEST_LEN
+1));
4291 } else if (!strcasecmp(line
->key
, "EntryGuardPathUseBias")) {
4292 double use_cnt
, success_cnt
;
4295 *msg
= tor_strdup("Unable to parse entry nodes: "
4296 "EntryGuardPathUseBias without EntryGuard");
4300 if (tor_sscanf(line
->value
, "%lf %lf",
4301 &use_cnt
, &success_cnt
) != 2) {
4302 log_info(LD_GENERAL
, "Malformed path use bias line for node %s",
4307 if (use_cnt
< success_cnt
) {
4308 int severity
= LOG_INFO
;
4309 /* If this state file was written by a Tor that would have
4310 * already fixed it, then the overcounting bug is still there.. */
4311 if (tor_version_as_new_as(state_version
, "0.2.4.13-alpha")) {
4312 severity
= LOG_NOTICE
;
4314 log_fn(severity
, LD_BUG
,
4315 "State file contains unexpectedly high usage success "
4316 "counts %lf/%lf for Guard %s ($%s)",
4317 success_cnt
, use_cnt
,
4318 node
->nickname
, hex_str(node
->identity
, DIGEST_LEN
));
4319 success_cnt
= use_cnt
;
4322 node
->pb
.use_attempts
= use_cnt
;
4323 node
->pb
.use_successes
= success_cnt
;
4325 log_info(LD_GENERAL
, "Read %f/%f path use bias for node %s",
4326 node
->pb
.use_successes
, node
->pb
.use_attempts
, node
->nickname
);
4328 pathbias_check_use_success_count(node
);
4330 } else if (!strcasecmp(line
->key
, "EntryGuardPathBias")) {
4331 double hop_cnt
, success_cnt
, timeouts
, collapsed
, successful_closed
,
4335 *msg
= tor_strdup("Unable to parse entry nodes: "
4336 "EntryGuardPathBias without EntryGuard");
4340 /* First try 3 params, then 2. */
4341 /* In the long run: circuit_success ~= successful_circuit_close +
4342 * collapsed_circuits +
4343 * unusable_circuits */
4344 if (tor_sscanf(line
->value
, "%lf %lf %lf %lf %lf %lf",
4345 &hop_cnt
, &success_cnt
, &successful_closed
,
4346 &collapsed
, &unusable
, &timeouts
) != 6) {
4347 int old_success
, old_hops
;
4348 if (tor_sscanf(line
->value
, "%u %u", &old_success
, &old_hops
) != 2) {
4351 log_info(LD_GENERAL
, "Reading old-style EntryGuardPathBias %s",
4352 escaped(line
->value
));
4354 success_cnt
= old_success
;
4355 successful_closed
= old_success
;
4362 if (hop_cnt
< success_cnt
) {
4363 int severity
= LOG_INFO
;
4364 /* If this state file was written by a Tor that would have
4365 * already fixed it, then the overcounting bug is still there.. */
4366 if (tor_version_as_new_as(state_version
, "0.2.4.13-alpha")) {
4367 severity
= LOG_NOTICE
;
4369 log_fn(severity
, LD_BUG
,
4370 "State file contains unexpectedly high success counts "
4371 "%lf/%lf for Guard %s ($%s)",
4372 success_cnt
, hop_cnt
,
4373 node
->nickname
, hex_str(node
->identity
, DIGEST_LEN
));
4374 success_cnt
= hop_cnt
;
4377 node
->pb
.circ_attempts
= hop_cnt
;
4378 node
->pb
.circ_successes
= success_cnt
;
4380 node
->pb
.successful_circuits_closed
= successful_closed
;
4381 node
->pb
.timeouts
= timeouts
;
4382 node
->pb
.collapsed_circuits
= collapsed
;
4383 node
->pb
.unusable_circuits
= unusable
;
4385 log_info(LD_GENERAL
, "Read %f/%f path bias for node %s",
4386 node
->pb
.circ_successes
, node
->pb
.circ_attempts
,
4389 pathbias_check_close_success_count(node
);
4391 log_warn(LD_BUG
, "Unexpected key %s", line
->key
);
4395 SMARTLIST_FOREACH_BEGIN(new_entry_guards
, entry_guard_t
*, e
) {
4397 char *val
= digestmap_get(added_by
, e
->identity
);
4398 if (val
&& (sp
= strchr(val
, ' '))) {
4401 if (parse_iso_time(sp
, &when
)<0) {
4402 log_warn(LD_BUG
, "Can't read time %s in EntryGuardAddedBy", sp
);
4404 e
->chosen_by_version
= tor_strdup(val
);
4405 e
->chosen_on_date
= when
;
4408 if (state_version
) {
4409 e
->chosen_on_date
= crypto_rand_time_range(now
- 3600*24*30, now
);
4410 e
->chosen_by_version
= tor_strdup(state_version
);
4413 if (e
->pb
.path_bias_disabled
&& !e
->bad_since
)
4414 e
->bad_since
= time(NULL
);
4416 SMARTLIST_FOREACH_END(e
);
4419 SMARTLIST_FOREACH(new_entry_guards
, entry_guard_t
*, e
,
4420 entry_guard_free(e
));
4421 smartlist_free(new_entry_guards
);
4422 } else { /* !err && set */
4423 if (gs
->chosen_entry_guards
) {
4424 SMARTLIST_FOREACH(gs
->chosen_entry_guards
, entry_guard_t
*, e
,
4425 entry_guard_free(e
));
4426 smartlist_free(gs
->chosen_entry_guards
);
4428 gs
->chosen_entry_guards
= new_entry_guards
;
4429 SMARTLIST_FOREACH(new_entry_guards
, entry_guard_t
*, e
,
4430 e
->in_selection
= gs
);
4432 /* XXX hand new_entry_guards to this func, and move it up a
4433 * few lines, so we don't have to re-dirty it */
4434 if (remove_obsolete_entry_guards(gs
, now
))
4435 entry_guards_dirty
= 1;
4437 digestmap_free(added_by
, tor_free_
);
4438 return *msg
? -1 : 0;
4441 /** Parse <b>state</b> and learn about the entry guards it describes.
4442 * If <b>set</b> is true, and there are no errors, replace the guard
4443 * list in the default guard selection context with what we find.
4444 * On success, return 0. On failure, alloc into *<b>msg</b> a string
4445 * describing the error, and return -1.
4448 entry_guards_parse_state(or_state_t
*state
, int set
, char **msg
)
4450 entry_guards_dirty
= 0;
4452 int r1
= entry_guards_load_guards_from_state(state
, set
);
4454 int r2
= entry_guards_parse_state_for_guard_selection(
4455 get_guard_selection_by_name("legacy", GS_TYPE_LEGACY
, 1),
4458 entry_guards_dirty
= 0;
4460 if (r1
< 0 || r2
< 0) {
4461 if (msg
&& *msg
== NULL
) {
4462 *msg
= tor_strdup("parsing error"); //xxxx prop271 should we try harder?
4469 /** How long will we let a change in our guard nodes stay un-saved
4470 * when we are trying to avoid disk writes? */
4471 #define SLOW_GUARD_STATE_FLUSH_TIME 600
4472 /** How long will we let a change in our guard nodes stay un-saved
4473 * when we are not trying to avoid disk writes? */
4474 #define FAST_GUARD_STATE_FLUSH_TIME 30
4476 /** Our list of entry guards has changed for a particular guard selection
4477 * context, or some element of one of our entry guards has changed for one.
4478 * Write the changes to disk within the next few minutes.
4481 entry_guards_changed_for_guard_selection(guard_selection_t
*gs
)
4485 tor_assert(gs
!= NULL
);
4487 entry_guards_dirty
= 1;
4489 if (get_options()->AvoidDiskWrites
)
4490 when
= time(NULL
) + SLOW_GUARD_STATE_FLUSH_TIME
;
4492 when
= time(NULL
) + FAST_GUARD_STATE_FLUSH_TIME
;
4494 /* or_state_save() will call entry_guards_update_state() and
4495 entry_guards_update_guards_in_state()
4497 or_state_mark_dirty(get_or_state(), when
);
4500 /** Our list of entry guards has changed for the default guard selection
4501 * context, or some element of one of our entry guards has changed. Write
4502 * the changes to disk within the next few minutes.
4505 entry_guards_changed(void)
4507 entry_guards_changed_for_guard_selection(get_guard_selection_info());
4510 /** If the entry guard info has not changed, do nothing and return.
4511 * Otherwise, free the EntryGuards piece of <b>state</b> and create
4512 * a new one out of the global entry_guards list, and then mark
4513 * <b>state</b> dirty so it will get saved to disk.
4516 entry_guards_update_state(or_state_t
*state
)
4518 config_line_t
**next
, *line
;
4520 entry_guards_dirty
= 0;
4522 // Handles all non-legacy guard info.
4523 entry_guards_update_guards_in_state(state
);
4525 entry_guards_dirty
= 0;
4527 guard_selection_t
*gs
;
4528 gs
= get_guard_selection_by_name("legacy", GS_TYPE_LEGACY
, 0);
4530 return; // nothign to save.
4531 tor_assert(gs
->chosen_entry_guards
!= NULL
);
4533 config_free_lines(state
->EntryGuards
);
4534 next
= &state
->EntryGuards
;
4536 SMARTLIST_FOREACH_BEGIN(gs
->chosen_entry_guards
, entry_guard_t
*, e
) {
4537 char dbuf
[HEX_DIGEST_LEN
+1];
4538 if (!e
->made_contact
)
4539 continue; /* don't write this one to disk */
4540 *next
= line
= tor_malloc_zero(sizeof(config_line_t
));
4541 line
->key
= tor_strdup("EntryGuard");
4542 base16_encode(dbuf
, sizeof(dbuf
), e
->identity
, DIGEST_LEN
);
4543 tor_asprintf(&line
->value
, "%s %s %sDirCache", e
->nickname
, dbuf
,
4544 e
->is_dir_cache
? "" : "No");
4545 next
= &(line
->next
);
4546 if (e
->unreachable_since
) {
4547 *next
= line
= tor_malloc_zero(sizeof(config_line_t
));
4548 line
->key
= tor_strdup("EntryGuardDownSince");
4549 line
->value
= tor_malloc(ISO_TIME_LEN
+1+ISO_TIME_LEN
+1);
4550 format_iso_time(line
->value
, e
->unreachable_since
);
4551 if (e
->last_attempted
) {
4552 line
->value
[ISO_TIME_LEN
] = ' ';
4553 format_iso_time(line
->value
+ISO_TIME_LEN
+1, e
->last_attempted
);
4555 next
= &(line
->next
);
4558 *next
= line
= tor_malloc_zero(sizeof(config_line_t
));
4559 line
->key
= tor_strdup("EntryGuardUnlistedSince");
4560 line
->value
= tor_malloc(ISO_TIME_LEN
+1);
4561 format_iso_time(line
->value
, e
->bad_since
);
4562 next
= &(line
->next
);
4564 if (e
->chosen_on_date
&& e
->chosen_by_version
&&
4565 !strchr(e
->chosen_by_version
, ' ')) {
4566 char d
[HEX_DIGEST_LEN
+1];
4567 char t
[ISO_TIME_LEN
+1];
4568 *next
= line
= tor_malloc_zero(sizeof(config_line_t
));
4569 line
->key
= tor_strdup("EntryGuardAddedBy");
4570 base16_encode(d
, sizeof(d
), e
->identity
, DIGEST_LEN
);
4571 format_iso_time(t
, e
->chosen_on_date
);
4572 tor_asprintf(&line
->value
, "%s %s %s",
4573 d
, e
->chosen_by_version
, t
);
4574 next
= &(line
->next
);
4576 if (e
->pb
.circ_attempts
> 0) {
4577 *next
= line
= tor_malloc_zero(sizeof(config_line_t
));
4578 line
->key
= tor_strdup("EntryGuardPathBias");
4579 /* In the long run: circuit_success ~= successful_circuit_close +
4580 * collapsed_circuits +
4581 * unusable_circuits */
4582 tor_asprintf(&line
->value
, "%f %f %f %f %f %f",
4583 e
->pb
.circ_attempts
, e
->pb
.circ_successes
,
4584 pathbias_get_close_success_count(e
),
4585 e
->pb
.collapsed_circuits
,
4586 e
->pb
.unusable_circuits
, e
->pb
.timeouts
);
4587 next
= &(line
->next
);
4589 if (e
->pb
.use_attempts
> 0) {
4590 *next
= line
= tor_malloc_zero(sizeof(config_line_t
));
4591 line
->key
= tor_strdup("EntryGuardPathUseBias");
4593 tor_asprintf(&line
->value
, "%f %f",
4595 pathbias_get_use_success_count(e
));
4596 next
= &(line
->next
);
4599 } SMARTLIST_FOREACH_END(e
);
4600 if (!get_options()->AvoidDiskWrites
)
4601 or_state_mark_dirty(get_or_state(), 0);
4602 entry_guards_dirty
= 0;
4605 /** If <b>question</b> is the string "entry-guards", then dump
4606 * to *<b>answer</b> a newly allocated string describing all of
4607 * the nodes in the global entry_guards list. See control-spec.txt
4609 * For backward compatibility, we also handle the string "helper-nodes".
4611 * XXX this should be totally redesigned after prop 271 too, and that's
4612 * going to take some control spec work.
4615 getinfo_helper_entry_guards(control_connection_t
*conn
,
4616 const char *question
, char **answer
,
4617 const char **errmsg
)
4619 guard_selection_t
*gs
= get_guard_selection_info();
4621 tor_assert(gs
!= NULL
);
4622 tor_assert(gs
->chosen_entry_guards
!= NULL
);
4627 if (!strcmp(question
,"entry-guards") ||
4628 !strcmp(question
,"helper-nodes")) {
4629 smartlist_t
*sl
= smartlist_new();
4630 char tbuf
[ISO_TIME_LEN
+1];
4631 char nbuf
[MAX_VERBOSE_NICKNAME_LEN
+1];
4633 SMARTLIST_FOREACH_BEGIN(gs
->chosen_entry_guards
, entry_guard_t
*, e
) {
4634 const char *status
= NULL
;
4638 if (!e
->made_contact
) {
4639 status
= "never-connected";
4640 } else if (e
->bad_since
) {
4641 when
= e
->bad_since
;
4642 status
= "unusable";
4643 } else if (e
->unreachable_since
) {
4644 when
= e
->unreachable_since
;
4650 node
= node_get_by_id(e
->identity
);
4652 node_get_verbose_nickname(node
, nbuf
);
4655 base16_encode(nbuf
+1, sizeof(nbuf
)-1, e
->identity
, DIGEST_LEN
);
4656 /* e->nickname field is not very reliable if we don't know about
4657 * this router any longer; don't include it. */
4661 format_iso_time(tbuf
, when
);
4662 smartlist_add_asprintf(sl
, "%s %s %s\n", nbuf
, status
, tbuf
);
4664 smartlist_add_asprintf(sl
, "%s %s\n", nbuf
, status
);
4666 } SMARTLIST_FOREACH_END(e
);
4667 *answer
= smartlist_join_strings(sl
, "", 0, NULL
);
4668 SMARTLIST_FOREACH(sl
, char *, c
, tor_free(c
));
4674 /* Given the original bandwidth of a guard and its guardfraction,
4675 * calculate how much bandwidth the guard should have as a guard and
4678 * Quoting from proposal236:
4680 * Let Wpf denote the weight from the 'bandwidth-weights' line a
4681 * client would apply to N for position p if it had the guard
4682 * flag, Wpn the weight if it did not have the guard flag, and B the
4683 * measured bandwidth of N in the consensus. Then instead of choosing
4684 * N for position p proportionally to Wpf*B or Wpn*B, clients should
4685 * choose N proportionally to F*Wpf*B + (1-F)*Wpn*B.
4687 * This function fills the <b>guardfraction_bw</b> structure. It sets
4688 * <b>guard_bw</b> to F*B and <b>non_guard_bw</b> to (1-F)*B.
4691 guard_get_guardfraction_bandwidth(guardfraction_bandwidth_t
*guardfraction_bw
,
4693 uint32_t guardfraction_percentage
)
4695 double guardfraction_fraction
;
4697 /* Turn the percentage into a fraction. */
4698 tor_assert(guardfraction_percentage
<= 100);
4699 guardfraction_fraction
= guardfraction_percentage
/ 100.0;
4701 long guard_bw
= tor_lround(guardfraction_fraction
* orig_bandwidth
);
4702 tor_assert(guard_bw
<= INT_MAX
);
4704 guardfraction_bw
->guard_bw
= (int) guard_bw
;
4706 guardfraction_bw
->non_guard_bw
= orig_bandwidth
- (int) guard_bw
;
4709 /** Returns true iff the node is used as a guard in the specified guard
4712 is_node_used_as_guard_for_guard_selection(guard_selection_t
*gs
,
4718 * We used to have a using_as_guard flag in node_t, but it had to go away
4719 * to allow for multiple guard selection contexts. Instead, search the
4720 * guard list for a matching digest.
4723 tor_assert(gs
!= NULL
);
4724 tor_assert(node
!= NULL
);
4726 SMARTLIST_FOREACH_BEGIN(gs
->chosen_entry_guards
, entry_guard_t
*, e
) {
4727 if (tor_memeq(e
->identity
, node
->identity
, DIGEST_LEN
)) {
4731 } SMARTLIST_FOREACH_END(e
);
4736 /** Returns true iff the node is used as a guard in the default guard
4739 is_node_used_as_guard
, (const node_t
*node
))
4741 return is_node_used_as_guard_for_guard_selection(
4742 get_guard_selection_info(), node
);
4745 /** Return 1 if we have at least one descriptor for an entry guard
4746 * (bridge or member of EntryNodes) and all descriptors we know are
4747 * down. Else return 0. If <b>act</b> is 1, then mark the down guards
4748 * up; else just observe and report. */
4750 entries_retry_helper(const or_options_t
*options
, int act
)
4754 int any_running
= 0;
4755 int need_bridges
= options
->UseBridges
!= 0;
4756 guard_selection_t
*gs
= get_guard_selection_info();
4758 tor_assert(gs
!= NULL
);
4759 tor_assert(gs
->chosen_entry_guards
!= NULL
);
4761 SMARTLIST_FOREACH_BEGIN(gs
->chosen_entry_guards
, entry_guard_t
*, e
) {
4762 node
= node_get_by_id(e
->identity
);
4763 if (node
&& node_has_descriptor(node
) &&
4764 node_is_bridge(node
) == need_bridges
&&
4765 (!need_bridges
|| (!e
->bad_since
&&
4766 node_is_a_configured_bridge(node
)))) {
4768 if (node
->is_running
)
4769 any_running
= 1; /* some entry is both known and running */
4771 /* Mark all current connections to this OR as unhealthy, since
4772 * otherwise there could be one that started 30 seconds
4773 * ago, and in 30 seconds it will time out, causing us to mark
4774 * the node down and undermine the retry attempt. We mark even
4775 * the established conns, since if the network just came back
4776 * we'll want to attach circuits to fresh conns. */
4777 connection_or_set_bad_connections(node
->identity
, 1);
4779 /* mark this entry node for retry */
4780 router_set_status(node
->identity
, 1);
4785 } SMARTLIST_FOREACH_END(e
);
4786 log_debug(LD_DIR
, "%d: any_known %d, any_running %d",
4787 act
, any_known
, any_running
);
4788 return any_known
&& !any_running
;
4791 /** Do we know any descriptors for our bridges / entrynodes, and are
4792 * all the ones we have descriptors for down? */
4794 entries_known_but_down(const or_options_t
*options
)
4796 tor_assert(entry_list_is_constrained(options
));
4797 return entries_retry_helper(options
, 0);
4800 /** Mark all down known bridges / entrynodes up. */
4802 entries_retry_all(const or_options_t
*options
)
4804 tor_assert(entry_list_is_constrained(options
));
4805 entries_retry_helper(options
, 1);
4808 /** Helper: Update the status of all entry guards, in whatever algorithm
4809 * is used. Return true if we should stop using all previously generated
4812 guards_update_all(void)
4814 int mark_circuits
= 0;
4815 if (update_guard_selection_choice(get_options()))
4818 tor_assert(curr_guard_context
);
4820 if (curr_guard_context
->type
== GS_TYPE_LEGACY
) {
4821 entry_guards_compute_status(get_options(), approx_time());
4823 if (entry_guards_update_all(curr_guard_context
))
4827 return mark_circuits
;
4830 /** Helper: pick a guard for a circuit, with whatever algorithm is
4833 guards_choose_guard(cpath_build_state_t
*state
,
4834 circuit_guard_state_t
**guard_state_out
)
4836 if (get_options()->UseDeprecatedGuardAlgorithm
) {
4837 return choose_random_entry(state
);
4839 const node_t
*r
= NULL
;
4840 const uint8_t *exit_id
= NULL
;
4841 entry_guard_restriction_t
*rst
= NULL
;
4842 // XXXX prop271 spec deviation -- use of restriction here.
4843 if (state
&& (exit_id
= build_state_get_exit_rsa_id(state
))) {
4844 /* We're building to a targeted exit node, so that node can't be
4845 * chosen as our guard for this circuit. */
4846 rst
= tor_malloc_zero(sizeof(entry_guard_restriction_t
));
4847 memcpy(rst
->exclude_id
, exit_id
, DIGEST_LEN
);
4849 if (entry_guard_pick_for_circuit(get_guard_selection_info(),
4852 guard_state_out
) < 0) {
4853 tor_assert(r
== NULL
);
4859 /** Helper: pick a directory guard, with whatever algorithm is used. */
4861 guards_choose_dirguard(dirinfo_type_t info
,
4862 circuit_guard_state_t
**guard_state_out
)
4864 if (get_options()->UseDeprecatedGuardAlgorithm
) {
4865 return choose_random_dirguard(info
);
4867 /* XXXX prop271 We don't need to look at the dirinfo_type_t here,
4868 * apparently. If you look at the old implementation, and you follow info
4869 * downwards through choose_random_dirguard(), into
4870 * choose_random_entry_impl(), into populate_live_entry_guards()... you
4871 * find out that it isn't even used, and hasn't been since 0.2.7.1-alpha,
4872 * when we realized that every Tor on the network would support
4873 * microdescriptors. -NM */
4874 const node_t
*r
= NULL
;
4875 if (entry_guard_pick_for_circuit(get_guard_selection_info(),
4878 guard_state_out
) < 0) {
4879 tor_assert(r
== NULL
);
4885 /** Free one guard selection context */
4887 guard_selection_free(guard_selection_t
*gs
)
4893 if (gs
->chosen_entry_guards
) {
4894 SMARTLIST_FOREACH(gs
->chosen_entry_guards
, entry_guard_t
*, e
,
4895 entry_guard_free(e
));
4896 smartlist_free(gs
->chosen_entry_guards
);
4897 gs
->chosen_entry_guards
= NULL
;
4900 if (gs
->sampled_entry_guards
) {
4901 SMARTLIST_FOREACH(gs
->sampled_entry_guards
, entry_guard_t
*, e
,
4902 entry_guard_free(e
));
4903 smartlist_free(gs
->sampled_entry_guards
);
4904 gs
->sampled_entry_guards
= NULL
;
4907 smartlist_free(gs
->confirmed_entry_guards
);
4908 smartlist_free(gs
->primary_entry_guards
);
4913 /** Release all storage held by the list of entry guards and related
4914 * memory structs. */
4916 entry_guards_free_all(void)
4918 /* Null out the default */
4919 curr_guard_context
= NULL
;
4920 /* Free all the guard contexts */
4921 if (guard_contexts
!= NULL
) {
4922 SMARTLIST_FOREACH_BEGIN(guard_contexts
, guard_selection_t
*, gs
) {
4923 guard_selection_free(gs
);
4924 } SMARTLIST_FOREACH_END(gs
);
4925 smartlist_free(guard_contexts
);
4926 guard_contexts
= NULL
;
4928 circuit_build_times_free_timeouts(get_circuit_build_times_mutable());