Rename *_isin to *_contains
[tor.git] / src / or / entrynodes.c
blob3e58371643776689e25c3cdb9d0d0b5381389f09
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 "nodelist.h"
27 #include "policies.h"
28 #include "router.h"
29 #include "routerlist.h"
30 #include "routerparse.h"
31 #include "routerset.h"
32 #include "transports.h"
33 #include "statefile.h"
35 /** Information about a configured bridge. Currently this just matches the
36 * ones in the torrc file, but one day we may be able to learn about new
37 * bridges on our own, and remember them in the state file. */
38 typedef struct {
39 /** Address of the bridge. */
40 tor_addr_t addr;
41 /** TLS port for the bridge. */
42 uint16_t port;
43 /** Boolean: We are re-parsing our bridge list, and we are going to remove
44 * this one if we don't find it in the list of configured bridges. */
45 unsigned marked_for_removal : 1;
46 /** Expected identity digest, or all zero bytes if we don't know what the
47 * digest should be. */
48 char identity[DIGEST_LEN];
50 /** Name of pluggable transport protocol taken from its config line. */
51 char *transport_name;
53 /** When should we next try to fetch a descriptor for this bridge? */
54 download_status_t fetch_status;
55 } bridge_info_t;
57 /** A list of our chosen entry guards. */
58 static smartlist_t *entry_guards = NULL;
59 /** A value of 1 means that the entry_guards list has changed
60 * and those changes need to be flushed to disk. */
61 static int entry_guards_dirty = 0;
63 static void bridge_free(bridge_info_t *bridge);
64 static const node_t *choose_random_entry_impl(cpath_build_state_t *state,
65 int for_directory,
66 dirinfo_type_t dirtype);
68 /** Return the list of entry guards, creating it if necessary. */
69 const smartlist_t *
70 get_entry_guards(void)
72 if (! entry_guards)
73 entry_guards = smartlist_new();
74 return entry_guards;
77 /** Check whether the entry guard <b>e</b> is usable, given the directory
78 * authorities' opinion about the router (stored in <b>ri</b>) and the user's
79 * configuration (in <b>options</b>). Set <b>e</b>-&gt;bad_since
80 * accordingly. Return true iff the entry guard's status changes.
82 * If it's not usable, set *<b>reason</b> to a static string explaining why.
84 static int
85 entry_guard_set_status(entry_guard_t *e, const node_t *node,
86 time_t now, const or_options_t *options,
87 const char **reason)
89 char buf[HEX_DIGEST_LEN+1];
90 int changed = 0;
92 *reason = NULL;
94 /* Do we want to mark this guard as bad? */
95 if (!node)
96 *reason = "unlisted";
97 else if (!node->is_running)
98 *reason = "down";
99 else if (options->UseBridges && (!node->ri ||
100 node->ri->purpose != ROUTER_PURPOSE_BRIDGE))
101 *reason = "not a bridge";
102 else if (options->UseBridges && !node_is_a_configured_bridge(node))
103 *reason = "not a configured bridge";
104 else if (!options->UseBridges && !node->is_possible_guard &&
105 !routerset_contains_node(options->EntryNodes,node))
106 *reason = "not recommended as a guard";
107 else if (routerset_contains_node(options->ExcludeNodes, node))
108 *reason = "excluded";
109 else if (e->path_bias_disabled)
110 *reason = "path-biased";
112 if (*reason && ! e->bad_since) {
113 /* Router is newly bad. */
114 base16_encode(buf, sizeof(buf), e->identity, DIGEST_LEN);
115 log_info(LD_CIRC, "Entry guard %s (%s) is %s: marking as unusable.",
116 e->nickname, buf, *reason);
118 e->bad_since = now;
119 control_event_guard(e->nickname, e->identity, "BAD");
120 changed = 1;
121 } else if (!*reason && e->bad_since) {
122 /* There's nothing wrong with the router any more. */
123 base16_encode(buf, sizeof(buf), e->identity, DIGEST_LEN);
124 log_info(LD_CIRC, "Entry guard %s (%s) is no longer unusable: "
125 "marking as ok.", e->nickname, buf);
127 e->bad_since = 0;
128 control_event_guard(e->nickname, e->identity, "GOOD");
129 changed = 1;
132 if (node) {
133 int is_dir = node_is_dir(node) && node->rs &&
134 node->rs->version_supports_microdesc_cache;
135 if (e->is_dir_cache != is_dir) {
136 e->is_dir_cache = is_dir;
137 changed = 1;
141 return changed;
144 /** Return true iff enough time has passed since we last tried to connect
145 * to the unreachable guard <b>e</b> that we're willing to try again. */
146 static int
147 entry_is_time_to_retry(entry_guard_t *e, time_t now)
149 long diff;
150 if (e->last_attempted < e->unreachable_since)
151 return 1;
152 diff = now - e->unreachable_since;
153 if (diff < 6*60*60)
154 return now > (e->last_attempted + 60*60);
155 else if (diff < 3*24*60*60)
156 return now > (e->last_attempted + 4*60*60);
157 else if (diff < 7*24*60*60)
158 return now > (e->last_attempted + 18*60*60);
159 else
160 return now > (e->last_attempted + 36*60*60);
163 /** Return the node corresponding to <b>e</b>, if <b>e</b> is
164 * working well enough that we are willing to use it as an entry
165 * right now. (Else return NULL.) In particular, it must be
166 * - Listed as either up or never yet contacted;
167 * - Present in the routerlist;
168 * - Listed as 'stable' or 'fast' by the current dirserver consensus,
169 * if demanded by <b>need_uptime</b> or <b>need_capacity</b>
170 * (unless it's a configured EntryNode);
171 * - Allowed by our current ReachableORAddresses config option; and
172 * - Currently thought to be reachable by us (unless <b>assume_reachable</b>
173 * is true).
175 * If the answer is no, set *<b>msg</b> to an explanation of why.
177 * If need_descriptor is true, only return the node if we currently have
178 * a descriptor (routerinfo or microdesc) for it.
180 static INLINE const node_t *
181 entry_is_live(entry_guard_t *e, int need_uptime, int need_capacity,
182 int assume_reachable, int need_descriptor, const char **msg)
184 const node_t *node;
185 const or_options_t *options = get_options();
186 tor_assert(msg);
188 if (e->path_bias_disabled) {
189 *msg = "path-biased";
190 return NULL;
192 if (e->bad_since) {
193 *msg = "bad";
194 return NULL;
196 /* no good if it's unreachable, unless assume_unreachable or can_retry. */
197 if (!assume_reachable && !e->can_retry &&
198 e->unreachable_since && !entry_is_time_to_retry(e, time(NULL))) {
199 *msg = "unreachable";
200 return NULL;
202 node = node_get_by_id(e->identity);
203 if (!node) {
204 *msg = "no node info";
205 return NULL;
207 if (need_descriptor && !node_has_descriptor(node)) {
208 *msg = "no descriptor";
209 return NULL;
211 if (get_options()->UseBridges) {
212 if (node_get_purpose(node) != ROUTER_PURPOSE_BRIDGE) {
213 *msg = "not a bridge";
214 return NULL;
216 if (!node_is_a_configured_bridge(node)) {
217 *msg = "not a configured bridge";
218 return NULL;
220 } else { /* !get_options()->UseBridges */
221 if (node_get_purpose(node) != ROUTER_PURPOSE_GENERAL) {
222 *msg = "not general-purpose";
223 return NULL;
226 if (routerset_contains_node(options->EntryNodes, node)) {
227 /* they asked for it, they get it */
228 need_uptime = need_capacity = 0;
230 if (node_is_unreliable(node, need_uptime, need_capacity, 0)) {
231 *msg = "not fast/stable";
232 return NULL;
234 if (!fascist_firewall_allows_node(node)) {
235 *msg = "unreachable by config";
236 return NULL;
238 return node;
241 /** Return the number of entry guards that we think are usable. */
243 num_live_entry_guards(int for_directory)
245 int n = 0;
246 const char *msg;
247 if (! entry_guards)
248 return 0;
249 SMARTLIST_FOREACH_BEGIN(entry_guards, entry_guard_t *, entry) {
250 if (for_directory && !entry->is_dir_cache)
251 continue;
252 if (entry_is_live(entry, 0, 1, 0, !for_directory, &msg))
253 ++n;
254 } SMARTLIST_FOREACH_END(entry);
255 return n;
258 /** If <b>digest</b> matches the identity of any node in the
259 * entry_guards list, return that node. Else return NULL. */
260 entry_guard_t *
261 entry_guard_get_by_id_digest(const char *digest)
263 SMARTLIST_FOREACH(entry_guards, entry_guard_t *, entry,
264 if (tor_memeq(digest, entry->identity, DIGEST_LEN))
265 return entry;
267 return NULL;
270 /** Dump a description of our list of entry guards to the log at level
271 * <b>severity</b>. */
272 static void
273 log_entry_guards(int severity)
275 smartlist_t *elements = smartlist_new();
276 char *s;
278 SMARTLIST_FOREACH_BEGIN(entry_guards, entry_guard_t *, e)
280 const char *msg = NULL;
281 if (entry_is_live(e, 0, 1, 0, 0, &msg))
282 smartlist_add_asprintf(elements, "%s [%s] (up %s)",
283 e->nickname,
284 hex_str(e->identity, DIGEST_LEN),
285 e->made_contact ? "made-contact" : "never-contacted");
286 else
287 smartlist_add_asprintf(elements, "%s [%s] (%s, %s)",
288 e->nickname,
289 hex_str(e->identity, DIGEST_LEN),
290 msg,
291 e->made_contact ? "made-contact" : "never-contacted");
293 SMARTLIST_FOREACH_END(e);
295 s = smartlist_join_strings(elements, ",", 0, NULL);
296 SMARTLIST_FOREACH(elements, char*, cp, tor_free(cp));
297 smartlist_free(elements);
298 log_fn(severity,LD_CIRC,"%s",s);
299 tor_free(s);
302 /** Called when one or more guards that we would previously have used for some
303 * purpose are no longer in use because a higher-priority guard has become
304 * usable again. */
305 static void
306 control_event_guard_deferred(void)
308 /* XXXX We don't actually have a good way to figure out _how many_ entries
309 * are live for some purpose. We need an entry_is_even_slightly_live()
310 * function for this to work right. NumEntryGuards isn't reliable: if we
311 * need guards with weird properties, we can have more than that number
312 * live.
314 #if 0
315 int n = 0;
316 const char *msg;
317 const or_options_t *options = get_options();
318 if (!entry_guards)
319 return;
320 SMARTLIST_FOREACH(entry_guards, entry_guard_t *, entry,
322 if (entry_is_live(entry, 0, 1, 0, &msg)) {
323 if (n++ == options->NumEntryGuards) {
324 control_event_guard(entry->nickname, entry->identity, "DEFERRED");
325 return;
329 #endif
332 /** Add a new (preferably stable and fast) router to our
333 * entry_guards list. Return a pointer to the router if we succeed,
334 * or NULL if we can't find any more suitable entries.
336 * If <b>chosen</b> is defined, use that one, and if it's not
337 * already in our entry_guards list, put it at the *beginning*.
338 * Else, put the one we pick at the end of the list. */
339 static const node_t *
340 add_an_entry_guard(const node_t *chosen, int reset_status, int prepend,
341 int for_directory)
343 const node_t *node;
344 entry_guard_t *entry;
346 if (chosen) {
347 node = chosen;
348 entry = entry_guard_get_by_id_digest(node->identity);
349 if (entry) {
350 if (reset_status) {
351 entry->bad_since = 0;
352 entry->can_retry = 1;
354 entry->is_dir_cache = node->rs &&
355 node->rs->version_supports_microdesc_cache;
356 return NULL;
358 } else if (!for_directory) {
359 node = choose_good_entry_server(CIRCUIT_PURPOSE_C_GENERAL, NULL);
360 if (!node)
361 return NULL;
362 } else {
363 const routerstatus_t *rs;
364 rs = router_pick_directory_server(MICRODESC_DIRINFO|V3_DIRINFO,
365 PDS_PREFER_TUNNELED_DIR_CONNS_);
366 if (!rs)
367 return NULL;
368 node = node_get_by_id(rs->identity_digest);
369 if (!node)
370 return NULL;
372 entry = tor_malloc_zero(sizeof(entry_guard_t));
373 log_info(LD_CIRC, "Chose %s as new entry guard.",
374 node_describe(node));
375 strlcpy(entry->nickname, node_get_nickname(node), sizeof(entry->nickname));
376 memcpy(entry->identity, node->identity, DIGEST_LEN);
377 entry->is_dir_cache = node_is_dir(node) &&
378 node->rs && node->rs->version_supports_microdesc_cache;
380 /* Choose expiry time smudged over the past month. The goal here
381 * is to a) spread out when Tor clients rotate their guards, so they
382 * don't all select them on the same day, and b) avoid leaving a
383 * precise timestamp in the state file about when we first picked
384 * this guard. For details, see the Jan 2010 or-dev thread. */
385 entry->chosen_on_date = time(NULL) - crypto_rand_int(3600*24*30);
386 entry->chosen_by_version = tor_strdup(VERSION);
387 if (prepend)
388 smartlist_insert(entry_guards, 0, entry);
389 else
390 smartlist_add(entry_guards, entry);
391 control_event_guard(entry->nickname, entry->identity, "NEW");
392 control_event_guard_deferred();
393 log_entry_guards(LOG_INFO);
394 return node;
397 /** If the use of entry guards is configured, choose more entry guards
398 * until we have enough in the list. */
399 static void
400 pick_entry_guards(const or_options_t *options, int for_directory)
402 int changed = 0;
403 const int num_needed = for_directory ? options->NumDirectoryGuards :
404 options->NumEntryGuards;
406 tor_assert(entry_guards);
408 while (num_live_entry_guards(for_directory) < num_needed) {
409 if (!add_an_entry_guard(NULL, 0, 0, for_directory))
410 break;
411 changed = 1;
413 if (changed)
414 entry_guards_changed();
417 /** How long (in seconds) do we allow an entry guard to be nonfunctional,
418 * unlisted, excluded, or otherwise nonusable before we give up on it? */
419 #define ENTRY_GUARD_REMOVE_AFTER (30*24*60*60)
421 /** Release all storage held by <b>e</b>. */
422 static void
423 entry_guard_free(entry_guard_t *e)
425 if (!e)
426 return;
427 tor_free(e->chosen_by_version);
428 tor_free(e);
431 /** Remove any entry guard which was selected by an unknown version of Tor,
432 * or which was selected by a version of Tor that's known to select
433 * entry guards badly, or which was selected more 2 months ago. */
434 /* XXXX The "obsolete guards" and "chosen long ago guards" things should
435 * probably be different functions. */
436 static int
437 remove_obsolete_entry_guards(time_t now)
439 int changed = 0, i;
441 for (i = 0; i < smartlist_len(entry_guards); ++i) {
442 entry_guard_t *entry = smartlist_get(entry_guards, i);
443 const char *ver = entry->chosen_by_version;
444 const char *msg = NULL;
445 tor_version_t v;
446 int version_is_bad = 0, date_is_bad = 0;
447 if (!ver) {
448 msg = "does not say what version of Tor it was selected by";
449 version_is_bad = 1;
450 } else if (tor_version_parse(ver, &v)) {
451 msg = "does not seem to be from any recognized version of Tor";
452 version_is_bad = 1;
453 } else {
454 char *tor_ver = NULL;
455 tor_asprintf(&tor_ver, "Tor %s", ver);
456 if ((tor_version_as_new_as(tor_ver, "0.1.0.10-alpha") &&
457 !tor_version_as_new_as(tor_ver, "0.1.2.16-dev")) ||
458 (tor_version_as_new_as(tor_ver, "0.2.0.0-alpha") &&
459 !tor_version_as_new_as(tor_ver, "0.2.0.6-alpha")) ||
460 /* above are bug 440; below are bug 1217 */
461 (tor_version_as_new_as(tor_ver, "0.2.1.3-alpha") &&
462 !tor_version_as_new_as(tor_ver, "0.2.1.23")) ||
463 (tor_version_as_new_as(tor_ver, "0.2.2.0-alpha") &&
464 !tor_version_as_new_as(tor_ver, "0.2.2.7-alpha"))) {
465 msg = "was selected without regard for guard bandwidth";
466 version_is_bad = 1;
468 tor_free(tor_ver);
470 if (!version_is_bad && entry->chosen_on_date + 3600*24*60 < now) {
471 /* It's been 2 months since the date listed in our state file. */
472 msg = "was selected several months ago";
473 date_is_bad = 1;
476 if (version_is_bad || date_is_bad) { /* we need to drop it */
477 char dbuf[HEX_DIGEST_LEN+1];
478 tor_assert(msg);
479 base16_encode(dbuf, sizeof(dbuf), entry->identity, DIGEST_LEN);
480 log_fn(version_is_bad ? LOG_NOTICE : LOG_INFO, LD_CIRC,
481 "Entry guard '%s' (%s) %s. (Version=%s.) Replacing it.",
482 entry->nickname, dbuf, msg, ver?escaped(ver):"none");
483 control_event_guard(entry->nickname, entry->identity, "DROPPED");
484 entry_guard_free(entry);
485 smartlist_del_keeporder(entry_guards, i--);
486 log_entry_guards(LOG_INFO);
487 changed = 1;
491 return changed ? 1 : 0;
494 /** Remove all entry guards that have been down or unlisted for so
495 * long that we don't think they'll come up again. Return 1 if we
496 * removed any, or 0 if we did nothing. */
497 static int
498 remove_dead_entry_guards(time_t now)
500 char dbuf[HEX_DIGEST_LEN+1];
501 char tbuf[ISO_TIME_LEN+1];
502 int i;
503 int changed = 0;
505 for (i = 0; i < smartlist_len(entry_guards); ) {
506 entry_guard_t *entry = smartlist_get(entry_guards, i);
507 if (entry->bad_since &&
508 ! entry->path_bias_disabled &&
509 entry->bad_since + ENTRY_GUARD_REMOVE_AFTER < now) {
511 base16_encode(dbuf, sizeof(dbuf), entry->identity, DIGEST_LEN);
512 format_local_iso_time(tbuf, entry->bad_since);
513 log_info(LD_CIRC, "Entry guard '%s' (%s) has been down or unlisted "
514 "since %s local time; removing.",
515 entry->nickname, dbuf, tbuf);
516 control_event_guard(entry->nickname, entry->identity, "DROPPED");
517 entry_guard_free(entry);
518 smartlist_del_keeporder(entry_guards, i);
519 log_entry_guards(LOG_INFO);
520 changed = 1;
521 } else
522 ++i;
524 return changed ? 1 : 0;
527 /** A new directory or router-status has arrived; update the down/listed
528 * status of the entry guards.
530 * An entry is 'down' if the directory lists it as nonrunning.
531 * An entry is 'unlisted' if the directory doesn't include it.
533 * Don't call this on startup; only on a fresh download. Otherwise we'll
534 * think that things are unlisted.
536 void
537 entry_guards_compute_status(const or_options_t *options, time_t now)
539 int changed = 0;
540 digestmap_t *reasons;
542 if (! entry_guards)
543 return;
545 if (options->EntryNodes) /* reshuffle the entry guard list if needed */
546 entry_nodes_should_be_added();
548 reasons = digestmap_new();
549 SMARTLIST_FOREACH_BEGIN(entry_guards, entry_guard_t *, entry)
551 const node_t *r = node_get_by_id(entry->identity);
552 const char *reason = NULL;
553 if (entry_guard_set_status(entry, r, now, options, &reason))
554 changed = 1;
556 if (entry->bad_since)
557 tor_assert(reason);
558 if (reason)
559 digestmap_set(reasons, entry->identity, (char*)reason);
561 SMARTLIST_FOREACH_END(entry);
563 if (remove_dead_entry_guards(now))
564 changed = 1;
565 if (remove_obsolete_entry_guards(now))
566 changed = 1;
568 if (changed) {
569 SMARTLIST_FOREACH_BEGIN(entry_guards, entry_guard_t *, entry) {
570 const char *reason = digestmap_get(reasons, entry->identity);
571 const char *live_msg = "";
572 const node_t *r = entry_is_live(entry, 0, 1, 0, 0, &live_msg);
573 log_info(LD_CIRC, "Summary: Entry %s [%s] is %s, %s%s%s, and %s%s.",
574 entry->nickname,
575 hex_str(entry->identity, DIGEST_LEN),
576 entry->unreachable_since ? "unreachable" : "reachable",
577 entry->bad_since ? "unusable" : "usable",
578 reason ? ", ": "",
579 reason ? reason : "",
580 r ? "live" : "not live / ",
581 r ? "" : live_msg);
582 } SMARTLIST_FOREACH_END(entry);
583 log_info(LD_CIRC, " (%d/%d entry guards are usable/new)",
584 num_live_entry_guards(0), smartlist_len(entry_guards));
585 log_entry_guards(LOG_INFO);
586 entry_guards_changed();
589 digestmap_free(reasons, NULL);
592 /** Called when a connection to an OR with the identity digest <b>digest</b>
593 * is established (<b>succeeded</b>==1) or has failed (<b>succeeded</b>==0).
594 * If the OR is an entry, change that entry's up/down status.
595 * Return 0 normally, or -1 if we want to tear down the new connection.
597 * If <b>mark_relay_status</b>, also call router_set_status() on this
598 * relay.
600 * XXX024 change succeeded and mark_relay_status into 'int flags'.
603 entry_guard_register_connect_status(const char *digest, int succeeded,
604 int mark_relay_status, time_t now)
606 int changed = 0;
607 int refuse_conn = 0;
608 int first_contact = 0;
609 entry_guard_t *entry = NULL;
610 int idx = -1;
611 char buf[HEX_DIGEST_LEN+1];
613 if (! entry_guards)
614 return 0;
616 SMARTLIST_FOREACH_BEGIN(entry_guards, entry_guard_t *, e) {
617 tor_assert(e);
618 if (tor_memeq(e->identity, digest, DIGEST_LEN)) {
619 entry = e;
620 idx = e_sl_idx;
621 break;
623 } SMARTLIST_FOREACH_END(e);
625 if (!entry)
626 return 0;
628 base16_encode(buf, sizeof(buf), entry->identity, DIGEST_LEN);
630 if (succeeded) {
631 if (entry->unreachable_since) {
632 log_info(LD_CIRC, "Entry guard '%s' (%s) is now reachable again. Good.",
633 entry->nickname, buf);
634 entry->can_retry = 0;
635 entry->unreachable_since = 0;
636 entry->last_attempted = now;
637 control_event_guard(entry->nickname, entry->identity, "UP");
638 changed = 1;
640 if (!entry->made_contact) {
641 entry->made_contact = 1;
642 first_contact = changed = 1;
644 } else { /* ! succeeded */
645 if (!entry->made_contact) {
646 /* We've never connected to this one. */
647 log_info(LD_CIRC,
648 "Connection to never-contacted entry guard '%s' (%s) failed. "
649 "Removing from the list. %d/%d entry guards usable/new.",
650 entry->nickname, buf,
651 num_live_entry_guards(0)-1, smartlist_len(entry_guards)-1);
652 control_event_guard(entry->nickname, entry->identity, "DROPPED");
653 entry_guard_free(entry);
654 smartlist_del_keeporder(entry_guards, idx);
655 log_entry_guards(LOG_INFO);
656 changed = 1;
657 } else if (!entry->unreachable_since) {
658 log_info(LD_CIRC, "Unable to connect to entry guard '%s' (%s). "
659 "Marking as unreachable.", entry->nickname, buf);
660 entry->unreachable_since = entry->last_attempted = now;
661 control_event_guard(entry->nickname, entry->identity, "DOWN");
662 changed = 1;
663 entry->can_retry = 0; /* We gave it an early chance; no good. */
664 } else {
665 char tbuf[ISO_TIME_LEN+1];
666 format_iso_time(tbuf, entry->unreachable_since);
667 log_debug(LD_CIRC, "Failed to connect to unreachable entry guard "
668 "'%s' (%s). It has been unreachable since %s.",
669 entry->nickname, buf, tbuf);
670 entry->last_attempted = now;
671 entry->can_retry = 0; /* We gave it an early chance; no good. */
675 /* if the caller asked us to, also update the is_running flags for this
676 * relay */
677 if (mark_relay_status)
678 router_set_status(digest, succeeded);
680 if (first_contact) {
681 /* We've just added a new long-term entry guard. Perhaps the network just
682 * came back? We should give our earlier entries another try too,
683 * and close this connection so we don't use it before we've given
684 * the others a shot. */
685 SMARTLIST_FOREACH_BEGIN(entry_guards, entry_guard_t *, e) {
686 if (e == entry)
687 break;
688 if (e->made_contact) {
689 const char *msg;
690 const node_t *r = entry_is_live(e, 0, 1, 1, 0, &msg);
691 if (r && e->unreachable_since) {
692 refuse_conn = 1;
693 e->can_retry = 1;
696 } SMARTLIST_FOREACH_END(e);
697 if (refuse_conn) {
698 log_info(LD_CIRC,
699 "Connected to new entry guard '%s' (%s). Marking earlier "
700 "entry guards up. %d/%d entry guards usable/new.",
701 entry->nickname, buf,
702 num_live_entry_guards(0), smartlist_len(entry_guards));
703 log_entry_guards(LOG_INFO);
704 changed = 1;
708 if (changed)
709 entry_guards_changed();
710 return refuse_conn ? -1 : 0;
713 /** When we try to choose an entry guard, should we parse and add
714 * config's EntryNodes first? */
715 static int should_add_entry_nodes = 0;
717 /** Called when the value of EntryNodes changes in our configuration. */
718 void
719 entry_nodes_should_be_added(void)
721 log_info(LD_CIRC, "EntryNodes config option set. Putting configured "
722 "relays at the front of the entry guard list.");
723 should_add_entry_nodes = 1;
726 /** Adjust the entry guards list so that it only contains entries from
727 * EntryNodes, adding new entries from EntryNodes to the list as needed. */
728 static void
729 entry_guards_set_from_config(const or_options_t *options)
731 smartlist_t *entry_nodes, *worse_entry_nodes, *entry_fps;
732 smartlist_t *old_entry_guards_on_list, *old_entry_guards_not_on_list;
733 tor_assert(entry_guards);
735 should_add_entry_nodes = 0;
737 if (!options->EntryNodes) {
738 /* It's possible that a controller set EntryNodes, thus making
739 * should_add_entry_nodes set, then cleared it again, all before the
740 * call to choose_random_entry() that triggered us. If so, just return.
742 return;
746 char *string = routerset_to_string(options->EntryNodes);
747 log_info(LD_CIRC,"Adding configured EntryNodes '%s'.", string);
748 tor_free(string);
751 entry_nodes = smartlist_new();
752 worse_entry_nodes = smartlist_new();
753 entry_fps = smartlist_new();
754 old_entry_guards_on_list = smartlist_new();
755 old_entry_guards_not_on_list = smartlist_new();
757 /* Split entry guards into those on the list and those not. */
759 routerset_get_all_nodes(entry_nodes, options->EntryNodes,
760 options->ExcludeNodes, 0);
761 SMARTLIST_FOREACH(entry_nodes, const node_t *,node,
762 smartlist_add(entry_fps, (void*)node->identity));
764 SMARTLIST_FOREACH(entry_guards, entry_guard_t *, e, {
765 if (smartlist_contains_digest(entry_fps, e->identity))
766 smartlist_add(old_entry_guards_on_list, e);
767 else
768 smartlist_add(old_entry_guards_not_on_list, e);
771 /* Remove all currently configured guard nodes, excluded nodes, unreachable
772 * nodes, or non-Guard nodes from entry_nodes. */
773 SMARTLIST_FOREACH_BEGIN(entry_nodes, const node_t *, node) {
774 if (entry_guard_get_by_id_digest(node->identity)) {
775 SMARTLIST_DEL_CURRENT(entry_nodes, node);
776 continue;
777 } else if (routerset_contains_node(options->ExcludeNodes, node)) {
778 SMARTLIST_DEL_CURRENT(entry_nodes, node);
779 continue;
780 } else if (!fascist_firewall_allows_node(node)) {
781 SMARTLIST_DEL_CURRENT(entry_nodes, node);
782 continue;
783 } else if (! node->is_possible_guard) {
784 smartlist_add(worse_entry_nodes, (node_t*)node);
785 SMARTLIST_DEL_CURRENT(entry_nodes, node);
787 } SMARTLIST_FOREACH_END(node);
789 /* Now build the new entry_guards list. */
790 smartlist_clear(entry_guards);
791 /* First, the previously configured guards that are in EntryNodes. */
792 smartlist_add_all(entry_guards, old_entry_guards_on_list);
793 /* Next, scramble the rest of EntryNodes, putting the guards first. */
794 smartlist_shuffle(entry_nodes);
795 smartlist_shuffle(worse_entry_nodes);
796 smartlist_add_all(entry_nodes, worse_entry_nodes);
798 /* Next, the rest of EntryNodes */
799 SMARTLIST_FOREACH_BEGIN(entry_nodes, const node_t *, node) {
800 add_an_entry_guard(node, 0, 0, 0);
801 if (smartlist_len(entry_guards) > options->NumEntryGuards * 10)
802 break;
803 } SMARTLIST_FOREACH_END(node);
804 log_notice(LD_GENERAL, "%d entries in guards", smartlist_len(entry_guards));
805 /* Finally, free the remaining previously configured guards that are not in
806 * EntryNodes. */
807 SMARTLIST_FOREACH(old_entry_guards_not_on_list, entry_guard_t *, e,
808 entry_guard_free(e));
810 smartlist_free(entry_nodes);
811 smartlist_free(worse_entry_nodes);
812 smartlist_free(entry_fps);
813 smartlist_free(old_entry_guards_on_list);
814 smartlist_free(old_entry_guards_not_on_list);
815 entry_guards_changed();
818 /** Return 0 if we're fine adding arbitrary routers out of the
819 * directory to our entry guard list, or return 1 if we have a
820 * list already and we must stick to it.
823 entry_list_is_constrained(const or_options_t *options)
825 if (options->EntryNodes)
826 return 1;
827 if (options->UseBridges)
828 return 1;
829 return 0;
832 /** Pick a live (up and listed) entry guard from entry_guards. If
833 * <b>state</b> is non-NULL, this is for a specific circuit --
834 * make sure not to pick this circuit's exit or any node in the
835 * exit's family. If <b>state</b> is NULL, we're looking for a random
836 * guard (likely a bridge). */
837 const node_t *
838 choose_random_entry(cpath_build_state_t *state)
840 return choose_random_entry_impl(state, 0, 0);
843 /** Pick a live (up and listed) directory guard from entry_guards for
844 * downloading information of type <b>type</b>. */
845 const node_t *
846 choose_random_dirguard(dirinfo_type_t type)
848 return choose_random_entry_impl(NULL, 1, type);
851 /** Helper for choose_random{entry,dirguard}. */
852 static const node_t *
853 choose_random_entry_impl(cpath_build_state_t *state, int for_directory,
854 dirinfo_type_t dirinfo_type)
856 const or_options_t *options = get_options();
857 smartlist_t *live_entry_guards = smartlist_new();
858 smartlist_t *exit_family = smartlist_new();
859 const node_t *chosen_exit =
860 state?build_state_get_exit_node(state) : NULL;
861 const node_t *node = NULL;
862 int need_uptime = state ? state->need_uptime : 0;
863 int need_capacity = state ? state->need_capacity : 0;
864 int preferred_min, consider_exit_family = 0;
865 int need_descriptor = !for_directory;
866 const int num_needed = for_directory ? options->NumDirectoryGuards :
867 options->NumEntryGuards;
869 /* Checking dirinfo_type isn't required yet, since we only choose directory
870 guards that can support microdescs, routerinfos, and networkstatuses, AND
871 we don't use directory guards if we're configured to do direct downloads
872 of anything else. */
873 (void) dirinfo_type;
875 if (chosen_exit) {
876 nodelist_add_node_and_family(exit_family, chosen_exit);
877 consider_exit_family = 1;
880 if (!entry_guards)
881 entry_guards = smartlist_new();
883 if (should_add_entry_nodes)
884 entry_guards_set_from_config(options);
886 if (!entry_list_is_constrained(options) &&
887 smartlist_len(entry_guards) < num_needed)
888 pick_entry_guards(options, for_directory);
890 retry:
891 smartlist_clear(live_entry_guards);
892 SMARTLIST_FOREACH_BEGIN(entry_guards, entry_guard_t *, entry) {
893 const char *msg;
894 node = entry_is_live(entry, need_uptime, need_capacity, 0,
895 need_descriptor, &msg);
896 if (!node)
897 continue; /* down, no point */
898 if (for_directory) {
899 if (!entry->is_dir_cache)
900 continue; /* We need a directory and didn't get one. */
902 if (node == chosen_exit)
903 continue; /* don't pick the same node for entry and exit */
904 if (consider_exit_family && smartlist_contains(exit_family, node))
905 continue; /* avoid relays that are family members of our exit */
906 #if 0 /* since EntryNodes is always strict now, this clause is moot */
907 if (options->EntryNodes &&
908 !routerset_contains_node(options->EntryNodes, node)) {
909 /* We've come to the end of our preferred entry nodes. */
910 if (smartlist_len(live_entry_guards))
911 goto choose_and_finish; /* only choose from the ones we like */
912 if (options->StrictNodes) {
913 /* in theory this case should never happen, since
914 * entry_guards_set_from_config() drops unwanted relays */
915 tor_fragile_assert();
916 } else {
917 log_info(LD_CIRC,
918 "No relays from EntryNodes available. Using others.");
921 #endif
922 smartlist_add(live_entry_guards, (void*)node);
923 if (!entry->made_contact) {
924 /* Always start with the first not-yet-contacted entry
925 * guard. Otherwise we might add several new ones, pick
926 * the second new one, and now we've expanded our entry
927 * guard list without needing to. */
928 goto choose_and_finish;
930 if (smartlist_len(live_entry_guards) >= num_needed)
931 goto choose_and_finish; /* we have enough */
932 } SMARTLIST_FOREACH_END(entry);
934 if (entry_list_is_constrained(options)) {
935 /* If we prefer the entry nodes we've got, and we have at least
936 * one choice, that's great. Use it. */
937 preferred_min = 1;
938 } else {
939 /* Try to have at least 2 choices available. This way we don't
940 * get stuck with a single live-but-crummy entry and just keep
941 * using him.
942 * (We might get 2 live-but-crummy entry guards, but so be it.) */
943 preferred_min = 2;
946 if (smartlist_len(live_entry_guards) < preferred_min) {
947 if (!entry_list_is_constrained(options)) {
948 /* still no? try adding a new entry then */
949 /* XXX if guard doesn't imply fast and stable, then we need
950 * to tell add_an_entry_guard below what we want, or it might
951 * be a long time til we get it. -RD */
952 node = add_an_entry_guard(NULL, 0, 0, for_directory);
953 if (node) {
954 entry_guards_changed();
955 /* XXX we start over here in case the new node we added shares
956 * a family with our exit node. There's a chance that we'll just
957 * load up on entry guards here, if the network we're using is
958 * one big family. Perhaps we should teach add_an_entry_guard()
959 * to understand nodes-to-avoid-if-possible? -RD */
960 goto retry;
963 if (!node && need_uptime) {
964 need_uptime = 0; /* try without that requirement */
965 goto retry;
967 if (!node && need_capacity) {
968 /* still no? last attempt, try without requiring capacity */
969 need_capacity = 0;
970 goto retry;
972 #if 0
973 /* Removing this retry logic: if we only allow one exit, and it is in the
974 same family as all our entries, then we are just plain not going to win
975 here. */
976 if (!node && entry_list_is_constrained(options) && consider_exit_family) {
977 /* still no? if we're using bridges or have strictentrynodes
978 * set, and our chosen exit is in the same family as all our
979 * bridges/entry guards, then be flexible about families. */
980 consider_exit_family = 0;
981 goto retry;
983 #endif
984 /* live_entry_guards may be empty below. Oh well, we tried. */
987 choose_and_finish:
988 if (entry_list_is_constrained(options)) {
989 /* We need to weight by bandwidth, because our bridges or entryguards
990 * were not already selected proportional to their bandwidth. */
991 node = node_sl_choose_by_bandwidth(live_entry_guards, WEIGHT_FOR_GUARD);
992 } else {
993 /* We choose uniformly at random here, because choose_good_entry_server()
994 * already weights its choices by bandwidth, so we don't want to
995 * *double*-weight our guard selection. */
996 node = smartlist_choose(live_entry_guards);
998 smartlist_free(live_entry_guards);
999 smartlist_free(exit_family);
1000 return node;
1003 /** Parse <b>state</b> and learn about the entry guards it describes.
1004 * If <b>set</b> is true, and there are no errors, replace the global
1005 * entry_list with what we find.
1006 * On success, return 0. On failure, alloc into *<b>msg</b> a string
1007 * describing the error, and return -1.
1010 entry_guards_parse_state(or_state_t *state, int set, char **msg)
1012 entry_guard_t *node = NULL;
1013 smartlist_t *new_entry_guards = smartlist_new();
1014 config_line_t *line;
1015 time_t now = time(NULL);
1016 const char *state_version = state->TorVersion;
1017 digestmap_t *added_by = digestmap_new();
1019 *msg = NULL;
1020 for (line = state->EntryGuards; line; line = line->next) {
1021 if (!strcasecmp(line->key, "EntryGuard")) {
1022 smartlist_t *args = smartlist_new();
1023 node = tor_malloc_zero(sizeof(entry_guard_t));
1024 /* all entry guards on disk have been contacted */
1025 node->made_contact = 1;
1026 smartlist_add(new_entry_guards, node);
1027 smartlist_split_string(args, line->value, " ",
1028 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
1029 if (smartlist_len(args)<2) {
1030 *msg = tor_strdup("Unable to parse entry nodes: "
1031 "Too few arguments to EntryGuard");
1032 } else if (!is_legal_nickname(smartlist_get(args,0))) {
1033 *msg = tor_strdup("Unable to parse entry nodes: "
1034 "Bad nickname for EntryGuard");
1035 } else {
1036 strlcpy(node->nickname, smartlist_get(args,0), MAX_NICKNAME_LEN+1);
1037 if (base16_decode(node->identity, DIGEST_LEN, smartlist_get(args,1),
1038 strlen(smartlist_get(args,1)))<0) {
1039 *msg = tor_strdup("Unable to parse entry nodes: "
1040 "Bad hex digest for EntryGuard");
1043 if (smartlist_len(args) >= 3) {
1044 const char *is_cache = smartlist_get(args, 2);
1045 if (!strcasecmp(is_cache, "DirCache")) {
1046 node->is_dir_cache = 1;
1047 } else if (!strcasecmp(is_cache, "NoDirCache")) {
1048 node->is_dir_cache = 0;
1049 } else {
1050 log_warn(LD_CONFIG, "Bogus third argument to EntryGuard line: %s",
1051 escaped(is_cache));
1054 SMARTLIST_FOREACH(args, char*, cp, tor_free(cp));
1055 smartlist_free(args);
1056 if (*msg)
1057 break;
1058 } else if (!strcasecmp(line->key, "EntryGuardDownSince") ||
1059 !strcasecmp(line->key, "EntryGuardUnlistedSince")) {
1060 time_t when;
1061 time_t last_try = 0;
1062 if (!node) {
1063 *msg = tor_strdup("Unable to parse entry nodes: "
1064 "EntryGuardDownSince/UnlistedSince without EntryGuard");
1065 break;
1067 if (parse_iso_time(line->value, &when)<0) {
1068 *msg = tor_strdup("Unable to parse entry nodes: "
1069 "Bad time in EntryGuardDownSince/UnlistedSince");
1070 break;
1072 if (when > now) {
1073 /* It's a bad idea to believe info in the future: you can wind
1074 * up with timeouts that aren't allowed to happen for years. */
1075 continue;
1077 if (strlen(line->value) >= ISO_TIME_LEN+ISO_TIME_LEN+1) {
1078 /* ignore failure */
1079 (void) parse_iso_time(line->value+ISO_TIME_LEN+1, &last_try);
1081 if (!strcasecmp(line->key, "EntryGuardDownSince")) {
1082 node->unreachable_since = when;
1083 node->last_attempted = last_try;
1084 } else {
1085 node->bad_since = when;
1087 } else if (!strcasecmp(line->key, "EntryGuardAddedBy")) {
1088 char d[DIGEST_LEN];
1089 /* format is digest version date */
1090 if (strlen(line->value) < HEX_DIGEST_LEN+1+1+1+ISO_TIME_LEN) {
1091 log_warn(LD_BUG, "EntryGuardAddedBy line is not long enough.");
1092 continue;
1094 if (base16_decode(d, sizeof(d), line->value, HEX_DIGEST_LEN)<0 ||
1095 line->value[HEX_DIGEST_LEN] != ' ') {
1096 log_warn(LD_BUG, "EntryGuardAddedBy line %s does not begin with "
1097 "hex digest", escaped(line->value));
1098 continue;
1100 digestmap_set(added_by, d, tor_strdup(line->value+HEX_DIGEST_LEN+1));
1101 } else if (!strcasecmp(line->key, "EntryGuardPathBias")) {
1102 const or_options_t *options = get_options();
1103 double hop_cnt, success_cnt, timeouts, collapsed, successful_closed,
1104 unusable;
1106 if (!node) {
1107 *msg = tor_strdup("Unable to parse entry nodes: "
1108 "EntryGuardPathBias without EntryGuard");
1109 break;
1112 /* First try 3 params, then 2. */
1113 /* In the long run: circuit_success ~= successful_circuit_close +
1114 * collapsed_circuits +
1115 * unusable_circuits */
1116 if (tor_sscanf(line->value, "%lf %lf %lf %lf %lf %lf",
1117 &hop_cnt, &success_cnt, &successful_closed,
1118 &collapsed, &unusable, &timeouts) != 6) {
1119 int old_success, old_hops;
1120 if (tor_sscanf(line->value, "%u %u", &old_success, &old_hops) != 2) {
1121 continue;
1123 log_info(LD_GENERAL, "Reading old-style EntryGuardPathBias %s",
1124 escaped(line->value));
1126 success_cnt = old_success;
1127 successful_closed = old_success;
1128 hop_cnt = old_hops;
1129 timeouts = 0;
1130 collapsed = 0;
1131 unusable = 0;
1134 node->circ_attempts = hop_cnt;
1135 node->circ_successes = success_cnt;
1137 node->successful_circuits_closed = successful_closed;
1138 node->timeouts = timeouts;
1139 node->collapsed_circuits = collapsed;
1140 node->unusable_circuits = unusable;
1142 log_info(LD_GENERAL, "Read %f/%f path bias for node %s",
1143 node->circ_successes, node->circ_attempts, node->nickname);
1144 /* Note: We rely on the < comparison here to allow us to set a 0
1145 * rate and disable the feature entirely. If refactoring, don't
1146 * change to <= */
1147 if (pathbias_get_success_count(node)/node->circ_attempts
1148 < pathbias_get_extreme_rate(options) &&
1149 pathbias_get_dropguards(options)) {
1150 node->path_bias_disabled = 1;
1151 log_info(LD_GENERAL,
1152 "Path bias is too high (%f/%f); disabling node %s",
1153 node->circ_successes, node->circ_attempts, node->nickname);
1156 } else {
1157 log_warn(LD_BUG, "Unexpected key %s", line->key);
1161 SMARTLIST_FOREACH_BEGIN(new_entry_guards, entry_guard_t *, e) {
1162 char *sp;
1163 char *val = digestmap_get(added_by, e->identity);
1164 if (val && (sp = strchr(val, ' '))) {
1165 time_t when;
1166 *sp++ = '\0';
1167 if (parse_iso_time(sp, &when)<0) {
1168 log_warn(LD_BUG, "Can't read time %s in EntryGuardAddedBy", sp);
1169 } else {
1170 e->chosen_by_version = tor_strdup(val);
1171 e->chosen_on_date = when;
1173 } else {
1174 if (state_version) {
1175 e->chosen_by_version = tor_strdup(state_version);
1176 e->chosen_on_date = time(NULL) - crypto_rand_int(3600*24*30);
1179 if (e->path_bias_disabled && !e->bad_since)
1180 e->bad_since = time(NULL);
1182 SMARTLIST_FOREACH_END(e);
1184 if (*msg || !set) {
1185 SMARTLIST_FOREACH(new_entry_guards, entry_guard_t *, e,
1186 entry_guard_free(e));
1187 smartlist_free(new_entry_guards);
1188 } else { /* !err && set */
1189 if (entry_guards) {
1190 SMARTLIST_FOREACH(entry_guards, entry_guard_t *, e,
1191 entry_guard_free(e));
1192 smartlist_free(entry_guards);
1194 entry_guards = new_entry_guards;
1195 entry_guards_dirty = 0;
1196 /* XXX024 hand new_entry_guards to this func, and move it up a
1197 * few lines, so we don't have to re-dirty it */
1198 if (remove_obsolete_entry_guards(now))
1199 entry_guards_dirty = 1;
1201 digestmap_free(added_by, tor_free_);
1202 return *msg ? -1 : 0;
1205 /** Our list of entry guards has changed, or some element of one
1206 * of our entry guards has changed. Write the changes to disk within
1207 * the next few minutes.
1209 void
1210 entry_guards_changed(void)
1212 time_t when;
1213 entry_guards_dirty = 1;
1215 /* or_state_save() will call entry_guards_update_state(). */
1216 when = get_options()->AvoidDiskWrites ? time(NULL) + 3600 : time(NULL)+600;
1217 or_state_mark_dirty(get_or_state(), when);
1220 /** If the entry guard info has not changed, do nothing and return.
1221 * Otherwise, free the EntryGuards piece of <b>state</b> and create
1222 * a new one out of the global entry_guards list, and then mark
1223 * <b>state</b> dirty so it will get saved to disk.
1225 void
1226 entry_guards_update_state(or_state_t *state)
1228 config_line_t **next, *line;
1229 if (! entry_guards_dirty)
1230 return;
1232 config_free_lines(state->EntryGuards);
1233 next = &state->EntryGuards;
1234 *next = NULL;
1235 if (!entry_guards)
1236 entry_guards = smartlist_new();
1237 SMARTLIST_FOREACH_BEGIN(entry_guards, entry_guard_t *, e) {
1238 char dbuf[HEX_DIGEST_LEN+1];
1239 if (!e->made_contact)
1240 continue; /* don't write this one to disk */
1241 *next = line = tor_malloc_zero(sizeof(config_line_t));
1242 line->key = tor_strdup("EntryGuard");
1243 base16_encode(dbuf, sizeof(dbuf), e->identity, DIGEST_LEN);
1244 tor_asprintf(&line->value, "%s %s %sDirCache", e->nickname, dbuf,
1245 e->is_dir_cache ? "" : "No");
1246 next = &(line->next);
1247 if (e->unreachable_since) {
1248 *next = line = tor_malloc_zero(sizeof(config_line_t));
1249 line->key = tor_strdup("EntryGuardDownSince");
1250 line->value = tor_malloc(ISO_TIME_LEN+1+ISO_TIME_LEN+1);
1251 format_iso_time(line->value, e->unreachable_since);
1252 if (e->last_attempted) {
1253 line->value[ISO_TIME_LEN] = ' ';
1254 format_iso_time(line->value+ISO_TIME_LEN+1, e->last_attempted);
1256 next = &(line->next);
1258 if (e->bad_since) {
1259 *next = line = tor_malloc_zero(sizeof(config_line_t));
1260 line->key = tor_strdup("EntryGuardUnlistedSince");
1261 line->value = tor_malloc(ISO_TIME_LEN+1);
1262 format_iso_time(line->value, e->bad_since);
1263 next = &(line->next);
1265 if (e->chosen_on_date && e->chosen_by_version &&
1266 !strchr(e->chosen_by_version, ' ')) {
1267 char d[HEX_DIGEST_LEN+1];
1268 char t[ISO_TIME_LEN+1];
1269 *next = line = tor_malloc_zero(sizeof(config_line_t));
1270 line->key = tor_strdup("EntryGuardAddedBy");
1271 base16_encode(d, sizeof(d), e->identity, DIGEST_LEN);
1272 format_iso_time(t, e->chosen_on_date);
1273 tor_asprintf(&line->value, "%s %s %s",
1274 d, e->chosen_by_version, t);
1275 next = &(line->next);
1277 if (e->circ_attempts > 0) {
1278 *next = line = tor_malloc_zero(sizeof(config_line_t));
1279 line->key = tor_strdup("EntryGuardPathBias");
1280 /* In the long run: circuit_success ~= successful_circuit_close +
1281 * collapsed_circuits +
1282 * unusable_circuits */
1283 tor_asprintf(&line->value, "%f %f %f %f %f %f",
1284 e->circ_attempts, e->circ_successes,
1285 pathbias_get_closed_count(e), e->collapsed_circuits,
1286 e->unusable_circuits, e->timeouts);
1287 next = &(line->next);
1290 } SMARTLIST_FOREACH_END(e);
1291 if (!get_options()->AvoidDiskWrites)
1292 or_state_mark_dirty(get_or_state(), 0);
1293 entry_guards_dirty = 0;
1296 /** If <b>question</b> is the string "entry-guards", then dump
1297 * to *<b>answer</b> a newly allocated string describing all of
1298 * the nodes in the global entry_guards list. See control-spec.txt
1299 * for details.
1300 * For backward compatibility, we also handle the string "helper-nodes".
1301 * */
1303 getinfo_helper_entry_guards(control_connection_t *conn,
1304 const char *question, char **answer,
1305 const char **errmsg)
1307 (void) conn;
1308 (void) errmsg;
1310 if (!strcmp(question,"entry-guards") ||
1311 !strcmp(question,"helper-nodes")) {
1312 smartlist_t *sl = smartlist_new();
1313 char tbuf[ISO_TIME_LEN+1];
1314 char nbuf[MAX_VERBOSE_NICKNAME_LEN+1];
1315 if (!entry_guards)
1316 entry_guards = smartlist_new();
1317 SMARTLIST_FOREACH_BEGIN(entry_guards, entry_guard_t *, e) {
1318 const char *status = NULL;
1319 time_t when = 0;
1320 const node_t *node;
1322 if (!e->made_contact) {
1323 status = "never-connected";
1324 } else if (e->bad_since) {
1325 when = e->bad_since;
1326 status = "unusable";
1327 } else {
1328 status = "up";
1331 node = node_get_by_id(e->identity);
1332 if (node) {
1333 node_get_verbose_nickname(node, nbuf);
1334 } else {
1335 nbuf[0] = '$';
1336 base16_encode(nbuf+1, sizeof(nbuf)-1, e->identity, DIGEST_LEN);
1337 /* e->nickname field is not very reliable if we don't know about
1338 * this router any longer; don't include it. */
1341 if (when) {
1342 format_iso_time(tbuf, when);
1343 smartlist_add_asprintf(sl, "%s %s %s\n", nbuf, status, tbuf);
1344 } else {
1345 smartlist_add_asprintf(sl, "%s %s\n", nbuf, status);
1347 } SMARTLIST_FOREACH_END(e);
1348 *answer = smartlist_join_strings(sl, "", 0, NULL);
1349 SMARTLIST_FOREACH(sl, char *, c, tor_free(c));
1350 smartlist_free(sl);
1352 return 0;
1355 /** A list of configured bridges. Whenever we actually get a descriptor
1356 * for one, we add it as an entry guard. Note that the order of bridges
1357 * in this list does not necessarily correspond to the order of bridges
1358 * in the torrc. */
1359 static smartlist_t *bridge_list = NULL;
1361 /** Mark every entry of the bridge list to be removed on our next call to
1362 * sweep_bridge_list unless it has first been un-marked. */
1363 void
1364 mark_bridge_list(void)
1366 if (!bridge_list)
1367 bridge_list = smartlist_new();
1368 SMARTLIST_FOREACH(bridge_list, bridge_info_t *, b,
1369 b->marked_for_removal = 1);
1372 /** Remove every entry of the bridge list that was marked with
1373 * mark_bridge_list if it has not subsequently been un-marked. */
1374 void
1375 sweep_bridge_list(void)
1377 if (!bridge_list)
1378 bridge_list = smartlist_new();
1379 SMARTLIST_FOREACH_BEGIN(bridge_list, bridge_info_t *, b) {
1380 if (b->marked_for_removal) {
1381 SMARTLIST_DEL_CURRENT(bridge_list, b);
1382 bridge_free(b);
1384 } SMARTLIST_FOREACH_END(b);
1387 /** Initialize the bridge list to empty, creating it if needed. */
1388 static void
1389 clear_bridge_list(void)
1391 if (!bridge_list)
1392 bridge_list = smartlist_new();
1393 SMARTLIST_FOREACH(bridge_list, bridge_info_t *, b, bridge_free(b));
1394 smartlist_clear(bridge_list);
1397 /** Free the bridge <b>bridge</b>. */
1398 static void
1399 bridge_free(bridge_info_t *bridge)
1401 if (!bridge)
1402 return;
1404 tor_free(bridge->transport_name);
1405 tor_free(bridge);
1408 /** If we have a bridge configured whose digest matches <b>digest</b>, or a
1409 * bridge with no known digest whose address matches any of the
1410 * tor_addr_port_t's in <b>orports</b>, return that bridge. Else return
1411 * NULL. */
1412 static bridge_info_t *
1413 get_configured_bridge_by_orports_digest(const char *digest,
1414 const smartlist_t *orports)
1416 if (!bridge_list)
1417 return NULL;
1418 SMARTLIST_FOREACH_BEGIN(bridge_list, bridge_info_t *, bridge)
1420 if (tor_digest_is_zero(bridge->identity)) {
1421 SMARTLIST_FOREACH_BEGIN(orports, tor_addr_port_t *, ap)
1423 if (tor_addr_compare(&bridge->addr, &ap->addr, CMP_EXACT) == 0 &&
1424 bridge->port == ap->port)
1425 return bridge;
1427 SMARTLIST_FOREACH_END(ap);
1429 if (digest && tor_memeq(bridge->identity, digest, DIGEST_LEN))
1430 return bridge;
1432 SMARTLIST_FOREACH_END(bridge);
1433 return NULL;
1436 /** If we have a bridge configured whose digest matches <b>digest</b>, or a
1437 * bridge with no known digest whose address matches <b>addr</b>:<b>/port</b>,
1438 * return that bridge. Else return NULL. */
1439 static bridge_info_t *
1440 get_configured_bridge_by_addr_port_digest(const tor_addr_t *addr,
1441 uint16_t port,
1442 const char *digest)
1444 if (!bridge_list)
1445 return NULL;
1446 SMARTLIST_FOREACH_BEGIN(bridge_list, bridge_info_t *, bridge)
1448 if (tor_digest_is_zero(bridge->identity) &&
1449 !tor_addr_compare(&bridge->addr, addr, CMP_EXACT) &&
1450 bridge->port == port)
1451 return bridge;
1452 if (digest && tor_memeq(bridge->identity, digest, DIGEST_LEN))
1453 return bridge;
1455 SMARTLIST_FOREACH_END(bridge);
1456 return NULL;
1459 /** Wrapper around get_configured_bridge_by_addr_port_digest() to look
1460 * it up via router descriptor <b>ri</b>. */
1461 static bridge_info_t *
1462 get_configured_bridge_by_routerinfo(const routerinfo_t *ri)
1464 bridge_info_t *bi = NULL;
1465 smartlist_t *orports = router_get_all_orports(ri);
1466 bi = get_configured_bridge_by_orports_digest(ri->cache_info.identity_digest,
1467 orports);
1468 SMARTLIST_FOREACH(orports, tor_addr_port_t *, p, tor_free(p));
1469 smartlist_free(orports);
1470 return bi;
1473 /** Return 1 if <b>ri</b> is one of our known bridges, else 0. */
1475 routerinfo_is_a_configured_bridge(const routerinfo_t *ri)
1477 return get_configured_bridge_by_routerinfo(ri) ? 1 : 0;
1480 /** Return 1 if <b>node</b> is one of our configured bridges, else 0. */
1482 node_is_a_configured_bridge(const node_t *node)
1484 int retval = 0;
1485 smartlist_t *orports = node_get_all_orports(node);
1486 retval = get_configured_bridge_by_orports_digest(node->identity,
1487 orports) != NULL;
1488 SMARTLIST_FOREACH(orports, tor_addr_port_t *, p, tor_free(p));
1489 smartlist_free(orports);
1490 return retval;
1493 /** We made a connection to a router at <b>addr</b>:<b>port</b>
1494 * without knowing its digest. Its digest turned out to be <b>digest</b>.
1495 * If it was a bridge, and we still don't know its digest, record it.
1497 void
1498 learned_router_identity(const tor_addr_t *addr, uint16_t port,
1499 const char *digest)
1501 bridge_info_t *bridge =
1502 get_configured_bridge_by_addr_port_digest(addr, port, digest);
1503 if (bridge && tor_digest_is_zero(bridge->identity)) {
1504 char *transport_info = NULL;
1505 const char *transport_name =
1506 find_transport_name_by_bridge_addrport(addr, port);
1507 if (transport_name)
1508 tor_asprintf(&transport_info, " (with transport '%s')", transport_name);
1510 memcpy(bridge->identity, digest, DIGEST_LEN);
1511 log_notice(LD_DIR, "Learned fingerprint %s for bridge %s%s.",
1512 hex_str(digest, DIGEST_LEN), fmt_addrport(addr, port),
1513 transport_info ? transport_info : "");
1514 tor_free(transport_info);
1518 /** Return true if <b>bridge</b> has the same identity digest as
1519 * <b>digest</b>. If <b>digest</b> is NULL, it matches
1520 * bridges with unspecified identity digests. */
1521 static int
1522 bridge_has_digest(const bridge_info_t *bridge, const char *digest)
1524 if (digest)
1525 return tor_memeq(digest, bridge->identity, DIGEST_LEN);
1526 else
1527 return tor_digest_is_zero(bridge->identity);
1530 /** We are about to add a new bridge at <b>addr</b>:<b>port</b>, with optional
1531 * <b>digest</b> and <b>transport_name</b>. Mark for removal any previously
1532 * existing bridge with the same address and port, and warn the user as
1533 * appropriate.
1535 static void
1536 bridge_resolve_conflicts(const tor_addr_t *addr, uint16_t port,
1537 const char *digest, const char *transport_name)
1539 /* Iterate the already-registered bridge list:
1541 If you find a bridge with the same adress and port, mark it for
1542 removal. It doesn't make sense to have two active bridges with
1543 the same IP:PORT. If the bridge in question has a different
1544 digest or transport than <b>digest</b>/<b>transport_name</b>,
1545 it's probably a misconfiguration and we should warn the user.
1547 SMARTLIST_FOREACH_BEGIN(bridge_list, bridge_info_t *, bridge) {
1548 if (bridge->marked_for_removal)
1549 continue;
1551 if (tor_addr_eq(&bridge->addr, addr) && (bridge->port == port)) {
1553 bridge->marked_for_removal = 1;
1555 if (!bridge_has_digest(bridge, digest) ||
1556 strcmp_opt(bridge->transport_name, transport_name)) {
1557 /* warn the user */
1558 char *bridge_description_new, *bridge_description_old;
1559 tor_asprintf(&bridge_description_new, "%s:%s:%s",
1560 fmt_addrport(addr, port),
1561 digest ? hex_str(digest, DIGEST_LEN) : "",
1562 transport_name ? transport_name : "");
1563 tor_asprintf(&bridge_description_old, "%s:%s:%s",
1564 fmt_addrport(&bridge->addr, bridge->port),
1565 tor_digest_is_zero(bridge->identity) ?
1566 "" : hex_str(bridge->identity,DIGEST_LEN),
1567 bridge->transport_name ? bridge->transport_name : "");
1569 log_warn(LD_GENERAL,"Tried to add bridge '%s', but we found a conflict"
1570 " with the already registered bridge '%s'. We will discard"
1571 " the old bridge and keep '%s'. If this is not what you"
1572 " wanted, please change your configuration file accordingly.",
1573 bridge_description_new, bridge_description_old,
1574 bridge_description_new);
1576 tor_free(bridge_description_new);
1577 tor_free(bridge_description_old);
1580 } SMARTLIST_FOREACH_END(bridge);
1583 /** Remember a new bridge at <b>addr</b>:<b>port</b>. If <b>digest</b>
1584 * is set, it tells us the identity key too. If we already had the
1585 * bridge in our list, unmark it, and don't actually add anything new.
1586 * If <b>transport_name</b> is non-NULL - the bridge is associated with a
1587 * pluggable transport - we assign the transport to the bridge. */
1588 void
1589 bridge_add_from_config(const tor_addr_t *addr, uint16_t port,
1590 const char *digest, const char *transport_name)
1592 bridge_info_t *b;
1594 bridge_resolve_conflicts(addr, port, digest, transport_name);
1596 b = tor_malloc_zero(sizeof(bridge_info_t));
1597 tor_addr_copy(&b->addr, addr);
1598 b->port = port;
1599 if (digest)
1600 memcpy(b->identity, digest, DIGEST_LEN);
1601 if (transport_name)
1602 b->transport_name = tor_strdup(transport_name);
1603 b->fetch_status.schedule = DL_SCHED_BRIDGE;
1604 if (!bridge_list)
1605 bridge_list = smartlist_new();
1607 smartlist_add(bridge_list, b);
1610 /** Return true iff <b>routerset</b> contains the bridge <b>bridge</b>. */
1611 static int
1612 routerset_contains_bridge(const routerset_t *routerset,
1613 const bridge_info_t *bridge)
1615 int result;
1616 extend_info_t *extinfo;
1617 tor_assert(bridge);
1618 if (!routerset)
1619 return 0;
1621 extinfo = extend_info_new(
1622 NULL, bridge->identity, NULL, NULL, &bridge->addr, bridge->port);
1623 result = routerset_contains_extendinfo(routerset, extinfo);
1624 extend_info_free(extinfo);
1625 return result;
1628 /** If <b>digest</b> is one of our known bridges, return it. */
1629 static bridge_info_t *
1630 find_bridge_by_digest(const char *digest)
1632 SMARTLIST_FOREACH(bridge_list, bridge_info_t *, bridge,
1634 if (tor_memeq(bridge->identity, digest, DIGEST_LEN))
1635 return bridge;
1637 return NULL;
1640 /** Given the <b>addr</b> and <b>port</b> of a bridge, if that bridge
1641 * supports a pluggable transport, return its name. Otherwise, return
1642 * NULL. */
1643 const char *
1644 find_transport_name_by_bridge_addrport(const tor_addr_t *addr, uint16_t port)
1646 if (!bridge_list)
1647 return NULL;
1649 SMARTLIST_FOREACH_BEGIN(bridge_list, const bridge_info_t *, bridge) {
1650 if (tor_addr_eq(&bridge->addr, addr) &&
1651 (bridge->port == port))
1652 return bridge->transport_name;
1653 } SMARTLIST_FOREACH_END(bridge);
1655 return NULL;
1658 /** If <b>addr</b> and <b>port</b> match the address and port of a
1659 * bridge of ours that uses pluggable transports, place its transport
1660 * in <b>transport</b>.
1662 * Return 0 on success (found a transport, or found a bridge with no
1663 * transport, or found no bridge); return -1 if we should be using a
1664 * transport, but the transport could not be found.
1667 find_transport_by_bridge_addrport(const tor_addr_t *addr, uint16_t port,
1668 const transport_t **transport)
1670 *transport = NULL;
1671 if (!bridge_list)
1672 return 0;
1674 SMARTLIST_FOREACH_BEGIN(bridge_list, const bridge_info_t *, bridge) {
1675 if (tor_addr_eq(&bridge->addr, addr) &&
1676 (bridge->port == port)) { /* bridge matched */
1677 if (bridge->transport_name) { /* it also uses pluggable transports */
1678 *transport = transport_get_by_name(bridge->transport_name);
1679 if (*transport == NULL) { /* it uses pluggable transports, but
1680 the transport could not be found! */
1681 return -1;
1683 return 0;
1684 } else { /* bridge matched, but it doesn't use transports. */
1685 break;
1688 } SMARTLIST_FOREACH_END(bridge);
1690 *transport = NULL;
1691 return 0;
1694 /** We need to ask <b>bridge</b> for its server descriptor. */
1695 static void
1696 launch_direct_bridge_descriptor_fetch(bridge_info_t *bridge)
1698 char *address;
1699 const or_options_t *options = get_options();
1701 if (connection_get_by_type_addr_port_purpose(
1702 CONN_TYPE_DIR, &bridge->addr, bridge->port,
1703 DIR_PURPOSE_FETCH_SERVERDESC))
1704 return; /* it's already on the way */
1706 if (routerset_contains_bridge(options->ExcludeNodes, bridge)) {
1707 download_status_mark_impossible(&bridge->fetch_status);
1708 log_warn(LD_APP, "Not using bridge at %s: it is in ExcludeNodes.",
1709 safe_str_client(fmt_and_decorate_addr(&bridge->addr)));
1710 return;
1713 address = tor_dup_addr(&bridge->addr);
1715 directory_initiate_command(address, &bridge->addr,
1716 bridge->port, 0/*no dirport*/,
1717 bridge->identity,
1718 DIR_PURPOSE_FETCH_SERVERDESC,
1719 ROUTER_PURPOSE_BRIDGE,
1720 DIRIND_ONEHOP, "authority.z", NULL, 0, 0);
1721 tor_free(address);
1724 /** Fetching the bridge descriptor from the bridge authority returned a
1725 * "not found". Fall back to trying a direct fetch. */
1726 void
1727 retry_bridge_descriptor_fetch_directly(const char *digest)
1729 bridge_info_t *bridge = find_bridge_by_digest(digest);
1730 if (!bridge)
1731 return; /* not found? oh well. */
1733 launch_direct_bridge_descriptor_fetch(bridge);
1736 /** For each bridge in our list for which we don't currently have a
1737 * descriptor, fetch a new copy of its descriptor -- either directly
1738 * from the bridge or via a bridge authority. */
1739 void
1740 fetch_bridge_descriptors(const or_options_t *options, time_t now)
1742 int num_bridge_auths = get_n_authorities(BRIDGE_DIRINFO);
1743 int ask_bridge_directly;
1744 int can_use_bridge_authority;
1746 if (!bridge_list)
1747 return;
1749 /* If we still have unconfigured managed proxies, don't go and
1750 connect to a bridge. */
1751 if (pt_proxies_configuration_pending())
1752 return;
1754 SMARTLIST_FOREACH_BEGIN(bridge_list, bridge_info_t *, bridge)
1756 if (!download_status_is_ready(&bridge->fetch_status, now,
1757 IMPOSSIBLE_TO_DOWNLOAD))
1758 continue; /* don't bother, no need to retry yet */
1759 if (routerset_contains_bridge(options->ExcludeNodes, bridge)) {
1760 download_status_mark_impossible(&bridge->fetch_status);
1761 log_warn(LD_APP, "Not using bridge at %s: it is in ExcludeNodes.",
1762 safe_str_client(fmt_and_decorate_addr(&bridge->addr)));
1763 continue;
1766 /* schedule another fetch as if this one will fail, in case it does */
1767 download_status_failed(&bridge->fetch_status, 0);
1769 can_use_bridge_authority = !tor_digest_is_zero(bridge->identity) &&
1770 num_bridge_auths;
1771 ask_bridge_directly = !can_use_bridge_authority ||
1772 !options->UpdateBridgesFromAuthority;
1773 log_debug(LD_DIR, "ask_bridge_directly=%d (%d, %d, %d)",
1774 ask_bridge_directly, tor_digest_is_zero(bridge->identity),
1775 !options->UpdateBridgesFromAuthority, !num_bridge_auths);
1777 if (ask_bridge_directly &&
1778 !fascist_firewall_allows_address_or(&bridge->addr, bridge->port)) {
1779 log_notice(LD_DIR, "Bridge at '%s' isn't reachable by our "
1780 "firewall policy. %s.",
1781 fmt_addrport(&bridge->addr, bridge->port),
1782 can_use_bridge_authority ?
1783 "Asking bridge authority instead" : "Skipping");
1784 if (can_use_bridge_authority)
1785 ask_bridge_directly = 0;
1786 else
1787 continue;
1790 if (ask_bridge_directly) {
1791 /* we need to ask the bridge itself for its descriptor. */
1792 launch_direct_bridge_descriptor_fetch(bridge);
1793 } else {
1794 /* We have a digest and we want to ask an authority. We could
1795 * combine all the requests into one, but that may give more
1796 * hints to the bridge authority than we want to give. */
1797 char resource[10 + HEX_DIGEST_LEN];
1798 memcpy(resource, "fp/", 3);
1799 base16_encode(resource+3, HEX_DIGEST_LEN+1,
1800 bridge->identity, DIGEST_LEN);
1801 memcpy(resource+3+HEX_DIGEST_LEN, ".z", 3);
1802 log_info(LD_DIR, "Fetching bridge info '%s' from bridge authority.",
1803 resource);
1804 directory_get_from_dirserver(DIR_PURPOSE_FETCH_SERVERDESC,
1805 ROUTER_PURPOSE_BRIDGE, resource, 0);
1808 SMARTLIST_FOREACH_END(bridge);
1811 /** If our <b>bridge</b> is configured to be a different address than
1812 * the bridge gives in <b>node</b>, rewrite the routerinfo
1813 * we received to use the address we meant to use. Now we handle
1814 * multihomed bridges better.
1816 static void
1817 rewrite_node_address_for_bridge(const bridge_info_t *bridge, node_t *node)
1819 /* XXXX move this function. */
1820 /* XXXX overridden addresses should really live in the node_t, so that the
1821 * routerinfo_t and the microdesc_t can be immutable. But we can only
1822 * do that safely if we know that no function that connects to an OR
1823 * does so through an address from any source other than node_get_addr().
1825 tor_addr_t addr;
1827 if (node->ri) {
1828 routerinfo_t *ri = node->ri;
1829 tor_addr_from_ipv4h(&addr, ri->addr);
1831 if ((!tor_addr_compare(&bridge->addr, &addr, CMP_EXACT) &&
1832 bridge->port == ri->or_port) ||
1833 (!tor_addr_compare(&bridge->addr, &ri->ipv6_addr, CMP_EXACT) &&
1834 bridge->port == ri->ipv6_orport)) {
1835 /* they match, so no need to do anything */
1836 } else {
1837 if (tor_addr_family(&bridge->addr) == AF_INET) {
1838 ri->addr = tor_addr_to_ipv4h(&bridge->addr);
1839 tor_free(ri->address);
1840 ri->address = tor_dup_ip(ri->addr);
1841 ri->or_port = bridge->port;
1842 log_info(LD_DIR,
1843 "Adjusted bridge routerinfo for '%s' to match configured "
1844 "address %s:%d.",
1845 ri->nickname, ri->address, ri->or_port);
1846 } else if (tor_addr_family(&bridge->addr) == AF_INET6) {
1847 tor_addr_copy(&ri->ipv6_addr, &bridge->addr);
1848 ri->ipv6_orport = bridge->port;
1849 log_info(LD_DIR,
1850 "Adjusted bridge routerinfo for '%s' to match configured "
1851 "address %s.",
1852 ri->nickname, fmt_addrport(&ri->ipv6_addr, ri->ipv6_orport));
1853 } else {
1854 log_err(LD_BUG, "Address family not supported: %d.",
1855 tor_addr_family(&bridge->addr));
1856 return;
1860 /* Mark which address to use based on which bridge_t we got. */
1861 node->ipv6_preferred = (tor_addr_family(&bridge->addr) == AF_INET6 &&
1862 !tor_addr_is_null(&node->ri->ipv6_addr));
1864 /* XXXipv6 we lack support for falling back to another address for
1865 the same relay, warn the user */
1866 if (!tor_addr_is_null(&ri->ipv6_addr)) {
1867 tor_addr_port_t ap;
1868 node_get_pref_orport(node, &ap);
1869 log_notice(LD_CONFIG,
1870 "Bridge '%s' has both an IPv4 and an IPv6 address. "
1871 "Will prefer using its %s address (%s).",
1872 ri->nickname,
1873 tor_addr_family(&ap.addr) == AF_INET6 ? "IPv6" : "IPv4",
1874 fmt_addrport(&ap.addr, ap.port));
1877 if (node->rs) {
1878 routerstatus_t *rs = node->rs;
1879 tor_addr_from_ipv4h(&addr, rs->addr);
1881 if (!tor_addr_compare(&bridge->addr, &addr, CMP_EXACT) &&
1882 bridge->port == rs->or_port) {
1883 /* they match, so no need to do anything */
1884 } else {
1885 rs->addr = tor_addr_to_ipv4h(&bridge->addr);
1886 rs->or_port = bridge->port;
1887 log_info(LD_DIR,
1888 "Adjusted bridge routerstatus for '%s' to match "
1889 "configured address %s.",
1890 rs->nickname, fmt_addrport(&bridge->addr, rs->or_port));
1895 /** We just learned a descriptor for a bridge. See if that
1896 * digest is in our entry guard list, and add it if not. */
1897 void
1898 learned_bridge_descriptor(routerinfo_t *ri, int from_cache)
1900 tor_assert(ri);
1901 tor_assert(ri->purpose == ROUTER_PURPOSE_BRIDGE);
1902 if (get_options()->UseBridges) {
1903 int first = !any_bridge_descriptors_known();
1904 bridge_info_t *bridge = get_configured_bridge_by_routerinfo(ri);
1905 time_t now = time(NULL);
1906 router_set_status(ri->cache_info.identity_digest, 1);
1908 if (bridge) { /* if we actually want to use this one */
1909 node_t *node;
1910 /* it's here; schedule its re-fetch for a long time from now. */
1911 if (!from_cache)
1912 download_status_reset(&bridge->fetch_status);
1914 node = node_get_mutable_by_id(ri->cache_info.identity_digest);
1915 tor_assert(node);
1916 rewrite_node_address_for_bridge(bridge, node);
1917 add_an_entry_guard(node, 1, 1, 0);
1919 log_notice(LD_DIR, "new bridge descriptor '%s' (%s): %s", ri->nickname,
1920 from_cache ? "cached" : "fresh", router_describe(ri));
1921 /* set entry->made_contact so if it goes down we don't drop it from
1922 * our entry node list */
1923 entry_guard_register_connect_status(ri->cache_info.identity_digest,
1924 1, 0, now);
1925 if (first)
1926 routerlist_retry_directory_downloads(now);
1931 /** Return 1 if any of our entry guards have descriptors that
1932 * are marked with purpose 'bridge' and are running. Else return 0.
1934 * We use this function to decide if we're ready to start building
1935 * circuits through our bridges, or if we need to wait until the
1936 * directory "server/authority" requests finish. */
1938 any_bridge_descriptors_known(void)
1940 tor_assert(get_options()->UseBridges);
1941 return choose_random_entry(NULL)!=NULL ? 1 : 0;
1944 /** Return 1 if there are any directory conns fetching bridge descriptors
1945 * that aren't marked for close. We use this to guess if we should tell
1946 * the controller that we have a problem. */
1948 any_pending_bridge_descriptor_fetches(void)
1950 smartlist_t *conns = get_connection_array();
1951 SMARTLIST_FOREACH_BEGIN(conns, connection_t *, conn) {
1952 if (conn->type == CONN_TYPE_DIR &&
1953 conn->purpose == DIR_PURPOSE_FETCH_SERVERDESC &&
1954 TO_DIR_CONN(conn)->router_purpose == ROUTER_PURPOSE_BRIDGE &&
1955 !conn->marked_for_close &&
1956 conn->linked &&
1957 conn->linked_conn && !conn->linked_conn->marked_for_close) {
1958 log_debug(LD_DIR, "found one: %s", conn->address);
1959 return 1;
1961 } SMARTLIST_FOREACH_END(conn);
1962 return 0;
1965 /** Return 1 if we have at least one descriptor for an entry guard
1966 * (bridge or member of EntryNodes) and all descriptors we know are
1967 * down. Else return 0. If <b>act</b> is 1, then mark the down guards
1968 * up; else just observe and report. */
1969 static int
1970 entries_retry_helper(const or_options_t *options, int act)
1972 const node_t *node;
1973 int any_known = 0;
1974 int any_running = 0;
1975 int need_bridges = options->UseBridges != 0;
1976 if (!entry_guards)
1977 entry_guards = smartlist_new();
1978 SMARTLIST_FOREACH_BEGIN(entry_guards, entry_guard_t *, e) {
1979 node = node_get_by_id(e->identity);
1980 if (node && node_has_descriptor(node) &&
1981 node_is_bridge(node) == need_bridges) {
1982 any_known = 1;
1983 if (node->is_running)
1984 any_running = 1; /* some entry is both known and running */
1985 else if (act) {
1986 /* Mark all current connections to this OR as unhealthy, since
1987 * otherwise there could be one that started 30 seconds
1988 * ago, and in 30 seconds it will time out, causing us to mark
1989 * the node down and undermine the retry attempt. We mark even
1990 * the established conns, since if the network just came back
1991 * we'll want to attach circuits to fresh conns. */
1992 connection_or_set_bad_connections(node->identity, 1);
1994 /* mark this entry node for retry */
1995 router_set_status(node->identity, 1);
1996 e->can_retry = 1;
1997 e->bad_since = 0;
2000 } SMARTLIST_FOREACH_END(e);
2001 log_debug(LD_DIR, "%d: any_known %d, any_running %d",
2002 act, any_known, any_running);
2003 return any_known && !any_running;
2006 /** Do we know any descriptors for our bridges / entrynodes, and are
2007 * all the ones we have descriptors for down? */
2009 entries_known_but_down(const or_options_t *options)
2011 tor_assert(entry_list_is_constrained(options));
2012 return entries_retry_helper(options, 0);
2015 /** Mark all down known bridges / entrynodes up. */
2016 void
2017 entries_retry_all(const or_options_t *options)
2019 tor_assert(entry_list_is_constrained(options));
2020 entries_retry_helper(options, 1);
2023 /** Return true if we've ever had a bridge running a Tor version that can't
2024 * provide microdescriptors to us. In that case fall back to asking for
2025 * full descriptors. Eventually all bridges will support microdescriptors
2026 * and we can take this check out; see bug 4013. */
2028 any_bridges_dont_support_microdescriptors(void)
2030 const node_t *node;
2031 static int ever_answered_yes = 0;
2032 if (!get_options()->UseBridges || !entry_guards)
2033 return 0;
2034 if (ever_answered_yes)
2035 return 1; /* if we ever answer 'yes', always answer 'yes' */
2036 SMARTLIST_FOREACH_BEGIN(entry_guards, entry_guard_t *, e) {
2037 node = node_get_by_id(e->identity);
2038 if (node && node->ri &&
2039 node_is_bridge(node) && node_is_a_configured_bridge(node) &&
2040 !tor_version_supports_microdescriptors(node->ri->platform)) {
2041 /* This is one of our current bridges, and we know enough about
2042 * it to know that it won't be able to answer our microdescriptor
2043 * questions. */
2044 ever_answered_yes = 1;
2045 return 1;
2047 } SMARTLIST_FOREACH_END(e);
2048 return 0;
2051 /** Release all storage held by the list of entry guards and related
2052 * memory structs. */
2053 void
2054 entry_guards_free_all(void)
2056 if (entry_guards) {
2057 SMARTLIST_FOREACH(entry_guards, entry_guard_t *, e,
2058 entry_guard_free(e));
2059 smartlist_free(entry_guards);
2060 entry_guards = NULL;
2062 clear_bridge_list();
2063 smartlist_free(bridge_list);
2064 bridge_list = NULL;
2065 circuit_build_times_free_timeouts(&circ_times);