Add and use a new NumEntryGuards consensus parameter.
[tor.git] / src / or / entrynodes.c
blobabd10e385e14a7e3c53b066db621e5d89c180fe0
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-2013, The Tor Project, Inc. */
5 /* See LICENSE for licensing information */
7 /**
8 * \file entrynodes.c
9 * \brief Code to manage our fixed first nodes for various functions.
11 * Entry nodes can be guards (for general use) or bridges (for censorship
12 * circumvention).
13 **/
15 #include "or.h"
16 #include "circuitbuild.h"
17 #include "circuitstats.h"
18 #include "config.h"
19 #include "confparse.h"
20 #include "connection.h"
21 #include "connection_or.h"
22 #include "control.h"
23 #include "directory.h"
24 #include "entrynodes.h"
25 #include "main.h"
26 #include "microdesc.h"
27 #include "networkstatus.h"
28 #include "nodelist.h"
29 #include "policies.h"
30 #include "router.h"
31 #include "routerlist.h"
32 #include "routerparse.h"
33 #include "routerset.h"
34 #include "transports.h"
35 #include "statefile.h"
37 /** Information about a configured bridge. Currently this just matches the
38 * ones in the torrc file, but one day we may be able to learn about new
39 * bridges on our own, and remember them in the state file. */
40 typedef struct {
41 /** Address of the bridge. */
42 tor_addr_t addr;
43 /** TLS port for the bridge. */
44 uint16_t port;
45 /** Boolean: We are re-parsing our bridge list, and we are going to remove
46 * this one if we don't find it in the list of configured bridges. */
47 unsigned marked_for_removal : 1;
48 /** Expected identity digest, or all zero bytes if we don't know what the
49 * digest should be. */
50 char identity[DIGEST_LEN];
52 /** Name of pluggable transport protocol taken from its config line. */
53 char *transport_name;
55 /** When should we next try to fetch a descriptor for this bridge? */
56 download_status_t fetch_status;
57 } bridge_info_t;
59 /** A list of our chosen entry guards. */
60 static smartlist_t *entry_guards = NULL;
61 /** A value of 1 means that the entry_guards list has changed
62 * and those changes need to be flushed to disk. */
63 static int entry_guards_dirty = 0;
65 static void bridge_free(bridge_info_t *bridge);
66 static const node_t *choose_random_entry_impl(cpath_build_state_t *state,
67 int for_directory,
68 dirinfo_type_t dirtype);
70 /** Return the list of entry guards, creating it if necessary. */
71 const smartlist_t *
72 get_entry_guards(void)
74 if (! entry_guards)
75 entry_guards = smartlist_new();
76 return entry_guards;
79 /** Check whether the entry guard <b>e</b> is usable, given the directory
80 * authorities' opinion about the router (stored in <b>ri</b>) and the user's
81 * configuration (in <b>options</b>). Set <b>e</b>-&gt;bad_since
82 * accordingly. Return true iff the entry guard's status changes.
84 * If it's not usable, set *<b>reason</b> to a static string explaining why.
86 static int
87 entry_guard_set_status(entry_guard_t *e, const node_t *node,
88 time_t now, const or_options_t *options,
89 const char **reason)
91 char buf[HEX_DIGEST_LEN+1];
92 int changed = 0;
94 *reason = NULL;
96 /* Do we want to mark this guard as bad? */
97 if (!node)
98 *reason = "unlisted";
99 else if (!node->is_running)
100 *reason = "down";
101 else if (options->UseBridges && (!node->ri ||
102 node->ri->purpose != ROUTER_PURPOSE_BRIDGE))
103 *reason = "not a bridge";
104 else if (options->UseBridges && !node_is_a_configured_bridge(node))
105 *reason = "not a configured bridge";
106 else if (!options->UseBridges && !node->is_possible_guard &&
107 !routerset_contains_node(options->EntryNodes,node))
108 *reason = "not recommended as a guard";
109 else if (routerset_contains_node(options->ExcludeNodes, node))
110 *reason = "excluded";
111 else if (e->path_bias_disabled)
112 *reason = "path-biased";
114 if (*reason && ! e->bad_since) {
115 /* Router is newly bad. */
116 base16_encode(buf, sizeof(buf), e->identity, DIGEST_LEN);
117 log_info(LD_CIRC, "Entry guard %s (%s) is %s: marking as unusable.",
118 e->nickname, buf, *reason);
120 e->bad_since = now;
121 control_event_guard(e->nickname, e->identity, "BAD");
122 changed = 1;
123 } else if (!*reason && e->bad_since) {
124 /* There's nothing wrong with the router any more. */
125 base16_encode(buf, sizeof(buf), e->identity, DIGEST_LEN);
126 log_info(LD_CIRC, "Entry guard %s (%s) is no longer unusable: "
127 "marking as ok.", e->nickname, buf);
129 e->bad_since = 0;
130 control_event_guard(e->nickname, e->identity, "GOOD");
131 changed = 1;
134 if (node) {
135 int is_dir = node_is_dir(node) && node->rs &&
136 node->rs->version_supports_microdesc_cache;
137 if (options->UseBridges && node_is_a_configured_bridge(node))
138 is_dir = 1;
139 if (e->is_dir_cache != is_dir) {
140 e->is_dir_cache = is_dir;
141 changed = 1;
145 return changed;
148 /** Return true iff enough time has passed since we last tried to connect
149 * to the unreachable guard <b>e</b> that we're willing to try again. */
150 static int
151 entry_is_time_to_retry(entry_guard_t *e, time_t now)
153 long diff;
154 if (e->last_attempted < e->unreachable_since)
155 return 1;
156 diff = now - e->unreachable_since;
157 if (diff < 6*60*60)
158 return now > (e->last_attempted + 60*60);
159 else if (diff < 3*24*60*60)
160 return now > (e->last_attempted + 4*60*60);
161 else if (diff < 7*24*60*60)
162 return now > (e->last_attempted + 18*60*60);
163 else
164 return now > (e->last_attempted + 36*60*60);
167 /** Return the node corresponding to <b>e</b>, if <b>e</b> is
168 * working well enough that we are willing to use it as an entry
169 * right now. (Else return NULL.) In particular, it must be
170 * - Listed as either up or never yet contacted;
171 * - Present in the routerlist;
172 * - Listed as 'stable' or 'fast' by the current dirserver consensus,
173 * if demanded by <b>need_uptime</b> or <b>need_capacity</b>
174 * (unless it's a configured EntryNode);
175 * - Allowed by our current ReachableORAddresses config option; and
176 * - Currently thought to be reachable by us (unless <b>assume_reachable</b>
177 * is true).
179 * If the answer is no, set *<b>msg</b> to an explanation of why.
181 * If need_descriptor is true, only return the node if we currently have
182 * a descriptor (routerinfo or microdesc) for it.
184 static INLINE const node_t *
185 entry_is_live(entry_guard_t *e, int need_uptime, int need_capacity,
186 int assume_reachable, int need_descriptor, const char **msg)
188 const node_t *node;
189 const or_options_t *options = get_options();
190 tor_assert(msg);
192 if (e->path_bias_disabled) {
193 *msg = "path-biased";
194 return NULL;
196 if (e->bad_since) {
197 *msg = "bad";
198 return NULL;
200 /* no good if it's unreachable, unless assume_unreachable or can_retry. */
201 if (!assume_reachable && !e->can_retry &&
202 e->unreachable_since && !entry_is_time_to_retry(e, time(NULL))) {
203 *msg = "unreachable";
204 return NULL;
206 node = node_get_by_id(e->identity);
207 if (!node) {
208 *msg = "no node info";
209 return NULL;
211 if (need_descriptor && !node_has_descriptor(node)) {
212 *msg = "no descriptor";
213 return NULL;
215 if (get_options()->UseBridges) {
216 if (node_get_purpose(node) != ROUTER_PURPOSE_BRIDGE) {
217 *msg = "not a bridge";
218 return NULL;
220 if (!node_is_a_configured_bridge(node)) {
221 *msg = "not a configured bridge";
222 return NULL;
224 } else { /* !get_options()->UseBridges */
225 if (node_get_purpose(node) != ROUTER_PURPOSE_GENERAL) {
226 *msg = "not general-purpose";
227 return NULL;
230 if (routerset_contains_node(options->EntryNodes, node)) {
231 /* they asked for it, they get it */
232 need_uptime = need_capacity = 0;
234 if (node_is_unreliable(node, need_uptime, need_capacity, 0)) {
235 *msg = "not fast/stable";
236 return NULL;
238 if (!fascist_firewall_allows_node(node)) {
239 *msg = "unreachable by config";
240 return NULL;
242 return node;
245 /** Return the number of entry guards that we think are usable. */
247 num_live_entry_guards(int for_directory)
249 int n = 0;
250 const char *msg;
251 if (! entry_guards)
252 return 0;
253 SMARTLIST_FOREACH_BEGIN(entry_guards, entry_guard_t *, entry) {
254 if (for_directory && !entry->is_dir_cache)
255 continue;
256 if (entry_is_live(entry, 0, 1, 0, !for_directory, &msg))
257 ++n;
258 } SMARTLIST_FOREACH_END(entry);
259 return n;
262 /** If <b>digest</b> matches the identity of any node in the
263 * entry_guards list, return that node. Else return NULL. */
264 entry_guard_t *
265 entry_guard_get_by_id_digest(const char *digest)
267 SMARTLIST_FOREACH(entry_guards, entry_guard_t *, entry,
268 if (tor_memeq(digest, entry->identity, DIGEST_LEN))
269 return entry;
271 return NULL;
274 /** Dump a description of our list of entry guards to the log at level
275 * <b>severity</b>. */
276 static void
277 log_entry_guards(int severity)
279 smartlist_t *elements = smartlist_new();
280 char *s;
282 SMARTLIST_FOREACH_BEGIN(entry_guards, entry_guard_t *, e)
284 const char *msg = NULL;
285 if (entry_is_live(e, 0, 1, 0, 0, &msg))
286 smartlist_add_asprintf(elements, "%s [%s] (up %s)",
287 e->nickname,
288 hex_str(e->identity, DIGEST_LEN),
289 e->made_contact ? "made-contact" : "never-contacted");
290 else
291 smartlist_add_asprintf(elements, "%s [%s] (%s, %s)",
292 e->nickname,
293 hex_str(e->identity, DIGEST_LEN),
294 msg,
295 e->made_contact ? "made-contact" : "never-contacted");
297 SMARTLIST_FOREACH_END(e);
299 s = smartlist_join_strings(elements, ",", 0, NULL);
300 SMARTLIST_FOREACH(elements, char*, cp, tor_free(cp));
301 smartlist_free(elements);
302 log_fn(severity,LD_CIRC,"%s",s);
303 tor_free(s);
306 /** Called when one or more guards that we would previously have used for some
307 * purpose are no longer in use because a higher-priority guard has become
308 * usable again. */
309 static void
310 control_event_guard_deferred(void)
312 /* XXXX We don't actually have a good way to figure out _how many_ entries
313 * are live for some purpose. We need an entry_is_even_slightly_live()
314 * function for this to work right. NumEntryGuards isn't reliable: if we
315 * need guards with weird properties, we can have more than that number
316 * live.
318 #if 0
319 int n = 0;
320 const char *msg;
321 const or_options_t *options = get_options();
322 if (!entry_guards)
323 return;
324 SMARTLIST_FOREACH(entry_guards, entry_guard_t *, entry,
326 if (entry_is_live(entry, 0, 1, 0, &msg)) {
327 if (n++ == options->NumEntryGuards) {
328 control_event_guard(entry->nickname, entry->identity, "DEFERRED");
329 return;
333 #endif
336 /** Largest amount that we'll backdate chosen_on_date */
337 #define CHOSEN_ON_DATE_SLOP (30*86400)
339 /** Add a new (preferably stable and fast) router to our
340 * entry_guards list. Return a pointer to the router if we succeed,
341 * or NULL if we can't find any more suitable entries.
343 * If <b>chosen</b> is defined, use that one, and if it's not
344 * already in our entry_guards list, put it at the *beginning*.
345 * Else, put the one we pick at the end of the list. */
346 static const node_t *
347 add_an_entry_guard(const node_t *chosen, int reset_status, int prepend,
348 int for_discovery, int for_directory)
350 const node_t *node;
351 entry_guard_t *entry;
353 if (chosen) {
354 node = chosen;
355 entry = entry_guard_get_by_id_digest(node->identity);
356 if (entry) {
357 if (reset_status) {
358 entry->bad_since = 0;
359 entry->can_retry = 1;
361 entry->is_dir_cache = node->rs &&
362 node->rs->version_supports_microdesc_cache;
363 if (get_options()->UseBridges && node_is_a_configured_bridge(node))
364 entry->is_dir_cache = 1;
365 return NULL;
367 } else if (!for_directory) {
368 node = choose_good_entry_server(CIRCUIT_PURPOSE_C_GENERAL, NULL);
369 if (!node)
370 return NULL;
371 } else {
372 const routerstatus_t *rs;
373 rs = router_pick_directory_server(MICRODESC_DIRINFO|V3_DIRINFO,
374 PDS_PREFER_TUNNELED_DIR_CONNS_|PDS_FOR_GUARD);
375 if (!rs)
376 return NULL;
377 node = node_get_by_id(rs->identity_digest);
378 if (!node)
379 return NULL;
381 if (node->using_as_guard)
382 return NULL;
383 if (entry_guard_get_by_id_digest(node->identity) != NULL) {
384 log_info(LD_CIRC, "I was about to add a duplicate entry guard.");
385 /* This can happen if we choose a guard, then the node goes away, then
386 * comes back. */
387 ((node_t*) node)->using_as_guard = 1;
388 return NULL;
390 entry = tor_malloc_zero(sizeof(entry_guard_t));
391 log_info(LD_CIRC, "Chose %s as new entry guard.",
392 node_describe(node));
393 strlcpy(entry->nickname, node_get_nickname(node), sizeof(entry->nickname));
394 memcpy(entry->identity, node->identity, DIGEST_LEN);
395 entry->is_dir_cache = node_is_dir(node) &&
396 node->rs && node->rs->version_supports_microdesc_cache;
397 if (get_options()->UseBridges && node_is_a_configured_bridge(node))
398 entry->is_dir_cache = 1;
400 /* Choose expiry time smudged over the past month. The goal here
401 * is to a) spread out when Tor clients rotate their guards, so they
402 * don't all select them on the same day, and b) avoid leaving a
403 * precise timestamp in the state file about when we first picked
404 * this guard. For details, see the Jan 2010 or-dev thread. */
405 entry->chosen_on_date = time(NULL) - crypto_rand_int(3600*24*30);
406 entry->chosen_by_version = tor_strdup(VERSION);
408 /* Are we picking this guard because all of our current guards are
409 * down so we need another one (for_discovery is 1), or because we
410 * decided we need more variety in our guard list (for_discovery is 0)?
412 * Currently we hack this behavior into place by setting "made_contact"
413 * for guards of the latter variety, so we'll be willing to use any of
414 * them right off the bat.
416 if (!for_discovery)
417 entry->made_contact = 1;
419 ((node_t*)node)->using_as_guard = 1;
420 if (prepend)
421 smartlist_insert(entry_guards, 0, entry);
422 else
423 smartlist_add(entry_guards, entry);
424 control_event_guard(entry->nickname, entry->identity, "NEW");
425 control_event_guard_deferred();
426 log_entry_guards(LOG_INFO);
427 return node;
430 /** Choose how many entry guards or directory guards we'll use. If
431 * <b>for_directory</b> is true, we return how many directory guards to
432 * use; else we return how many entry guards to use. */
433 static int
434 decide_num_guards(const or_options_t *options, int for_directory)
436 if (for_directory && options->NumDirectoryGuards != 0)
437 return options->NumDirectoryGuards;
438 if (options->NumEntryGuards)
439 return options->NumEntryGuards;
440 /* Use the value from the consensus, or 3 if no guidance. */
441 return networkstatus_get_param(NULL, "NumEntryGuards", 3, 1, 10);
444 /** If the use of entry guards is configured, choose more entry guards
445 * until we have enough in the list. */
446 static void
447 pick_entry_guards(const or_options_t *options, int for_directory)
449 int changed = 0;
450 const int num_needed = decide_num_guards(options, for_directory);
452 tor_assert(entry_guards);
454 while (num_live_entry_guards(for_directory) < num_needed) {
455 if (!add_an_entry_guard(NULL, 0, 0, 0, for_directory))
456 break;
457 changed = 1;
459 if (changed)
460 entry_guards_changed();
463 /** How long (in seconds) do we allow an entry guard to be nonfunctional,
464 * unlisted, excluded, or otherwise nonusable before we give up on it? */
465 #define ENTRY_GUARD_REMOVE_AFTER (30*24*60*60)
467 /** Release all storage held by <b>e</b>. */
468 static void
469 entry_guard_free(entry_guard_t *e)
471 if (!e)
472 return;
473 tor_free(e->chosen_by_version);
474 tor_free(e);
478 * Return the minimum lifetime of working entry guard, in seconds,
479 * as given in the consensus networkstatus. (Plus CHOSEN_ON_DATE_SLOP,
480 * so that we can do the chosen_on_date randomization while achieving the
481 * desired minimum lifetime.)
483 static int32_t
484 guards_get_lifetime(void)
486 const or_options_t *options = get_options();
487 #define DFLT_GUARD_LIFETIME (86400 * 60) /* Two months. */
488 #define MIN_GUARD_LIFETIME (86400 * 30) /* One months. */
489 #define MAX_GUARD_LIFETIME (86400 * 1826) /* Five years. */
491 if (options->GuardLifetime >= 1) {
492 return CLAMP(MIN_GUARD_LIFETIME,
493 options->GuardLifetime,
494 MAX_GUARD_LIFETIME) + CHOSEN_ON_DATE_SLOP;
497 return networkstatus_get_param(NULL, "GuardLifetime",
498 DFLT_GUARD_LIFETIME,
499 MIN_GUARD_LIFETIME,
500 MAX_GUARD_LIFETIME) + CHOSEN_ON_DATE_SLOP;
503 /** Remove any entry guard which was selected by an unknown version of Tor,
504 * or which was selected by a version of Tor that's known to select
505 * entry guards badly, or which was selected more 2 months ago. */
506 /* XXXX The "obsolete guards" and "chosen long ago guards" things should
507 * probably be different functions. */
508 static int
509 remove_obsolete_entry_guards(time_t now)
511 int changed = 0, i;
512 int32_t guard_lifetime = guards_get_lifetime();
514 for (i = 0; i < smartlist_len(entry_guards); ++i) {
515 entry_guard_t *entry = smartlist_get(entry_guards, i);
516 const char *ver = entry->chosen_by_version;
517 const char *msg = NULL;
518 tor_version_t v;
519 int version_is_bad = 0, date_is_bad = 0;
520 if (!ver) {
521 msg = "does not say what version of Tor it was selected by";
522 version_is_bad = 1;
523 } else if (tor_version_parse(ver, &v)) {
524 msg = "does not seem to be from any recognized version of Tor";
525 version_is_bad = 1;
526 } else {
527 char *tor_ver = NULL;
528 tor_asprintf(&tor_ver, "Tor %s", ver);
529 if ((tor_version_as_new_as(tor_ver, "0.1.0.10-alpha") &&
530 !tor_version_as_new_as(tor_ver, "0.1.2.16-dev")) ||
531 (tor_version_as_new_as(tor_ver, "0.2.0.0-alpha") &&
532 !tor_version_as_new_as(tor_ver, "0.2.0.6-alpha")) ||
533 /* above are bug 440; below are bug 1217 */
534 (tor_version_as_new_as(tor_ver, "0.2.1.3-alpha") &&
535 !tor_version_as_new_as(tor_ver, "0.2.1.23")) ||
536 (tor_version_as_new_as(tor_ver, "0.2.2.0-alpha") &&
537 !tor_version_as_new_as(tor_ver, "0.2.2.7-alpha"))) {
538 msg = "was selected without regard for guard bandwidth";
539 version_is_bad = 1;
541 tor_free(tor_ver);
543 if (!version_is_bad && entry->chosen_on_date + guard_lifetime < now) {
544 /* It's been too long since the date listed in our state file. */
545 msg = "was selected several months ago";
546 date_is_bad = 1;
549 if (version_is_bad || date_is_bad) { /* we need to drop it */
550 char dbuf[HEX_DIGEST_LEN+1];
551 tor_assert(msg);
552 base16_encode(dbuf, sizeof(dbuf), entry->identity, DIGEST_LEN);
553 log_fn(version_is_bad ? LOG_NOTICE : LOG_INFO, LD_CIRC,
554 "Entry guard '%s' (%s) %s. (Version=%s.) Replacing it.",
555 entry->nickname, dbuf, msg, ver?escaped(ver):"none");
556 control_event_guard(entry->nickname, entry->identity, "DROPPED");
557 entry_guard_free(entry);
558 smartlist_del_keeporder(entry_guards, i--);
559 log_entry_guards(LOG_INFO);
560 changed = 1;
564 return changed ? 1 : 0;
567 /** Remove all entry guards that have been down or unlisted for so
568 * long that we don't think they'll come up again. Return 1 if we
569 * removed any, or 0 if we did nothing. */
570 static int
571 remove_dead_entry_guards(time_t now)
573 char dbuf[HEX_DIGEST_LEN+1];
574 char tbuf[ISO_TIME_LEN+1];
575 int i;
576 int changed = 0;
578 for (i = 0; i < smartlist_len(entry_guards); ) {
579 entry_guard_t *entry = smartlist_get(entry_guards, i);
580 if (entry->bad_since &&
581 ! entry->path_bias_disabled &&
582 entry->bad_since + ENTRY_GUARD_REMOVE_AFTER < now) {
584 base16_encode(dbuf, sizeof(dbuf), entry->identity, DIGEST_LEN);
585 format_local_iso_time(tbuf, entry->bad_since);
586 log_info(LD_CIRC, "Entry guard '%s' (%s) has been down or unlisted "
587 "since %s local time; removing.",
588 entry->nickname, dbuf, tbuf);
589 control_event_guard(entry->nickname, entry->identity, "DROPPED");
590 entry_guard_free(entry);
591 smartlist_del_keeporder(entry_guards, i);
592 log_entry_guards(LOG_INFO);
593 changed = 1;
594 } else
595 ++i;
597 return changed ? 1 : 0;
600 /** A new directory or router-status has arrived; update the down/listed
601 * status of the entry guards.
603 * An entry is 'down' if the directory lists it as nonrunning.
604 * An entry is 'unlisted' if the directory doesn't include it.
606 * Don't call this on startup; only on a fresh download. Otherwise we'll
607 * think that things are unlisted.
609 void
610 entry_guards_compute_status(const or_options_t *options, time_t now)
612 int changed = 0;
613 digestmap_t *reasons;
615 if (! entry_guards)
616 return;
618 if (options->EntryNodes) /* reshuffle the entry guard list if needed */
619 entry_nodes_should_be_added();
621 reasons = digestmap_new();
622 SMARTLIST_FOREACH_BEGIN(entry_guards, entry_guard_t *, entry)
624 const node_t *r = node_get_by_id(entry->identity);
625 const char *reason = NULL;
626 if (entry_guard_set_status(entry, r, now, options, &reason))
627 changed = 1;
629 if (entry->bad_since)
630 tor_assert(reason);
631 if (reason)
632 digestmap_set(reasons, entry->identity, (char*)reason);
634 SMARTLIST_FOREACH_END(entry);
636 if (remove_dead_entry_guards(now))
637 changed = 1;
638 if (remove_obsolete_entry_guards(now))
639 changed = 1;
641 if (changed) {
642 SMARTLIST_FOREACH_BEGIN(entry_guards, entry_guard_t *, entry) {
643 const char *reason = digestmap_get(reasons, entry->identity);
644 const char *live_msg = "";
645 const node_t *r = entry_is_live(entry, 0, 1, 0, 0, &live_msg);
646 log_info(LD_CIRC, "Summary: Entry %s [%s] is %s, %s%s%s, and %s%s.",
647 entry->nickname,
648 hex_str(entry->identity, DIGEST_LEN),
649 entry->unreachable_since ? "unreachable" : "reachable",
650 entry->bad_since ? "unusable" : "usable",
651 reason ? ", ": "",
652 reason ? reason : "",
653 r ? "live" : "not live / ",
654 r ? "" : live_msg);
655 } SMARTLIST_FOREACH_END(entry);
656 log_info(LD_CIRC, " (%d/%d entry guards are usable/new)",
657 num_live_entry_guards(0), smartlist_len(entry_guards));
658 log_entry_guards(LOG_INFO);
659 entry_guards_changed();
662 digestmap_free(reasons, NULL);
665 /** Called when a connection to an OR with the identity digest <b>digest</b>
666 * is established (<b>succeeded</b>==1) or has failed (<b>succeeded</b>==0).
667 * If the OR is an entry, change that entry's up/down status.
668 * Return 0 normally, or -1 if we want to tear down the new connection.
670 * If <b>mark_relay_status</b>, also call router_set_status() on this
671 * relay.
673 * XXX024 change succeeded and mark_relay_status into 'int flags'.
676 entry_guard_register_connect_status(const char *digest, int succeeded,
677 int mark_relay_status, time_t now)
679 int changed = 0;
680 int refuse_conn = 0;
681 int first_contact = 0;
682 entry_guard_t *entry = NULL;
683 int idx = -1;
684 char buf[HEX_DIGEST_LEN+1];
686 if (! entry_guards)
687 return 0;
689 SMARTLIST_FOREACH_BEGIN(entry_guards, entry_guard_t *, e) {
690 tor_assert(e);
691 if (tor_memeq(e->identity, digest, DIGEST_LEN)) {
692 entry = e;
693 idx = e_sl_idx;
694 break;
696 } SMARTLIST_FOREACH_END(e);
698 if (!entry)
699 return 0;
701 base16_encode(buf, sizeof(buf), entry->identity, DIGEST_LEN);
703 if (succeeded) {
704 if (entry->unreachable_since) {
705 log_info(LD_CIRC, "Entry guard '%s' (%s) is now reachable again. Good.",
706 entry->nickname, buf);
707 entry->can_retry = 0;
708 entry->unreachable_since = 0;
709 entry->last_attempted = now;
710 control_event_guard(entry->nickname, entry->identity, "UP");
711 changed = 1;
713 if (!entry->made_contact) {
714 entry->made_contact = 1;
715 first_contact = changed = 1;
717 } else { /* ! succeeded */
718 if (!entry->made_contact) {
719 /* We've never connected to this one. */
720 log_info(LD_CIRC,
721 "Connection to never-contacted entry guard '%s' (%s) failed. "
722 "Removing from the list. %d/%d entry guards usable/new.",
723 entry->nickname, buf,
724 num_live_entry_guards(0)-1, smartlist_len(entry_guards)-1);
725 control_event_guard(entry->nickname, entry->identity, "DROPPED");
726 entry_guard_free(entry);
727 smartlist_del_keeporder(entry_guards, idx);
728 log_entry_guards(LOG_INFO);
729 changed = 1;
730 } else if (!entry->unreachable_since) {
731 log_info(LD_CIRC, "Unable to connect to entry guard '%s' (%s). "
732 "Marking as unreachable.", entry->nickname, buf);
733 entry->unreachable_since = entry->last_attempted = now;
734 control_event_guard(entry->nickname, entry->identity, "DOWN");
735 changed = 1;
736 entry->can_retry = 0; /* We gave it an early chance; no good. */
737 } else {
738 char tbuf[ISO_TIME_LEN+1];
739 format_iso_time(tbuf, entry->unreachable_since);
740 log_debug(LD_CIRC, "Failed to connect to unreachable entry guard "
741 "'%s' (%s). It has been unreachable since %s.",
742 entry->nickname, buf, tbuf);
743 entry->last_attempted = now;
744 entry->can_retry = 0; /* We gave it an early chance; no good. */
748 /* if the caller asked us to, also update the is_running flags for this
749 * relay */
750 if (mark_relay_status)
751 router_set_status(digest, succeeded);
753 if (first_contact) {
754 /* We've just added a new long-term entry guard. Perhaps the network just
755 * came back? We should give our earlier entries another try too,
756 * and close this connection so we don't use it before we've given
757 * the others a shot. */
758 SMARTLIST_FOREACH_BEGIN(entry_guards, entry_guard_t *, e) {
759 if (e == entry)
760 break;
761 if (e->made_contact) {
762 const char *msg;
763 const node_t *r = entry_is_live(e, 0, 1, 1, 0, &msg);
764 if (r && e->unreachable_since) {
765 refuse_conn = 1;
766 e->can_retry = 1;
769 } SMARTLIST_FOREACH_END(e);
770 if (refuse_conn) {
771 log_info(LD_CIRC,
772 "Connected to new entry guard '%s' (%s). Marking earlier "
773 "entry guards up. %d/%d entry guards usable/new.",
774 entry->nickname, buf,
775 num_live_entry_guards(0), smartlist_len(entry_guards));
776 log_entry_guards(LOG_INFO);
777 changed = 1;
781 if (changed)
782 entry_guards_changed();
783 return refuse_conn ? -1 : 0;
786 /** When we try to choose an entry guard, should we parse and add
787 * config's EntryNodes first? */
788 static int should_add_entry_nodes = 0;
790 /** Called when the value of EntryNodes changes in our configuration. */
791 void
792 entry_nodes_should_be_added(void)
794 log_info(LD_CIRC, "EntryNodes config option set. Putting configured "
795 "relays at the front of the entry guard list.");
796 should_add_entry_nodes = 1;
799 /** Update the using_as_guard fields of all the nodes. We do this after we
800 * remove entry guards from the list: This is the only function that clears
801 * the using_as_guard field. */
802 static void
803 update_node_guard_status(void)
805 smartlist_t *nodes = nodelist_get_list();
806 SMARTLIST_FOREACH(nodes, node_t *, node, node->using_as_guard = 0);
807 SMARTLIST_FOREACH_BEGIN(entry_guards, entry_guard_t *, entry) {
808 node_t *node = node_get_mutable_by_id(entry->identity);
809 if (node)
810 node->using_as_guard = 1;
811 } SMARTLIST_FOREACH_END(entry);
814 /** Adjust the entry guards list so that it only contains entries from
815 * EntryNodes, adding new entries from EntryNodes to the list as needed. */
816 static void
817 entry_guards_set_from_config(const or_options_t *options)
819 smartlist_t *entry_nodes, *worse_entry_nodes, *entry_fps;
820 smartlist_t *old_entry_guards_on_list, *old_entry_guards_not_on_list;
821 const int numentryguards = decide_num_guards(options, 0);
822 tor_assert(entry_guards);
824 should_add_entry_nodes = 0;
826 if (!options->EntryNodes) {
827 /* It's possible that a controller set EntryNodes, thus making
828 * should_add_entry_nodes set, then cleared it again, all before the
829 * call to choose_random_entry() that triggered us. If so, just return.
831 return;
835 char *string = routerset_to_string(options->EntryNodes);
836 log_info(LD_CIRC,"Adding configured EntryNodes '%s'.", string);
837 tor_free(string);
840 entry_nodes = smartlist_new();
841 worse_entry_nodes = smartlist_new();
842 entry_fps = smartlist_new();
843 old_entry_guards_on_list = smartlist_new();
844 old_entry_guards_not_on_list = smartlist_new();
846 /* Split entry guards into those on the list and those not. */
848 routerset_get_all_nodes(entry_nodes, options->EntryNodes,
849 options->ExcludeNodes, 0);
850 SMARTLIST_FOREACH(entry_nodes, const node_t *,node,
851 smartlist_add(entry_fps, (void*)node->identity));
853 SMARTLIST_FOREACH(entry_guards, entry_guard_t *, e, {
854 if (smartlist_contains_digest(entry_fps, e->identity))
855 smartlist_add(old_entry_guards_on_list, e);
856 else
857 smartlist_add(old_entry_guards_not_on_list, e);
860 /* Remove all currently configured guard nodes, excluded nodes, unreachable
861 * nodes, or non-Guard nodes from entry_nodes. */
862 SMARTLIST_FOREACH_BEGIN(entry_nodes, const node_t *, node) {
863 if (entry_guard_get_by_id_digest(node->identity)) {
864 SMARTLIST_DEL_CURRENT(entry_nodes, node);
865 continue;
866 } else if (routerset_contains_node(options->ExcludeNodes, node)) {
867 SMARTLIST_DEL_CURRENT(entry_nodes, node);
868 continue;
869 } else if (!fascist_firewall_allows_node(node)) {
870 SMARTLIST_DEL_CURRENT(entry_nodes, node);
871 continue;
872 } else if (! node->is_possible_guard) {
873 smartlist_add(worse_entry_nodes, (node_t*)node);
874 SMARTLIST_DEL_CURRENT(entry_nodes, node);
876 } SMARTLIST_FOREACH_END(node);
878 /* Now build the new entry_guards list. */
879 smartlist_clear(entry_guards);
880 /* First, the previously configured guards that are in EntryNodes. */
881 smartlist_add_all(entry_guards, old_entry_guards_on_list);
882 /* Next, scramble the rest of EntryNodes, putting the guards first. */
883 smartlist_shuffle(entry_nodes);
884 smartlist_shuffle(worse_entry_nodes);
885 smartlist_add_all(entry_nodes, worse_entry_nodes);
887 /* Next, the rest of EntryNodes */
888 SMARTLIST_FOREACH_BEGIN(entry_nodes, const node_t *, node) {
889 add_an_entry_guard(node, 0, 0, 1, 0);
890 if (smartlist_len(entry_guards) > numentryguards * 10)
891 break;
892 } SMARTLIST_FOREACH_END(node);
893 log_notice(LD_GENERAL, "%d entries in guards", smartlist_len(entry_guards));
894 /* Finally, free the remaining previously configured guards that are not in
895 * EntryNodes. */
896 SMARTLIST_FOREACH(old_entry_guards_not_on_list, entry_guard_t *, e,
897 entry_guard_free(e));
899 update_node_guard_status();
901 smartlist_free(entry_nodes);
902 smartlist_free(worse_entry_nodes);
903 smartlist_free(entry_fps);
904 smartlist_free(old_entry_guards_on_list);
905 smartlist_free(old_entry_guards_not_on_list);
906 entry_guards_changed();
909 /** Return 0 if we're fine adding arbitrary routers out of the
910 * directory to our entry guard list, or return 1 if we have a
911 * list already and we must stick to it.
914 entry_list_is_constrained(const or_options_t *options)
916 if (options->EntryNodes)
917 return 1;
918 if (options->UseBridges)
919 return 1;
920 return 0;
923 /** Return true iff this node can answer directory questions about
924 * microdescriptors. */
925 static int
926 node_understands_microdescriptors(const node_t *node)
928 tor_assert(node);
929 if (node->rs && node->rs->version_supports_microdesc_cache)
930 return 1;
931 if (node->ri && tor_version_supports_microdescriptors(node->ri->platform))
932 return 1;
933 return 0;
936 /** Return true iff <b>node</b> is able to answer directory questions
937 * of type <b>dirinfo</b>. */
938 static int
939 node_can_handle_dirinfo(const node_t *node, dirinfo_type_t dirinfo)
941 /* Checking dirinfo for any type other than microdescriptors isn't required
942 yet, since we only choose directory guards that can support microdescs,
943 routerinfos, and networkstatuses, AND we don't use directory guards if
944 we're configured to do direct downloads of anything else. The only case
945 where we might have a guard that doesn't know about a type of directory
946 information is when we're retrieving directory information from a
947 bridge. */
949 if ((dirinfo & MICRODESC_DIRINFO) &&
950 !node_understands_microdescriptors(node))
951 return 0;
952 return 1;
955 /** Pick a live (up and listed) entry guard from entry_guards. If
956 * <b>state</b> is non-NULL, this is for a specific circuit --
957 * make sure not to pick this circuit's exit or any node in the
958 * exit's family. If <b>state</b> is NULL, we're looking for a random
959 * guard (likely a bridge). If <b>dirinfo</b> is not NO_DIRINFO, then
960 * only select from nodes that know how to answer directory questions
961 * of that type. */
962 const node_t *
963 choose_random_entry(cpath_build_state_t *state)
965 return choose_random_entry_impl(state, 0, 0);
968 /** Pick a live (up and listed) directory guard from entry_guards for
969 * downloading information of type <b>type</b>. */
970 const node_t *
971 choose_random_dirguard(dirinfo_type_t type)
973 return choose_random_entry_impl(NULL, 1, type);
976 /** Helper for choose_random{entry,dirguard}. */
977 static const node_t *
978 choose_random_entry_impl(cpath_build_state_t *state, int for_directory,
979 dirinfo_type_t dirinfo_type)
981 const or_options_t *options = get_options();
982 smartlist_t *live_entry_guards = smartlist_new();
983 smartlist_t *exit_family = smartlist_new();
984 const node_t *chosen_exit =
985 state?build_state_get_exit_node(state) : NULL;
986 const node_t *node = NULL;
987 int need_uptime = state ? state->need_uptime : 0;
988 int need_capacity = state ? state->need_capacity : 0;
989 int preferred_min, consider_exit_family = 0;
990 int need_descriptor = !for_directory;
991 const int num_needed = decide_num_guards(options, for_directory);
993 if (chosen_exit) {
994 nodelist_add_node_and_family(exit_family, chosen_exit);
995 consider_exit_family = 1;
998 if (!entry_guards)
999 entry_guards = smartlist_new();
1001 if (should_add_entry_nodes)
1002 entry_guards_set_from_config(options);
1004 if (!entry_list_is_constrained(options) &&
1005 smartlist_len(entry_guards) < num_needed)
1006 pick_entry_guards(options, for_directory);
1008 retry:
1009 smartlist_clear(live_entry_guards);
1010 SMARTLIST_FOREACH_BEGIN(entry_guards, entry_guard_t *, entry) {
1011 const char *msg;
1012 node = entry_is_live(entry, need_uptime, need_capacity, 0,
1013 need_descriptor, &msg);
1014 if (!node)
1015 continue; /* down, no point */
1016 if (for_directory) {
1017 if (!entry->is_dir_cache)
1018 continue; /* We need a directory and didn't get one. */
1020 if (node == chosen_exit)
1021 continue; /* don't pick the same node for entry and exit */
1022 if (consider_exit_family && smartlist_contains(exit_family, node))
1023 continue; /* avoid relays that are family members of our exit */
1024 if (dirinfo_type != NO_DIRINFO &&
1025 !node_can_handle_dirinfo(node, dirinfo_type))
1026 continue; /* this node won't be able to answer our dir questions */
1027 #if 0 /* since EntryNodes is always strict now, this clause is moot */
1028 if (options->EntryNodes &&
1029 !routerset_contains_node(options->EntryNodes, node)) {
1030 /* We've come to the end of our preferred entry nodes. */
1031 if (smartlist_len(live_entry_guards))
1032 goto choose_and_finish; /* only choose from the ones we like */
1033 if (options->StrictNodes) {
1034 /* in theory this case should never happen, since
1035 * entry_guards_set_from_config() drops unwanted relays */
1036 tor_fragile_assert();
1037 } else {
1038 log_info(LD_CIRC,
1039 "No relays from EntryNodes available. Using others.");
1042 #endif
1043 smartlist_add(live_entry_guards, (void*)node);
1044 if (!entry->made_contact) {
1045 /* Always start with the first not-yet-contacted entry
1046 * guard. Otherwise we might add several new ones, pick
1047 * the second new one, and now we've expanded our entry
1048 * guard list without needing to. */
1049 goto choose_and_finish;
1051 if (smartlist_len(live_entry_guards) >= num_needed)
1052 goto choose_and_finish; /* we have enough */
1053 } SMARTLIST_FOREACH_END(entry);
1055 if (entry_list_is_constrained(options)) {
1056 /* If we prefer the entry nodes we've got, and we have at least
1057 * one choice, that's great. Use it. */
1058 preferred_min = 1;
1059 } else {
1060 /* Try to have at least 2 choices available. This way we don't
1061 * get stuck with a single live-but-crummy entry and just keep
1062 * using him.
1063 * (We might get 2 live-but-crummy entry guards, but so be it.) */
1064 preferred_min = 2;
1067 if (smartlist_len(live_entry_guards) < preferred_min) {
1068 if (!entry_list_is_constrained(options)) {
1069 /* still no? try adding a new entry then */
1070 /* XXX if guard doesn't imply fast and stable, then we need
1071 * to tell add_an_entry_guard below what we want, or it might
1072 * be a long time til we get it. -RD */
1073 node = add_an_entry_guard(NULL, 0, 0, 1, for_directory);
1074 if (node) {
1075 entry_guards_changed();
1076 /* XXX we start over here in case the new node we added shares
1077 * a family with our exit node. There's a chance that we'll just
1078 * load up on entry guards here, if the network we're using is
1079 * one big family. Perhaps we should teach add_an_entry_guard()
1080 * to understand nodes-to-avoid-if-possible? -RD */
1081 goto retry;
1084 if (!node && need_uptime) {
1085 need_uptime = 0; /* try without that requirement */
1086 goto retry;
1088 if (!node && need_capacity) {
1089 /* still no? last attempt, try without requiring capacity */
1090 need_capacity = 0;
1091 goto retry;
1093 #if 0
1094 /* Removing this retry logic: if we only allow one exit, and it is in the
1095 same family as all our entries, then we are just plain not going to win
1096 here. */
1097 if (!node && entry_list_is_constrained(options) && consider_exit_family) {
1098 /* still no? if we're using bridges or have strictentrynodes
1099 * set, and our chosen exit is in the same family as all our
1100 * bridges/entry guards, then be flexible about families. */
1101 consider_exit_family = 0;
1102 goto retry;
1104 #endif
1105 /* live_entry_guards may be empty below. Oh well, we tried. */
1108 choose_and_finish:
1109 if (entry_list_is_constrained(options)) {
1110 /* We need to weight by bandwidth, because our bridges or entryguards
1111 * were not already selected proportional to their bandwidth. */
1112 node = node_sl_choose_by_bandwidth(live_entry_guards, WEIGHT_FOR_GUARD);
1113 } else {
1114 /* We choose uniformly at random here, because choose_good_entry_server()
1115 * already weights its choices by bandwidth, so we don't want to
1116 * *double*-weight our guard selection. */
1117 node = smartlist_choose(live_entry_guards);
1119 smartlist_free(live_entry_guards);
1120 smartlist_free(exit_family);
1121 return node;
1124 /** Parse <b>state</b> and learn about the entry guards it describes.
1125 * If <b>set</b> is true, and there are no errors, replace the global
1126 * entry_list with what we find.
1127 * On success, return 0. On failure, alloc into *<b>msg</b> a string
1128 * describing the error, and return -1.
1131 entry_guards_parse_state(or_state_t *state, int set, char **msg)
1133 entry_guard_t *node = NULL;
1134 smartlist_t *new_entry_guards = smartlist_new();
1135 config_line_t *line;
1136 time_t now = time(NULL);
1137 const char *state_version = state->TorVersion;
1138 digestmap_t *added_by = digestmap_new();
1140 *msg = NULL;
1141 for (line = state->EntryGuards; line; line = line->next) {
1142 if (!strcasecmp(line->key, "EntryGuard")) {
1143 smartlist_t *args = smartlist_new();
1144 node = tor_malloc_zero(sizeof(entry_guard_t));
1145 /* all entry guards on disk have been contacted */
1146 node->made_contact = 1;
1147 smartlist_add(new_entry_guards, node);
1148 smartlist_split_string(args, line->value, " ",
1149 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
1150 if (smartlist_len(args)<2) {
1151 *msg = tor_strdup("Unable to parse entry nodes: "
1152 "Too few arguments to EntryGuard");
1153 } else if (!is_legal_nickname(smartlist_get(args,0))) {
1154 *msg = tor_strdup("Unable to parse entry nodes: "
1155 "Bad nickname for EntryGuard");
1156 } else {
1157 strlcpy(node->nickname, smartlist_get(args,0), MAX_NICKNAME_LEN+1);
1158 if (base16_decode(node->identity, DIGEST_LEN, smartlist_get(args,1),
1159 strlen(smartlist_get(args,1)))<0) {
1160 *msg = tor_strdup("Unable to parse entry nodes: "
1161 "Bad hex digest for EntryGuard");
1164 if (smartlist_len(args) >= 3) {
1165 const char *is_cache = smartlist_get(args, 2);
1166 if (!strcasecmp(is_cache, "DirCache")) {
1167 node->is_dir_cache = 1;
1168 } else if (!strcasecmp(is_cache, "NoDirCache")) {
1169 node->is_dir_cache = 0;
1170 } else {
1171 log_warn(LD_CONFIG, "Bogus third argument to EntryGuard line: %s",
1172 escaped(is_cache));
1175 SMARTLIST_FOREACH(args, char*, cp, tor_free(cp));
1176 smartlist_free(args);
1177 if (*msg)
1178 break;
1179 } else if (!strcasecmp(line->key, "EntryGuardDownSince") ||
1180 !strcasecmp(line->key, "EntryGuardUnlistedSince")) {
1181 time_t when;
1182 time_t last_try = 0;
1183 if (!node) {
1184 *msg = tor_strdup("Unable to parse entry nodes: "
1185 "EntryGuardDownSince/UnlistedSince without EntryGuard");
1186 break;
1188 if (parse_iso_time(line->value, &when)<0) {
1189 *msg = tor_strdup("Unable to parse entry nodes: "
1190 "Bad time in EntryGuardDownSince/UnlistedSince");
1191 break;
1193 if (when > now) {
1194 /* It's a bad idea to believe info in the future: you can wind
1195 * up with timeouts that aren't allowed to happen for years. */
1196 continue;
1198 if (strlen(line->value) >= ISO_TIME_LEN+ISO_TIME_LEN+1) {
1199 /* ignore failure */
1200 (void) parse_iso_time(line->value+ISO_TIME_LEN+1, &last_try);
1202 if (!strcasecmp(line->key, "EntryGuardDownSince")) {
1203 node->unreachable_since = when;
1204 node->last_attempted = last_try;
1205 } else {
1206 node->bad_since = when;
1208 } else if (!strcasecmp(line->key, "EntryGuardAddedBy")) {
1209 char d[DIGEST_LEN];
1210 /* format is digest version date */
1211 if (strlen(line->value) < HEX_DIGEST_LEN+1+1+1+ISO_TIME_LEN) {
1212 log_warn(LD_BUG, "EntryGuardAddedBy line is not long enough.");
1213 continue;
1215 if (base16_decode(d, sizeof(d), line->value, HEX_DIGEST_LEN)<0 ||
1216 line->value[HEX_DIGEST_LEN] != ' ') {
1217 log_warn(LD_BUG, "EntryGuardAddedBy line %s does not begin with "
1218 "hex digest", escaped(line->value));
1219 continue;
1221 digestmap_set(added_by, d, tor_strdup(line->value+HEX_DIGEST_LEN+1));
1222 } else if (!strcasecmp(line->key, "EntryGuardPathUseBias")) {
1223 const or_options_t *options = get_options();
1224 double use_cnt, success_cnt;
1226 if (!node) {
1227 *msg = tor_strdup("Unable to parse entry nodes: "
1228 "EntryGuardPathUseBias without EntryGuard");
1229 break;
1232 if (tor_sscanf(line->value, "%lf %lf",
1233 &use_cnt, &success_cnt) != 2) {
1234 log_info(LD_GENERAL, "Malformed path use bias line for node %s",
1235 node->nickname);
1236 continue;
1239 if (use_cnt < success_cnt) {
1240 int severity = LOG_INFO;
1241 /* If this state file was written by a Tor that would have
1242 * already fixed it, then the overcounting bug is still there.. */
1243 if (tor_version_as_new_as(state_version, "0.2.4.13-alpha")) {
1244 severity = LOG_NOTICE;
1246 log_fn(severity, LD_BUG,
1247 "State file contains unexpectedly high usage success "
1248 "counts %lf/%lf for Guard %s ($%s)",
1249 success_cnt, use_cnt,
1250 node->nickname, hex_str(node->identity, DIGEST_LEN));
1251 success_cnt = use_cnt;
1254 node->use_attempts = use_cnt;
1255 node->use_successes = success_cnt;
1257 log_info(LD_GENERAL, "Read %f/%f path use bias for node %s",
1258 node->use_successes, node->use_attempts, node->nickname);
1260 /* Note: We rely on the < comparison here to allow us to set a 0
1261 * rate and disable the feature entirely. If refactoring, don't
1262 * change to <= */
1263 if (pathbias_get_use_success_count(node)/node->use_attempts
1264 < pathbias_get_extreme_use_rate(options) &&
1265 pathbias_get_dropguards(options)) {
1266 node->path_bias_disabled = 1;
1267 log_info(LD_GENERAL,
1268 "Path use bias is too high (%f/%f); disabling node %s",
1269 node->circ_successes, node->circ_attempts, node->nickname);
1271 } else if (!strcasecmp(line->key, "EntryGuardPathBias")) {
1272 const or_options_t *options = get_options();
1273 double hop_cnt, success_cnt, timeouts, collapsed, successful_closed,
1274 unusable;
1276 if (!node) {
1277 *msg = tor_strdup("Unable to parse entry nodes: "
1278 "EntryGuardPathBias without EntryGuard");
1279 break;
1282 /* First try 3 params, then 2. */
1283 /* In the long run: circuit_success ~= successful_circuit_close +
1284 * collapsed_circuits +
1285 * unusable_circuits */
1286 if (tor_sscanf(line->value, "%lf %lf %lf %lf %lf %lf",
1287 &hop_cnt, &success_cnt, &successful_closed,
1288 &collapsed, &unusable, &timeouts) != 6) {
1289 int old_success, old_hops;
1290 if (tor_sscanf(line->value, "%u %u", &old_success, &old_hops) != 2) {
1291 continue;
1293 log_info(LD_GENERAL, "Reading old-style EntryGuardPathBias %s",
1294 escaped(line->value));
1296 success_cnt = old_success;
1297 successful_closed = old_success;
1298 hop_cnt = old_hops;
1299 timeouts = 0;
1300 collapsed = 0;
1301 unusable = 0;
1304 if (hop_cnt < success_cnt) {
1305 int severity = LOG_INFO;
1306 /* If this state file was written by a Tor that would have
1307 * already fixed it, then the overcounting bug is still there.. */
1308 if (tor_version_as_new_as(state_version, "0.2.4.13-alpha")) {
1309 severity = LOG_NOTICE;
1311 log_fn(severity, LD_BUG,
1312 "State file contains unexpectedly high success counts "
1313 "%lf/%lf for Guard %s ($%s)",
1314 success_cnt, hop_cnt,
1315 node->nickname, hex_str(node->identity, DIGEST_LEN));
1316 success_cnt = hop_cnt;
1319 node->circ_attempts = hop_cnt;
1320 node->circ_successes = success_cnt;
1322 node->successful_circuits_closed = successful_closed;
1323 node->timeouts = timeouts;
1324 node->collapsed_circuits = collapsed;
1325 node->unusable_circuits = unusable;
1327 log_info(LD_GENERAL, "Read %f/%f path bias for node %s",
1328 node->circ_successes, node->circ_attempts, node->nickname);
1329 /* Note: We rely on the < comparison here to allow us to set a 0
1330 * rate and disable the feature entirely. If refactoring, don't
1331 * change to <= */
1332 if (pathbias_get_close_success_count(node)/node->circ_attempts
1333 < pathbias_get_extreme_rate(options) &&
1334 pathbias_get_dropguards(options)) {
1335 node->path_bias_disabled = 1;
1336 log_info(LD_GENERAL,
1337 "Path bias is too high (%f/%f); disabling node %s",
1338 node->circ_successes, node->circ_attempts, node->nickname);
1341 } else {
1342 log_warn(LD_BUG, "Unexpected key %s", line->key);
1346 SMARTLIST_FOREACH_BEGIN(new_entry_guards, entry_guard_t *, e) {
1347 char *sp;
1348 char *val = digestmap_get(added_by, e->identity);
1349 if (val && (sp = strchr(val, ' '))) {
1350 time_t when;
1351 *sp++ = '\0';
1352 if (parse_iso_time(sp, &when)<0) {
1353 log_warn(LD_BUG, "Can't read time %s in EntryGuardAddedBy", sp);
1354 } else {
1355 e->chosen_by_version = tor_strdup(val);
1356 e->chosen_on_date = when;
1358 } else {
1359 if (state_version) {
1360 e->chosen_by_version = tor_strdup(state_version);
1361 e->chosen_on_date = time(NULL) - crypto_rand_int(3600*24*30);
1364 if (e->path_bias_disabled && !e->bad_since)
1365 e->bad_since = time(NULL);
1367 SMARTLIST_FOREACH_END(e);
1369 if (*msg || !set) {
1370 SMARTLIST_FOREACH(new_entry_guards, entry_guard_t *, e,
1371 entry_guard_free(e));
1372 smartlist_free(new_entry_guards);
1373 } else { /* !err && set */
1374 if (entry_guards) {
1375 SMARTLIST_FOREACH(entry_guards, entry_guard_t *, e,
1376 entry_guard_free(e));
1377 smartlist_free(entry_guards);
1379 entry_guards = new_entry_guards;
1380 entry_guards_dirty = 0;
1381 /* XXX024 hand new_entry_guards to this func, and move it up a
1382 * few lines, so we don't have to re-dirty it */
1383 if (remove_obsolete_entry_guards(now))
1384 entry_guards_dirty = 1;
1386 update_node_guard_status();
1388 digestmap_free(added_by, tor_free_);
1389 return *msg ? -1 : 0;
1392 /** Our list of entry guards has changed, or some element of one
1393 * of our entry guards has changed. Write the changes to disk within
1394 * the next few minutes.
1396 void
1397 entry_guards_changed(void)
1399 time_t when;
1400 entry_guards_dirty = 1;
1402 /* or_state_save() will call entry_guards_update_state(). */
1403 when = get_options()->AvoidDiskWrites ? time(NULL) + 3600 : time(NULL)+600;
1404 or_state_mark_dirty(get_or_state(), when);
1407 /** If the entry guard info has not changed, do nothing and return.
1408 * Otherwise, free the EntryGuards piece of <b>state</b> and create
1409 * a new one out of the global entry_guards list, and then mark
1410 * <b>state</b> dirty so it will get saved to disk.
1412 void
1413 entry_guards_update_state(or_state_t *state)
1415 config_line_t **next, *line;
1416 if (! entry_guards_dirty)
1417 return;
1419 config_free_lines(state->EntryGuards);
1420 next = &state->EntryGuards;
1421 *next = NULL;
1422 if (!entry_guards)
1423 entry_guards = smartlist_new();
1424 SMARTLIST_FOREACH_BEGIN(entry_guards, entry_guard_t *, e) {
1425 char dbuf[HEX_DIGEST_LEN+1];
1426 if (!e->made_contact)
1427 continue; /* don't write this one to disk */
1428 *next = line = tor_malloc_zero(sizeof(config_line_t));
1429 line->key = tor_strdup("EntryGuard");
1430 base16_encode(dbuf, sizeof(dbuf), e->identity, DIGEST_LEN);
1431 tor_asprintf(&line->value, "%s %s %sDirCache", e->nickname, dbuf,
1432 e->is_dir_cache ? "" : "No");
1433 next = &(line->next);
1434 if (e->unreachable_since) {
1435 *next = line = tor_malloc_zero(sizeof(config_line_t));
1436 line->key = tor_strdup("EntryGuardDownSince");
1437 line->value = tor_malloc(ISO_TIME_LEN+1+ISO_TIME_LEN+1);
1438 format_iso_time(line->value, e->unreachable_since);
1439 if (e->last_attempted) {
1440 line->value[ISO_TIME_LEN] = ' ';
1441 format_iso_time(line->value+ISO_TIME_LEN+1, e->last_attempted);
1443 next = &(line->next);
1445 if (e->bad_since) {
1446 *next = line = tor_malloc_zero(sizeof(config_line_t));
1447 line->key = tor_strdup("EntryGuardUnlistedSince");
1448 line->value = tor_malloc(ISO_TIME_LEN+1);
1449 format_iso_time(line->value, e->bad_since);
1450 next = &(line->next);
1452 if (e->chosen_on_date && e->chosen_by_version &&
1453 !strchr(e->chosen_by_version, ' ')) {
1454 char d[HEX_DIGEST_LEN+1];
1455 char t[ISO_TIME_LEN+1];
1456 *next = line = tor_malloc_zero(sizeof(config_line_t));
1457 line->key = tor_strdup("EntryGuardAddedBy");
1458 base16_encode(d, sizeof(d), e->identity, DIGEST_LEN);
1459 format_iso_time(t, e->chosen_on_date);
1460 tor_asprintf(&line->value, "%s %s %s",
1461 d, e->chosen_by_version, t);
1462 next = &(line->next);
1464 if (e->circ_attempts > 0) {
1465 *next = line = tor_malloc_zero(sizeof(config_line_t));
1466 line->key = tor_strdup("EntryGuardPathBias");
1467 /* In the long run: circuit_success ~= successful_circuit_close +
1468 * collapsed_circuits +
1469 * unusable_circuits */
1470 tor_asprintf(&line->value, "%f %f %f %f %f %f",
1471 e->circ_attempts, e->circ_successes,
1472 pathbias_get_close_success_count(e),
1473 e->collapsed_circuits,
1474 e->unusable_circuits, e->timeouts);
1475 next = &(line->next);
1477 if (e->use_attempts > 0) {
1478 *next = line = tor_malloc_zero(sizeof(config_line_t));
1479 line->key = tor_strdup("EntryGuardPathUseBias");
1481 tor_asprintf(&line->value, "%f %f",
1482 e->use_attempts,
1483 pathbias_get_use_success_count(e));
1484 next = &(line->next);
1487 } SMARTLIST_FOREACH_END(e);
1488 if (!get_options()->AvoidDiskWrites)
1489 or_state_mark_dirty(get_or_state(), 0);
1490 entry_guards_dirty = 0;
1493 /** If <b>question</b> is the string "entry-guards", then dump
1494 * to *<b>answer</b> a newly allocated string describing all of
1495 * the nodes in the global entry_guards list. See control-spec.txt
1496 * for details.
1497 * For backward compatibility, we also handle the string "helper-nodes".
1498 * */
1500 getinfo_helper_entry_guards(control_connection_t *conn,
1501 const char *question, char **answer,
1502 const char **errmsg)
1504 (void) conn;
1505 (void) errmsg;
1507 if (!strcmp(question,"entry-guards") ||
1508 !strcmp(question,"helper-nodes")) {
1509 smartlist_t *sl = smartlist_new();
1510 char tbuf[ISO_TIME_LEN+1];
1511 char nbuf[MAX_VERBOSE_NICKNAME_LEN+1];
1512 if (!entry_guards)
1513 entry_guards = smartlist_new();
1514 SMARTLIST_FOREACH_BEGIN(entry_guards, entry_guard_t *, e) {
1515 const char *status = NULL;
1516 time_t when = 0;
1517 const node_t *node;
1519 if (!e->made_contact) {
1520 status = "never-connected";
1521 } else if (e->bad_since) {
1522 when = e->bad_since;
1523 status = "unusable";
1524 } else {
1525 status = "up";
1528 node = node_get_by_id(e->identity);
1529 if (node) {
1530 node_get_verbose_nickname(node, nbuf);
1531 } else {
1532 nbuf[0] = '$';
1533 base16_encode(nbuf+1, sizeof(nbuf)-1, e->identity, DIGEST_LEN);
1534 /* e->nickname field is not very reliable if we don't know about
1535 * this router any longer; don't include it. */
1538 if (when) {
1539 format_iso_time(tbuf, when);
1540 smartlist_add_asprintf(sl, "%s %s %s\n", nbuf, status, tbuf);
1541 } else {
1542 smartlist_add_asprintf(sl, "%s %s\n", nbuf, status);
1544 } SMARTLIST_FOREACH_END(e);
1545 *answer = smartlist_join_strings(sl, "", 0, NULL);
1546 SMARTLIST_FOREACH(sl, char *, c, tor_free(c));
1547 smartlist_free(sl);
1549 return 0;
1552 /** A list of configured bridges. Whenever we actually get a descriptor
1553 * for one, we add it as an entry guard. Note that the order of bridges
1554 * in this list does not necessarily correspond to the order of bridges
1555 * in the torrc. */
1556 static smartlist_t *bridge_list = NULL;
1558 /** Mark every entry of the bridge list to be removed on our next call to
1559 * sweep_bridge_list unless it has first been un-marked. */
1560 void
1561 mark_bridge_list(void)
1563 if (!bridge_list)
1564 bridge_list = smartlist_new();
1565 SMARTLIST_FOREACH(bridge_list, bridge_info_t *, b,
1566 b->marked_for_removal = 1);
1569 /** Remove every entry of the bridge list that was marked with
1570 * mark_bridge_list if it has not subsequently been un-marked. */
1571 void
1572 sweep_bridge_list(void)
1574 if (!bridge_list)
1575 bridge_list = smartlist_new();
1576 SMARTLIST_FOREACH_BEGIN(bridge_list, bridge_info_t *, b) {
1577 if (b->marked_for_removal) {
1578 SMARTLIST_DEL_CURRENT(bridge_list, b);
1579 bridge_free(b);
1581 } SMARTLIST_FOREACH_END(b);
1584 /** Initialize the bridge list to empty, creating it if needed. */
1585 static void
1586 clear_bridge_list(void)
1588 if (!bridge_list)
1589 bridge_list = smartlist_new();
1590 SMARTLIST_FOREACH(bridge_list, bridge_info_t *, b, bridge_free(b));
1591 smartlist_clear(bridge_list);
1594 /** Free the bridge <b>bridge</b>. */
1595 static void
1596 bridge_free(bridge_info_t *bridge)
1598 if (!bridge)
1599 return;
1601 tor_free(bridge->transport_name);
1602 tor_free(bridge);
1605 /** If we have a bridge configured whose digest matches <b>digest</b>, or a
1606 * bridge with no known digest whose address matches any of the
1607 * tor_addr_port_t's in <b>orports</b>, return that bridge. Else return
1608 * NULL. */
1609 static bridge_info_t *
1610 get_configured_bridge_by_orports_digest(const char *digest,
1611 const smartlist_t *orports)
1613 if (!bridge_list)
1614 return NULL;
1615 SMARTLIST_FOREACH_BEGIN(bridge_list, bridge_info_t *, bridge)
1617 if (tor_digest_is_zero(bridge->identity)) {
1618 SMARTLIST_FOREACH_BEGIN(orports, tor_addr_port_t *, ap)
1620 if (tor_addr_compare(&bridge->addr, &ap->addr, CMP_EXACT) == 0 &&
1621 bridge->port == ap->port)
1622 return bridge;
1624 SMARTLIST_FOREACH_END(ap);
1626 if (digest && tor_memeq(bridge->identity, digest, DIGEST_LEN))
1627 return bridge;
1629 SMARTLIST_FOREACH_END(bridge);
1630 return NULL;
1633 /** If we have a bridge configured whose digest matches <b>digest</b>, or a
1634 * bridge with no known digest whose address matches <b>addr</b>:<b>/port</b>,
1635 * return that bridge. Else return NULL. */
1636 static bridge_info_t *
1637 get_configured_bridge_by_addr_port_digest(const tor_addr_t *addr,
1638 uint16_t port,
1639 const char *digest)
1641 if (!bridge_list)
1642 return NULL;
1643 SMARTLIST_FOREACH_BEGIN(bridge_list, bridge_info_t *, bridge)
1645 if (tor_digest_is_zero(bridge->identity) &&
1646 !tor_addr_compare(&bridge->addr, addr, CMP_EXACT) &&
1647 bridge->port == port)
1648 return bridge;
1649 if (digest && tor_memeq(bridge->identity, digest, DIGEST_LEN))
1650 return bridge;
1652 SMARTLIST_FOREACH_END(bridge);
1653 return NULL;
1656 /** Wrapper around get_configured_bridge_by_addr_port_digest() to look
1657 * it up via router descriptor <b>ri</b>. */
1658 static bridge_info_t *
1659 get_configured_bridge_by_routerinfo(const routerinfo_t *ri)
1661 bridge_info_t *bi = NULL;
1662 smartlist_t *orports = router_get_all_orports(ri);
1663 bi = get_configured_bridge_by_orports_digest(ri->cache_info.identity_digest,
1664 orports);
1665 SMARTLIST_FOREACH(orports, tor_addr_port_t *, p, tor_free(p));
1666 smartlist_free(orports);
1667 return bi;
1670 /** Return 1 if <b>ri</b> is one of our known bridges, else 0. */
1672 routerinfo_is_a_configured_bridge(const routerinfo_t *ri)
1674 return get_configured_bridge_by_routerinfo(ri) ? 1 : 0;
1677 /** Return 1 if <b>node</b> is one of our configured bridges, else 0. */
1679 node_is_a_configured_bridge(const node_t *node)
1681 int retval = 0;
1682 smartlist_t *orports = node_get_all_orports(node);
1683 retval = get_configured_bridge_by_orports_digest(node->identity,
1684 orports) != NULL;
1685 SMARTLIST_FOREACH(orports, tor_addr_port_t *, p, tor_free(p));
1686 smartlist_free(orports);
1687 return retval;
1690 /** We made a connection to a router at <b>addr</b>:<b>port</b>
1691 * without knowing its digest. Its digest turned out to be <b>digest</b>.
1692 * If it was a bridge, and we still don't know its digest, record it.
1694 void
1695 learned_router_identity(const tor_addr_t *addr, uint16_t port,
1696 const char *digest)
1698 bridge_info_t *bridge =
1699 get_configured_bridge_by_addr_port_digest(addr, port, digest);
1700 if (bridge && tor_digest_is_zero(bridge->identity)) {
1701 char *transport_info = NULL;
1702 const char *transport_name =
1703 find_transport_name_by_bridge_addrport(addr, port);
1704 if (transport_name)
1705 tor_asprintf(&transport_info, " (with transport '%s')", transport_name);
1707 memcpy(bridge->identity, digest, DIGEST_LEN);
1708 log_notice(LD_DIR, "Learned fingerprint %s for bridge %s%s.",
1709 hex_str(digest, DIGEST_LEN), fmt_addrport(addr, port),
1710 transport_info ? transport_info : "");
1711 tor_free(transport_info);
1715 /** Return true if <b>bridge</b> has the same identity digest as
1716 * <b>digest</b>. If <b>digest</b> is NULL, it matches
1717 * bridges with unspecified identity digests. */
1718 static int
1719 bridge_has_digest(const bridge_info_t *bridge, const char *digest)
1721 if (digest)
1722 return tor_memeq(digest, bridge->identity, DIGEST_LEN);
1723 else
1724 return tor_digest_is_zero(bridge->identity);
1727 /** We are about to add a new bridge at <b>addr</b>:<b>port</b>, with optional
1728 * <b>digest</b> and <b>transport_name</b>. Mark for removal any previously
1729 * existing bridge with the same address and port, and warn the user as
1730 * appropriate.
1732 static void
1733 bridge_resolve_conflicts(const tor_addr_t *addr, uint16_t port,
1734 const char *digest, const char *transport_name)
1736 /* Iterate the already-registered bridge list:
1738 If you find a bridge with the same adress and port, mark it for
1739 removal. It doesn't make sense to have two active bridges with
1740 the same IP:PORT. If the bridge in question has a different
1741 digest or transport than <b>digest</b>/<b>transport_name</b>,
1742 it's probably a misconfiguration and we should warn the user.
1744 SMARTLIST_FOREACH_BEGIN(bridge_list, bridge_info_t *, bridge) {
1745 if (bridge->marked_for_removal)
1746 continue;
1748 if (tor_addr_eq(&bridge->addr, addr) && (bridge->port == port)) {
1750 bridge->marked_for_removal = 1;
1752 if (!bridge_has_digest(bridge, digest) ||
1753 strcmp_opt(bridge->transport_name, transport_name)) {
1754 /* warn the user */
1755 char *bridge_description_new, *bridge_description_old;
1756 tor_asprintf(&bridge_description_new, "%s:%s:%s",
1757 fmt_addrport(addr, port),
1758 digest ? hex_str(digest, DIGEST_LEN) : "",
1759 transport_name ? transport_name : "");
1760 tor_asprintf(&bridge_description_old, "%s:%s:%s",
1761 fmt_addrport(&bridge->addr, bridge->port),
1762 tor_digest_is_zero(bridge->identity) ?
1763 "" : hex_str(bridge->identity,DIGEST_LEN),
1764 bridge->transport_name ? bridge->transport_name : "");
1766 log_warn(LD_GENERAL,"Tried to add bridge '%s', but we found a conflict"
1767 " with the already registered bridge '%s'. We will discard"
1768 " the old bridge and keep '%s'. If this is not what you"
1769 " wanted, please change your configuration file accordingly.",
1770 bridge_description_new, bridge_description_old,
1771 bridge_description_new);
1773 tor_free(bridge_description_new);
1774 tor_free(bridge_description_old);
1777 } SMARTLIST_FOREACH_END(bridge);
1780 /** Remember a new bridge at <b>addr</b>:<b>port</b>. If <b>digest</b>
1781 * is set, it tells us the identity key too. If we already had the
1782 * bridge in our list, unmark it, and don't actually add anything new.
1783 * If <b>transport_name</b> is non-NULL - the bridge is associated with a
1784 * pluggable transport - we assign the transport to the bridge. */
1785 void
1786 bridge_add_from_config(const tor_addr_t *addr, uint16_t port,
1787 const char *digest, const char *transport_name)
1789 bridge_info_t *b;
1791 bridge_resolve_conflicts(addr, port, digest, transport_name);
1793 b = tor_malloc_zero(sizeof(bridge_info_t));
1794 tor_addr_copy(&b->addr, addr);
1795 b->port = port;
1796 if (digest)
1797 memcpy(b->identity, digest, DIGEST_LEN);
1798 if (transport_name)
1799 b->transport_name = tor_strdup(transport_name);
1800 b->fetch_status.schedule = DL_SCHED_BRIDGE;
1801 if (!bridge_list)
1802 bridge_list = smartlist_new();
1804 smartlist_add(bridge_list, b);
1807 /** Return true iff <b>routerset</b> contains the bridge <b>bridge</b>. */
1808 static int
1809 routerset_contains_bridge(const routerset_t *routerset,
1810 const bridge_info_t *bridge)
1812 int result;
1813 extend_info_t *extinfo;
1814 tor_assert(bridge);
1815 if (!routerset)
1816 return 0;
1818 extinfo = extend_info_new(
1819 NULL, bridge->identity, NULL, NULL, &bridge->addr, bridge->port);
1820 result = routerset_contains_extendinfo(routerset, extinfo);
1821 extend_info_free(extinfo);
1822 return result;
1825 /** If <b>digest</b> is one of our known bridges, return it. */
1826 static bridge_info_t *
1827 find_bridge_by_digest(const char *digest)
1829 SMARTLIST_FOREACH(bridge_list, bridge_info_t *, bridge,
1831 if (tor_memeq(bridge->identity, digest, DIGEST_LEN))
1832 return bridge;
1834 return NULL;
1837 /** Given the <b>addr</b> and <b>port</b> of a bridge, if that bridge
1838 * supports a pluggable transport, return its name. Otherwise, return
1839 * NULL. */
1840 const char *
1841 find_transport_name_by_bridge_addrport(const tor_addr_t *addr, uint16_t port)
1843 if (!bridge_list)
1844 return NULL;
1846 SMARTLIST_FOREACH_BEGIN(bridge_list, const bridge_info_t *, bridge) {
1847 if (tor_addr_eq(&bridge->addr, addr) &&
1848 (bridge->port == port))
1849 return bridge->transport_name;
1850 } SMARTLIST_FOREACH_END(bridge);
1852 return NULL;
1855 /** If <b>addr</b> and <b>port</b> match the address and port of a
1856 * bridge of ours that uses pluggable transports, place its transport
1857 * in <b>transport</b>.
1859 * Return 0 on success (found a transport, or found a bridge with no
1860 * transport, or found no bridge); return -1 if we should be using a
1861 * transport, but the transport could not be found.
1864 find_transport_by_bridge_addrport(const tor_addr_t *addr, uint16_t port,
1865 const transport_t **transport)
1867 *transport = NULL;
1868 if (!bridge_list)
1869 return 0;
1871 SMARTLIST_FOREACH_BEGIN(bridge_list, const bridge_info_t *, bridge) {
1872 if (tor_addr_eq(&bridge->addr, addr) &&
1873 (bridge->port == port)) { /* bridge matched */
1874 if (bridge->transport_name) { /* it also uses pluggable transports */
1875 *transport = transport_get_by_name(bridge->transport_name);
1876 if (*transport == NULL) { /* it uses pluggable transports, but
1877 the transport could not be found! */
1878 return -1;
1880 return 0;
1881 } else { /* bridge matched, but it doesn't use transports. */
1882 break;
1885 } SMARTLIST_FOREACH_END(bridge);
1887 *transport = NULL;
1888 return 0;
1891 /** We need to ask <b>bridge</b> for its server descriptor. */
1892 static void
1893 launch_direct_bridge_descriptor_fetch(bridge_info_t *bridge)
1895 char *address;
1896 const or_options_t *options = get_options();
1898 if (connection_get_by_type_addr_port_purpose(
1899 CONN_TYPE_DIR, &bridge->addr, bridge->port,
1900 DIR_PURPOSE_FETCH_SERVERDESC))
1901 return; /* it's already on the way */
1903 if (routerset_contains_bridge(options->ExcludeNodes, bridge)) {
1904 download_status_mark_impossible(&bridge->fetch_status);
1905 log_warn(LD_APP, "Not using bridge at %s: it is in ExcludeNodes.",
1906 safe_str_client(fmt_and_decorate_addr(&bridge->addr)));
1907 return;
1910 address = tor_dup_addr(&bridge->addr);
1912 directory_initiate_command(address, &bridge->addr,
1913 bridge->port, 0/*no dirport*/,
1914 bridge->identity,
1915 DIR_PURPOSE_FETCH_SERVERDESC,
1916 ROUTER_PURPOSE_BRIDGE,
1917 DIRIND_ONEHOP, "authority.z", NULL, 0, 0);
1918 tor_free(address);
1921 /** Fetching the bridge descriptor from the bridge authority returned a
1922 * "not found". Fall back to trying a direct fetch. */
1923 void
1924 retry_bridge_descriptor_fetch_directly(const char *digest)
1926 bridge_info_t *bridge = find_bridge_by_digest(digest);
1927 if (!bridge)
1928 return; /* not found? oh well. */
1930 launch_direct_bridge_descriptor_fetch(bridge);
1933 /** For each bridge in our list for which we don't currently have a
1934 * descriptor, fetch a new copy of its descriptor -- either directly
1935 * from the bridge or via a bridge authority. */
1936 void
1937 fetch_bridge_descriptors(const or_options_t *options, time_t now)
1939 int num_bridge_auths = get_n_authorities(BRIDGE_DIRINFO);
1940 int ask_bridge_directly;
1941 int can_use_bridge_authority;
1943 if (!bridge_list)
1944 return;
1946 /* If we still have unconfigured managed proxies, don't go and
1947 connect to a bridge. */
1948 if (pt_proxies_configuration_pending())
1949 return;
1951 SMARTLIST_FOREACH_BEGIN(bridge_list, bridge_info_t *, bridge)
1953 if (!download_status_is_ready(&bridge->fetch_status, now,
1954 IMPOSSIBLE_TO_DOWNLOAD))
1955 continue; /* don't bother, no need to retry yet */
1956 if (routerset_contains_bridge(options->ExcludeNodes, bridge)) {
1957 download_status_mark_impossible(&bridge->fetch_status);
1958 log_warn(LD_APP, "Not using bridge at %s: it is in ExcludeNodes.",
1959 safe_str_client(fmt_and_decorate_addr(&bridge->addr)));
1960 continue;
1963 /* schedule another fetch as if this one will fail, in case it does */
1964 download_status_failed(&bridge->fetch_status, 0);
1966 can_use_bridge_authority = !tor_digest_is_zero(bridge->identity) &&
1967 num_bridge_auths;
1968 ask_bridge_directly = !can_use_bridge_authority ||
1969 !options->UpdateBridgesFromAuthority;
1970 log_debug(LD_DIR, "ask_bridge_directly=%d (%d, %d, %d)",
1971 ask_bridge_directly, tor_digest_is_zero(bridge->identity),
1972 !options->UpdateBridgesFromAuthority, !num_bridge_auths);
1974 if (ask_bridge_directly &&
1975 !fascist_firewall_allows_address_or(&bridge->addr, bridge->port)) {
1976 log_notice(LD_DIR, "Bridge at '%s' isn't reachable by our "
1977 "firewall policy. %s.",
1978 fmt_addrport(&bridge->addr, bridge->port),
1979 can_use_bridge_authority ?
1980 "Asking bridge authority instead" : "Skipping");
1981 if (can_use_bridge_authority)
1982 ask_bridge_directly = 0;
1983 else
1984 continue;
1987 if (ask_bridge_directly) {
1988 /* we need to ask the bridge itself for its descriptor. */
1989 launch_direct_bridge_descriptor_fetch(bridge);
1990 } else {
1991 /* We have a digest and we want to ask an authority. We could
1992 * combine all the requests into one, but that may give more
1993 * hints to the bridge authority than we want to give. */
1994 char resource[10 + HEX_DIGEST_LEN];
1995 memcpy(resource, "fp/", 3);
1996 base16_encode(resource+3, HEX_DIGEST_LEN+1,
1997 bridge->identity, DIGEST_LEN);
1998 memcpy(resource+3+HEX_DIGEST_LEN, ".z", 3);
1999 log_info(LD_DIR, "Fetching bridge info '%s' from bridge authority.",
2000 resource);
2001 directory_get_from_dirserver(DIR_PURPOSE_FETCH_SERVERDESC,
2002 ROUTER_PURPOSE_BRIDGE, resource, 0);
2005 SMARTLIST_FOREACH_END(bridge);
2008 /** If our <b>bridge</b> is configured to be a different address than
2009 * the bridge gives in <b>node</b>, rewrite the routerinfo
2010 * we received to use the address we meant to use. Now we handle
2011 * multihomed bridges better.
2013 static void
2014 rewrite_node_address_for_bridge(const bridge_info_t *bridge, node_t *node)
2016 /* XXXX move this function. */
2017 /* XXXX overridden addresses should really live in the node_t, so that the
2018 * routerinfo_t and the microdesc_t can be immutable. But we can only
2019 * do that safely if we know that no function that connects to an OR
2020 * does so through an address from any source other than node_get_addr().
2022 tor_addr_t addr;
2024 if (node->ri) {
2025 routerinfo_t *ri = node->ri;
2026 tor_addr_from_ipv4h(&addr, ri->addr);
2028 if ((!tor_addr_compare(&bridge->addr, &addr, CMP_EXACT) &&
2029 bridge->port == ri->or_port) ||
2030 (!tor_addr_compare(&bridge->addr, &ri->ipv6_addr, CMP_EXACT) &&
2031 bridge->port == ri->ipv6_orport)) {
2032 /* they match, so no need to do anything */
2033 } else {
2034 if (tor_addr_family(&bridge->addr) == AF_INET) {
2035 ri->addr = tor_addr_to_ipv4h(&bridge->addr);
2036 tor_free(ri->address);
2037 ri->address = tor_dup_ip(ri->addr);
2038 ri->or_port = bridge->port;
2039 log_info(LD_DIR,
2040 "Adjusted bridge routerinfo for '%s' to match configured "
2041 "address %s:%d.",
2042 ri->nickname, ri->address, ri->or_port);
2043 } else if (tor_addr_family(&bridge->addr) == AF_INET6) {
2044 tor_addr_copy(&ri->ipv6_addr, &bridge->addr);
2045 ri->ipv6_orport = bridge->port;
2046 log_info(LD_DIR,
2047 "Adjusted bridge routerinfo for '%s' to match configured "
2048 "address %s.",
2049 ri->nickname, fmt_addrport(&ri->ipv6_addr, ri->ipv6_orport));
2050 } else {
2051 log_err(LD_BUG, "Address family not supported: %d.",
2052 tor_addr_family(&bridge->addr));
2053 return;
2057 /* Mark which address to use based on which bridge_t we got. */
2058 node->ipv6_preferred = (tor_addr_family(&bridge->addr) == AF_INET6 &&
2059 !tor_addr_is_null(&node->ri->ipv6_addr));
2061 /* XXXipv6 we lack support for falling back to another address for
2062 the same relay, warn the user */
2063 if (!tor_addr_is_null(&ri->ipv6_addr)) {
2064 tor_addr_port_t ap;
2065 node_get_pref_orport(node, &ap);
2066 log_notice(LD_CONFIG,
2067 "Bridge '%s' has both an IPv4 and an IPv6 address. "
2068 "Will prefer using its %s address (%s).",
2069 ri->nickname,
2070 tor_addr_family(&ap.addr) == AF_INET6 ? "IPv6" : "IPv4",
2071 fmt_addrport(&ap.addr, ap.port));
2074 if (node->rs) {
2075 routerstatus_t *rs = node->rs;
2076 tor_addr_from_ipv4h(&addr, rs->addr);
2078 if (!tor_addr_compare(&bridge->addr, &addr, CMP_EXACT) &&
2079 bridge->port == rs->or_port) {
2080 /* they match, so no need to do anything */
2081 } else {
2082 rs->addr = tor_addr_to_ipv4h(&bridge->addr);
2083 rs->or_port = bridge->port;
2084 log_info(LD_DIR,
2085 "Adjusted bridge routerstatus for '%s' to match "
2086 "configured address %s.",
2087 rs->nickname, fmt_addrport(&bridge->addr, rs->or_port));
2092 /** We just learned a descriptor for a bridge. See if that
2093 * digest is in our entry guard list, and add it if not. */
2094 void
2095 learned_bridge_descriptor(routerinfo_t *ri, int from_cache)
2097 tor_assert(ri);
2098 tor_assert(ri->purpose == ROUTER_PURPOSE_BRIDGE);
2099 if (get_options()->UseBridges) {
2100 int first = !any_bridge_descriptors_known();
2101 bridge_info_t *bridge = get_configured_bridge_by_routerinfo(ri);
2102 time_t now = time(NULL);
2103 router_set_status(ri->cache_info.identity_digest, 1);
2105 if (bridge) { /* if we actually want to use this one */
2106 node_t *node;
2107 /* it's here; schedule its re-fetch for a long time from now. */
2108 if (!from_cache)
2109 download_status_reset(&bridge->fetch_status);
2111 node = node_get_mutable_by_id(ri->cache_info.identity_digest);
2112 tor_assert(node);
2113 rewrite_node_address_for_bridge(bridge, node);
2114 add_an_entry_guard(node, 1, 1, 0, 0);
2116 log_notice(LD_DIR, "new bridge descriptor '%s' (%s): %s", ri->nickname,
2117 from_cache ? "cached" : "fresh", router_describe(ri));
2118 /* set entry->made_contact so if it goes down we don't drop it from
2119 * our entry node list */
2120 entry_guard_register_connect_status(ri->cache_info.identity_digest,
2121 1, 0, now);
2122 if (first) {
2123 /* XXXX apparently, this is never called. See bug #9229. */
2124 routerlist_retry_directory_downloads(now);
2127 update_networkstatus_downloads(now);
2132 /** Return 1 if any of our entry guards have descriptors that
2133 * are marked with purpose 'bridge' and are running. Else return 0.
2135 * We use this function to decide if we're ready to start building
2136 * circuits through our bridges, or if we need to wait until the
2137 * directory "server/authority" requests finish. */
2139 any_bridge_descriptors_known(void)
2141 tor_assert(get_options()->UseBridges);
2142 return choose_random_entry(NULL) != NULL;
2145 /** Return 1 if there are any directory conns fetching bridge descriptors
2146 * that aren't marked for close. We use this to guess if we should tell
2147 * the controller that we have a problem. */
2149 any_pending_bridge_descriptor_fetches(void)
2151 smartlist_t *conns = get_connection_array();
2152 SMARTLIST_FOREACH_BEGIN(conns, connection_t *, conn) {
2153 if (conn->type == CONN_TYPE_DIR &&
2154 conn->purpose == DIR_PURPOSE_FETCH_SERVERDESC &&
2155 TO_DIR_CONN(conn)->router_purpose == ROUTER_PURPOSE_BRIDGE &&
2156 !conn->marked_for_close &&
2157 conn->linked &&
2158 conn->linked_conn && !conn->linked_conn->marked_for_close) {
2159 log_debug(LD_DIR, "found one: %s", conn->address);
2160 return 1;
2162 } SMARTLIST_FOREACH_END(conn);
2163 return 0;
2166 /** Return 1 if we have at least one descriptor for an entry guard
2167 * (bridge or member of EntryNodes) and all descriptors we know are
2168 * down. Else return 0. If <b>act</b> is 1, then mark the down guards
2169 * up; else just observe and report. */
2170 static int
2171 entries_retry_helper(const or_options_t *options, int act)
2173 const node_t *node;
2174 int any_known = 0;
2175 int any_running = 0;
2176 int need_bridges = options->UseBridges != 0;
2177 if (!entry_guards)
2178 entry_guards = smartlist_new();
2179 SMARTLIST_FOREACH_BEGIN(entry_guards, entry_guard_t *, e) {
2180 node = node_get_by_id(e->identity);
2181 if (node && node_has_descriptor(node) &&
2182 node_is_bridge(node) == need_bridges) {
2183 any_known = 1;
2184 if (node->is_running)
2185 any_running = 1; /* some entry is both known and running */
2186 else if (act) {
2187 /* Mark all current connections to this OR as unhealthy, since
2188 * otherwise there could be one that started 30 seconds
2189 * ago, and in 30 seconds it will time out, causing us to mark
2190 * the node down and undermine the retry attempt. We mark even
2191 * the established conns, since if the network just came back
2192 * we'll want to attach circuits to fresh conns. */
2193 connection_or_set_bad_connections(node->identity, 1);
2195 /* mark this entry node for retry */
2196 router_set_status(node->identity, 1);
2197 e->can_retry = 1;
2198 e->bad_since = 0;
2201 } SMARTLIST_FOREACH_END(e);
2202 log_debug(LD_DIR, "%d: any_known %d, any_running %d",
2203 act, any_known, any_running);
2204 return any_known && !any_running;
2207 /** Do we know any descriptors for our bridges / entrynodes, and are
2208 * all the ones we have descriptors for down? */
2210 entries_known_but_down(const or_options_t *options)
2212 tor_assert(entry_list_is_constrained(options));
2213 return entries_retry_helper(options, 0);
2216 /** Mark all down known bridges / entrynodes up. */
2217 void
2218 entries_retry_all(const or_options_t *options)
2220 tor_assert(entry_list_is_constrained(options));
2221 entries_retry_helper(options, 1);
2224 /** Return true if at least one of our bridges runs a Tor version that can
2225 * provide microdescriptors to us. If not, we'll fall back to asking for
2226 * full descriptors. */
2228 any_bridge_supports_microdescriptors(void)
2230 const node_t *node;
2231 if (!get_options()->UseBridges || !entry_guards)
2232 return 0;
2233 SMARTLIST_FOREACH_BEGIN(entry_guards, entry_guard_t *, e) {
2234 node = node_get_by_id(e->identity);
2235 if (node && node->is_running &&
2236 node_is_bridge(node) && node_is_a_configured_bridge(node) &&
2237 node_understands_microdescriptors(node)) {
2238 /* This is one of our current bridges, and we know enough about
2239 * it to know that it will be able to answer our microdescriptor
2240 * questions. */
2241 return 1;
2243 } SMARTLIST_FOREACH_END(e);
2244 return 0;
2247 /** Release all storage held by the list of entry guards and related
2248 * memory structs. */
2249 void
2250 entry_guards_free_all(void)
2252 if (entry_guards) {
2253 SMARTLIST_FOREACH(entry_guards, entry_guard_t *, e,
2254 entry_guard_free(e));
2255 smartlist_free(entry_guards);
2256 entry_guards = NULL;
2258 clear_bridge_list();
2259 smartlist_free(bridge_list);
2260 bridge_list = NULL;
2261 circuit_build_times_free_timeouts(&circ_times);