In routerlist_assert_ok(), check r2 before taking &(r2->cache_info)
[tor.git] / src / or / entrynodes.c
blob66b720118797fc40bf7a882a58c97337a4b35040
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 "circpathbias.h"
17 #include "circuitbuild.h"
18 #include "circuitstats.h"
19 #include "config.h"
20 #include "confparse.h"
21 #include "connection.h"
22 #include "connection_or.h"
23 #include "control.h"
24 #include "directory.h"
25 #include "entrynodes.h"
26 #include "main.h"
27 #include "microdesc.h"
28 #include "networkstatus.h"
29 #include "nodelist.h"
30 #include "policies.h"
31 #include "router.h"
32 #include "routerlist.h"
33 #include "routerparse.h"
34 #include "routerset.h"
35 #include "transports.h"
36 #include "statefile.h"
38 /** Information about a configured bridge. Currently this just matches the
39 * ones in the torrc file, but one day we may be able to learn about new
40 * bridges on our own, and remember them in the state file. */
41 typedef struct {
42 /** Address of the bridge. */
43 tor_addr_t addr;
44 /** TLS port for the bridge. */
45 uint16_t port;
46 /** Boolean: We are re-parsing our bridge list, and we are going to remove
47 * this one if we don't find it in the list of configured bridges. */
48 unsigned marked_for_removal : 1;
49 /** Expected identity digest, or all zero bytes if we don't know what the
50 * digest should be. */
51 char identity[DIGEST_LEN];
53 /** Name of pluggable transport protocol taken from its config line. */
54 char *transport_name;
56 /** When should we next try to fetch a descriptor for this bridge? */
57 download_status_t fetch_status;
59 /** A smartlist of k=v values to be passed to the SOCKS proxy, if
60 transports are used for this bridge. */
61 smartlist_t *socks_args;
62 } bridge_info_t;
64 /** A list of our chosen entry guards. */
65 static smartlist_t *entry_guards = NULL;
66 /** A value of 1 means that the entry_guards list has changed
67 * and those changes need to be flushed to disk. */
68 static int entry_guards_dirty = 0;
70 static void bridge_free(bridge_info_t *bridge);
71 static const node_t *choose_random_entry_impl(cpath_build_state_t *state,
72 int for_directory,
73 dirinfo_type_t dirtype,
74 int *n_options_out);
75 static int num_bridges_usable(void);
77 /** Return the list of entry guards, creating it if necessary. */
78 const smartlist_t *
79 get_entry_guards(void)
81 if (! entry_guards)
82 entry_guards = smartlist_new();
83 return entry_guards;
86 /** Check whether the entry guard <b>e</b> is usable, given the directory
87 * authorities' opinion about the router (stored in <b>ri</b>) and the user's
88 * configuration (in <b>options</b>). Set <b>e</b>-&gt;bad_since
89 * accordingly. Return true iff the entry guard's status changes.
91 * If it's not usable, set *<b>reason</b> to a static string explaining why.
93 static int
94 entry_guard_set_status(entry_guard_t *e, const node_t *node,
95 time_t now, const or_options_t *options,
96 const char **reason)
98 char buf[HEX_DIGEST_LEN+1];
99 int changed = 0;
101 *reason = NULL;
103 /* Do we want to mark this guard as bad? */
104 if (!node)
105 *reason = "unlisted";
106 else if (!node->is_running)
107 *reason = "down";
108 else if (options->UseBridges && (!node->ri ||
109 node->ri->purpose != ROUTER_PURPOSE_BRIDGE))
110 *reason = "not a bridge";
111 else if (options->UseBridges && !node_is_a_configured_bridge(node))
112 *reason = "not a configured bridge";
113 else if (!options->UseBridges && !node->is_possible_guard &&
114 !routerset_contains_node(options->EntryNodes,node))
115 *reason = "not recommended as a guard";
116 else if (routerset_contains_node(options->ExcludeNodes, node))
117 *reason = "excluded";
118 else if (e->path_bias_disabled)
119 *reason = "path-biased";
121 if (*reason && ! e->bad_since) {
122 /* Router is newly bad. */
123 base16_encode(buf, sizeof(buf), e->identity, DIGEST_LEN);
124 log_info(LD_CIRC, "Entry guard %s (%s) is %s: marking as unusable.",
125 e->nickname, buf, *reason);
127 e->bad_since = now;
128 control_event_guard(e->nickname, e->identity, "BAD");
129 changed = 1;
130 } else if (!*reason && e->bad_since) {
131 /* There's nothing wrong with the router any more. */
132 base16_encode(buf, sizeof(buf), e->identity, DIGEST_LEN);
133 log_info(LD_CIRC, "Entry guard %s (%s) is no longer unusable: "
134 "marking as ok.", e->nickname, buf);
136 e->bad_since = 0;
137 control_event_guard(e->nickname, e->identity, "GOOD");
138 changed = 1;
141 if (node) {
142 int is_dir = node_is_dir(node) && node->rs &&
143 node->rs->version_supports_microdesc_cache;
144 if (options->UseBridges && node_is_a_configured_bridge(node))
145 is_dir = 1;
146 if (e->is_dir_cache != is_dir) {
147 e->is_dir_cache = is_dir;
148 changed = 1;
152 return changed;
155 /** Return true iff enough time has passed since we last tried to connect
156 * to the unreachable guard <b>e</b> that we're willing to try again. */
157 static int
158 entry_is_time_to_retry(entry_guard_t *e, time_t now)
160 long diff;
161 if (e->last_attempted < e->unreachable_since)
162 return 1;
163 diff = now - e->unreachable_since;
164 if (diff < 6*60*60)
165 return now > (e->last_attempted + 60*60);
166 else if (diff < 3*24*60*60)
167 return now > (e->last_attempted + 4*60*60);
168 else if (diff < 7*24*60*60)
169 return now > (e->last_attempted + 18*60*60);
170 else
171 return now > (e->last_attempted + 36*60*60);
174 /** Return the node corresponding to <b>e</b>, if <b>e</b> is
175 * working well enough that we are willing to use it as an entry
176 * right now. (Else return NULL.) In particular, it must be
177 * - Listed as either up or never yet contacted;
178 * - Present in the routerlist;
179 * - Listed as 'stable' or 'fast' by the current dirserver consensus,
180 * if demanded by <b>need_uptime</b> or <b>need_capacity</b>
181 * (unless it's a configured EntryNode);
182 * - Allowed by our current ReachableORAddresses config option; and
183 * - Currently thought to be reachable by us (unless <b>assume_reachable</b>
184 * is true).
186 * If the answer is no, set *<b>msg</b> to an explanation of why.
188 * If need_descriptor is true, only return the node if we currently have
189 * a descriptor (routerinfo or microdesc) for it.
191 static INLINE const node_t *
192 entry_is_live(entry_guard_t *e, int need_uptime, int need_capacity,
193 int assume_reachable, int need_descriptor, const char **msg)
195 const node_t *node;
196 const or_options_t *options = get_options();
197 tor_assert(msg);
199 if (e->path_bias_disabled) {
200 *msg = "path-biased";
201 return NULL;
203 if (e->bad_since) {
204 *msg = "bad";
205 return NULL;
207 /* no good if it's unreachable, unless assume_unreachable or can_retry. */
208 if (!assume_reachable && !e->can_retry &&
209 e->unreachable_since && !entry_is_time_to_retry(e, time(NULL))) {
210 *msg = "unreachable";
211 return NULL;
213 node = node_get_by_id(e->identity);
214 if (!node) {
215 *msg = "no node info";
216 return NULL;
218 if (need_descriptor && !node_has_descriptor(node)) {
219 *msg = "no descriptor";
220 return NULL;
222 if (get_options()->UseBridges) {
223 if (node_get_purpose(node) != ROUTER_PURPOSE_BRIDGE) {
224 *msg = "not a bridge";
225 return NULL;
227 if (!node_is_a_configured_bridge(node)) {
228 *msg = "not a configured bridge";
229 return NULL;
231 } else { /* !get_options()->UseBridges */
232 if (node_get_purpose(node) != ROUTER_PURPOSE_GENERAL) {
233 *msg = "not general-purpose";
234 return NULL;
237 if (routerset_contains_node(options->EntryNodes, node)) {
238 /* they asked for it, they get it */
239 need_uptime = need_capacity = 0;
241 if (node_is_unreliable(node, need_uptime, need_capacity, 0)) {
242 *msg = "not fast/stable";
243 return NULL;
245 if (!fascist_firewall_allows_node(node)) {
246 *msg = "unreachable by config";
247 return NULL;
249 return node;
252 /** Return the number of entry guards that we think are usable. */
254 num_live_entry_guards(int for_directory)
256 int n = 0;
257 const char *msg;
258 if (! entry_guards)
259 return 0;
260 SMARTLIST_FOREACH_BEGIN(entry_guards, entry_guard_t *, entry) {
261 if (for_directory && !entry->is_dir_cache)
262 continue;
263 if (entry_is_live(entry, 0, 1, 0, !for_directory, &msg))
264 ++n;
265 } SMARTLIST_FOREACH_END(entry);
266 return n;
269 /** If <b>digest</b> matches the identity of any node in the
270 * entry_guards list, return that node. Else return NULL. */
271 entry_guard_t *
272 entry_guard_get_by_id_digest(const char *digest)
274 SMARTLIST_FOREACH(entry_guards, entry_guard_t *, entry,
275 if (tor_memeq(digest, entry->identity, DIGEST_LEN))
276 return entry;
278 return NULL;
281 /** Dump a description of our list of entry guards to the log at level
282 * <b>severity</b>. */
283 static void
284 log_entry_guards(int severity)
286 smartlist_t *elements = smartlist_new();
287 char *s;
289 SMARTLIST_FOREACH_BEGIN(entry_guards, entry_guard_t *, e)
291 const char *msg = NULL;
292 if (entry_is_live(e, 0, 1, 0, 0, &msg))
293 smartlist_add_asprintf(elements, "%s [%s] (up %s)",
294 e->nickname,
295 hex_str(e->identity, DIGEST_LEN),
296 e->made_contact ? "made-contact" : "never-contacted");
297 else
298 smartlist_add_asprintf(elements, "%s [%s] (%s, %s)",
299 e->nickname,
300 hex_str(e->identity, DIGEST_LEN),
301 msg,
302 e->made_contact ? "made-contact" : "never-contacted");
304 SMARTLIST_FOREACH_END(e);
306 s = smartlist_join_strings(elements, ",", 0, NULL);
307 SMARTLIST_FOREACH(elements, char*, cp, tor_free(cp));
308 smartlist_free(elements);
309 log_fn(severity,LD_CIRC,"%s",s);
310 tor_free(s);
313 /** Called when one or more guards that we would previously have used for some
314 * purpose are no longer in use because a higher-priority guard has become
315 * usable again. */
316 static void
317 control_event_guard_deferred(void)
319 /* XXXX We don't actually have a good way to figure out _how many_ entries
320 * are live for some purpose. We need an entry_is_even_slightly_live()
321 * function for this to work right. NumEntryGuards isn't reliable: if we
322 * need guards with weird properties, we can have more than that number
323 * live.
325 #if 0
326 int n = 0;
327 const char *msg;
328 const or_options_t *options = get_options();
329 if (!entry_guards)
330 return;
331 SMARTLIST_FOREACH(entry_guards, entry_guard_t *, entry,
333 if (entry_is_live(entry, 0, 1, 0, &msg)) {
334 if (n++ == options->NumEntryGuards) {
335 control_event_guard(entry->nickname, entry->identity, "DEFERRED");
336 return;
340 #endif
343 /** Largest amount that we'll backdate chosen_on_date */
344 #define CHOSEN_ON_DATE_SLOP (30*86400)
346 /** Add a new (preferably stable and fast) router to our
347 * entry_guards list. Return a pointer to the router if we succeed,
348 * or NULL if we can't find any more suitable entries.
350 * If <b>chosen</b> is defined, use that one, and if it's not
351 * already in our entry_guards list, put it at the *beginning*.
352 * Else, put the one we pick at the end of the list. */
353 static const node_t *
354 add_an_entry_guard(const node_t *chosen, int reset_status, int prepend,
355 int for_discovery, int for_directory)
357 const node_t *node;
358 entry_guard_t *entry;
360 if (chosen) {
361 node = chosen;
362 entry = entry_guard_get_by_id_digest(node->identity);
363 if (entry) {
364 if (reset_status) {
365 entry->bad_since = 0;
366 entry->can_retry = 1;
368 entry->is_dir_cache = node->rs &&
369 node->rs->version_supports_microdesc_cache;
370 if (get_options()->UseBridges && node_is_a_configured_bridge(node))
371 entry->is_dir_cache = 1;
372 return NULL;
374 } else if (!for_directory) {
375 node = choose_good_entry_server(CIRCUIT_PURPOSE_C_GENERAL, NULL);
376 if (!node)
377 return NULL;
378 } else {
379 const routerstatus_t *rs;
380 rs = router_pick_directory_server(MICRODESC_DIRINFO|V3_DIRINFO,
381 PDS_FOR_GUARD);
382 if (!rs)
383 return NULL;
384 node = node_get_by_id(rs->identity_digest);
385 if (!node)
386 return NULL;
388 if (node->using_as_guard)
389 return NULL;
390 if (entry_guard_get_by_id_digest(node->identity) != NULL) {
391 log_info(LD_CIRC, "I was about to add a duplicate entry guard.");
392 /* This can happen if we choose a guard, then the node goes away, then
393 * comes back. */
394 ((node_t*) node)->using_as_guard = 1;
395 return NULL;
397 entry = tor_malloc_zero(sizeof(entry_guard_t));
398 log_info(LD_CIRC, "Chose %s as new entry guard.",
399 node_describe(node));
400 strlcpy(entry->nickname, node_get_nickname(node), sizeof(entry->nickname));
401 memcpy(entry->identity, node->identity, DIGEST_LEN);
402 entry->is_dir_cache = node_is_dir(node) && node->rs &&
403 node->rs->version_supports_microdesc_cache;
404 if (get_options()->UseBridges && node_is_a_configured_bridge(node))
405 entry->is_dir_cache = 1;
407 /* Choose expiry time smudged over the past month. The goal here
408 * is to a) spread out when Tor clients rotate their guards, so they
409 * don't all select them on the same day, and b) avoid leaving a
410 * precise timestamp in the state file about when we first picked
411 * this guard. For details, see the Jan 2010 or-dev thread. */
412 entry->chosen_on_date = time(NULL) - crypto_rand_int(3600*24*30);
413 entry->chosen_by_version = tor_strdup(VERSION);
415 /* Are we picking this guard because all of our current guards are
416 * down so we need another one (for_discovery is 1), or because we
417 * decided we need more variety in our guard list (for_discovery is 0)?
419 * Currently we hack this behavior into place by setting "made_contact"
420 * for guards of the latter variety, so we'll be willing to use any of
421 * them right off the bat.
423 if (!for_discovery)
424 entry->made_contact = 1;
426 ((node_t*)node)->using_as_guard = 1;
427 if (prepend)
428 smartlist_insert(entry_guards, 0, entry);
429 else
430 smartlist_add(entry_guards, entry);
431 control_event_guard(entry->nickname, entry->identity, "NEW");
432 control_event_guard_deferred();
433 log_entry_guards(LOG_INFO);
434 return node;
437 /** Choose how many entry guards or directory guards we'll use. If
438 * <b>for_directory</b> is true, we return how many directory guards to
439 * use; else we return how many entry guards to use. */
440 static int
441 decide_num_guards(const or_options_t *options, int for_directory)
443 if (for_directory) {
444 int answer;
445 if (options->NumDirectoryGuards != 0)
446 return options->NumDirectoryGuards;
447 answer = networkstatus_get_param(NULL, "NumDirectoryGuards", 0, 0, 10);
448 if (answer) /* non-zero means use the consensus value */
449 return answer;
452 if (options->NumEntryGuards)
453 return options->NumEntryGuards;
455 /* Use the value from the consensus, or 3 if no guidance. */
456 return networkstatus_get_param(NULL, "NumEntryGuards", 3, 1, 10);
459 /** If the use of entry guards is configured, choose more entry guards
460 * until we have enough in the list. */
461 static void
462 pick_entry_guards(const or_options_t *options, int for_directory)
464 int changed = 0;
465 const int num_needed = decide_num_guards(options, for_directory);
467 tor_assert(entry_guards);
469 while (num_live_entry_guards(for_directory) < num_needed) {
470 if (!add_an_entry_guard(NULL, 0, 0, 0, for_directory))
471 break;
472 changed = 1;
474 if (changed)
475 entry_guards_changed();
478 /** How long (in seconds) do we allow an entry guard to be nonfunctional,
479 * unlisted, excluded, or otherwise nonusable before we give up on it? */
480 #define ENTRY_GUARD_REMOVE_AFTER (30*24*60*60)
482 /** Release all storage held by <b>e</b>. */
483 static void
484 entry_guard_free(entry_guard_t *e)
486 if (!e)
487 return;
488 tor_free(e->chosen_by_version);
489 tor_free(e);
493 * Return the minimum lifetime of working entry guard, in seconds,
494 * as given in the consensus networkstatus. (Plus CHOSEN_ON_DATE_SLOP,
495 * so that we can do the chosen_on_date randomization while achieving the
496 * desired minimum lifetime.)
498 static int32_t
499 guards_get_lifetime(void)
501 const or_options_t *options = get_options();
502 #define DFLT_GUARD_LIFETIME (86400 * 60) /* Two months. */
503 #define MIN_GUARD_LIFETIME (86400 * 30) /* One months. */
504 #define MAX_GUARD_LIFETIME (86400 * 1826) /* Five years. */
506 if (options->GuardLifetime >= 1) {
507 return CLAMP(MIN_GUARD_LIFETIME,
508 options->GuardLifetime,
509 MAX_GUARD_LIFETIME) + CHOSEN_ON_DATE_SLOP;
512 return networkstatus_get_param(NULL, "GuardLifetime",
513 DFLT_GUARD_LIFETIME,
514 MIN_GUARD_LIFETIME,
515 MAX_GUARD_LIFETIME) + CHOSEN_ON_DATE_SLOP;
518 /** Remove any entry guard which was selected by an unknown version of Tor,
519 * or which was selected by a version of Tor that's known to select
520 * entry guards badly, or which was selected more 2 months ago. */
521 /* XXXX The "obsolete guards" and "chosen long ago guards" things should
522 * probably be different functions. */
523 static int
524 remove_obsolete_entry_guards(time_t now)
526 int changed = 0, i;
527 int32_t guard_lifetime = guards_get_lifetime();
529 for (i = 0; i < smartlist_len(entry_guards); ++i) {
530 entry_guard_t *entry = smartlist_get(entry_guards, i);
531 const char *ver = entry->chosen_by_version;
532 const char *msg = NULL;
533 tor_version_t v;
534 int version_is_bad = 0, date_is_bad = 0;
535 if (!ver) {
536 msg = "does not say what version of Tor it was selected by";
537 version_is_bad = 1;
538 } else if (tor_version_parse(ver, &v)) {
539 msg = "does not seem to be from any recognized version of Tor";
540 version_is_bad = 1;
541 } else {
542 char *tor_ver = NULL;
543 tor_asprintf(&tor_ver, "Tor %s", ver);
544 if ((tor_version_as_new_as(tor_ver, "0.1.0.10-alpha") &&
545 !tor_version_as_new_as(tor_ver, "0.1.2.16-dev")) ||
546 (tor_version_as_new_as(tor_ver, "0.2.0.0-alpha") &&
547 !tor_version_as_new_as(tor_ver, "0.2.0.6-alpha")) ||
548 /* above are bug 440; below are bug 1217 */
549 (tor_version_as_new_as(tor_ver, "0.2.1.3-alpha") &&
550 !tor_version_as_new_as(tor_ver, "0.2.1.23")) ||
551 (tor_version_as_new_as(tor_ver, "0.2.2.0-alpha") &&
552 !tor_version_as_new_as(tor_ver, "0.2.2.7-alpha"))) {
553 msg = "was selected without regard for guard bandwidth";
554 version_is_bad = 1;
556 tor_free(tor_ver);
558 if (!version_is_bad && entry->chosen_on_date + guard_lifetime < now) {
559 /* It's been too long since the date listed in our state file. */
560 msg = "was selected several months ago";
561 date_is_bad = 1;
564 if (version_is_bad || date_is_bad) { /* we need to drop it */
565 char dbuf[HEX_DIGEST_LEN+1];
566 tor_assert(msg);
567 base16_encode(dbuf, sizeof(dbuf), entry->identity, DIGEST_LEN);
568 log_fn(version_is_bad ? LOG_NOTICE : LOG_INFO, LD_CIRC,
569 "Entry guard '%s' (%s) %s. (Version=%s.) Replacing it.",
570 entry->nickname, dbuf, msg, ver?escaped(ver):"none");
571 control_event_guard(entry->nickname, entry->identity, "DROPPED");
572 entry_guard_free(entry);
573 smartlist_del_keeporder(entry_guards, i--);
574 log_entry_guards(LOG_INFO);
575 changed = 1;
579 return changed ? 1 : 0;
582 /** Remove all entry guards that have been down or unlisted for so
583 * long that we don't think they'll come up again. Return 1 if we
584 * removed any, or 0 if we did nothing. */
585 static int
586 remove_dead_entry_guards(time_t now)
588 char dbuf[HEX_DIGEST_LEN+1];
589 char tbuf[ISO_TIME_LEN+1];
590 int i;
591 int changed = 0;
593 for (i = 0; i < smartlist_len(entry_guards); ) {
594 entry_guard_t *entry = smartlist_get(entry_guards, i);
595 if (entry->bad_since &&
596 ! entry->path_bias_disabled &&
597 entry->bad_since + ENTRY_GUARD_REMOVE_AFTER < now) {
599 base16_encode(dbuf, sizeof(dbuf), entry->identity, DIGEST_LEN);
600 format_local_iso_time(tbuf, entry->bad_since);
601 log_info(LD_CIRC, "Entry guard '%s' (%s) has been down or unlisted "
602 "since %s local time; removing.",
603 entry->nickname, dbuf, tbuf);
604 control_event_guard(entry->nickname, entry->identity, "DROPPED");
605 entry_guard_free(entry);
606 smartlist_del_keeporder(entry_guards, i);
607 log_entry_guards(LOG_INFO);
608 changed = 1;
609 } else
610 ++i;
612 return changed ? 1 : 0;
615 /** Remove all currently listed entry guards. So new ones will be chosen. */
616 void
617 remove_all_entry_guards(void)
619 char dbuf[HEX_DIGEST_LEN+1];
621 while (smartlist_len(entry_guards)) {
622 entry_guard_t *entry = smartlist_get(entry_guards, 0);
623 base16_encode(dbuf, sizeof(dbuf), entry->identity, DIGEST_LEN);
624 log_info(LD_CIRC, "Entry guard '%s' (%s) has been dropped.",
625 entry->nickname, dbuf);
626 control_event_guard(entry->nickname, entry->identity, "DROPPED");
627 entry_guard_free(entry);
628 smartlist_del(entry_guards, 0);
630 log_entry_guards(LOG_INFO);
631 entry_guards_changed();
634 /** A new directory or router-status has arrived; update the down/listed
635 * status of the entry guards.
637 * An entry is 'down' if the directory lists it as nonrunning.
638 * An entry is 'unlisted' if the directory doesn't include it.
640 * Don't call this on startup; only on a fresh download. Otherwise we'll
641 * think that things are unlisted.
643 void
644 entry_guards_compute_status(const or_options_t *options, time_t now)
646 int changed = 0;
647 digestmap_t *reasons;
649 if (! entry_guards)
650 return;
652 if (options->EntryNodes) /* reshuffle the entry guard list if needed */
653 entry_nodes_should_be_added();
655 reasons = digestmap_new();
656 SMARTLIST_FOREACH_BEGIN(entry_guards, entry_guard_t *, entry)
658 const node_t *r = node_get_by_id(entry->identity);
659 const char *reason = NULL;
660 if (entry_guard_set_status(entry, r, now, options, &reason))
661 changed = 1;
663 if (entry->bad_since)
664 tor_assert(reason);
665 if (reason)
666 digestmap_set(reasons, entry->identity, (char*)reason);
668 SMARTLIST_FOREACH_END(entry);
670 if (remove_dead_entry_guards(now))
671 changed = 1;
672 if (remove_obsolete_entry_guards(now))
673 changed = 1;
675 if (changed) {
676 SMARTLIST_FOREACH_BEGIN(entry_guards, entry_guard_t *, entry) {
677 const char *reason = digestmap_get(reasons, entry->identity);
678 const char *live_msg = "";
679 const node_t *r = entry_is_live(entry, 0, 1, 0, 0, &live_msg);
680 log_info(LD_CIRC, "Summary: Entry %s [%s] is %s, %s%s%s, and %s%s.",
681 entry->nickname,
682 hex_str(entry->identity, DIGEST_LEN),
683 entry->unreachable_since ? "unreachable" : "reachable",
684 entry->bad_since ? "unusable" : "usable",
685 reason ? ", ": "",
686 reason ? reason : "",
687 r ? "live" : "not live / ",
688 r ? "" : live_msg);
689 } SMARTLIST_FOREACH_END(entry);
690 log_info(LD_CIRC, " (%d/%d entry guards are usable/new)",
691 num_live_entry_guards(0), smartlist_len(entry_guards));
692 log_entry_guards(LOG_INFO);
693 entry_guards_changed();
696 digestmap_free(reasons, NULL);
699 /** Called when a connection to an OR with the identity digest <b>digest</b>
700 * is established (<b>succeeded</b>==1) or has failed (<b>succeeded</b>==0).
701 * If the OR is an entry, change that entry's up/down status.
702 * Return 0 normally, or -1 if we want to tear down the new connection.
704 * If <b>mark_relay_status</b>, also call router_set_status() on this
705 * relay.
707 * XXX024 change succeeded and mark_relay_status into 'int flags'.
710 entry_guard_register_connect_status(const char *digest, int succeeded,
711 int mark_relay_status, time_t now)
713 int changed = 0;
714 int refuse_conn = 0;
715 int first_contact = 0;
716 entry_guard_t *entry = NULL;
717 int idx = -1;
718 char buf[HEX_DIGEST_LEN+1];
720 if (! entry_guards)
721 return 0;
723 SMARTLIST_FOREACH_BEGIN(entry_guards, entry_guard_t *, e) {
724 tor_assert(e);
725 if (tor_memeq(e->identity, digest, DIGEST_LEN)) {
726 entry = e;
727 idx = e_sl_idx;
728 break;
730 } SMARTLIST_FOREACH_END(e);
732 if (!entry)
733 return 0;
735 base16_encode(buf, sizeof(buf), entry->identity, DIGEST_LEN);
737 if (succeeded) {
738 if (entry->unreachable_since) {
739 log_info(LD_CIRC, "Entry guard '%s' (%s) is now reachable again. Good.",
740 entry->nickname, buf);
741 entry->can_retry = 0;
742 entry->unreachable_since = 0;
743 entry->last_attempted = now;
744 control_event_guard(entry->nickname, entry->identity, "UP");
745 changed = 1;
747 if (!entry->made_contact) {
748 entry->made_contact = 1;
749 first_contact = changed = 1;
751 } else { /* ! succeeded */
752 if (!entry->made_contact) {
753 /* We've never connected to this one. */
754 log_info(LD_CIRC,
755 "Connection to never-contacted entry guard '%s' (%s) failed. "
756 "Removing from the list. %d/%d entry guards usable/new.",
757 entry->nickname, buf,
758 num_live_entry_guards(0)-1, smartlist_len(entry_guards)-1);
759 control_event_guard(entry->nickname, entry->identity, "DROPPED");
760 entry_guard_free(entry);
761 smartlist_del_keeporder(entry_guards, idx);
762 log_entry_guards(LOG_INFO);
763 changed = 1;
764 } else if (!entry->unreachable_since) {
765 log_info(LD_CIRC, "Unable to connect to entry guard '%s' (%s). "
766 "Marking as unreachable.", entry->nickname, buf);
767 entry->unreachable_since = entry->last_attempted = now;
768 control_event_guard(entry->nickname, entry->identity, "DOWN");
769 changed = 1;
770 entry->can_retry = 0; /* We gave it an early chance; no good. */
771 } else {
772 char tbuf[ISO_TIME_LEN+1];
773 format_iso_time(tbuf, entry->unreachable_since);
774 log_debug(LD_CIRC, "Failed to connect to unreachable entry guard "
775 "'%s' (%s). It has been unreachable since %s.",
776 entry->nickname, buf, tbuf);
777 entry->last_attempted = now;
778 entry->can_retry = 0; /* We gave it an early chance; no good. */
782 /* if the caller asked us to, also update the is_running flags for this
783 * relay */
784 if (mark_relay_status)
785 router_set_status(digest, succeeded);
787 if (first_contact) {
788 /* We've just added a new long-term entry guard. Perhaps the network just
789 * came back? We should give our earlier entries another try too,
790 * and close this connection so we don't use it before we've given
791 * the others a shot. */
792 SMARTLIST_FOREACH_BEGIN(entry_guards, entry_guard_t *, e) {
793 if (e == entry)
794 break;
795 if (e->made_contact) {
796 const char *msg;
797 const node_t *r = entry_is_live(e, 0, 1, 1, 0, &msg);
798 if (r && e->unreachable_since) {
799 refuse_conn = 1;
800 e->can_retry = 1;
803 } SMARTLIST_FOREACH_END(e);
804 if (refuse_conn) {
805 log_info(LD_CIRC,
806 "Connected to new entry guard '%s' (%s). Marking earlier "
807 "entry guards up. %d/%d entry guards usable/new.",
808 entry->nickname, buf,
809 num_live_entry_guards(0), smartlist_len(entry_guards));
810 log_entry_guards(LOG_INFO);
811 changed = 1;
815 if (changed)
816 entry_guards_changed();
817 return refuse_conn ? -1 : 0;
820 /** When we try to choose an entry guard, should we parse and add
821 * config's EntryNodes first? */
822 static int should_add_entry_nodes = 0;
824 /** Called when the value of EntryNodes changes in our configuration. */
825 void
826 entry_nodes_should_be_added(void)
828 log_info(LD_CIRC, "EntryNodes config option set. Putting configured "
829 "relays at the front of the entry guard list.");
830 should_add_entry_nodes = 1;
833 /** Update the using_as_guard fields of all the nodes. We do this after we
834 * remove entry guards from the list: This is the only function that clears
835 * the using_as_guard field. */
836 static void
837 update_node_guard_status(void)
839 smartlist_t *nodes = nodelist_get_list();
840 SMARTLIST_FOREACH(nodes, node_t *, node, node->using_as_guard = 0);
841 SMARTLIST_FOREACH_BEGIN(entry_guards, entry_guard_t *, entry) {
842 node_t *node = node_get_mutable_by_id(entry->identity);
843 if (node)
844 node->using_as_guard = 1;
845 } SMARTLIST_FOREACH_END(entry);
848 /** Adjust the entry guards list so that it only contains entries from
849 * EntryNodes, adding new entries from EntryNodes to the list as needed. */
850 static void
851 entry_guards_set_from_config(const or_options_t *options)
853 smartlist_t *entry_nodes, *worse_entry_nodes, *entry_fps;
854 smartlist_t *old_entry_guards_on_list, *old_entry_guards_not_on_list;
855 const int numentryguards = decide_num_guards(options, 0);
856 tor_assert(entry_guards);
858 should_add_entry_nodes = 0;
860 if (!options->EntryNodes) {
861 /* It's possible that a controller set EntryNodes, thus making
862 * should_add_entry_nodes set, then cleared it again, all before the
863 * call to choose_random_entry() that triggered us. If so, just return.
865 return;
869 char *string = routerset_to_string(options->EntryNodes);
870 log_info(LD_CIRC,"Adding configured EntryNodes '%s'.", string);
871 tor_free(string);
874 entry_nodes = smartlist_new();
875 worse_entry_nodes = smartlist_new();
876 entry_fps = smartlist_new();
877 old_entry_guards_on_list = smartlist_new();
878 old_entry_guards_not_on_list = smartlist_new();
880 /* Split entry guards into those on the list and those not. */
882 routerset_get_all_nodes(entry_nodes, options->EntryNodes,
883 options->ExcludeNodes, 0);
884 SMARTLIST_FOREACH(entry_nodes, const node_t *,node,
885 smartlist_add(entry_fps, (void*)node->identity));
887 SMARTLIST_FOREACH(entry_guards, entry_guard_t *, e, {
888 if (smartlist_contains_digest(entry_fps, e->identity))
889 smartlist_add(old_entry_guards_on_list, e);
890 else
891 smartlist_add(old_entry_guards_not_on_list, e);
894 /* Remove all currently configured guard nodes, excluded nodes, unreachable
895 * nodes, or non-Guard nodes from entry_nodes. */
896 SMARTLIST_FOREACH_BEGIN(entry_nodes, const node_t *, node) {
897 if (entry_guard_get_by_id_digest(node->identity)) {
898 SMARTLIST_DEL_CURRENT(entry_nodes, node);
899 continue;
900 } else if (routerset_contains_node(options->ExcludeNodes, node)) {
901 SMARTLIST_DEL_CURRENT(entry_nodes, node);
902 continue;
903 } else if (!fascist_firewall_allows_node(node)) {
904 SMARTLIST_DEL_CURRENT(entry_nodes, node);
905 continue;
906 } else if (! node->is_possible_guard) {
907 smartlist_add(worse_entry_nodes, (node_t*)node);
908 SMARTLIST_DEL_CURRENT(entry_nodes, node);
910 } SMARTLIST_FOREACH_END(node);
912 /* Now build the new entry_guards list. */
913 smartlist_clear(entry_guards);
914 /* First, the previously configured guards that are in EntryNodes. */
915 smartlist_add_all(entry_guards, old_entry_guards_on_list);
916 /* Next, scramble the rest of EntryNodes, putting the guards first. */
917 smartlist_shuffle(entry_nodes);
918 smartlist_shuffle(worse_entry_nodes);
919 smartlist_add_all(entry_nodes, worse_entry_nodes);
921 /* Next, the rest of EntryNodes */
922 SMARTLIST_FOREACH_BEGIN(entry_nodes, const node_t *, node) {
923 add_an_entry_guard(node, 0, 0, 1, 0);
924 if (smartlist_len(entry_guards) > numentryguards * 10)
925 break;
926 } SMARTLIST_FOREACH_END(node);
927 log_notice(LD_GENERAL, "%d entries in guards", smartlist_len(entry_guards));
928 /* Finally, free the remaining previously configured guards that are not in
929 * EntryNodes. */
930 SMARTLIST_FOREACH(old_entry_guards_not_on_list, entry_guard_t *, e,
931 entry_guard_free(e));
933 update_node_guard_status();
935 smartlist_free(entry_nodes);
936 smartlist_free(worse_entry_nodes);
937 smartlist_free(entry_fps);
938 smartlist_free(old_entry_guards_on_list);
939 smartlist_free(old_entry_guards_not_on_list);
940 entry_guards_changed();
943 /** Return 0 if we're fine adding arbitrary routers out of the
944 * directory to our entry guard list, or return 1 if we have a
945 * list already and we must stick to it.
948 entry_list_is_constrained(const or_options_t *options)
950 if (options->EntryNodes)
951 return 1;
952 if (options->UseBridges)
953 return 1;
954 return 0;
957 /** Return true iff this node can answer directory questions about
958 * microdescriptors. */
959 static int
960 node_understands_microdescriptors(const node_t *node)
962 tor_assert(node);
963 if (node->rs && node->rs->version_supports_microdesc_cache)
964 return 1;
965 if (node->ri && tor_version_supports_microdescriptors(node->ri->platform))
966 return 1;
967 return 0;
970 /** Return true iff <b>node</b> is able to answer directory questions
971 * of type <b>dirinfo</b>. */
972 static int
973 node_can_handle_dirinfo(const node_t *node, dirinfo_type_t dirinfo)
975 /* Checking dirinfo for any type other than microdescriptors isn't required
976 yet, since we only choose directory guards that can support microdescs,
977 routerinfos, and networkstatuses, AND we don't use directory guards if
978 we're configured to do direct downloads of anything else. The only case
979 where we might have a guard that doesn't know about a type of directory
980 information is when we're retrieving directory information from a
981 bridge. */
983 if ((dirinfo & MICRODESC_DIRINFO) &&
984 !node_understands_microdescriptors(node))
985 return 0;
986 return 1;
989 /** Pick a live (up and listed) entry guard from entry_guards. If
990 * <b>state</b> is non-NULL, this is for a specific circuit --
991 * make sure not to pick this circuit's exit or any node in the
992 * exit's family. If <b>state</b> is NULL, we're looking for a random
993 * guard (likely a bridge). If <b>dirinfo</b> is not NO_DIRINFO, then
994 * only select from nodes that know how to answer directory questions
995 * of that type. */
996 const node_t *
997 choose_random_entry(cpath_build_state_t *state)
999 return choose_random_entry_impl(state, 0, 0, NULL);
1002 /** Pick a live (up and listed) directory guard from entry_guards for
1003 * downloading information of type <b>type</b>. */
1004 const node_t *
1005 choose_random_dirguard(dirinfo_type_t type)
1007 return choose_random_entry_impl(NULL, 1, type, NULL);
1010 /** Helper for choose_random{entry,dirguard}. */
1011 static const node_t *
1012 choose_random_entry_impl(cpath_build_state_t *state, int for_directory,
1013 dirinfo_type_t dirinfo_type, int *n_options_out)
1015 const or_options_t *options = get_options();
1016 smartlist_t *live_entry_guards = smartlist_new();
1017 smartlist_t *exit_family = smartlist_new();
1018 const node_t *chosen_exit =
1019 state?build_state_get_exit_node(state) : NULL;
1020 const node_t *node = NULL;
1021 int need_uptime = state ? state->need_uptime : 0;
1022 int need_capacity = state ? state->need_capacity : 0;
1023 int preferred_min, consider_exit_family = 0;
1024 int need_descriptor = !for_directory;
1025 const int num_needed = decide_num_guards(options, for_directory);
1027 if (n_options_out)
1028 *n_options_out = 0;
1030 if (chosen_exit) {
1031 nodelist_add_node_and_family(exit_family, chosen_exit);
1032 consider_exit_family = 1;
1035 if (!entry_guards)
1036 entry_guards = smartlist_new();
1038 if (should_add_entry_nodes)
1039 entry_guards_set_from_config(options);
1041 if (!entry_list_is_constrained(options) &&
1042 smartlist_len(entry_guards) < num_needed)
1043 pick_entry_guards(options, for_directory);
1045 retry:
1046 smartlist_clear(live_entry_guards);
1047 SMARTLIST_FOREACH_BEGIN(entry_guards, entry_guard_t *, entry) {
1048 const char *msg;
1049 node = entry_is_live(entry, need_uptime, need_capacity, 0,
1050 need_descriptor, &msg);
1051 if (!node)
1052 continue; /* down, no point */
1053 if (for_directory) {
1054 if (!entry->is_dir_cache)
1055 continue; /* We need a directory and didn't get one. */
1057 if (node == chosen_exit)
1058 continue; /* don't pick the same node for entry and exit */
1059 if (consider_exit_family && smartlist_contains(exit_family, node))
1060 continue; /* avoid relays that are family members of our exit */
1061 if (dirinfo_type != NO_DIRINFO &&
1062 !node_can_handle_dirinfo(node, dirinfo_type))
1063 continue; /* this node won't be able to answer our dir questions */
1064 #if 0 /* since EntryNodes is always strict now, this clause is moot */
1065 if (options->EntryNodes &&
1066 !routerset_contains_node(options->EntryNodes, node)) {
1067 /* We've come to the end of our preferred entry nodes. */
1068 if (smartlist_len(live_entry_guards))
1069 goto choose_and_finish; /* only choose from the ones we like */
1070 if (options->StrictNodes) {
1071 /* in theory this case should never happen, since
1072 * entry_guards_set_from_config() drops unwanted relays */
1073 tor_fragile_assert();
1074 } else {
1075 log_info(LD_CIRC,
1076 "No relays from EntryNodes available. Using others.");
1079 #endif
1080 smartlist_add(live_entry_guards, (void*)node);
1081 if (!entry->made_contact) {
1082 /* Always start with the first not-yet-contacted entry
1083 * guard. Otherwise we might add several new ones, pick
1084 * the second new one, and now we've expanded our entry
1085 * guard list without needing to. */
1086 goto choose_and_finish;
1088 if (smartlist_len(live_entry_guards) >= num_needed)
1089 goto choose_and_finish; /* we have enough */
1090 } SMARTLIST_FOREACH_END(entry);
1092 if (entry_list_is_constrained(options)) {
1093 /* If we prefer the entry nodes we've got, and we have at least
1094 * one choice, that's great. Use it. */
1095 preferred_min = 1;
1096 } else {
1097 /* Try to have at least 2 choices available. This way we don't
1098 * get stuck with a single live-but-crummy entry and just keep
1099 * using him.
1100 * (We might get 2 live-but-crummy entry guards, but so be it.) */
1101 preferred_min = 2;
1104 if (smartlist_len(live_entry_guards) < preferred_min) {
1105 if (!entry_list_is_constrained(options)) {
1106 /* still no? try adding a new entry then */
1107 /* XXX if guard doesn't imply fast and stable, then we need
1108 * to tell add_an_entry_guard below what we want, or it might
1109 * be a long time til we get it. -RD */
1110 node = add_an_entry_guard(NULL, 0, 0, 1, for_directory);
1111 if (node) {
1112 entry_guards_changed();
1113 /* XXX we start over here in case the new node we added shares
1114 * a family with our exit node. There's a chance that we'll just
1115 * load up on entry guards here, if the network we're using is
1116 * one big family. Perhaps we should teach add_an_entry_guard()
1117 * to understand nodes-to-avoid-if-possible? -RD */
1118 goto retry;
1121 if (!node && need_uptime) {
1122 need_uptime = 0; /* try without that requirement */
1123 goto retry;
1125 if (!node && need_capacity) {
1126 /* still no? last attempt, try without requiring capacity */
1127 need_capacity = 0;
1128 goto retry;
1130 #if 0
1131 /* Removing this retry logic: if we only allow one exit, and it is in the
1132 same family as all our entries, then we are just plain not going to win
1133 here. */
1134 if (!node && entry_list_is_constrained(options) && consider_exit_family) {
1135 /* still no? if we're using bridges or have strictentrynodes
1136 * set, and our chosen exit is in the same family as all our
1137 * bridges/entry guards, then be flexible about families. */
1138 consider_exit_family = 0;
1139 goto retry;
1141 #endif
1142 /* live_entry_guards may be empty below. Oh well, we tried. */
1145 choose_and_finish:
1146 if (entry_list_is_constrained(options)) {
1147 /* We need to weight by bandwidth, because our bridges or entryguards
1148 * were not already selected proportional to their bandwidth. */
1149 node = node_sl_choose_by_bandwidth(live_entry_guards, WEIGHT_FOR_GUARD);
1150 } else {
1151 /* We choose uniformly at random here, because choose_good_entry_server()
1152 * already weights its choices by bandwidth, so we don't want to
1153 * *double*-weight our guard selection. */
1154 node = smartlist_choose(live_entry_guards);
1156 if (n_options_out)
1157 *n_options_out = smartlist_len(live_entry_guards);
1158 smartlist_free(live_entry_guards);
1159 smartlist_free(exit_family);
1160 return node;
1163 /** Parse <b>state</b> and learn about the entry guards it describes.
1164 * If <b>set</b> is true, and there are no errors, replace the global
1165 * entry_list with what we find.
1166 * On success, return 0. On failure, alloc into *<b>msg</b> a string
1167 * describing the error, and return -1.
1170 entry_guards_parse_state(or_state_t *state, int set, char **msg)
1172 entry_guard_t *node = NULL;
1173 smartlist_t *new_entry_guards = smartlist_new();
1174 config_line_t *line;
1175 time_t now = time(NULL);
1176 const char *state_version = state->TorVersion;
1177 digestmap_t *added_by = digestmap_new();
1179 *msg = NULL;
1180 for (line = state->EntryGuards; line; line = line->next) {
1181 if (!strcasecmp(line->key, "EntryGuard")) {
1182 smartlist_t *args = smartlist_new();
1183 node = tor_malloc_zero(sizeof(entry_guard_t));
1184 /* all entry guards on disk have been contacted */
1185 node->made_contact = 1;
1186 smartlist_add(new_entry_guards, node);
1187 smartlist_split_string(args, line->value, " ",
1188 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
1189 if (smartlist_len(args)<2) {
1190 *msg = tor_strdup("Unable to parse entry nodes: "
1191 "Too few arguments to EntryGuard");
1192 } else if (!is_legal_nickname(smartlist_get(args,0))) {
1193 *msg = tor_strdup("Unable to parse entry nodes: "
1194 "Bad nickname for EntryGuard");
1195 } else {
1196 strlcpy(node->nickname, smartlist_get(args,0), MAX_NICKNAME_LEN+1);
1197 if (base16_decode(node->identity, DIGEST_LEN, smartlist_get(args,1),
1198 strlen(smartlist_get(args,1)))<0) {
1199 *msg = tor_strdup("Unable to parse entry nodes: "
1200 "Bad hex digest for EntryGuard");
1203 if (smartlist_len(args) >= 3) {
1204 const char *is_cache = smartlist_get(args, 2);
1205 if (!strcasecmp(is_cache, "DirCache")) {
1206 node->is_dir_cache = 1;
1207 } else if (!strcasecmp(is_cache, "NoDirCache")) {
1208 node->is_dir_cache = 0;
1209 } else {
1210 log_warn(LD_CONFIG, "Bogus third argument to EntryGuard line: %s",
1211 escaped(is_cache));
1214 SMARTLIST_FOREACH(args, char*, cp, tor_free(cp));
1215 smartlist_free(args);
1216 if (*msg)
1217 break;
1218 } else if (!strcasecmp(line->key, "EntryGuardDownSince") ||
1219 !strcasecmp(line->key, "EntryGuardUnlistedSince")) {
1220 time_t when;
1221 time_t last_try = 0;
1222 if (!node) {
1223 *msg = tor_strdup("Unable to parse entry nodes: "
1224 "EntryGuardDownSince/UnlistedSince without EntryGuard");
1225 break;
1227 if (parse_iso_time(line->value, &when)<0) {
1228 *msg = tor_strdup("Unable to parse entry nodes: "
1229 "Bad time in EntryGuardDownSince/UnlistedSince");
1230 break;
1232 if (when > now) {
1233 /* It's a bad idea to believe info in the future: you can wind
1234 * up with timeouts that aren't allowed to happen for years. */
1235 continue;
1237 if (strlen(line->value) >= ISO_TIME_LEN+ISO_TIME_LEN+1) {
1238 /* ignore failure */
1239 (void) parse_iso_time(line->value+ISO_TIME_LEN+1, &last_try);
1241 if (!strcasecmp(line->key, "EntryGuardDownSince")) {
1242 node->unreachable_since = when;
1243 node->last_attempted = last_try;
1244 } else {
1245 node->bad_since = when;
1247 } else if (!strcasecmp(line->key, "EntryGuardAddedBy")) {
1248 char d[DIGEST_LEN];
1249 /* format is digest version date */
1250 if (strlen(line->value) < HEX_DIGEST_LEN+1+1+1+ISO_TIME_LEN) {
1251 log_warn(LD_BUG, "EntryGuardAddedBy line is not long enough.");
1252 continue;
1254 if (base16_decode(d, sizeof(d), line->value, HEX_DIGEST_LEN)<0 ||
1255 line->value[HEX_DIGEST_LEN] != ' ') {
1256 log_warn(LD_BUG, "EntryGuardAddedBy line %s does not begin with "
1257 "hex digest", escaped(line->value));
1258 continue;
1260 digestmap_set(added_by, d, tor_strdup(line->value+HEX_DIGEST_LEN+1));
1261 } else if (!strcasecmp(line->key, "EntryGuardPathUseBias")) {
1262 const or_options_t *options = get_options();
1263 double use_cnt, success_cnt;
1265 if (!node) {
1266 *msg = tor_strdup("Unable to parse entry nodes: "
1267 "EntryGuardPathUseBias without EntryGuard");
1268 break;
1271 if (tor_sscanf(line->value, "%lf %lf",
1272 &use_cnt, &success_cnt) != 2) {
1273 log_info(LD_GENERAL, "Malformed path use bias line for node %s",
1274 node->nickname);
1275 continue;
1278 if (use_cnt < success_cnt) {
1279 int severity = LOG_INFO;
1280 /* If this state file was written by a Tor that would have
1281 * already fixed it, then the overcounting bug is still there.. */
1282 if (tor_version_as_new_as(state_version, "0.2.4.13-alpha")) {
1283 severity = LOG_NOTICE;
1285 log_fn(severity, LD_BUG,
1286 "State file contains unexpectedly high usage success "
1287 "counts %lf/%lf for Guard %s ($%s)",
1288 success_cnt, use_cnt,
1289 node->nickname, hex_str(node->identity, DIGEST_LEN));
1290 success_cnt = use_cnt;
1293 node->use_attempts = use_cnt;
1294 node->use_successes = success_cnt;
1296 log_info(LD_GENERAL, "Read %f/%f path use bias for node %s",
1297 node->use_successes, node->use_attempts, node->nickname);
1299 /* Note: We rely on the < comparison here to allow us to set a 0
1300 * rate and disable the feature entirely. If refactoring, don't
1301 * change to <= */
1302 if (pathbias_get_use_success_count(node)/node->use_attempts
1303 < pathbias_get_extreme_use_rate(options) &&
1304 pathbias_get_dropguards(options)) {
1305 node->path_bias_disabled = 1;
1306 log_info(LD_GENERAL,
1307 "Path use bias is too high (%f/%f); disabling node %s",
1308 node->circ_successes, node->circ_attempts, node->nickname);
1310 } else if (!strcasecmp(line->key, "EntryGuardPathBias")) {
1311 const or_options_t *options = get_options();
1312 double hop_cnt, success_cnt, timeouts, collapsed, successful_closed,
1313 unusable;
1315 if (!node) {
1316 *msg = tor_strdup("Unable to parse entry nodes: "
1317 "EntryGuardPathBias without EntryGuard");
1318 break;
1321 /* First try 3 params, then 2. */
1322 /* In the long run: circuit_success ~= successful_circuit_close +
1323 * collapsed_circuits +
1324 * unusable_circuits */
1325 if (tor_sscanf(line->value, "%lf %lf %lf %lf %lf %lf",
1326 &hop_cnt, &success_cnt, &successful_closed,
1327 &collapsed, &unusable, &timeouts) != 6) {
1328 int old_success, old_hops;
1329 if (tor_sscanf(line->value, "%u %u", &old_success, &old_hops) != 2) {
1330 continue;
1332 log_info(LD_GENERAL, "Reading old-style EntryGuardPathBias %s",
1333 escaped(line->value));
1335 success_cnt = old_success;
1336 successful_closed = old_success;
1337 hop_cnt = old_hops;
1338 timeouts = 0;
1339 collapsed = 0;
1340 unusable = 0;
1343 if (hop_cnt < success_cnt) {
1344 int severity = LOG_INFO;
1345 /* If this state file was written by a Tor that would have
1346 * already fixed it, then the overcounting bug is still there.. */
1347 if (tor_version_as_new_as(state_version, "0.2.4.13-alpha")) {
1348 severity = LOG_NOTICE;
1350 log_fn(severity, LD_BUG,
1351 "State file contains unexpectedly high success counts "
1352 "%lf/%lf for Guard %s ($%s)",
1353 success_cnt, hop_cnt,
1354 node->nickname, hex_str(node->identity, DIGEST_LEN));
1355 success_cnt = hop_cnt;
1358 node->circ_attempts = hop_cnt;
1359 node->circ_successes = success_cnt;
1361 node->successful_circuits_closed = successful_closed;
1362 node->timeouts = timeouts;
1363 node->collapsed_circuits = collapsed;
1364 node->unusable_circuits = unusable;
1366 log_info(LD_GENERAL, "Read %f/%f path bias for node %s",
1367 node->circ_successes, node->circ_attempts, node->nickname);
1368 /* Note: We rely on the < comparison here to allow us to set a 0
1369 * rate and disable the feature entirely. If refactoring, don't
1370 * change to <= */
1371 if (pathbias_get_close_success_count(node)/node->circ_attempts
1372 < pathbias_get_extreme_rate(options) &&
1373 pathbias_get_dropguards(options)) {
1374 node->path_bias_disabled = 1;
1375 log_info(LD_GENERAL,
1376 "Path bias is too high (%f/%f); disabling node %s",
1377 node->circ_successes, node->circ_attempts, node->nickname);
1380 } else {
1381 log_warn(LD_BUG, "Unexpected key %s", line->key);
1385 SMARTLIST_FOREACH_BEGIN(new_entry_guards, entry_guard_t *, e) {
1386 char *sp;
1387 char *val = digestmap_get(added_by, e->identity);
1388 if (val && (sp = strchr(val, ' '))) {
1389 time_t when;
1390 *sp++ = '\0';
1391 if (parse_iso_time(sp, &when)<0) {
1392 log_warn(LD_BUG, "Can't read time %s in EntryGuardAddedBy", sp);
1393 } else {
1394 e->chosen_by_version = tor_strdup(val);
1395 e->chosen_on_date = when;
1397 } else {
1398 if (state_version) {
1399 e->chosen_by_version = tor_strdup(state_version);
1400 e->chosen_on_date = time(NULL) - crypto_rand_int(3600*24*30);
1403 if (e->path_bias_disabled && !e->bad_since)
1404 e->bad_since = time(NULL);
1406 SMARTLIST_FOREACH_END(e);
1408 if (*msg || !set) {
1409 SMARTLIST_FOREACH(new_entry_guards, entry_guard_t *, e,
1410 entry_guard_free(e));
1411 smartlist_free(new_entry_guards);
1412 } else { /* !err && set */
1413 if (entry_guards) {
1414 SMARTLIST_FOREACH(entry_guards, entry_guard_t *, e,
1415 entry_guard_free(e));
1416 smartlist_free(entry_guards);
1418 entry_guards = new_entry_guards;
1419 entry_guards_dirty = 0;
1420 /* XXX024 hand new_entry_guards to this func, and move it up a
1421 * few lines, so we don't have to re-dirty it */
1422 if (remove_obsolete_entry_guards(now))
1423 entry_guards_dirty = 1;
1425 update_node_guard_status();
1427 digestmap_free(added_by, tor_free_);
1428 return *msg ? -1 : 0;
1431 /** Our list of entry guards has changed, or some element of one
1432 * of our entry guards has changed. Write the changes to disk within
1433 * the next few minutes.
1435 void
1436 entry_guards_changed(void)
1438 time_t when;
1439 entry_guards_dirty = 1;
1441 /* or_state_save() will call entry_guards_update_state(). */
1442 when = get_options()->AvoidDiskWrites ? time(NULL) + 3600 : time(NULL)+600;
1443 or_state_mark_dirty(get_or_state(), when);
1446 /** If the entry guard info has not changed, do nothing and return.
1447 * Otherwise, free the EntryGuards piece of <b>state</b> and create
1448 * a new one out of the global entry_guards list, and then mark
1449 * <b>state</b> dirty so it will get saved to disk.
1451 void
1452 entry_guards_update_state(or_state_t *state)
1454 config_line_t **next, *line;
1455 if (! entry_guards_dirty)
1456 return;
1458 config_free_lines(state->EntryGuards);
1459 next = &state->EntryGuards;
1460 *next = NULL;
1461 if (!entry_guards)
1462 entry_guards = smartlist_new();
1463 SMARTLIST_FOREACH_BEGIN(entry_guards, entry_guard_t *, e) {
1464 char dbuf[HEX_DIGEST_LEN+1];
1465 if (!e->made_contact)
1466 continue; /* don't write this one to disk */
1467 *next = line = tor_malloc_zero(sizeof(config_line_t));
1468 line->key = tor_strdup("EntryGuard");
1469 base16_encode(dbuf, sizeof(dbuf), e->identity, DIGEST_LEN);
1470 tor_asprintf(&line->value, "%s %s %sDirCache", e->nickname, dbuf,
1471 e->is_dir_cache ? "" : "No");
1472 next = &(line->next);
1473 if (e->unreachable_since) {
1474 *next = line = tor_malloc_zero(sizeof(config_line_t));
1475 line->key = tor_strdup("EntryGuardDownSince");
1476 line->value = tor_malloc(ISO_TIME_LEN+1+ISO_TIME_LEN+1);
1477 format_iso_time(line->value, e->unreachable_since);
1478 if (e->last_attempted) {
1479 line->value[ISO_TIME_LEN] = ' ';
1480 format_iso_time(line->value+ISO_TIME_LEN+1, e->last_attempted);
1482 next = &(line->next);
1484 if (e->bad_since) {
1485 *next = line = tor_malloc_zero(sizeof(config_line_t));
1486 line->key = tor_strdup("EntryGuardUnlistedSince");
1487 line->value = tor_malloc(ISO_TIME_LEN+1);
1488 format_iso_time(line->value, e->bad_since);
1489 next = &(line->next);
1491 if (e->chosen_on_date && e->chosen_by_version &&
1492 !strchr(e->chosen_by_version, ' ')) {
1493 char d[HEX_DIGEST_LEN+1];
1494 char t[ISO_TIME_LEN+1];
1495 *next = line = tor_malloc_zero(sizeof(config_line_t));
1496 line->key = tor_strdup("EntryGuardAddedBy");
1497 base16_encode(d, sizeof(d), e->identity, DIGEST_LEN);
1498 format_iso_time(t, e->chosen_on_date);
1499 tor_asprintf(&line->value, "%s %s %s",
1500 d, e->chosen_by_version, t);
1501 next = &(line->next);
1503 if (e->circ_attempts > 0) {
1504 *next = line = tor_malloc_zero(sizeof(config_line_t));
1505 line->key = tor_strdup("EntryGuardPathBias");
1506 /* In the long run: circuit_success ~= successful_circuit_close +
1507 * collapsed_circuits +
1508 * unusable_circuits */
1509 tor_asprintf(&line->value, "%f %f %f %f %f %f",
1510 e->circ_attempts, e->circ_successes,
1511 pathbias_get_close_success_count(e),
1512 e->collapsed_circuits,
1513 e->unusable_circuits, e->timeouts);
1514 next = &(line->next);
1516 if (e->use_attempts > 0) {
1517 *next = line = tor_malloc_zero(sizeof(config_line_t));
1518 line->key = tor_strdup("EntryGuardPathUseBias");
1520 tor_asprintf(&line->value, "%f %f",
1521 e->use_attempts,
1522 pathbias_get_use_success_count(e));
1523 next = &(line->next);
1526 } SMARTLIST_FOREACH_END(e);
1527 if (!get_options()->AvoidDiskWrites)
1528 or_state_mark_dirty(get_or_state(), 0);
1529 entry_guards_dirty = 0;
1532 /** If <b>question</b> is the string "entry-guards", then dump
1533 * to *<b>answer</b> a newly allocated string describing all of
1534 * the nodes in the global entry_guards list. See control-spec.txt
1535 * for details.
1536 * For backward compatibility, we also handle the string "helper-nodes".
1537 * */
1539 getinfo_helper_entry_guards(control_connection_t *conn,
1540 const char *question, char **answer,
1541 const char **errmsg)
1543 (void) conn;
1544 (void) errmsg;
1546 if (!strcmp(question,"entry-guards") ||
1547 !strcmp(question,"helper-nodes")) {
1548 smartlist_t *sl = smartlist_new();
1549 char tbuf[ISO_TIME_LEN+1];
1550 char nbuf[MAX_VERBOSE_NICKNAME_LEN+1];
1551 if (!entry_guards)
1552 entry_guards = smartlist_new();
1553 SMARTLIST_FOREACH_BEGIN(entry_guards, entry_guard_t *, e) {
1554 const char *status = NULL;
1555 time_t when = 0;
1556 const node_t *node;
1558 if (!e->made_contact) {
1559 status = "never-connected";
1560 } else if (e->bad_since) {
1561 when = e->bad_since;
1562 status = "unusable";
1563 } else {
1564 status = "up";
1567 node = node_get_by_id(e->identity);
1568 if (node) {
1569 node_get_verbose_nickname(node, nbuf);
1570 } else {
1571 nbuf[0] = '$';
1572 base16_encode(nbuf+1, sizeof(nbuf)-1, e->identity, DIGEST_LEN);
1573 /* e->nickname field is not very reliable if we don't know about
1574 * this router any longer; don't include it. */
1577 if (when) {
1578 format_iso_time(tbuf, when);
1579 smartlist_add_asprintf(sl, "%s %s %s\n", nbuf, status, tbuf);
1580 } else {
1581 smartlist_add_asprintf(sl, "%s %s\n", nbuf, status);
1583 } SMARTLIST_FOREACH_END(e);
1584 *answer = smartlist_join_strings(sl, "", 0, NULL);
1585 SMARTLIST_FOREACH(sl, char *, c, tor_free(c));
1586 smartlist_free(sl);
1588 return 0;
1591 /** A list of configured bridges. Whenever we actually get a descriptor
1592 * for one, we add it as an entry guard. Note that the order of bridges
1593 * in this list does not necessarily correspond to the order of bridges
1594 * in the torrc. */
1595 static smartlist_t *bridge_list = NULL;
1597 /** Mark every entry of the bridge list to be removed on our next call to
1598 * sweep_bridge_list unless it has first been un-marked. */
1599 void
1600 mark_bridge_list(void)
1602 if (!bridge_list)
1603 bridge_list = smartlist_new();
1604 SMARTLIST_FOREACH(bridge_list, bridge_info_t *, b,
1605 b->marked_for_removal = 1);
1608 /** Remove every entry of the bridge list that was marked with
1609 * mark_bridge_list if it has not subsequently been un-marked. */
1610 void
1611 sweep_bridge_list(void)
1613 if (!bridge_list)
1614 bridge_list = smartlist_new();
1615 SMARTLIST_FOREACH_BEGIN(bridge_list, bridge_info_t *, b) {
1616 if (b->marked_for_removal) {
1617 SMARTLIST_DEL_CURRENT(bridge_list, b);
1618 bridge_free(b);
1620 } SMARTLIST_FOREACH_END(b);
1623 /** Initialize the bridge list to empty, creating it if needed. */
1624 static void
1625 clear_bridge_list(void)
1627 if (!bridge_list)
1628 bridge_list = smartlist_new();
1629 SMARTLIST_FOREACH(bridge_list, bridge_info_t *, b, bridge_free(b));
1630 smartlist_clear(bridge_list);
1633 /** Free the bridge <b>bridge</b>. */
1634 static void
1635 bridge_free(bridge_info_t *bridge)
1637 if (!bridge)
1638 return;
1640 tor_free(bridge->transport_name);
1641 if (bridge->socks_args) {
1642 SMARTLIST_FOREACH(bridge->socks_args, char*, s, tor_free(s));
1643 smartlist_free(bridge->socks_args);
1646 tor_free(bridge);
1649 /** If we have a bridge configured whose digest matches <b>digest</b>, or a
1650 * bridge with no known digest whose address matches any of the
1651 * tor_addr_port_t's in <b>orports</b>, return that bridge. Else return
1652 * NULL. */
1653 static bridge_info_t *
1654 get_configured_bridge_by_orports_digest(const char *digest,
1655 const smartlist_t *orports)
1657 if (!bridge_list)
1658 return NULL;
1659 SMARTLIST_FOREACH_BEGIN(bridge_list, bridge_info_t *, bridge)
1661 if (tor_digest_is_zero(bridge->identity)) {
1662 SMARTLIST_FOREACH_BEGIN(orports, tor_addr_port_t *, ap)
1664 if (tor_addr_compare(&bridge->addr, &ap->addr, CMP_EXACT) == 0 &&
1665 bridge->port == ap->port)
1666 return bridge;
1668 SMARTLIST_FOREACH_END(ap);
1670 if (digest && tor_memeq(bridge->identity, digest, DIGEST_LEN))
1671 return bridge;
1673 SMARTLIST_FOREACH_END(bridge);
1674 return NULL;
1677 /** If we have a bridge configured whose digest matches <b>digest</b>, or a
1678 * bridge with no known digest whose address matches <b>addr</b>:<b>/port</b>,
1679 * return that bridge. Else return NULL. If <b>digest</b> is NULL, check for
1680 * address/port matches only. */
1681 static bridge_info_t *
1682 get_configured_bridge_by_addr_port_digest(const tor_addr_t *addr,
1683 uint16_t port,
1684 const char *digest)
1686 if (!bridge_list)
1687 return NULL;
1688 SMARTLIST_FOREACH_BEGIN(bridge_list, bridge_info_t *, bridge)
1690 if ((tor_digest_is_zero(bridge->identity) || digest == NULL) &&
1691 !tor_addr_compare(&bridge->addr, addr, CMP_EXACT) &&
1692 bridge->port == port)
1693 return bridge;
1694 if (digest && tor_memeq(bridge->identity, digest, DIGEST_LEN))
1695 return bridge;
1697 SMARTLIST_FOREACH_END(bridge);
1698 return NULL;
1701 /** Wrapper around get_configured_bridge_by_addr_port_digest() to look
1702 * it up via router descriptor <b>ri</b>. */
1703 static bridge_info_t *
1704 get_configured_bridge_by_routerinfo(const routerinfo_t *ri)
1706 bridge_info_t *bi = NULL;
1707 smartlist_t *orports = router_get_all_orports(ri);
1708 bi = get_configured_bridge_by_orports_digest(ri->cache_info.identity_digest,
1709 orports);
1710 SMARTLIST_FOREACH(orports, tor_addr_port_t *, p, tor_free(p));
1711 smartlist_free(orports);
1712 return bi;
1715 /** Return 1 if <b>ri</b> is one of our known bridges, else 0. */
1717 routerinfo_is_a_configured_bridge(const routerinfo_t *ri)
1719 return get_configured_bridge_by_routerinfo(ri) ? 1 : 0;
1722 /** Return 1 if <b>node</b> is one of our configured bridges, else 0. */
1724 node_is_a_configured_bridge(const node_t *node)
1726 int retval = 0;
1727 smartlist_t *orports = node_get_all_orports(node);
1728 retval = get_configured_bridge_by_orports_digest(node->identity,
1729 orports) != NULL;
1730 SMARTLIST_FOREACH(orports, tor_addr_port_t *, p, tor_free(p));
1731 smartlist_free(orports);
1732 return retval;
1735 /** We made a connection to a router at <b>addr</b>:<b>port</b>
1736 * without knowing its digest. Its digest turned out to be <b>digest</b>.
1737 * If it was a bridge, and we still don't know its digest, record it.
1739 void
1740 learned_router_identity(const tor_addr_t *addr, uint16_t port,
1741 const char *digest)
1743 bridge_info_t *bridge =
1744 get_configured_bridge_by_addr_port_digest(addr, port, digest);
1745 if (bridge && tor_digest_is_zero(bridge->identity)) {
1746 char *transport_info = NULL;
1747 const char *transport_name =
1748 find_transport_name_by_bridge_addrport(addr, port);
1749 if (transport_name)
1750 tor_asprintf(&transport_info, " (with transport '%s')", transport_name);
1752 memcpy(bridge->identity, digest, DIGEST_LEN);
1753 log_notice(LD_DIR, "Learned fingerprint %s for bridge %s%s.",
1754 hex_str(digest, DIGEST_LEN), fmt_addrport(addr, port),
1755 transport_info ? transport_info : "");
1756 tor_free(transport_info);
1760 /** Return true if <b>bridge</b> has the same identity digest as
1761 * <b>digest</b>. If <b>digest</b> is NULL, it matches
1762 * bridges with unspecified identity digests. */
1763 static int
1764 bridge_has_digest(const bridge_info_t *bridge, const char *digest)
1766 if (digest)
1767 return tor_memeq(digest, bridge->identity, DIGEST_LEN);
1768 else
1769 return tor_digest_is_zero(bridge->identity);
1772 /** We are about to add a new bridge at <b>addr</b>:<b>port</b>, with optional
1773 * <b>digest</b> and <b>transport_name</b>. Mark for removal any previously
1774 * existing bridge with the same address and port, and warn the user as
1775 * appropriate.
1777 static void
1778 bridge_resolve_conflicts(const tor_addr_t *addr, uint16_t port,
1779 const char *digest, const char *transport_name)
1781 /* Iterate the already-registered bridge list:
1783 If you find a bridge with the same adress and port, mark it for
1784 removal. It doesn't make sense to have two active bridges with
1785 the same IP:PORT. If the bridge in question has a different
1786 digest or transport than <b>digest</b>/<b>transport_name</b>,
1787 it's probably a misconfiguration and we should warn the user.
1789 SMARTLIST_FOREACH_BEGIN(bridge_list, bridge_info_t *, bridge) {
1790 if (bridge->marked_for_removal)
1791 continue;
1793 if (tor_addr_eq(&bridge->addr, addr) && (bridge->port == port)) {
1795 bridge->marked_for_removal = 1;
1797 if (!bridge_has_digest(bridge, digest) ||
1798 strcmp_opt(bridge->transport_name, transport_name)) {
1799 /* warn the user */
1800 char *bridge_description_new, *bridge_description_old;
1801 tor_asprintf(&bridge_description_new, "%s:%s:%s",
1802 fmt_addrport(addr, port),
1803 digest ? hex_str(digest, DIGEST_LEN) : "",
1804 transport_name ? transport_name : "");
1805 tor_asprintf(&bridge_description_old, "%s:%s:%s",
1806 fmt_addrport(&bridge->addr, bridge->port),
1807 tor_digest_is_zero(bridge->identity) ?
1808 "" : hex_str(bridge->identity,DIGEST_LEN),
1809 bridge->transport_name ? bridge->transport_name : "");
1811 log_warn(LD_GENERAL,"Tried to add bridge '%s', but we found a conflict"
1812 " with the already registered bridge '%s'. We will discard"
1813 " the old bridge and keep '%s'. If this is not what you"
1814 " wanted, please change your configuration file accordingly.",
1815 bridge_description_new, bridge_description_old,
1816 bridge_description_new);
1818 tor_free(bridge_description_new);
1819 tor_free(bridge_description_old);
1822 } SMARTLIST_FOREACH_END(bridge);
1825 /** Return True if we have a bridge that uses a transport with name
1826 * <b>transport_name</b>. */
1828 transport_is_needed(const char *transport_name)
1830 if (!bridge_list)
1831 return 0;
1833 SMARTLIST_FOREACH_BEGIN(bridge_list, const bridge_info_t *, bridge) {
1834 if (bridge->transport_name &&
1835 !strcmp(bridge->transport_name, transport_name))
1836 return 1;
1837 } SMARTLIST_FOREACH_END(bridge);
1839 return 0;
1842 /** Register the bridge information in <b>bridge_line</b> to the
1843 * bridge subsystem. Steals reference of <b>bridge_line</b>. */
1844 void
1845 bridge_add_from_config(bridge_line_t *bridge_line)
1847 bridge_info_t *b;
1849 { /* Log the bridge we are about to register: */
1850 log_debug(LD_GENERAL, "Registering bridge at %s (transport: %s) (%s)",
1851 fmt_addrport(&bridge_line->addr, bridge_line->port),
1852 bridge_line->transport_name ?
1853 bridge_line->transport_name : "no transport",
1854 tor_digest_is_zero(bridge_line->digest) ?
1855 "no key listed" : hex_str(bridge_line->digest, DIGEST_LEN));
1857 if (bridge_line->socks_args) { /* print socks arguments */
1858 int i = 0;
1860 tor_assert(smartlist_len(bridge_line->socks_args) > 0);
1862 log_debug(LD_GENERAL, "Bridge uses %d SOCKS arguments:",
1863 smartlist_len(bridge_line->socks_args));
1864 SMARTLIST_FOREACH(bridge_line->socks_args, const char *, arg,
1865 log_debug(LD_CONFIG, "%d: %s", ++i, arg));
1869 bridge_resolve_conflicts(&bridge_line->addr,
1870 bridge_line->port,
1871 bridge_line->digest,
1872 bridge_line->transport_name);
1874 b = tor_malloc_zero(sizeof(bridge_info_t));
1875 tor_addr_copy(&b->addr, &bridge_line->addr);
1876 b->port = bridge_line->port;
1877 memcpy(b->identity, bridge_line->digest, DIGEST_LEN);
1878 if (bridge_line->transport_name)
1879 b->transport_name = bridge_line->transport_name;
1880 b->fetch_status.schedule = DL_SCHED_BRIDGE;
1881 b->socks_args = bridge_line->socks_args;
1882 if (!bridge_list)
1883 bridge_list = smartlist_new();
1885 tor_free(bridge_line); /* Deallocate bridge_line now. */
1887 smartlist_add(bridge_list, b);
1890 /** Return true iff <b>routerset</b> contains the bridge <b>bridge</b>. */
1891 static int
1892 routerset_contains_bridge(const routerset_t *routerset,
1893 const bridge_info_t *bridge)
1895 int result;
1896 extend_info_t *extinfo;
1897 tor_assert(bridge);
1898 if (!routerset)
1899 return 0;
1901 extinfo = extend_info_new(
1902 NULL, bridge->identity, NULL, NULL, &bridge->addr, bridge->port);
1903 result = routerset_contains_extendinfo(routerset, extinfo);
1904 extend_info_free(extinfo);
1905 return result;
1908 /** If <b>digest</b> is one of our known bridges, return it. */
1909 static bridge_info_t *
1910 find_bridge_by_digest(const char *digest)
1912 SMARTLIST_FOREACH(bridge_list, bridge_info_t *, bridge,
1914 if (tor_memeq(bridge->identity, digest, DIGEST_LEN))
1915 return bridge;
1917 return NULL;
1920 /** Given the <b>addr</b> and <b>port</b> of a bridge, if that bridge
1921 * supports a pluggable transport, return its name. Otherwise, return
1922 * NULL. */
1923 const char *
1924 find_transport_name_by_bridge_addrport(const tor_addr_t *addr, uint16_t port)
1926 if (!bridge_list)
1927 return NULL;
1929 SMARTLIST_FOREACH_BEGIN(bridge_list, const bridge_info_t *, bridge) {
1930 if (tor_addr_eq(&bridge->addr, addr) &&
1931 (bridge->port == port))
1932 return bridge->transport_name;
1933 } SMARTLIST_FOREACH_END(bridge);
1935 return NULL;
1938 /** If <b>addr</b> and <b>port</b> match the address and port of a
1939 * bridge of ours that uses pluggable transports, place its transport
1940 * in <b>transport</b>.
1942 * Return 0 on success (found a transport, or found a bridge with no
1943 * transport, or found no bridge); return -1 if we should be using a
1944 * transport, but the transport could not be found.
1947 get_transport_by_bridge_addrport(const tor_addr_t *addr, uint16_t port,
1948 const transport_t **transport)
1950 *transport = NULL;
1951 if (!bridge_list)
1952 return 0;
1954 SMARTLIST_FOREACH_BEGIN(bridge_list, const bridge_info_t *, bridge) {
1955 if (tor_addr_eq(&bridge->addr, addr) &&
1956 (bridge->port == port)) { /* bridge matched */
1957 if (bridge->transport_name) { /* it also uses pluggable transports */
1958 *transport = transport_get_by_name(bridge->transport_name);
1959 if (*transport == NULL) { /* it uses pluggable transports, but
1960 the transport could not be found! */
1961 return -1;
1963 return 0;
1964 } else { /* bridge matched, but it doesn't use transports. */
1965 break;
1968 } SMARTLIST_FOREACH_END(bridge);
1970 *transport = NULL;
1971 return 0;
1974 /** Return a smartlist containing all the SOCKS arguments that we
1975 * should pass to the SOCKS proxy. */
1976 const smartlist_t *
1977 get_socks_args_by_bridge_addrport(const tor_addr_t *addr, uint16_t port)
1979 bridge_info_t *bridge = get_configured_bridge_by_addr_port_digest(addr,
1980 port,
1981 NULL);
1982 return bridge ? bridge->socks_args : NULL;
1985 /** We need to ask <b>bridge</b> for its server descriptor. */
1986 static void
1987 launch_direct_bridge_descriptor_fetch(bridge_info_t *bridge)
1989 const or_options_t *options = get_options();
1991 if (connection_get_by_type_addr_port_purpose(
1992 CONN_TYPE_DIR, &bridge->addr, bridge->port,
1993 DIR_PURPOSE_FETCH_SERVERDESC))
1994 return; /* it's already on the way */
1996 if (routerset_contains_bridge(options->ExcludeNodes, bridge)) {
1997 download_status_mark_impossible(&bridge->fetch_status);
1998 log_warn(LD_APP, "Not using bridge at %s: it is in ExcludeNodes.",
1999 safe_str_client(fmt_and_decorate_addr(&bridge->addr)));
2000 return;
2003 directory_initiate_command(&bridge->addr,
2004 bridge->port, 0/*no dirport*/,
2005 bridge->identity,
2006 DIR_PURPOSE_FETCH_SERVERDESC,
2007 ROUTER_PURPOSE_BRIDGE,
2008 DIRIND_ONEHOP, "authority.z", NULL, 0, 0);
2011 /** Fetching the bridge descriptor from the bridge authority returned a
2012 * "not found". Fall back to trying a direct fetch. */
2013 void
2014 retry_bridge_descriptor_fetch_directly(const char *digest)
2016 bridge_info_t *bridge = find_bridge_by_digest(digest);
2017 if (!bridge)
2018 return; /* not found? oh well. */
2020 launch_direct_bridge_descriptor_fetch(bridge);
2023 /** For each bridge in our list for which we don't currently have a
2024 * descriptor, fetch a new copy of its descriptor -- either directly
2025 * from the bridge or via a bridge authority. */
2026 void
2027 fetch_bridge_descriptors(const or_options_t *options, time_t now)
2029 int num_bridge_auths = get_n_authorities(BRIDGE_DIRINFO);
2030 int ask_bridge_directly;
2031 int can_use_bridge_authority;
2033 if (!bridge_list)
2034 return;
2036 /* If we still have unconfigured managed proxies, don't go and
2037 connect to a bridge. */
2038 if (pt_proxies_configuration_pending())
2039 return;
2041 SMARTLIST_FOREACH_BEGIN(bridge_list, bridge_info_t *, bridge)
2043 if (!download_status_is_ready(&bridge->fetch_status, now,
2044 IMPOSSIBLE_TO_DOWNLOAD))
2045 continue; /* don't bother, no need to retry yet */
2046 if (routerset_contains_bridge(options->ExcludeNodes, bridge)) {
2047 download_status_mark_impossible(&bridge->fetch_status);
2048 log_warn(LD_APP, "Not using bridge at %s: it is in ExcludeNodes.",
2049 safe_str_client(fmt_and_decorate_addr(&bridge->addr)));
2050 continue;
2053 /* schedule another fetch as if this one will fail, in case it does */
2054 download_status_failed(&bridge->fetch_status, 0);
2056 can_use_bridge_authority = !tor_digest_is_zero(bridge->identity) &&
2057 num_bridge_auths;
2058 ask_bridge_directly = !can_use_bridge_authority ||
2059 !options->UpdateBridgesFromAuthority;
2060 log_debug(LD_DIR, "ask_bridge_directly=%d (%d, %d, %d)",
2061 ask_bridge_directly, tor_digest_is_zero(bridge->identity),
2062 !options->UpdateBridgesFromAuthority, !num_bridge_auths);
2064 if (ask_bridge_directly &&
2065 !fascist_firewall_allows_address_or(&bridge->addr, bridge->port)) {
2066 log_notice(LD_DIR, "Bridge at '%s' isn't reachable by our "
2067 "firewall policy. %s.",
2068 fmt_addrport(&bridge->addr, bridge->port),
2069 can_use_bridge_authority ?
2070 "Asking bridge authority instead" : "Skipping");
2071 if (can_use_bridge_authority)
2072 ask_bridge_directly = 0;
2073 else
2074 continue;
2077 if (ask_bridge_directly) {
2078 /* we need to ask the bridge itself for its descriptor. */
2079 launch_direct_bridge_descriptor_fetch(bridge);
2080 } else {
2081 /* We have a digest and we want to ask an authority. We could
2082 * combine all the requests into one, but that may give more
2083 * hints to the bridge authority than we want to give. */
2084 char resource[10 + HEX_DIGEST_LEN];
2085 memcpy(resource, "fp/", 3);
2086 base16_encode(resource+3, HEX_DIGEST_LEN+1,
2087 bridge->identity, DIGEST_LEN);
2088 memcpy(resource+3+HEX_DIGEST_LEN, ".z", 3);
2089 log_info(LD_DIR, "Fetching bridge info '%s' from bridge authority.",
2090 resource);
2091 directory_get_from_dirserver(DIR_PURPOSE_FETCH_SERVERDESC,
2092 ROUTER_PURPOSE_BRIDGE, resource, 0);
2095 SMARTLIST_FOREACH_END(bridge);
2098 /** If our <b>bridge</b> is configured to be a different address than
2099 * the bridge gives in <b>node</b>, rewrite the routerinfo
2100 * we received to use the address we meant to use. Now we handle
2101 * multihomed bridges better.
2103 static void
2104 rewrite_node_address_for_bridge(const bridge_info_t *bridge, node_t *node)
2106 /* XXXX move this function. */
2107 /* XXXX overridden addresses should really live in the node_t, so that the
2108 * routerinfo_t and the microdesc_t can be immutable. But we can only
2109 * do that safely if we know that no function that connects to an OR
2110 * does so through an address from any source other than node_get_addr().
2112 tor_addr_t addr;
2114 if (node->ri) {
2115 routerinfo_t *ri = node->ri;
2116 tor_addr_from_ipv4h(&addr, ri->addr);
2118 if ((!tor_addr_compare(&bridge->addr, &addr, CMP_EXACT) &&
2119 bridge->port == ri->or_port) ||
2120 (!tor_addr_compare(&bridge->addr, &ri->ipv6_addr, CMP_EXACT) &&
2121 bridge->port == ri->ipv6_orport)) {
2122 /* they match, so no need to do anything */
2123 } else {
2124 if (tor_addr_family(&bridge->addr) == AF_INET) {
2125 ri->addr = tor_addr_to_ipv4h(&bridge->addr);
2126 ri->or_port = bridge->port;
2127 log_info(LD_DIR,
2128 "Adjusted bridge routerinfo for '%s' to match configured "
2129 "address %s:%d.",
2130 ri->nickname, fmt_addr32(ri->addr), ri->or_port);
2131 } else if (tor_addr_family(&bridge->addr) == AF_INET6) {
2132 tor_addr_copy(&ri->ipv6_addr, &bridge->addr);
2133 ri->ipv6_orport = bridge->port;
2134 log_info(LD_DIR,
2135 "Adjusted bridge routerinfo for '%s' to match configured "
2136 "address %s.",
2137 ri->nickname, fmt_addrport(&ri->ipv6_addr, ri->ipv6_orport));
2138 } else {
2139 log_err(LD_BUG, "Address family not supported: %d.",
2140 tor_addr_family(&bridge->addr));
2141 return;
2145 /* Mark which address to use based on which bridge_t we got. */
2146 node->ipv6_preferred = (tor_addr_family(&bridge->addr) == AF_INET6 &&
2147 !tor_addr_is_null(&node->ri->ipv6_addr));
2149 /* XXXipv6 we lack support for falling back to another address for
2150 the same relay, warn the user */
2151 if (!tor_addr_is_null(&ri->ipv6_addr)) {
2152 tor_addr_port_t ap;
2153 node_get_pref_orport(node, &ap);
2154 log_notice(LD_CONFIG,
2155 "Bridge '%s' has both an IPv4 and an IPv6 address. "
2156 "Will prefer using its %s address (%s).",
2157 ri->nickname,
2158 tor_addr_family(&ap.addr) == AF_INET6 ? "IPv6" : "IPv4",
2159 fmt_addrport(&ap.addr, ap.port));
2162 if (node->rs) {
2163 routerstatus_t *rs = node->rs;
2164 tor_addr_from_ipv4h(&addr, rs->addr);
2166 if (!tor_addr_compare(&bridge->addr, &addr, CMP_EXACT) &&
2167 bridge->port == rs->or_port) {
2168 /* they match, so no need to do anything */
2169 } else {
2170 rs->addr = tor_addr_to_ipv4h(&bridge->addr);
2171 rs->or_port = bridge->port;
2172 log_info(LD_DIR,
2173 "Adjusted bridge routerstatus for '%s' to match "
2174 "configured address %s.",
2175 rs->nickname, fmt_addrport(&bridge->addr, rs->or_port));
2180 /** We just learned a descriptor for a bridge. See if that
2181 * digest is in our entry guard list, and add it if not. */
2182 void
2183 learned_bridge_descriptor(routerinfo_t *ri, int from_cache)
2185 tor_assert(ri);
2186 tor_assert(ri->purpose == ROUTER_PURPOSE_BRIDGE);
2187 if (get_options()->UseBridges) {
2188 int first = num_bridges_usable() <= 1;
2189 bridge_info_t *bridge = get_configured_bridge_by_routerinfo(ri);
2190 time_t now = time(NULL);
2191 router_set_status(ri->cache_info.identity_digest, 1);
2193 if (bridge) { /* if we actually want to use this one */
2194 node_t *node;
2195 /* it's here; schedule its re-fetch for a long time from now. */
2196 if (!from_cache)
2197 download_status_reset(&bridge->fetch_status);
2199 node = node_get_mutable_by_id(ri->cache_info.identity_digest);
2200 tor_assert(node);
2201 rewrite_node_address_for_bridge(bridge, node);
2202 add_an_entry_guard(node, 1, 1, 0, 0);
2204 log_notice(LD_DIR, "new bridge descriptor '%s' (%s): %s", ri->nickname,
2205 from_cache ? "cached" : "fresh", router_describe(ri));
2206 /* set entry->made_contact so if it goes down we don't drop it from
2207 * our entry node list */
2208 entry_guard_register_connect_status(ri->cache_info.identity_digest,
2209 1, 0, now);
2210 if (first) {
2211 routerlist_retry_directory_downloads(now);
2217 /** Return the number of bridges that have descriptors that
2218 * are marked with purpose 'bridge' and are running.
2220 * We use this function to decide if we're ready to start building
2221 * circuits through our bridges, or if we need to wait until the
2222 * directory "server/authority" requests finish. */
2224 any_bridge_descriptors_known(void)
2226 tor_assert(get_options()->UseBridges);
2227 return choose_random_entry(NULL) != NULL;
2230 /** Return the number of bridges that have descriptors that are marked with
2231 * purpose 'bridge' and are running.
2233 static int
2234 num_bridges_usable(void)
2236 int n_options = 0;
2237 tor_assert(get_options()->UseBridges);
2238 (void) choose_random_entry_impl(NULL, 0, 0, &n_options);
2239 return n_options;
2242 /** Return 1 if we have at least one descriptor for an entry guard
2243 * (bridge or member of EntryNodes) and all descriptors we know are
2244 * down. Else return 0. If <b>act</b> is 1, then mark the down guards
2245 * up; else just observe and report. */
2246 static int
2247 entries_retry_helper(const or_options_t *options, int act)
2249 const node_t *node;
2250 int any_known = 0;
2251 int any_running = 0;
2252 int need_bridges = options->UseBridges != 0;
2253 if (!entry_guards)
2254 entry_guards = smartlist_new();
2255 SMARTLIST_FOREACH_BEGIN(entry_guards, entry_guard_t *, e) {
2256 node = node_get_by_id(e->identity);
2257 if (node && node_has_descriptor(node) &&
2258 node_is_bridge(node) == need_bridges) {
2259 any_known = 1;
2260 if (node->is_running)
2261 any_running = 1; /* some entry is both known and running */
2262 else if (act) {
2263 /* Mark all current connections to this OR as unhealthy, since
2264 * otherwise there could be one that started 30 seconds
2265 * ago, and in 30 seconds it will time out, causing us to mark
2266 * the node down and undermine the retry attempt. We mark even
2267 * the established conns, since if the network just came back
2268 * we'll want to attach circuits to fresh conns. */
2269 connection_or_set_bad_connections(node->identity, 1);
2271 /* mark this entry node for retry */
2272 router_set_status(node->identity, 1);
2273 e->can_retry = 1;
2274 e->bad_since = 0;
2277 } SMARTLIST_FOREACH_END(e);
2278 log_debug(LD_DIR, "%d: any_known %d, any_running %d",
2279 act, any_known, any_running);
2280 return any_known && !any_running;
2283 /** Do we know any descriptors for our bridges / entrynodes, and are
2284 * all the ones we have descriptors for down? */
2286 entries_known_but_down(const or_options_t *options)
2288 tor_assert(entry_list_is_constrained(options));
2289 return entries_retry_helper(options, 0);
2292 /** Mark all down known bridges / entrynodes up. */
2293 void
2294 entries_retry_all(const or_options_t *options)
2296 tor_assert(entry_list_is_constrained(options));
2297 entries_retry_helper(options, 1);
2300 /** Return true if at least one of our bridges runs a Tor version that can
2301 * provide microdescriptors to us. If not, we'll fall back to asking for
2302 * full descriptors. */
2304 any_bridge_supports_microdescriptors(void)
2306 const node_t *node;
2307 if (!get_options()->UseBridges || !entry_guards)
2308 return 0;
2309 SMARTLIST_FOREACH_BEGIN(entry_guards, entry_guard_t *, e) {
2310 node = node_get_by_id(e->identity);
2311 if (node && node->is_running &&
2312 node_is_bridge(node) && node_is_a_configured_bridge(node) &&
2313 node_understands_microdescriptors(node)) {
2314 /* This is one of our current bridges, and we know enough about
2315 * it to know that it will be able to answer our microdescriptor
2316 * questions. */
2317 return 1;
2319 } SMARTLIST_FOREACH_END(e);
2320 return 0;
2323 /** Release all storage held by the list of entry guards and related
2324 * memory structs. */
2325 void
2326 entry_guards_free_all(void)
2328 if (entry_guards) {
2329 SMARTLIST_FOREACH(entry_guards, entry_guard_t *, e,
2330 entry_guard_free(e));
2331 smartlist_free(entry_guards);
2332 entry_guards = NULL;
2334 clear_bridge_list();
2335 smartlist_free(bridge_list);
2336 bridge_list = NULL;
2337 circuit_build_times_free_timeouts(get_circuit_build_times_mutable());