copy changelog to releasenotes
[tor.git] / src / or / routerlist.c
blob45b3838792e5b04e1b8361cca14af37ffd15aa48
1 /* Copyright (c) 2001 Matej Pfajfar.
2 * Copyright (c) 2001-2004, Roger Dingledine.
3 * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
4 * Copyright (c) 2007-2016, The Tor Project, Inc. */
5 /* See LICENSE for licensing information */
7 /**
8 * \file routerlist.c
9 * \brief Code to
10 * maintain and access the global list of routerinfos for known
11 * servers.
13 * A "routerinfo_t" object represents a single self-signed router
14 * descriptor, as generated by a Tor relay in order to tell the rest of
15 * the world about its keys, address, and capabilities. An
16 * "extrainfo_t" object represents an adjunct "extra-info" object,
17 * certified by a corresponding router descriptor, reporting more
18 * information about the relay that nearly all users will not need.
20 * Most users will not use router descriptors for most relays. Instead,
21 * they use the information in microdescriptors and in the consensus
22 * networkstatus.
24 * Right now, routerinfo_t objects are used in these ways:
25 * <ul>
26 * <li>By clients, in order to learn about bridge keys and capabilities.
27 * (Bridges aren't listed in the consensus networkstatus, so they
28 * can't have microdescriptors.)
29 * <li>By relays, since relays want more information about other relays
30 * than they can learn from microdescriptors. (TODO: Is this still true?)
31 * <li>By authorities, which receive them and use them to generate the
32 * consensus and the microdescriptors.
33 * <li>By all directory caches, which download them in case somebody
34 * else wants them.
35 * </ul>
37 * Routerinfos are mostly created by parsing them from a string, in
38 * routerparse.c. We store them to disk on receiving them, and
39 * periodically discard the ones we don't need. On restarting, we
40 * re-read them from disk. (This also applies to extrainfo documents, if
41 * we are configured to fetch them.)
43 * In order to keep our list of routerinfos up-to-date, we periodically
44 * check whether there are any listed in the latest consensus (or in the
45 * votes from other authorities, if we are an authority) that we don't
46 * have. (This also applies to extrainfo documents, if we are
47 * configured to fetch them.)
49 * Almost nothing in Tor should use a routerinfo_t to refer directly to
50 * a relay; instead, almost everything should use node_t (implemented in
51 * nodelist.c), which provides a common interface to routerinfo_t,
52 * routerstatus_t, and microdescriptor_t.
54 * <br>
56 * This module also has some of the functions used for choosing random
57 * nodes according to different rules and weights. Historically, they
58 * were all in this module. Now, they are spread across this module,
59 * nodelist.c, and networkstatus.c. (TODO: Fix that.)
61 * <br>
63 * (For historical reasons) this module also contains code for handling
64 * the list of fallback directories, the list of directory authorities,
65 * and the list of authority certificates.
67 * For the directory authorities, we have a list containing the public
68 * identity key, and contact points, for each authority. The
69 * authorities receive descriptors from relays, and publish consensuses,
70 * descriptors, and microdescriptors. This list is pre-configured.
72 * Fallback directories are well-known, stable, but untrusted directory
73 * caches that clients which have not yet bootstrapped can use to get
74 * their first networkstatus consensus, in order to find out where the
75 * Tor network really is. This list is pre-configured in
76 * fallback_dirs.inc. Every authority also serves as a fallback.
78 * Both fallback directories and directory authorities are are
79 * represented by a dir_server_t.
81 * Authority certificates are signed with authority identity keys; they
82 * are used to authenticate shorter-term authority signing keys. We
83 * fetch them when we find a consensus or a vote that has been signed
84 * with a signing key we don't recognize. We cache them on disk and
85 * load them on startup. Authority operators generate them with the
86 * "tor-gencert" utility.
88 * TODO: Authority certificates should be a separate module.
90 * TODO: dir_server_t stuff should be in a separate module.
91 **/
93 #define ROUTERLIST_PRIVATE
94 #include "or.h"
95 #include "backtrace.h"
96 #include "bridges.h"
97 #include "crypto_ed25519.h"
98 #include "circuitstats.h"
99 #include "config.h"
100 #include "connection.h"
101 #include "control.h"
102 #include "directory.h"
103 #include "dirserv.h"
104 #include "dirvote.h"
105 #include "entrynodes.h"
106 #include "fp_pair.h"
107 #include "geoip.h"
108 #include "hibernate.h"
109 #include "main.h"
110 #include "microdesc.h"
111 #include "networkstatus.h"
112 #include "nodelist.h"
113 #include "policies.h"
114 #include "reasons.h"
115 #include "rendcommon.h"
116 #include "rendservice.h"
117 #include "rephist.h"
118 #include "router.h"
119 #include "routerlist.h"
120 #include "routerparse.h"
121 #include "routerset.h"
122 #include "sandbox.h"
123 #include "torcert.h"
125 // #define DEBUG_ROUTERLIST
127 /****************************************************************************/
129 /* Typed wrappers for different digestmap types; used to avoid type
130 * confusion. */
132 DECLARE_TYPED_DIGESTMAP_FNS(sdmap_, digest_sd_map_t, signed_descriptor_t)
133 DECLARE_TYPED_DIGESTMAP_FNS(rimap_, digest_ri_map_t, routerinfo_t)
134 DECLARE_TYPED_DIGESTMAP_FNS(eimap_, digest_ei_map_t, extrainfo_t)
135 DECLARE_TYPED_DIGESTMAP_FNS(dsmap_, digest_ds_map_t, download_status_t)
136 #define SDMAP_FOREACH(map, keyvar, valvar) \
137 DIGESTMAP_FOREACH(sdmap_to_digestmap(map), keyvar, signed_descriptor_t *, \
138 valvar)
139 #define RIMAP_FOREACH(map, keyvar, valvar) \
140 DIGESTMAP_FOREACH(rimap_to_digestmap(map), keyvar, routerinfo_t *, valvar)
141 #define EIMAP_FOREACH(map, keyvar, valvar) \
142 DIGESTMAP_FOREACH(eimap_to_digestmap(map), keyvar, extrainfo_t *, valvar)
143 #define DSMAP_FOREACH(map, keyvar, valvar) \
144 DIGESTMAP_FOREACH(dsmap_to_digestmap(map), keyvar, download_status_t *, \
145 valvar)
147 /* Forward declaration for cert_list_t */
148 typedef struct cert_list_t cert_list_t;
150 /* static function prototypes */
151 static int compute_weighted_bandwidths(const smartlist_t *sl,
152 bandwidth_weight_rule_t rule,
153 double **bandwidths_out);
154 static const routerstatus_t *router_pick_trusteddirserver_impl(
155 const smartlist_t *sourcelist, dirinfo_type_t auth,
156 int flags, int *n_busy_out);
157 static const routerstatus_t *router_pick_dirserver_generic(
158 smartlist_t *sourcelist,
159 dirinfo_type_t type, int flags);
160 static void mark_all_dirservers_up(smartlist_t *server_list);
161 static void dir_server_free(dir_server_t *ds);
162 static int signed_desc_digest_is_recognized(signed_descriptor_t *desc);
163 static const char *signed_descriptor_get_body_impl(
164 const signed_descriptor_t *desc,
165 int with_annotations);
166 static void list_pending_downloads(digestmap_t *result,
167 digest256map_t *result256,
168 int purpose, const char *prefix);
169 static void list_pending_fpsk_downloads(fp_pair_map_t *result);
170 static void launch_dummy_descriptor_download_as_needed(time_t now,
171 const or_options_t *options);
172 static void download_status_reset_by_sk_in_cl(cert_list_t *cl,
173 const char *digest);
174 static int download_status_is_ready_by_sk_in_cl(cert_list_t *cl,
175 const char *digest,
176 time_t now, int max_failures);
178 /****************************************************************************/
180 /** Global list of a dir_server_t object for each directory
181 * authority. */
182 static smartlist_t *trusted_dir_servers = NULL;
183 /** Global list of dir_server_t objects for all directory authorities
184 * and all fallback directory servers. */
185 static smartlist_t *fallback_dir_servers = NULL;
187 /** List of certificates for a single authority, and download status for
188 * latest certificate.
190 struct cert_list_t {
192 * The keys of download status map are cert->signing_key_digest for pending
193 * downloads by (identity digest/signing key digest) pair; functions such
194 * as authority_cert_get_by_digest() already assume these are unique.
196 struct digest_ds_map_t *dl_status_map;
197 /* There is also a dlstatus for the download by identity key only */
198 download_status_t dl_status_by_id;
199 smartlist_t *certs;
201 /** Map from v3 identity key digest to cert_list_t. */
202 static digestmap_t *trusted_dir_certs = NULL;
203 /** True iff any key certificate in at least one member of
204 * <b>trusted_dir_certs</b> has changed since we last flushed the
205 * certificates to disk. */
206 static int trusted_dir_servers_certs_changed = 0;
208 /** Global list of all of the routers that we know about. */
209 static routerlist_t *routerlist = NULL;
211 /** List of strings for nicknames we've already warned about and that are
212 * still unknown / unavailable. */
213 static smartlist_t *warned_nicknames = NULL;
215 /** The last time we tried to download any routerdesc, or 0 for "never". We
216 * use this to rate-limit download attempts when the number of routerdescs to
217 * download is low. */
218 static time_t last_descriptor_download_attempted = 0;
220 /** Return the number of directory authorities whose type matches some bit set
221 * in <b>type</b> */
223 get_n_authorities(dirinfo_type_t type)
225 int n = 0;
226 if (!trusted_dir_servers)
227 return 0;
228 SMARTLIST_FOREACH(trusted_dir_servers, dir_server_t *, ds,
229 if (ds->type & type)
230 ++n);
231 return n;
234 /** Initialise schedule, want_authority, and increment on in the download
235 * status dlstatus, then call download_status_reset() on it.
236 * It is safe to call this function or download_status_reset() multiple times
237 * on a new dlstatus. But it should *not* be called after a dlstatus has been
238 * used to count download attempts or failures. */
239 static void
240 download_status_cert_init(download_status_t *dlstatus)
242 dlstatus->schedule = DL_SCHED_CONSENSUS;
243 dlstatus->want_authority = DL_WANT_ANY_DIRSERVER;
244 dlstatus->increment_on = DL_SCHED_INCREMENT_FAILURE;
245 dlstatus->backoff = DL_SCHED_RANDOM_EXPONENTIAL;
246 dlstatus->last_backoff_position = 0;
247 dlstatus->last_delay_used = 0;
249 /* Use the new schedule to set next_attempt_at */
250 download_status_reset(dlstatus);
253 /** Reset the download status of a specified element in a dsmap */
254 static void
255 download_status_reset_by_sk_in_cl(cert_list_t *cl, const char *digest)
257 download_status_t *dlstatus = NULL;
259 tor_assert(cl);
260 tor_assert(digest);
262 /* Make sure we have a dsmap */
263 if (!(cl->dl_status_map)) {
264 cl->dl_status_map = dsmap_new();
266 /* Look for a download_status_t in the map with this digest */
267 dlstatus = dsmap_get(cl->dl_status_map, digest);
268 /* Got one? */
269 if (!dlstatus) {
270 /* Insert before we reset */
271 dlstatus = tor_malloc_zero(sizeof(*dlstatus));
272 dsmap_set(cl->dl_status_map, digest, dlstatus);
273 download_status_cert_init(dlstatus);
275 tor_assert(dlstatus);
276 /* Go ahead and reset it */
277 download_status_reset(dlstatus);
281 * Return true if the download for this signing key digest in cl is ready
282 * to be re-attempted.
284 static int
285 download_status_is_ready_by_sk_in_cl(cert_list_t *cl,
286 const char *digest,
287 time_t now, int max_failures)
289 int rv = 0;
290 download_status_t *dlstatus = NULL;
292 tor_assert(cl);
293 tor_assert(digest);
295 /* Make sure we have a dsmap */
296 if (!(cl->dl_status_map)) {
297 cl->dl_status_map = dsmap_new();
299 /* Look for a download_status_t in the map with this digest */
300 dlstatus = dsmap_get(cl->dl_status_map, digest);
301 /* Got one? */
302 if (dlstatus) {
303 /* Use download_status_is_ready() */
304 rv = download_status_is_ready(dlstatus, now, max_failures);
305 } else {
307 * If we don't know anything about it, return 1, since we haven't
308 * tried this one before. We need to create a new entry here,
309 * too.
311 dlstatus = tor_malloc_zero(sizeof(*dlstatus));
312 download_status_cert_init(dlstatus);
313 dsmap_set(cl->dl_status_map, digest, dlstatus);
314 rv = 1;
317 return rv;
320 /** Helper: Return the cert_list_t for an authority whose authority ID is
321 * <b>id_digest</b>, allocating a new list if necessary. */
322 static cert_list_t *
323 get_cert_list(const char *id_digest)
325 cert_list_t *cl;
326 if (!trusted_dir_certs)
327 trusted_dir_certs = digestmap_new();
328 cl = digestmap_get(trusted_dir_certs, id_digest);
329 if (!cl) {
330 cl = tor_malloc_zero(sizeof(cert_list_t));
331 download_status_cert_init(&cl->dl_status_by_id);
332 cl->certs = smartlist_new();
333 cl->dl_status_map = dsmap_new();
334 digestmap_set(trusted_dir_certs, id_digest, cl);
336 return cl;
339 /** Return a list of authority ID digests with potentially enumerable lists
340 * of download_status_t objects; used by controller GETINFO queries.
343 MOCK_IMPL(smartlist_t *,
344 list_authority_ids_with_downloads, (void))
346 smartlist_t *ids = smartlist_new();
347 digestmap_iter_t *i;
348 const char *digest;
349 char *tmp;
350 void *cl;
352 if (trusted_dir_certs) {
353 for (i = digestmap_iter_init(trusted_dir_certs);
354 !(digestmap_iter_done(i));
355 i = digestmap_iter_next(trusted_dir_certs, i)) {
357 * We always have at least dl_status_by_id to query, so no need to
358 * probe deeper than the existence of a cert_list_t.
360 digestmap_iter_get(i, &digest, &cl);
361 tmp = tor_malloc(DIGEST_LEN);
362 memcpy(tmp, digest, DIGEST_LEN);
363 smartlist_add(ids, tmp);
366 /* else definitely no downlaods going since nothing even has a cert list */
368 return ids;
371 /** Given an authority ID digest, return a pointer to the default download
372 * status, or NULL if there is no such entry in trusted_dir_certs */
374 MOCK_IMPL(download_status_t *,
375 id_only_download_status_for_authority_id, (const char *digest))
377 download_status_t *dl = NULL;
378 cert_list_t *cl;
380 if (trusted_dir_certs) {
381 cl = digestmap_get(trusted_dir_certs, digest);
382 if (cl) {
383 dl = &(cl->dl_status_by_id);
387 return dl;
390 /** Given an authority ID digest, return a smartlist of signing key digests
391 * for which download_status_t is potentially queryable, or NULL if no such
392 * authority ID digest is known. */
394 MOCK_IMPL(smartlist_t *,
395 list_sk_digests_for_authority_id, (const char *digest))
397 smartlist_t *sks = NULL;
398 cert_list_t *cl;
399 dsmap_iter_t *i;
400 const char *sk_digest;
401 char *tmp;
402 download_status_t *dl;
404 if (trusted_dir_certs) {
405 cl = digestmap_get(trusted_dir_certs, digest);
406 if (cl) {
407 sks = smartlist_new();
408 if (cl->dl_status_map) {
409 for (i = dsmap_iter_init(cl->dl_status_map);
410 !(dsmap_iter_done(i));
411 i = dsmap_iter_next(cl->dl_status_map, i)) {
412 /* Pull the digest out and add it to the list */
413 dsmap_iter_get(i, &sk_digest, &dl);
414 tmp = tor_malloc(DIGEST_LEN);
415 memcpy(tmp, sk_digest, DIGEST_LEN);
416 smartlist_add(sks, tmp);
422 return sks;
425 /** Given an authority ID digest and a signing key digest, return the
426 * download_status_t or NULL if none exists. */
428 MOCK_IMPL(download_status_t *,
429 download_status_for_authority_id_and_sk,
430 (const char *id_digest, const char *sk_digest))
432 download_status_t *dl = NULL;
433 cert_list_t *cl = NULL;
435 if (trusted_dir_certs) {
436 cl = digestmap_get(trusted_dir_certs, id_digest);
437 if (cl && cl->dl_status_map) {
438 dl = dsmap_get(cl->dl_status_map, sk_digest);
442 return dl;
445 /** Release all space held by a cert_list_t */
446 static void
447 cert_list_free(cert_list_t *cl)
449 if (!cl)
450 return;
452 SMARTLIST_FOREACH(cl->certs, authority_cert_t *, cert,
453 authority_cert_free(cert));
454 smartlist_free(cl->certs);
455 dsmap_free(cl->dl_status_map, tor_free_);
456 tor_free(cl);
459 /** Wrapper for cert_list_free so we can pass it to digestmap_free */
460 static void
461 cert_list_free_(void *cl)
463 cert_list_free(cl);
466 /** Reload the cached v3 key certificates from the cached-certs file in
467 * the data directory. Return 0 on success, -1 on failure. */
469 trusted_dirs_reload_certs(void)
471 char *filename;
472 char *contents;
473 int r;
475 filename = get_datadir_fname("cached-certs");
476 contents = read_file_to_str(filename, RFTS_IGNORE_MISSING, NULL);
477 tor_free(filename);
478 if (!contents)
479 return 0;
480 r = trusted_dirs_load_certs_from_string(
481 contents,
482 TRUSTED_DIRS_CERTS_SRC_FROM_STORE, 1, NULL);
483 tor_free(contents);
484 return r;
487 /** Helper: return true iff we already have loaded the exact cert
488 * <b>cert</b>. */
489 static inline int
490 already_have_cert(authority_cert_t *cert)
492 cert_list_t *cl = get_cert_list(cert->cache_info.identity_digest);
494 SMARTLIST_FOREACH(cl->certs, authority_cert_t *, c,
496 if (tor_memeq(c->cache_info.signed_descriptor_digest,
497 cert->cache_info.signed_descriptor_digest,
498 DIGEST_LEN))
499 return 1;
501 return 0;
504 /** Load a bunch of new key certificates from the string <b>contents</b>. If
505 * <b>source</b> is TRUSTED_DIRS_CERTS_SRC_FROM_STORE, the certificates are
506 * from the cache, and we don't need to flush them to disk. If we are a
507 * dirauth loading our own cert, source is TRUSTED_DIRS_CERTS_SRC_SELF.
508 * Otherwise, source is download type: TRUSTED_DIRS_CERTS_SRC_DL_BY_ID_DIGEST
509 * or TRUSTED_DIRS_CERTS_SRC_DL_BY_ID_SK_DIGEST. If <b>flush</b> is true, we
510 * need to flush any changed certificates to disk now. Return 0 on success,
511 * -1 if any certs fail to parse.
513 * If source_dir is non-NULL, it's the identity digest for a directory that
514 * we've just successfully retrieved certificates from, so try it first to
515 * fetch any missing certificates.
518 trusted_dirs_load_certs_from_string(const char *contents, int source,
519 int flush, const char *source_dir)
521 dir_server_t *ds;
522 const char *s, *eos;
523 int failure_code = 0;
524 int from_store = (source == TRUSTED_DIRS_CERTS_SRC_FROM_STORE);
525 int added_trusted_cert = 0;
527 for (s = contents; *s; s = eos) {
528 authority_cert_t *cert = authority_cert_parse_from_string(s, &eos);
529 cert_list_t *cl;
530 if (!cert) {
531 failure_code = -1;
532 break;
534 ds = trusteddirserver_get_by_v3_auth_digest(
535 cert->cache_info.identity_digest);
536 log_debug(LD_DIR, "Parsed certificate for %s",
537 ds ? ds->nickname : "unknown authority");
539 if (already_have_cert(cert)) {
540 /* we already have this one. continue. */
541 log_info(LD_DIR, "Skipping %s certificate for %s that we "
542 "already have.",
543 from_store ? "cached" : "downloaded",
544 ds ? ds->nickname : "an old or new authority");
547 * A duplicate on download should be treated as a failure, so we call
548 * authority_cert_dl_failed() to reset the download status to make sure
549 * we can't try again. Since we've implemented the fp-sk mechanism
550 * to download certs by signing key, this should be much rarer than it
551 * was and is perhaps cause for concern.
553 if (!from_store) {
554 if (authdir_mode(get_options())) {
555 log_warn(LD_DIR,
556 "Got a certificate for %s, but we already have it. "
557 "Maybe they haven't updated it. Waiting for a while.",
558 ds ? ds->nickname : "an old or new authority");
559 } else {
560 log_info(LD_DIR,
561 "Got a certificate for %s, but we already have it. "
562 "Maybe they haven't updated it. Waiting for a while.",
563 ds ? ds->nickname : "an old or new authority");
567 * This is where we care about the source; authority_cert_dl_failed()
568 * needs to know whether the download was by fp or (fp,sk) pair to
569 * twiddle the right bit in the download map.
571 if (source == TRUSTED_DIRS_CERTS_SRC_DL_BY_ID_DIGEST) {
572 authority_cert_dl_failed(cert->cache_info.identity_digest,
573 NULL, 404);
574 } else if (source == TRUSTED_DIRS_CERTS_SRC_DL_BY_ID_SK_DIGEST) {
575 authority_cert_dl_failed(cert->cache_info.identity_digest,
576 cert->signing_key_digest, 404);
580 authority_cert_free(cert);
581 continue;
584 if (ds) {
585 added_trusted_cert = 1;
586 log_info(LD_DIR, "Adding %s certificate for directory authority %s with "
587 "signing key %s", from_store ? "cached" : "downloaded",
588 ds->nickname, hex_str(cert->signing_key_digest,DIGEST_LEN));
589 } else {
590 int adding = we_want_to_fetch_unknown_auth_certs(get_options());
591 log_info(LD_DIR, "%s %s certificate for unrecognized directory "
592 "authority with signing key %s",
593 adding ? "Adding" : "Not adding",
594 from_store ? "cached" : "downloaded",
595 hex_str(cert->signing_key_digest,DIGEST_LEN));
596 if (!adding) {
597 authority_cert_free(cert);
598 continue;
602 cl = get_cert_list(cert->cache_info.identity_digest);
603 smartlist_add(cl->certs, cert);
604 if (ds && cert->cache_info.published_on > ds->addr_current_at) {
605 /* Check to see whether we should update our view of the authority's
606 * address. */
607 if (cert->addr && cert->dir_port &&
608 (ds->addr != cert->addr ||
609 ds->dir_port != cert->dir_port)) {
610 char *a = tor_dup_ip(cert->addr);
611 log_notice(LD_DIR, "Updating address for directory authority %s "
612 "from %s:%d to %s:%d based on certificate.",
613 ds->nickname, ds->address, (int)ds->dir_port,
614 a, cert->dir_port);
615 tor_free(a);
616 ds->addr = cert->addr;
617 ds->dir_port = cert->dir_port;
619 ds->addr_current_at = cert->cache_info.published_on;
622 if (!from_store)
623 trusted_dir_servers_certs_changed = 1;
626 if (flush)
627 trusted_dirs_flush_certs_to_disk();
629 /* call this even if failure_code is <0, since some certs might have
630 * succeeded, but only pass source_dir if there were no failures,
631 * and at least one more authority certificate was added to the store.
632 * This avoids retrying a directory that's serving bad or entirely duplicate
633 * certificates. */
634 if (failure_code == 0 && added_trusted_cert) {
635 networkstatus_note_certs_arrived(source_dir);
636 } else {
637 networkstatus_note_certs_arrived(NULL);
640 return failure_code;
643 /** Save all v3 key certificates to the cached-certs file. */
644 void
645 trusted_dirs_flush_certs_to_disk(void)
647 char *filename;
648 smartlist_t *chunks;
650 if (!trusted_dir_servers_certs_changed || !trusted_dir_certs)
651 return;
653 chunks = smartlist_new();
654 DIGESTMAP_FOREACH(trusted_dir_certs, key, cert_list_t *, cl) {
655 SMARTLIST_FOREACH(cl->certs, authority_cert_t *, cert,
657 sized_chunk_t *c = tor_malloc(sizeof(sized_chunk_t));
658 c->bytes = cert->cache_info.signed_descriptor_body;
659 c->len = cert->cache_info.signed_descriptor_len;
660 smartlist_add(chunks, c);
662 } DIGESTMAP_FOREACH_END;
664 filename = get_datadir_fname("cached-certs");
665 if (write_chunks_to_file(filename, chunks, 0, 0)) {
666 log_warn(LD_FS, "Error writing certificates to disk.");
668 tor_free(filename);
669 SMARTLIST_FOREACH(chunks, sized_chunk_t *, c, tor_free(c));
670 smartlist_free(chunks);
672 trusted_dir_servers_certs_changed = 0;
675 static int
676 compare_certs_by_pubdates(const void **_a, const void **_b)
678 const authority_cert_t *cert1 = *_a, *cert2=*_b;
680 if (cert1->cache_info.published_on < cert2->cache_info.published_on)
681 return -1;
682 else if (cert1->cache_info.published_on > cert2->cache_info.published_on)
683 return 1;
684 else
685 return 0;
688 /** Remove all expired v3 authority certificates that have been superseded for
689 * more than 48 hours or, if not expired, that were published more than 7 days
690 * before being superseded. (If the most recent cert was published more than 48
691 * hours ago, then we aren't going to get any consensuses signed with older
692 * keys.) */
693 static void
694 trusted_dirs_remove_old_certs(void)
696 time_t now = time(NULL);
697 #define DEAD_CERT_LIFETIME (2*24*60*60)
698 #define SUPERSEDED_CERT_LIFETIME (2*24*60*60)
699 if (!trusted_dir_certs)
700 return;
702 DIGESTMAP_FOREACH(trusted_dir_certs, key, cert_list_t *, cl) {
703 /* Sort the list from first-published to last-published */
704 smartlist_sort(cl->certs, compare_certs_by_pubdates);
706 SMARTLIST_FOREACH_BEGIN(cl->certs, authority_cert_t *, cert) {
707 if (cert_sl_idx == smartlist_len(cl->certs) - 1) {
708 /* This is the most recently published cert. Keep it. */
709 continue;
711 authority_cert_t *next_cert = smartlist_get(cl->certs, cert_sl_idx+1);
712 const time_t next_cert_published = next_cert->cache_info.published_on;
713 if (next_cert_published > now) {
714 /* All later certs are published in the future. Keep everything
715 * we didn't discard. */
716 break;
718 int should_remove = 0;
719 if (cert->expires + DEAD_CERT_LIFETIME < now) {
720 /* Certificate has been expired for at least DEAD_CERT_LIFETIME.
721 * Remove it. */
722 should_remove = 1;
723 } else if (next_cert_published + SUPERSEDED_CERT_LIFETIME < now) {
724 /* Certificate has been superseded for OLD_CERT_LIFETIME.
725 * Remove it.
727 should_remove = 1;
729 if (should_remove) {
730 SMARTLIST_DEL_CURRENT_KEEPORDER(cl->certs, cert);
731 authority_cert_free(cert);
732 trusted_dir_servers_certs_changed = 1;
734 } SMARTLIST_FOREACH_END(cert);
736 } DIGESTMAP_FOREACH_END;
737 #undef DEAD_CERT_LIFETIME
738 #undef OLD_CERT_LIFETIME
740 trusted_dirs_flush_certs_to_disk();
743 /** Return the newest v3 authority certificate whose v3 authority identity key
744 * has digest <b>id_digest</b>. Return NULL if no such authority is known,
745 * or it has no certificate. */
746 authority_cert_t *
747 authority_cert_get_newest_by_id(const char *id_digest)
749 cert_list_t *cl;
750 authority_cert_t *best = NULL;
751 if (!trusted_dir_certs ||
752 !(cl = digestmap_get(trusted_dir_certs, id_digest)))
753 return NULL;
755 SMARTLIST_FOREACH(cl->certs, authority_cert_t *, cert,
757 if (!best || cert->cache_info.published_on > best->cache_info.published_on)
758 best = cert;
760 return best;
763 /** Return the newest v3 authority certificate whose directory signing key has
764 * digest <b>sk_digest</b>. Return NULL if no such certificate is known.
766 authority_cert_t *
767 authority_cert_get_by_sk_digest(const char *sk_digest)
769 authority_cert_t *c;
770 if (!trusted_dir_certs)
771 return NULL;
773 if ((c = get_my_v3_authority_cert()) &&
774 tor_memeq(c->signing_key_digest, sk_digest, DIGEST_LEN))
775 return c;
776 if ((c = get_my_v3_legacy_cert()) &&
777 tor_memeq(c->signing_key_digest, sk_digest, DIGEST_LEN))
778 return c;
780 DIGESTMAP_FOREACH(trusted_dir_certs, key, cert_list_t *, cl) {
781 SMARTLIST_FOREACH(cl->certs, authority_cert_t *, cert,
783 if (tor_memeq(cert->signing_key_digest, sk_digest, DIGEST_LEN))
784 return cert;
786 } DIGESTMAP_FOREACH_END;
787 return NULL;
790 /** Return the v3 authority certificate with signing key matching
791 * <b>sk_digest</b>, for the authority with identity digest <b>id_digest</b>.
792 * Return NULL if no such authority is known. */
793 authority_cert_t *
794 authority_cert_get_by_digests(const char *id_digest,
795 const char *sk_digest)
797 cert_list_t *cl;
798 if (!trusted_dir_certs ||
799 !(cl = digestmap_get(trusted_dir_certs, id_digest)))
800 return NULL;
801 SMARTLIST_FOREACH(cl->certs, authority_cert_t *, cert,
802 if (tor_memeq(cert->signing_key_digest, sk_digest, DIGEST_LEN))
803 return cert; );
805 return NULL;
808 /** Add every known authority_cert_t to <b>certs_out</b>. */
809 void
810 authority_cert_get_all(smartlist_t *certs_out)
812 tor_assert(certs_out);
813 if (!trusted_dir_certs)
814 return;
816 DIGESTMAP_FOREACH(trusted_dir_certs, key, cert_list_t *, cl) {
817 SMARTLIST_FOREACH(cl->certs, authority_cert_t *, c,
818 smartlist_add(certs_out, c));
819 } DIGESTMAP_FOREACH_END;
822 /** Called when an attempt to download a certificate with the authority with
823 * ID <b>id_digest</b> and, if not NULL, signed with key signing_key_digest
824 * fails with HTTP response code <b>status</b>: remember the failure, so we
825 * don't try again immediately. */
826 void
827 authority_cert_dl_failed(const char *id_digest,
828 const char *signing_key_digest, int status)
830 cert_list_t *cl;
831 download_status_t *dlstatus = NULL;
832 char id_digest_str[2*DIGEST_LEN+1];
833 char sk_digest_str[2*DIGEST_LEN+1];
835 if (!trusted_dir_certs ||
836 !(cl = digestmap_get(trusted_dir_certs, id_digest)))
837 return;
840 * Are we noting a failed download of the latest cert for the id digest,
841 * or of a download by (id, signing key) digest pair?
843 if (!signing_key_digest) {
844 /* Just by id digest */
845 download_status_failed(&cl->dl_status_by_id, status);
846 } else {
847 /* Reset by (id, signing key) digest pair
849 * Look for a download_status_t in the map with this digest
851 dlstatus = dsmap_get(cl->dl_status_map, signing_key_digest);
852 /* Got one? */
853 if (dlstatus) {
854 download_status_failed(dlstatus, status);
855 } else {
857 * Do this rather than hex_str(), since hex_str clobbers
858 * old results and we call twice in the param list.
860 base16_encode(id_digest_str, sizeof(id_digest_str),
861 id_digest, DIGEST_LEN);
862 base16_encode(sk_digest_str, sizeof(sk_digest_str),
863 signing_key_digest, DIGEST_LEN);
864 log_warn(LD_BUG,
865 "Got failure for cert fetch with (fp,sk) = (%s,%s), with "
866 "status %d, but knew nothing about the download.",
867 id_digest_str, sk_digest_str, status);
872 static const char *BAD_SIGNING_KEYS[] = {
873 "09CD84F751FD6E955E0F8ADB497D5401470D697E", // Expires 2015-01-11 16:26:31
874 "0E7E9C07F0969D0468AD741E172A6109DC289F3C", // Expires 2014-08-12 10:18:26
875 "57B85409891D3FB32137F642FDEDF8B7F8CDFDCD", // Expires 2015-02-11 17:19:09
876 "87326329007AF781F587AF5B594E540B2B6C7630", // Expires 2014-07-17 11:10:09
877 "98CC82342DE8D298CF99D3F1A396475901E0D38E", // Expires 2014-11-10 13:18:56
878 "9904B52336713A5ADCB13E4FB14DC919E0D45571", // Expires 2014-04-20 20:01:01
879 "9DCD8E3F1DD1597E2AD476BBA28A1A89F3095227", // Expires 2015-01-16 03:52:30
880 "A61682F34B9BB9694AC98491FE1ABBFE61923941", // Expires 2014-06-11 09:25:09
881 "B59F6E99C575113650C99F1C425BA7B20A8C071D", // Expires 2014-07-31 13:22:10
882 "D27178388FA75B96D37FA36E0B015227DDDBDA51", // Expires 2014-08-04 04:01:57
883 NULL,
886 /** Return true iff <b>cert</b> authenticates some atuhority signing key
887 * which, because of the old openssl heartbleed vulnerability, should
888 * never be trusted. */
890 authority_cert_is_blacklisted(const authority_cert_t *cert)
892 char hex_digest[HEX_DIGEST_LEN+1];
893 int i;
894 base16_encode(hex_digest, sizeof(hex_digest),
895 cert->signing_key_digest, sizeof(cert->signing_key_digest));
897 for (i = 0; BAD_SIGNING_KEYS[i]; ++i) {
898 if (!strcasecmp(hex_digest, BAD_SIGNING_KEYS[i])) {
899 return 1;
902 return 0;
905 /** Return true iff when we've been getting enough failures when trying to
906 * download the certificate with ID digest <b>id_digest</b> that we're willing
907 * to start bugging the user about it. */
909 authority_cert_dl_looks_uncertain(const char *id_digest)
911 #define N_AUTH_CERT_DL_FAILURES_TO_BUG_USER 2
912 cert_list_t *cl;
913 int n_failures;
914 if (!trusted_dir_certs ||
915 !(cl = digestmap_get(trusted_dir_certs, id_digest)))
916 return 0;
918 n_failures = download_status_get_n_failures(&cl->dl_status_by_id);
919 return n_failures >= N_AUTH_CERT_DL_FAILURES_TO_BUG_USER;
922 /* Fetch the authority certificates specified in resource.
923 * If we are a bridge client, and node is a configured bridge, fetch from node
924 * using dir_hint as the fingerprint. Otherwise, if rs is not NULL, fetch from
925 * rs. Otherwise, fetch from a random directory mirror. */
926 static void
927 authority_certs_fetch_resource_impl(const char *resource,
928 const char *dir_hint,
929 const node_t *node,
930 const routerstatus_t *rs)
932 const or_options_t *options = get_options();
933 int get_via_tor = purpose_needs_anonymity(DIR_PURPOSE_FETCH_CERTIFICATE, 0,
934 resource);
936 /* Make sure bridge clients never connect to anything but a bridge */
937 if (options->UseBridges) {
938 if (node && !node_is_a_configured_bridge(node)) {
939 /* If we're using bridges, and node is not a bridge, use a 3-hop path. */
940 get_via_tor = 1;
941 } else if (!node) {
942 /* If we're using bridges, and there's no node, use a 3-hop path. */
943 get_via_tor = 1;
947 const dir_indirection_t indirection = get_via_tor ? DIRIND_ANONYMOUS
948 : DIRIND_ONEHOP;
950 /* If we've just downloaded a consensus from a bridge, re-use that
951 * bridge */
952 if (options->UseBridges && node && node->ri && !get_via_tor) {
953 /* clients always make OR connections to bridges */
954 tor_addr_port_t or_ap;
955 /* we are willing to use a non-preferred address if we need to */
956 fascist_firewall_choose_address_node(node, FIREWALL_OR_CONNECTION, 0,
957 &or_ap);
958 directory_initiate_command(&or_ap.addr, or_ap.port,
959 NULL, 0, /*no dirport*/
960 dir_hint,
961 DIR_PURPOSE_FETCH_CERTIFICATE,
963 indirection,
964 resource, NULL, 0, 0);
965 return;
968 if (rs) {
969 /* If we've just downloaded a consensus from a directory, re-use that
970 * directory */
971 directory_initiate_command_routerstatus(rs,
972 DIR_PURPOSE_FETCH_CERTIFICATE,
973 0, indirection, resource, NULL,
974 0, 0, NULL);
975 return;
978 /* Otherwise, we want certs from a random fallback or directory
979 * mirror, because they will almost always succeed. */
980 directory_get_from_dirserver(DIR_PURPOSE_FETCH_CERTIFICATE, 0,
981 resource, PDS_RETRY_IF_NO_SERVERS,
982 DL_WANT_ANY_DIRSERVER);
985 /** Try to download any v3 authority certificates that we may be missing. If
986 * <b>status</b> is provided, try to get all the ones that were used to sign
987 * <b>status</b>. Additionally, try to have a non-expired certificate for
988 * every V3 authority in trusted_dir_servers. Don't fetch certificates we
989 * already have.
991 * If dir_hint is non-NULL, it's the identity digest for a directory that
992 * we've just successfully retrieved a consensus or certificates from, so try
993 * it first to fetch any missing certificates.
995 void
996 authority_certs_fetch_missing(networkstatus_t *status, time_t now,
997 const char *dir_hint)
1000 * The pending_id digestmap tracks pending certificate downloads by
1001 * identity digest; the pending_cert digestmap tracks pending downloads
1002 * by (identity digest, signing key digest) pairs.
1004 digestmap_t *pending_id;
1005 fp_pair_map_t *pending_cert;
1007 * The missing_id_digests smartlist will hold a list of id digests
1008 * we want to fetch the newest cert for; the missing_cert_digests
1009 * smartlist will hold a list of fp_pair_t with an identity and
1010 * signing key digest.
1012 smartlist_t *missing_cert_digests, *missing_id_digests;
1013 char *resource = NULL;
1014 cert_list_t *cl;
1015 const or_options_t *options = get_options();
1016 const int keep_unknown = we_want_to_fetch_unknown_auth_certs(options);
1017 fp_pair_t *fp_tmp = NULL;
1018 char id_digest_str[2*DIGEST_LEN+1];
1019 char sk_digest_str[2*DIGEST_LEN+1];
1021 if (should_delay_dir_fetches(options, NULL))
1022 return;
1024 pending_cert = fp_pair_map_new();
1025 pending_id = digestmap_new();
1026 missing_cert_digests = smartlist_new();
1027 missing_id_digests = smartlist_new();
1030 * First, we get the lists of already pending downloads so we don't
1031 * duplicate effort.
1033 list_pending_downloads(pending_id, NULL,
1034 DIR_PURPOSE_FETCH_CERTIFICATE, "fp/");
1035 list_pending_fpsk_downloads(pending_cert);
1038 * Now, we download any trusted authority certs we don't have by
1039 * identity digest only. This gets the latest cert for that authority.
1041 SMARTLIST_FOREACH_BEGIN(trusted_dir_servers, dir_server_t *, ds) {
1042 int found = 0;
1043 if (!(ds->type & V3_DIRINFO))
1044 continue;
1045 if (smartlist_contains_digest(missing_id_digests,
1046 ds->v3_identity_digest))
1047 continue;
1048 cl = get_cert_list(ds->v3_identity_digest);
1049 SMARTLIST_FOREACH_BEGIN(cl->certs, authority_cert_t *, cert) {
1050 if (now < cert->expires) {
1051 /* It's not expired, and we weren't looking for something to
1052 * verify a consensus with. Call it done. */
1053 download_status_reset(&(cl->dl_status_by_id));
1054 /* No sense trying to download it specifically by signing key hash */
1055 download_status_reset_by_sk_in_cl(cl, cert->signing_key_digest);
1056 found = 1;
1057 break;
1059 } SMARTLIST_FOREACH_END(cert);
1060 if (!found &&
1061 download_status_is_ready(&(cl->dl_status_by_id), now,
1062 options->TestingCertMaxDownloadTries) &&
1063 !digestmap_get(pending_id, ds->v3_identity_digest)) {
1064 log_info(LD_DIR,
1065 "No current certificate known for authority %s "
1066 "(ID digest %s); launching request.",
1067 ds->nickname, hex_str(ds->v3_identity_digest, DIGEST_LEN));
1068 smartlist_add(missing_id_digests, ds->v3_identity_digest);
1070 } SMARTLIST_FOREACH_END(ds);
1073 * Next, if we have a consensus, scan through it and look for anything
1074 * signed with a key from a cert we don't have. Those get downloaded
1075 * by (fp,sk) pair, but if we don't know any certs at all for the fp
1076 * (identity digest), and it's one of the trusted dir server certs
1077 * we started off above or a pending download in pending_id, don't
1078 * try to get it yet. Most likely, the one we'll get for that will
1079 * have the right signing key too, and we'd just be downloading
1080 * redundantly.
1082 if (status) {
1083 SMARTLIST_FOREACH_BEGIN(status->voters, networkstatus_voter_info_t *,
1084 voter) {
1085 if (!smartlist_len(voter->sigs))
1086 continue; /* This authority never signed this consensus, so don't
1087 * go looking for a cert with key digest 0000000000. */
1088 if (!keep_unknown &&
1089 !trusteddirserver_get_by_v3_auth_digest(voter->identity_digest))
1090 continue; /* We don't want unknown certs, and we don't know this
1091 * authority.*/
1094 * If we don't know *any* cert for this authority, and a download by ID
1095 * is pending or we added it to missing_id_digests above, skip this
1096 * one for now to avoid duplicate downloads.
1098 cl = get_cert_list(voter->identity_digest);
1099 if (smartlist_len(cl->certs) == 0) {
1100 /* We have no certs at all for this one */
1102 /* Do we have a download of one pending? */
1103 if (digestmap_get(pending_id, voter->identity_digest))
1104 continue;
1107 * Are we about to launch a download of one due to the trusted
1108 * dir server check above?
1110 if (smartlist_contains_digest(missing_id_digests,
1111 voter->identity_digest))
1112 continue;
1115 SMARTLIST_FOREACH_BEGIN(voter->sigs, document_signature_t *, sig) {
1116 authority_cert_t *cert =
1117 authority_cert_get_by_digests(voter->identity_digest,
1118 sig->signing_key_digest);
1119 if (cert) {
1120 if (now < cert->expires)
1121 download_status_reset_by_sk_in_cl(cl, sig->signing_key_digest);
1122 continue;
1124 if (download_status_is_ready_by_sk_in_cl(
1125 cl, sig->signing_key_digest,
1126 now, options->TestingCertMaxDownloadTries) &&
1127 !fp_pair_map_get_by_digests(pending_cert,
1128 voter->identity_digest,
1129 sig->signing_key_digest)) {
1131 * Do this rather than hex_str(), since hex_str clobbers
1132 * old results and we call twice in the param list.
1134 base16_encode(id_digest_str, sizeof(id_digest_str),
1135 voter->identity_digest, DIGEST_LEN);
1136 base16_encode(sk_digest_str, sizeof(sk_digest_str),
1137 sig->signing_key_digest, DIGEST_LEN);
1139 if (voter->nickname) {
1140 log_info(LD_DIR,
1141 "We're missing a certificate from authority %s "
1142 "(ID digest %s) with signing key %s: "
1143 "launching request.",
1144 voter->nickname, id_digest_str, sk_digest_str);
1145 } else {
1146 log_info(LD_DIR,
1147 "We're missing a certificate from authority ID digest "
1148 "%s with signing key %s: launching request.",
1149 id_digest_str, sk_digest_str);
1152 /* Allocate a new fp_pair_t to append */
1153 fp_tmp = tor_malloc(sizeof(*fp_tmp));
1154 memcpy(fp_tmp->first, voter->identity_digest, sizeof(fp_tmp->first));
1155 memcpy(fp_tmp->second, sig->signing_key_digest,
1156 sizeof(fp_tmp->second));
1157 smartlist_add(missing_cert_digests, fp_tmp);
1159 } SMARTLIST_FOREACH_END(sig);
1160 } SMARTLIST_FOREACH_END(voter);
1163 /* Bridge clients look up the node for the dir_hint */
1164 const node_t *node = NULL;
1165 /* All clients, including bridge clients, look up the routerstatus for the
1166 * dir_hint */
1167 const routerstatus_t *rs = NULL;
1169 /* If we still need certificates, try the directory that just successfully
1170 * served us a consensus or certificates.
1171 * As soon as the directory fails to provide additional certificates, we try
1172 * another, randomly selected directory. This avoids continual retries.
1173 * (We only ever have one outstanding request per certificate.)
1175 if (dir_hint) {
1176 if (options->UseBridges) {
1177 /* Bridge clients try the nodelist. If the dir_hint is from an authority,
1178 * or something else fetched over tor, we won't find the node here, but
1179 * we will find the rs. */
1180 node = node_get_by_id(dir_hint);
1183 /* All clients try the consensus routerstatus, then the fallback
1184 * routerstatus */
1185 rs = router_get_consensus_status_by_id(dir_hint);
1186 if (!rs) {
1187 /* This will also find authorities */
1188 const dir_server_t *ds = router_get_fallback_dirserver_by_digest(
1189 dir_hint);
1190 if (ds) {
1191 rs = &ds->fake_status;
1195 if (!node && !rs) {
1196 log_warn(LD_BUG, "Directory %s delivered a consensus, but %s"
1197 "no routerstatus could be found for it.",
1198 options->UseBridges ? "no node and " : "",
1199 hex_str(dir_hint, DIGEST_LEN));
1203 /* Do downloads by identity digest */
1204 if (smartlist_len(missing_id_digests) > 0) {
1205 int need_plus = 0;
1206 smartlist_t *fps = smartlist_new();
1208 smartlist_add_strdup(fps, "fp/");
1210 SMARTLIST_FOREACH_BEGIN(missing_id_digests, const char *, d) {
1211 char *fp = NULL;
1213 if (digestmap_get(pending_id, d))
1214 continue;
1216 base16_encode(id_digest_str, sizeof(id_digest_str),
1217 d, DIGEST_LEN);
1219 if (need_plus) {
1220 tor_asprintf(&fp, "+%s", id_digest_str);
1221 } else {
1222 /* No need for tor_asprintf() in this case; first one gets no '+' */
1223 fp = tor_strdup(id_digest_str);
1224 need_plus = 1;
1227 smartlist_add(fps, fp);
1228 } SMARTLIST_FOREACH_END(d);
1230 if (smartlist_len(fps) > 1) {
1231 resource = smartlist_join_strings(fps, "", 0, NULL);
1232 /* node and rs are directories that just gave us a consensus or
1233 * certificates */
1234 authority_certs_fetch_resource_impl(resource, dir_hint, node, rs);
1235 tor_free(resource);
1237 /* else we didn't add any: they were all pending */
1239 SMARTLIST_FOREACH(fps, char *, cp, tor_free(cp));
1240 smartlist_free(fps);
1243 /* Do downloads by identity digest/signing key pair */
1244 if (smartlist_len(missing_cert_digests) > 0) {
1245 int need_plus = 0;
1246 smartlist_t *fp_pairs = smartlist_new();
1248 smartlist_add_strdup(fp_pairs, "fp-sk/");
1250 SMARTLIST_FOREACH_BEGIN(missing_cert_digests, const fp_pair_t *, d) {
1251 char *fp_pair = NULL;
1253 if (fp_pair_map_get(pending_cert, d))
1254 continue;
1256 /* Construct string encodings of the digests */
1257 base16_encode(id_digest_str, sizeof(id_digest_str),
1258 d->first, DIGEST_LEN);
1259 base16_encode(sk_digest_str, sizeof(sk_digest_str),
1260 d->second, DIGEST_LEN);
1262 /* Now tor_asprintf() */
1263 if (need_plus) {
1264 tor_asprintf(&fp_pair, "+%s-%s", id_digest_str, sk_digest_str);
1265 } else {
1266 /* First one in the list doesn't get a '+' */
1267 tor_asprintf(&fp_pair, "%s-%s", id_digest_str, sk_digest_str);
1268 need_plus = 1;
1271 /* Add it to the list of pairs to request */
1272 smartlist_add(fp_pairs, fp_pair);
1273 } SMARTLIST_FOREACH_END(d);
1275 if (smartlist_len(fp_pairs) > 1) {
1276 resource = smartlist_join_strings(fp_pairs, "", 0, NULL);
1277 /* node and rs are directories that just gave us a consensus or
1278 * certificates */
1279 authority_certs_fetch_resource_impl(resource, dir_hint, node, rs);
1280 tor_free(resource);
1282 /* else they were all pending */
1284 SMARTLIST_FOREACH(fp_pairs, char *, p, tor_free(p));
1285 smartlist_free(fp_pairs);
1288 smartlist_free(missing_id_digests);
1289 SMARTLIST_FOREACH(missing_cert_digests, fp_pair_t *, p, tor_free(p));
1290 smartlist_free(missing_cert_digests);
1291 digestmap_free(pending_id, NULL);
1292 fp_pair_map_free(pending_cert, NULL);
1295 /* Router descriptor storage.
1297 * Routerdescs are stored in a big file, named "cached-descriptors". As new
1298 * routerdescs arrive, we append them to a journal file named
1299 * "cached-descriptors.new".
1301 * From time to time, we replace "cached-descriptors" with a new file
1302 * containing only the live, non-superseded descriptors, and clear
1303 * cached-routers.new.
1305 * On startup, we read both files.
1308 /** Helper: return 1 iff the router log is so big we want to rebuild the
1309 * store. */
1310 static int
1311 router_should_rebuild_store(desc_store_t *store)
1313 if (store->store_len > (1<<16))
1314 return (store->journal_len > store->store_len / 2 ||
1315 store->bytes_dropped > store->store_len / 2);
1316 else
1317 return store->journal_len > (1<<15);
1320 /** Return the desc_store_t in <b>rl</b> that should be used to store
1321 * <b>sd</b>. */
1322 static inline desc_store_t *
1323 desc_get_store(routerlist_t *rl, const signed_descriptor_t *sd)
1325 if (sd->is_extrainfo)
1326 return &rl->extrainfo_store;
1327 else
1328 return &rl->desc_store;
1331 /** Add the signed_descriptor_t in <b>desc</b> to the router
1332 * journal; change its saved_location to SAVED_IN_JOURNAL and set its
1333 * offset appropriately. */
1334 static int
1335 signed_desc_append_to_journal(signed_descriptor_t *desc,
1336 desc_store_t *store)
1338 char *fname = get_datadir_fname_suffix(store->fname_base, ".new");
1339 const char *body = signed_descriptor_get_body_impl(desc,1);
1340 size_t len = desc->signed_descriptor_len + desc->annotations_len;
1342 if (append_bytes_to_file(fname, body, len, 1)) {
1343 log_warn(LD_FS, "Unable to store router descriptor");
1344 tor_free(fname);
1345 return -1;
1347 desc->saved_location = SAVED_IN_JOURNAL;
1348 tor_free(fname);
1350 desc->saved_offset = store->journal_len;
1351 store->journal_len += len;
1353 return 0;
1356 /** Sorting helper: return &lt;0, 0, or &gt;0 depending on whether the
1357 * signed_descriptor_t* in *<b>a</b> is older, the same age as, or newer than
1358 * the signed_descriptor_t* in *<b>b</b>. */
1359 static int
1360 compare_signed_descriptors_by_age_(const void **_a, const void **_b)
1362 const signed_descriptor_t *r1 = *_a, *r2 = *_b;
1363 return (int)(r1->published_on - r2->published_on);
1366 #define RRS_FORCE 1
1367 #define RRS_DONT_REMOVE_OLD 2
1369 /** If the journal of <b>store</b> is too long, or if RRS_FORCE is set in
1370 * <b>flags</b>, then atomically replace the saved router store with the
1371 * routers currently in our routerlist, and clear the journal. Unless
1372 * RRS_DONT_REMOVE_OLD is set in <b>flags</b>, delete expired routers before
1373 * rebuilding the store. Return 0 on success, -1 on failure.
1375 static int
1376 router_rebuild_store(int flags, desc_store_t *store)
1378 smartlist_t *chunk_list = NULL;
1379 char *fname = NULL, *fname_tmp = NULL;
1380 int r = -1;
1381 off_t offset = 0;
1382 smartlist_t *signed_descriptors = NULL;
1383 int nocache=0;
1384 size_t total_expected_len = 0;
1385 int had_any;
1386 int force = flags & RRS_FORCE;
1388 if (!force && !router_should_rebuild_store(store)) {
1389 r = 0;
1390 goto done;
1392 if (!routerlist) {
1393 r = 0;
1394 goto done;
1397 if (store->type == EXTRAINFO_STORE)
1398 had_any = !eimap_isempty(routerlist->extra_info_map);
1399 else
1400 had_any = (smartlist_len(routerlist->routers)+
1401 smartlist_len(routerlist->old_routers))>0;
1403 /* Don't save deadweight. */
1404 if (!(flags & RRS_DONT_REMOVE_OLD))
1405 routerlist_remove_old_routers();
1407 log_info(LD_DIR, "Rebuilding %s cache", store->description);
1409 fname = get_datadir_fname(store->fname_base);
1410 fname_tmp = get_datadir_fname_suffix(store->fname_base, ".tmp");
1412 chunk_list = smartlist_new();
1414 /* We sort the routers by age to enhance locality on disk. */
1415 signed_descriptors = smartlist_new();
1416 if (store->type == EXTRAINFO_STORE) {
1417 eimap_iter_t *iter;
1418 for (iter = eimap_iter_init(routerlist->extra_info_map);
1419 !eimap_iter_done(iter);
1420 iter = eimap_iter_next(routerlist->extra_info_map, iter)) {
1421 const char *key;
1422 extrainfo_t *ei;
1423 eimap_iter_get(iter, &key, &ei);
1424 smartlist_add(signed_descriptors, &ei->cache_info);
1426 } else {
1427 SMARTLIST_FOREACH(routerlist->old_routers, signed_descriptor_t *, sd,
1428 smartlist_add(signed_descriptors, sd));
1429 SMARTLIST_FOREACH(routerlist->routers, routerinfo_t *, ri,
1430 smartlist_add(signed_descriptors, &ri->cache_info));
1433 smartlist_sort(signed_descriptors, compare_signed_descriptors_by_age_);
1435 /* Now, add the appropriate members to chunk_list */
1436 SMARTLIST_FOREACH_BEGIN(signed_descriptors, signed_descriptor_t *, sd) {
1437 sized_chunk_t *c;
1438 const char *body = signed_descriptor_get_body_impl(sd, 1);
1439 if (!body) {
1440 log_warn(LD_BUG, "No descriptor available for router.");
1441 goto done;
1443 if (sd->do_not_cache) {
1444 ++nocache;
1445 continue;
1447 c = tor_malloc(sizeof(sized_chunk_t));
1448 c->bytes = body;
1449 c->len = sd->signed_descriptor_len + sd->annotations_len;
1450 total_expected_len += c->len;
1451 smartlist_add(chunk_list, c);
1452 } SMARTLIST_FOREACH_END(sd);
1454 if (write_chunks_to_file(fname_tmp, chunk_list, 1, 1)<0) {
1455 log_warn(LD_FS, "Error writing router store to disk.");
1456 goto done;
1459 /* Our mmap is now invalid. */
1460 if (store->mmap) {
1461 int res = tor_munmap_file(store->mmap);
1462 store->mmap = NULL;
1463 if (res != 0) {
1464 log_warn(LD_FS, "Unable to munmap route store in %s", fname);
1468 if (replace_file(fname_tmp, fname)<0) {
1469 log_warn(LD_FS, "Error replacing old router store: %s", strerror(errno));
1470 goto done;
1473 errno = 0;
1474 store->mmap = tor_mmap_file(fname);
1475 if (! store->mmap) {
1476 if (errno == ERANGE) {
1477 /* empty store.*/
1478 if (total_expected_len) {
1479 log_warn(LD_FS, "We wrote some bytes to a new descriptor file at '%s',"
1480 " but when we went to mmap it, it was empty!", fname);
1481 } else if (had_any) {
1482 log_info(LD_FS, "We just removed every descriptor in '%s'. This is "
1483 "okay if we're just starting up after a long time. "
1484 "Otherwise, it's a bug.", fname);
1486 } else {
1487 log_warn(LD_FS, "Unable to mmap new descriptor file at '%s'.",fname);
1491 log_info(LD_DIR, "Reconstructing pointers into cache");
1493 offset = 0;
1494 SMARTLIST_FOREACH_BEGIN(signed_descriptors, signed_descriptor_t *, sd) {
1495 if (sd->do_not_cache)
1496 continue;
1497 sd->saved_location = SAVED_IN_CACHE;
1498 if (store->mmap) {
1499 tor_free(sd->signed_descriptor_body); // sets it to null
1500 sd->saved_offset = offset;
1502 offset += sd->signed_descriptor_len + sd->annotations_len;
1503 signed_descriptor_get_body(sd); /* reconstruct and assert */
1504 } SMARTLIST_FOREACH_END(sd);
1506 tor_free(fname);
1507 fname = get_datadir_fname_suffix(store->fname_base, ".new");
1508 write_str_to_file(fname, "", 1);
1510 r = 0;
1511 store->store_len = (size_t) offset;
1512 store->journal_len = 0;
1513 store->bytes_dropped = 0;
1514 done:
1515 smartlist_free(signed_descriptors);
1516 tor_free(fname);
1517 tor_free(fname_tmp);
1518 if (chunk_list) {
1519 SMARTLIST_FOREACH(chunk_list, sized_chunk_t *, c, tor_free(c));
1520 smartlist_free(chunk_list);
1523 return r;
1526 /** Helper: Reload a cache file and its associated journal, setting metadata
1527 * appropriately. If <b>extrainfo</b> is true, reload the extrainfo store;
1528 * else reload the router descriptor store. */
1529 static int
1530 router_reload_router_list_impl(desc_store_t *store)
1532 char *fname = NULL, *contents = NULL;
1533 struct stat st;
1534 int extrainfo = (store->type == EXTRAINFO_STORE);
1535 store->journal_len = store->store_len = 0;
1537 fname = get_datadir_fname(store->fname_base);
1539 if (store->mmap) {
1540 /* get rid of it first */
1541 int res = tor_munmap_file(store->mmap);
1542 store->mmap = NULL;
1543 if (res != 0) {
1544 log_warn(LD_FS, "Failed to munmap %s", fname);
1545 tor_free(fname);
1546 return -1;
1550 store->mmap = tor_mmap_file(fname);
1551 if (store->mmap) {
1552 store->store_len = store->mmap->size;
1553 if (extrainfo)
1554 router_load_extrainfo_from_string(store->mmap->data,
1555 store->mmap->data+store->mmap->size,
1556 SAVED_IN_CACHE, NULL, 0);
1557 else
1558 router_load_routers_from_string(store->mmap->data,
1559 store->mmap->data+store->mmap->size,
1560 SAVED_IN_CACHE, NULL, 0, NULL);
1563 tor_free(fname);
1564 fname = get_datadir_fname_suffix(store->fname_base, ".new");
1565 /* don't load empty files - we wouldn't get any data, even if we tried */
1566 if (file_status(fname) == FN_FILE)
1567 contents = read_file_to_str(fname, RFTS_BIN|RFTS_IGNORE_MISSING, &st);
1568 if (contents) {
1569 if (extrainfo)
1570 router_load_extrainfo_from_string(contents, NULL,SAVED_IN_JOURNAL,
1571 NULL, 0);
1572 else
1573 router_load_routers_from_string(contents, NULL, SAVED_IN_JOURNAL,
1574 NULL, 0, NULL);
1575 store->journal_len = (size_t) st.st_size;
1576 tor_free(contents);
1579 tor_free(fname);
1581 if (store->journal_len) {
1582 /* Always clear the journal on startup.*/
1583 router_rebuild_store(RRS_FORCE, store);
1584 } else if (!extrainfo) {
1585 /* Don't cache expired routers. (This is in an else because
1586 * router_rebuild_store() also calls remove_old_routers().) */
1587 routerlist_remove_old_routers();
1590 return 0;
1593 /** Load all cached router descriptors and extra-info documents from the
1594 * store. Return 0 on success and -1 on failure.
1597 router_reload_router_list(void)
1599 routerlist_t *rl = router_get_routerlist();
1600 if (router_reload_router_list_impl(&rl->desc_store))
1601 return -1;
1602 if (router_reload_router_list_impl(&rl->extrainfo_store))
1603 return -1;
1604 return 0;
1607 /** Return a smartlist containing a list of dir_server_t * for all
1608 * known trusted dirservers. Callers must not modify the list or its
1609 * contents.
1611 const smartlist_t *
1612 router_get_trusted_dir_servers(void)
1614 if (!trusted_dir_servers)
1615 trusted_dir_servers = smartlist_new();
1617 return trusted_dir_servers;
1620 const smartlist_t *
1621 router_get_fallback_dir_servers(void)
1623 if (!fallback_dir_servers)
1624 fallback_dir_servers = smartlist_new();
1626 return fallback_dir_servers;
1629 /** Try to find a running dirserver that supports operations of <b>type</b>.
1631 * If there are no running dirservers in our routerlist and the
1632 * <b>PDS_RETRY_IF_NO_SERVERS</b> flag is set, set all the fallback ones
1633 * (including authorities) as running again, and pick one.
1635 * If the <b>PDS_IGNORE_FASCISTFIREWALL</b> flag is set, then include
1636 * dirservers that we can't reach.
1638 * If the <b>PDS_ALLOW_SELF</b> flag is not set, then don't include ourself
1639 * (if we're a dirserver).
1641 * Don't pick a fallback directory mirror if any non-fallback is viable;
1642 * (the fallback directory mirrors include the authorities)
1643 * try to avoid using servers that have returned 503 recently.
1645 const routerstatus_t *
1646 router_pick_directory_server(dirinfo_type_t type, int flags)
1648 int busy = 0;
1649 const routerstatus_t *choice;
1651 if (!routerlist)
1652 return NULL;
1654 choice = router_pick_directory_server_impl(type, flags, &busy);
1655 if (choice || !(flags & PDS_RETRY_IF_NO_SERVERS))
1656 return choice;
1658 if (busy) {
1659 /* If the reason that we got no server is that servers are "busy",
1660 * we must be excluding good servers because we already have serverdesc
1661 * fetches with them. Do not mark down servers up because of this. */
1662 tor_assert((flags & (PDS_NO_EXISTING_SERVERDESC_FETCH|
1663 PDS_NO_EXISTING_MICRODESC_FETCH)));
1664 return NULL;
1667 log_info(LD_DIR,
1668 "No reachable router entries for dirservers. "
1669 "Trying them all again.");
1670 /* mark all fallback directory mirrors as up again */
1671 mark_all_dirservers_up(fallback_dir_servers);
1672 /* try again */
1673 choice = router_pick_directory_server_impl(type, flags, NULL);
1674 return choice;
1677 /** Return the dir_server_t for the directory authority whose identity
1678 * key hashes to <b>digest</b>, or NULL if no such authority is known.
1680 dir_server_t *
1681 router_get_trusteddirserver_by_digest(const char *digest)
1683 if (!trusted_dir_servers)
1684 return NULL;
1686 SMARTLIST_FOREACH(trusted_dir_servers, dir_server_t *, ds,
1688 if (tor_memeq(ds->digest, digest, DIGEST_LEN))
1689 return ds;
1692 return NULL;
1695 /** Return the dir_server_t for the fallback dirserver whose identity
1696 * key hashes to <b>digest</b>, or NULL if no such fallback is in the list of
1697 * fallback_dir_servers. (fallback_dir_servers is affected by the FallbackDir
1698 * and UseDefaultFallbackDirs torrc options.)
1699 * The list of fallback directories includes the list of authorities.
1701 dir_server_t *
1702 router_get_fallback_dirserver_by_digest(const char *digest)
1704 if (!fallback_dir_servers)
1705 return NULL;
1707 if (!digest)
1708 return NULL;
1710 SMARTLIST_FOREACH(fallback_dir_servers, dir_server_t *, ds,
1712 if (tor_memeq(ds->digest, digest, DIGEST_LEN))
1713 return ds;
1716 return NULL;
1719 /** Return 1 if any fallback dirserver's identity key hashes to <b>digest</b>,
1720 * or 0 if no such fallback is in the list of fallback_dir_servers.
1721 * (fallback_dir_servers is affected by the FallbackDir and
1722 * UseDefaultFallbackDirs torrc options.)
1723 * The list of fallback directories includes the list of authorities.
1726 router_digest_is_fallback_dir(const char *digest)
1728 return (router_get_fallback_dirserver_by_digest(digest) != NULL);
1731 /** Return the dir_server_t for the directory authority whose
1732 * v3 identity key hashes to <b>digest</b>, or NULL if no such authority
1733 * is known.
1735 MOCK_IMPL(dir_server_t *,
1736 trusteddirserver_get_by_v3_auth_digest, (const char *digest))
1738 if (!trusted_dir_servers)
1739 return NULL;
1741 SMARTLIST_FOREACH(trusted_dir_servers, dir_server_t *, ds,
1743 if (tor_memeq(ds->v3_identity_digest, digest, DIGEST_LEN) &&
1744 (ds->type & V3_DIRINFO))
1745 return ds;
1748 return NULL;
1751 /** Try to find a running directory authority. Flags are as for
1752 * router_pick_directory_server.
1754 const routerstatus_t *
1755 router_pick_trusteddirserver(dirinfo_type_t type, int flags)
1757 return router_pick_dirserver_generic(trusted_dir_servers, type, flags);
1760 /** Try to find a running fallback directory. Flags are as for
1761 * router_pick_directory_server.
1763 const routerstatus_t *
1764 router_pick_fallback_dirserver(dirinfo_type_t type, int flags)
1766 return router_pick_dirserver_generic(fallback_dir_servers, type, flags);
1769 /** Try to find a running fallback directory. Flags are as for
1770 * router_pick_directory_server.
1772 static const routerstatus_t *
1773 router_pick_dirserver_generic(smartlist_t *sourcelist,
1774 dirinfo_type_t type, int flags)
1776 const routerstatus_t *choice;
1777 int busy = 0;
1779 choice = router_pick_trusteddirserver_impl(sourcelist, type, flags, &busy);
1780 if (choice || !(flags & PDS_RETRY_IF_NO_SERVERS))
1781 return choice;
1782 if (busy) {
1783 /* If the reason that we got no server is that servers are "busy",
1784 * we must be excluding good servers because we already have serverdesc
1785 * fetches with them. Do not mark down servers up because of this. */
1786 tor_assert((flags & (PDS_NO_EXISTING_SERVERDESC_FETCH|
1787 PDS_NO_EXISTING_MICRODESC_FETCH)));
1788 return NULL;
1791 log_info(LD_DIR,
1792 "No dirservers are reachable. Trying them all again.");
1793 mark_all_dirservers_up(sourcelist);
1794 return router_pick_trusteddirserver_impl(sourcelist, type, flags, NULL);
1797 /* Check if we already have a directory fetch from ap, for serverdesc
1798 * (including extrainfo) or microdesc documents.
1799 * If so, return 1, if not, return 0.
1800 * Also returns 0 if addr is NULL, tor_addr_is_null(addr), or dir_port is 0.
1802 STATIC int
1803 router_is_already_dir_fetching(const tor_addr_port_t *ap, int serverdesc,
1804 int microdesc)
1806 if (!ap || tor_addr_is_null(&ap->addr) || !ap->port) {
1807 return 0;
1810 /* XX/teor - we're not checking tunnel connections here, see #17848
1812 if (serverdesc && (
1813 connection_get_by_type_addr_port_purpose(
1814 CONN_TYPE_DIR, &ap->addr, ap->port, DIR_PURPOSE_FETCH_SERVERDESC)
1815 || connection_get_by_type_addr_port_purpose(
1816 CONN_TYPE_DIR, &ap->addr, ap->port, DIR_PURPOSE_FETCH_EXTRAINFO))) {
1817 return 1;
1820 if (microdesc && (
1821 connection_get_by_type_addr_port_purpose(
1822 CONN_TYPE_DIR, &ap->addr, ap->port, DIR_PURPOSE_FETCH_MICRODESC))) {
1823 return 1;
1826 return 0;
1829 /* Check if we already have a directory fetch from the ipv4 or ipv6
1830 * router, for serverdesc (including extrainfo) or microdesc documents.
1831 * If so, return 1, if not, return 0.
1833 static int
1834 router_is_already_dir_fetching_(uint32_t ipv4_addr,
1835 const tor_addr_t *ipv6_addr,
1836 uint16_t dir_port,
1837 int serverdesc,
1838 int microdesc)
1840 tor_addr_port_t ipv4_dir_ap, ipv6_dir_ap;
1842 /* Assume IPv6 DirPort is the same as IPv4 DirPort */
1843 tor_addr_from_ipv4h(&ipv4_dir_ap.addr, ipv4_addr);
1844 ipv4_dir_ap.port = dir_port;
1845 tor_addr_copy(&ipv6_dir_ap.addr, ipv6_addr);
1846 ipv6_dir_ap.port = dir_port;
1848 return (router_is_already_dir_fetching(&ipv4_dir_ap, serverdesc, microdesc)
1849 || router_is_already_dir_fetching(&ipv6_dir_ap, serverdesc, microdesc));
1852 #ifndef LOG_FALSE_POSITIVES_DURING_BOOTSTRAP
1853 #define LOG_FALSE_POSITIVES_DURING_BOOTSTRAP 0
1854 #endif
1856 /* Log a message if rs is not found or not a preferred address */
1857 static void
1858 router_picked_poor_directory_log(const routerstatus_t *rs)
1860 const networkstatus_t *usable_consensus;
1861 usable_consensus = networkstatus_get_reasonably_live_consensus(time(NULL),
1862 usable_consensus_flavor());
1864 #if !LOG_FALSE_POSITIVES_DURING_BOOTSTRAP
1865 /* Don't log early in the bootstrap process, it's normal to pick from a
1866 * small pool of nodes. Of course, this won't help if we're trying to
1867 * diagnose bootstrap issues. */
1868 if (!smartlist_len(nodelist_get_list()) || !usable_consensus
1869 || !router_have_minimum_dir_info()) {
1870 return;
1872 #endif
1874 /* We couldn't find a node, or the one we have doesn't fit our preferences.
1875 * Sometimes this is normal, sometimes it can be a reachability issue. */
1876 if (!rs) {
1877 /* This happens a lot, so it's at debug level */
1878 log_debug(LD_DIR, "Wanted to make an outgoing directory connection, but "
1879 "we couldn't find a directory that fit our criteria. "
1880 "Perhaps we will succeed next time with less strict criteria.");
1881 } else if (!fascist_firewall_allows_rs(rs, FIREWALL_OR_CONNECTION, 1)
1882 && !fascist_firewall_allows_rs(rs, FIREWALL_DIR_CONNECTION, 1)
1884 /* This is rare, and might be interesting to users trying to diagnose
1885 * connection issues on dual-stack machines. */
1886 log_info(LD_DIR, "Selected a directory %s with non-preferred OR and Dir "
1887 "addresses for launching an outgoing connection: "
1888 "IPv4 %s OR %d Dir %d IPv6 %s OR %d Dir %d",
1889 routerstatus_describe(rs),
1890 fmt_addr32(rs->addr), rs->or_port,
1891 rs->dir_port, fmt_addr(&rs->ipv6_addr),
1892 rs->ipv6_orport, rs->dir_port);
1896 #undef LOG_FALSE_POSITIVES_DURING_BOOTSTRAP
1898 /** How long do we avoid using a directory server after it's given us a 503? */
1899 #define DIR_503_TIMEOUT (60*60)
1901 /* Common retry code for router_pick_directory_server_impl and
1902 * router_pick_trusteddirserver_impl. Retry with the non-preferred IP version.
1903 * Must be called before RETRY_WITHOUT_EXCLUDE().
1905 * If we got no result, and we are applying IP preferences, and we are a
1906 * client that could use an alternate IP version, try again with the
1907 * opposite preferences. */
1908 #define RETRY_ALTERNATE_IP_VERSION(retry_label) \
1909 STMT_BEGIN \
1910 if (result == NULL && try_ip_pref && options->ClientUseIPv4 \
1911 && fascist_firewall_use_ipv6(options) && !server_mode(options) \
1912 && !n_busy) { \
1913 n_excluded = 0; \
1914 n_busy = 0; \
1915 try_ip_pref = 0; \
1916 goto retry_label; \
1918 STMT_END \
1920 /* Common retry code for router_pick_directory_server_impl and
1921 * router_pick_trusteddirserver_impl. Retry without excluding nodes, but with
1922 * the preferred IP version. Must be called after RETRY_ALTERNATE_IP_VERSION().
1924 * If we got no result, and we are excluding nodes, and StrictNodes is
1925 * not set, try again without excluding nodes. */
1926 #define RETRY_WITHOUT_EXCLUDE(retry_label) \
1927 STMT_BEGIN \
1928 if (result == NULL && try_excluding && !options->StrictNodes \
1929 && n_excluded && !n_busy) { \
1930 try_excluding = 0; \
1931 n_excluded = 0; \
1932 n_busy = 0; \
1933 try_ip_pref = 1; \
1934 goto retry_label; \
1936 STMT_END
1938 /* Common code used in the loop within router_pick_directory_server_impl and
1939 * router_pick_trusteddirserver_impl.
1941 * Check if the given <b>identity</b> supports extrainfo. If not, skip further
1942 * checks.
1944 #define SKIP_MISSING_TRUSTED_EXTRAINFO(type, identity) \
1945 STMT_BEGIN \
1946 int is_trusted_extrainfo = router_digest_is_trusted_dir_type( \
1947 (identity), EXTRAINFO_DIRINFO); \
1948 if (((type) & EXTRAINFO_DIRINFO) && \
1949 !router_supports_extrainfo((identity), is_trusted_extrainfo)) \
1950 continue; \
1951 STMT_END
1953 /* When iterating through the routerlist, can OR address/port preference
1954 * and reachability checks be skipped?
1957 router_skip_or_reachability(const or_options_t *options, int try_ip_pref)
1959 /* Servers always have and prefer IPv4.
1960 * And if clients are checking against the firewall for reachability only,
1961 * but there's no firewall, don't bother checking */
1962 return server_mode(options) || (!try_ip_pref && !firewall_is_fascist_or());
1965 /* When iterating through the routerlist, can Dir address/port preference
1966 * and reachability checks be skipped?
1968 static int
1969 router_skip_dir_reachability(const or_options_t *options, int try_ip_pref)
1971 /* Servers always have and prefer IPv4.
1972 * And if clients are checking against the firewall for reachability only,
1973 * but there's no firewall, don't bother checking */
1974 return server_mode(options) || (!try_ip_pref && !firewall_is_fascist_dir());
1977 /** Pick a random running valid directory server/mirror from our
1978 * routerlist. Arguments are as for router_pick_directory_server(), except:
1980 * If <b>n_busy_out</b> is provided, set *<b>n_busy_out</b> to the number of
1981 * directories that we excluded for no other reason than
1982 * PDS_NO_EXISTING_SERVERDESC_FETCH or PDS_NO_EXISTING_MICRODESC_FETCH.
1984 STATIC const routerstatus_t *
1985 router_pick_directory_server_impl(dirinfo_type_t type, int flags,
1986 int *n_busy_out)
1988 const or_options_t *options = get_options();
1989 const node_t *result;
1990 smartlist_t *direct, *tunnel;
1991 smartlist_t *trusted_direct, *trusted_tunnel;
1992 smartlist_t *overloaded_direct, *overloaded_tunnel;
1993 time_t now = time(NULL);
1994 const networkstatus_t *consensus = networkstatus_get_latest_consensus();
1995 const int requireother = ! (flags & PDS_ALLOW_SELF);
1996 const int fascistfirewall = ! (flags & PDS_IGNORE_FASCISTFIREWALL);
1997 const int no_serverdesc_fetching =(flags & PDS_NO_EXISTING_SERVERDESC_FETCH);
1998 const int no_microdesc_fetching = (flags & PDS_NO_EXISTING_MICRODESC_FETCH);
1999 int try_excluding = 1, n_excluded = 0, n_busy = 0;
2000 int try_ip_pref = 1;
2002 if (!consensus)
2003 return NULL;
2005 retry_search:
2007 direct = smartlist_new();
2008 tunnel = smartlist_new();
2009 trusted_direct = smartlist_new();
2010 trusted_tunnel = smartlist_new();
2011 overloaded_direct = smartlist_new();
2012 overloaded_tunnel = smartlist_new();
2014 const int skip_or_fw = router_skip_or_reachability(options, try_ip_pref);
2015 const int skip_dir_fw = router_skip_dir_reachability(options, try_ip_pref);
2016 const int must_have_or = directory_must_use_begindir(options);
2018 /* Find all the running dirservers we know about. */
2019 SMARTLIST_FOREACH_BEGIN(nodelist_get_list(), const node_t *, node) {
2020 int is_trusted;
2021 int is_overloaded;
2022 const routerstatus_t *status = node->rs;
2023 const country_t country = node->country;
2024 if (!status)
2025 continue;
2027 if (!node->is_running || !node_is_dir(node) || !node->is_valid)
2028 continue;
2029 if (requireother && router_digest_is_me(node->identity))
2030 continue;
2032 SKIP_MISSING_TRUSTED_EXTRAINFO(type, node->identity);
2034 if (try_excluding &&
2035 routerset_contains_routerstatus(options->ExcludeNodes, status,
2036 country)) {
2037 ++n_excluded;
2038 continue;
2041 if (router_is_already_dir_fetching_(status->addr,
2042 &status->ipv6_addr,
2043 status->dir_port,
2044 no_serverdesc_fetching,
2045 no_microdesc_fetching)) {
2046 ++n_busy;
2047 continue;
2050 is_overloaded = status->last_dir_503_at + DIR_503_TIMEOUT > now;
2051 is_trusted = router_digest_is_trusted_dir(node->identity);
2053 /* Clients use IPv6 addresses if the server has one and the client
2054 * prefers IPv6.
2055 * Add the router if its preferred address and port are reachable.
2056 * If we don't get any routers, we'll try again with the non-preferred
2057 * address for each router (if any). (To ensure correct load-balancing
2058 * we try routers that only have one address both times.)
2060 if (!fascistfirewall || skip_or_fw ||
2061 fascist_firewall_allows_node(node, FIREWALL_OR_CONNECTION,
2062 try_ip_pref))
2063 smartlist_add(is_trusted ? trusted_tunnel :
2064 is_overloaded ? overloaded_tunnel : tunnel, (void*)node);
2065 else if (!must_have_or && (skip_dir_fw ||
2066 fascist_firewall_allows_node(node, FIREWALL_DIR_CONNECTION,
2067 try_ip_pref)))
2068 smartlist_add(is_trusted ? trusted_direct :
2069 is_overloaded ? overloaded_direct : direct, (void*)node);
2070 } SMARTLIST_FOREACH_END(node);
2072 if (smartlist_len(tunnel)) {
2073 result = node_sl_choose_by_bandwidth(tunnel, WEIGHT_FOR_DIR);
2074 } else if (smartlist_len(overloaded_tunnel)) {
2075 result = node_sl_choose_by_bandwidth(overloaded_tunnel,
2076 WEIGHT_FOR_DIR);
2077 } else if (smartlist_len(trusted_tunnel)) {
2078 /* FFFF We don't distinguish between trusteds and overloaded trusteds
2079 * yet. Maybe one day we should. */
2080 /* FFFF We also don't load balance over authorities yet. I think this
2081 * is a feature, but it could easily be a bug. -RD */
2082 result = smartlist_choose(trusted_tunnel);
2083 } else if (smartlist_len(direct)) {
2084 result = node_sl_choose_by_bandwidth(direct, WEIGHT_FOR_DIR);
2085 } else if (smartlist_len(overloaded_direct)) {
2086 result = node_sl_choose_by_bandwidth(overloaded_direct,
2087 WEIGHT_FOR_DIR);
2088 } else {
2089 result = smartlist_choose(trusted_direct);
2091 smartlist_free(direct);
2092 smartlist_free(tunnel);
2093 smartlist_free(trusted_direct);
2094 smartlist_free(trusted_tunnel);
2095 smartlist_free(overloaded_direct);
2096 smartlist_free(overloaded_tunnel);
2098 RETRY_ALTERNATE_IP_VERSION(retry_search);
2100 RETRY_WITHOUT_EXCLUDE(retry_search);
2102 if (n_busy_out)
2103 *n_busy_out = n_busy;
2105 router_picked_poor_directory_log(result ? result->rs : NULL);
2107 return result ? result->rs : NULL;
2110 /** Pick a random element from a list of dir_server_t, weighting by their
2111 * <b>weight</b> field. */
2112 static const dir_server_t *
2113 dirserver_choose_by_weight(const smartlist_t *servers, double authority_weight)
2115 int n = smartlist_len(servers);
2116 int i;
2117 double *weights_dbl;
2118 uint64_t *weights_u64;
2119 const dir_server_t *ds;
2121 weights_dbl = tor_calloc(n, sizeof(double));
2122 weights_u64 = tor_calloc(n, sizeof(uint64_t));
2123 for (i = 0; i < n; ++i) {
2124 ds = smartlist_get(servers, i);
2125 weights_dbl[i] = ds->weight;
2126 if (ds->is_authority)
2127 weights_dbl[i] *= authority_weight;
2130 scale_array_elements_to_u64(weights_u64, weights_dbl, n, NULL);
2131 i = choose_array_element_by_weight(weights_u64, n);
2132 tor_free(weights_dbl);
2133 tor_free(weights_u64);
2134 return (i < 0) ? NULL : smartlist_get(servers, i);
2137 /** Choose randomly from among the dir_server_ts in sourcelist that
2138 * are up. Flags are as for router_pick_directory_server_impl().
2140 static const routerstatus_t *
2141 router_pick_trusteddirserver_impl(const smartlist_t *sourcelist,
2142 dirinfo_type_t type, int flags,
2143 int *n_busy_out)
2145 const or_options_t *options = get_options();
2146 smartlist_t *direct, *tunnel;
2147 smartlist_t *overloaded_direct, *overloaded_tunnel;
2148 const routerinfo_t *me = router_get_my_routerinfo();
2149 const routerstatus_t *result = NULL;
2150 time_t now = time(NULL);
2151 const int requireother = ! (flags & PDS_ALLOW_SELF);
2152 const int fascistfirewall = ! (flags & PDS_IGNORE_FASCISTFIREWALL);
2153 const int no_serverdesc_fetching =(flags & PDS_NO_EXISTING_SERVERDESC_FETCH);
2154 const int no_microdesc_fetching =(flags & PDS_NO_EXISTING_MICRODESC_FETCH);
2155 const double auth_weight = (sourcelist == fallback_dir_servers) ?
2156 options->DirAuthorityFallbackRate : 1.0;
2157 smartlist_t *pick_from;
2158 int n_busy = 0;
2159 int try_excluding = 1, n_excluded = 0;
2160 int try_ip_pref = 1;
2162 if (!sourcelist)
2163 return NULL;
2165 retry_search:
2167 direct = smartlist_new();
2168 tunnel = smartlist_new();
2169 overloaded_direct = smartlist_new();
2170 overloaded_tunnel = smartlist_new();
2172 const int skip_or_fw = router_skip_or_reachability(options, try_ip_pref);
2173 const int skip_dir_fw = router_skip_dir_reachability(options, try_ip_pref);
2174 const int must_have_or = directory_must_use_begindir(options);
2176 SMARTLIST_FOREACH_BEGIN(sourcelist, const dir_server_t *, d)
2178 int is_overloaded =
2179 d->fake_status.last_dir_503_at + DIR_503_TIMEOUT > now;
2180 if (!d->is_running) continue;
2181 if ((type & d->type) == 0)
2182 continue;
2184 SKIP_MISSING_TRUSTED_EXTRAINFO(type, d->digest);
2186 if (requireother && me && router_digest_is_me(d->digest))
2187 continue;
2188 if (try_excluding &&
2189 routerset_contains_routerstatus(options->ExcludeNodes,
2190 &d->fake_status, -1)) {
2191 ++n_excluded;
2192 continue;
2195 if (router_is_already_dir_fetching_(d->addr,
2196 &d->ipv6_addr,
2197 d->dir_port,
2198 no_serverdesc_fetching,
2199 no_microdesc_fetching)) {
2200 ++n_busy;
2201 continue;
2204 /* Clients use IPv6 addresses if the server has one and the client
2205 * prefers IPv6.
2206 * Add the router if its preferred address and port are reachable.
2207 * If we don't get any routers, we'll try again with the non-preferred
2208 * address for each router (if any). (To ensure correct load-balancing
2209 * we try routers that only have one address both times.)
2211 if (!fascistfirewall || skip_or_fw ||
2212 fascist_firewall_allows_dir_server(d, FIREWALL_OR_CONNECTION,
2213 try_ip_pref))
2214 smartlist_add(is_overloaded ? overloaded_tunnel : tunnel, (void*)d);
2215 else if (!must_have_or && (skip_dir_fw ||
2216 fascist_firewall_allows_dir_server(d, FIREWALL_DIR_CONNECTION,
2217 try_ip_pref)))
2218 smartlist_add(is_overloaded ? overloaded_direct : direct, (void*)d);
2220 SMARTLIST_FOREACH_END(d);
2222 if (smartlist_len(tunnel)) {
2223 pick_from = tunnel;
2224 } else if (smartlist_len(overloaded_tunnel)) {
2225 pick_from = overloaded_tunnel;
2226 } else if (smartlist_len(direct)) {
2227 pick_from = direct;
2228 } else {
2229 pick_from = overloaded_direct;
2233 const dir_server_t *selection =
2234 dirserver_choose_by_weight(pick_from, auth_weight);
2236 if (selection)
2237 result = &selection->fake_status;
2240 smartlist_free(direct);
2241 smartlist_free(tunnel);
2242 smartlist_free(overloaded_direct);
2243 smartlist_free(overloaded_tunnel);
2245 RETRY_ALTERNATE_IP_VERSION(retry_search);
2247 RETRY_WITHOUT_EXCLUDE(retry_search);
2249 router_picked_poor_directory_log(result);
2251 if (n_busy_out)
2252 *n_busy_out = n_busy;
2253 return result;
2256 /** Mark as running every dir_server_t in <b>server_list</b>. */
2257 static void
2258 mark_all_dirservers_up(smartlist_t *server_list)
2260 if (server_list) {
2261 SMARTLIST_FOREACH_BEGIN(server_list, dir_server_t *, dir) {
2262 routerstatus_t *rs;
2263 node_t *node;
2264 dir->is_running = 1;
2265 node = node_get_mutable_by_id(dir->digest);
2266 if (node)
2267 node->is_running = 1;
2268 rs = router_get_mutable_consensus_status_by_id(dir->digest);
2269 if (rs) {
2270 rs->last_dir_503_at = 0;
2271 control_event_networkstatus_changed_single(rs);
2273 } SMARTLIST_FOREACH_END(dir);
2275 router_dir_info_changed();
2278 /** Return true iff r1 and r2 have the same address and OR port. */
2280 routers_have_same_or_addrs(const routerinfo_t *r1, const routerinfo_t *r2)
2282 return r1->addr == r2->addr && r1->or_port == r2->or_port &&
2283 tor_addr_eq(&r1->ipv6_addr, &r2->ipv6_addr) &&
2284 r1->ipv6_orport == r2->ipv6_orport;
2287 /** Reset all internal variables used to count failed downloads of network
2288 * status objects. */
2289 void
2290 router_reset_status_download_failures(void)
2292 mark_all_dirservers_up(fallback_dir_servers);
2295 /** Given a <b>router</b>, add every node_t in its family (including the
2296 * node itself!) to <b>sl</b>.
2298 * Note the type mismatch: This function takes a routerinfo, but adds nodes
2299 * to the smartlist!
2301 static void
2302 routerlist_add_node_and_family(smartlist_t *sl, const routerinfo_t *router)
2304 /* XXXX MOVE ? */
2305 node_t fake_node;
2306 const node_t *node = node_get_by_id(router->cache_info.identity_digest);;
2307 if (node == NULL) {
2308 memset(&fake_node, 0, sizeof(fake_node));
2309 fake_node.ri = (routerinfo_t *)router;
2310 memcpy(fake_node.identity, router->cache_info.identity_digest, DIGEST_LEN);
2311 node = &fake_node;
2313 nodelist_add_node_and_family(sl, node);
2316 /** Add every suitable node from our nodelist to <b>sl</b>, so that
2317 * we can pick a node for a circuit.
2319 void
2320 router_add_running_nodes_to_smartlist(smartlist_t *sl, int allow_invalid,
2321 int need_uptime, int need_capacity,
2322 int need_guard, int need_desc,
2323 int pref_addr, int direct_conn)
2325 const int check_reach = !router_skip_or_reachability(get_options(),
2326 pref_addr);
2327 /* XXXX MOVE */
2328 SMARTLIST_FOREACH_BEGIN(nodelist_get_list(), const node_t *, node) {
2329 if (!node->is_running ||
2330 (!node->is_valid && !allow_invalid))
2331 continue;
2332 if (need_desc && !(node->ri || (node->rs && node->md)))
2333 continue;
2334 if (node->ri && node->ri->purpose != ROUTER_PURPOSE_GENERAL)
2335 continue;
2336 if (node_is_unreliable(node, need_uptime, need_capacity, need_guard))
2337 continue;
2338 /* Don't choose nodes if we are certain they can't do EXTEND2 cells */
2339 if (node->rs && !routerstatus_version_supports_extend2_cells(node->rs, 1))
2340 continue;
2341 /* Don't choose nodes if we are certain they can't do ntor. */
2342 if ((node->ri || node->md) && !node_has_curve25519_onion_key(node))
2343 continue;
2344 /* Choose a node with an OR address that matches the firewall rules */
2345 if (direct_conn && check_reach &&
2346 !fascist_firewall_allows_node(node,
2347 FIREWALL_OR_CONNECTION,
2348 pref_addr))
2349 continue;
2351 smartlist_add(sl, (void *)node);
2352 } SMARTLIST_FOREACH_END(node);
2355 /** Look through the routerlist until we find a router that has my key.
2356 Return it. */
2357 const routerinfo_t *
2358 routerlist_find_my_routerinfo(void)
2360 if (!routerlist)
2361 return NULL;
2363 SMARTLIST_FOREACH(routerlist->routers, routerinfo_t *, router,
2365 if (router_is_me(router))
2366 return router;
2368 return NULL;
2371 /** Return the smaller of the router's configured BandwidthRate
2372 * and its advertised capacity. */
2373 uint32_t
2374 router_get_advertised_bandwidth(const routerinfo_t *router)
2376 if (router->bandwidthcapacity < router->bandwidthrate)
2377 return router->bandwidthcapacity;
2378 return router->bandwidthrate;
2381 /** Do not weight any declared bandwidth more than this much when picking
2382 * routers by bandwidth. */
2383 #define DEFAULT_MAX_BELIEVABLE_BANDWIDTH 10000000 /* 10 MB/sec */
2385 /** Return the smaller of the router's configured BandwidthRate
2386 * and its advertised capacity, capped by max-believe-bw. */
2387 uint32_t
2388 router_get_advertised_bandwidth_capped(const routerinfo_t *router)
2390 uint32_t result = router->bandwidthcapacity;
2391 if (result > router->bandwidthrate)
2392 result = router->bandwidthrate;
2393 if (result > DEFAULT_MAX_BELIEVABLE_BANDWIDTH)
2394 result = DEFAULT_MAX_BELIEVABLE_BANDWIDTH;
2395 return result;
2398 /** Given an array of double/uint64_t unions that are currently being used as
2399 * doubles, convert them to uint64_t, and try to scale them linearly so as to
2400 * much of the range of uint64_t. If <b>total_out</b> is provided, set it to
2401 * the sum of all elements in the array _before_ scaling. */
2402 STATIC void
2403 scale_array_elements_to_u64(uint64_t *entries_out, const double *entries_in,
2404 int n_entries,
2405 uint64_t *total_out)
2407 double total = 0.0;
2408 double scale_factor = 0.0;
2409 int i;
2411 for (i = 0; i < n_entries; ++i)
2412 total += entries_in[i];
2414 if (total > 0.0) {
2415 scale_factor = ((double)INT64_MAX) / total;
2416 scale_factor /= 4.0; /* make sure we're very far away from overflowing */
2419 for (i = 0; i < n_entries; ++i)
2420 entries_out[i] = tor_llround(entries_in[i] * scale_factor);
2422 if (total_out)
2423 *total_out = (uint64_t) total;
2426 /** Pick a random element of <b>n_entries</b>-element array <b>entries</b>,
2427 * choosing each element with a probability proportional to its (uint64_t)
2428 * value, and return the index of that element. If all elements are 0, choose
2429 * an index at random. Return -1 on error.
2431 STATIC int
2432 choose_array_element_by_weight(const uint64_t *entries, int n_entries)
2434 int i;
2435 uint64_t rand_val;
2436 uint64_t total = 0;
2438 for (i = 0; i < n_entries; ++i)
2439 total += entries[i];
2441 if (n_entries < 1)
2442 return -1;
2444 if (total == 0)
2445 return crypto_rand_int(n_entries);
2447 tor_assert(total < INT64_MAX);
2449 rand_val = crypto_rand_uint64(total);
2451 return select_array_member_cumulative_timei(
2452 entries, n_entries, total, rand_val);
2455 /** When weighting bridges, enforce these values as lower and upper
2456 * bound for believable bandwidth, because there is no way for us
2457 * to verify a bridge's bandwidth currently. */
2458 #define BRIDGE_MIN_BELIEVABLE_BANDWIDTH 20000 /* 20 kB/sec */
2459 #define BRIDGE_MAX_BELIEVABLE_BANDWIDTH 100000 /* 100 kB/sec */
2461 /** Return the smaller of the router's configured BandwidthRate
2462 * and its advertised capacity, making sure to stay within the
2463 * interval between bridge-min-believe-bw and
2464 * bridge-max-believe-bw. */
2465 static uint32_t
2466 bridge_get_advertised_bandwidth_bounded(routerinfo_t *router)
2468 uint32_t result = router->bandwidthcapacity;
2469 if (result > router->bandwidthrate)
2470 result = router->bandwidthrate;
2471 if (result > BRIDGE_MAX_BELIEVABLE_BANDWIDTH)
2472 result = BRIDGE_MAX_BELIEVABLE_BANDWIDTH;
2473 else if (result < BRIDGE_MIN_BELIEVABLE_BANDWIDTH)
2474 result = BRIDGE_MIN_BELIEVABLE_BANDWIDTH;
2475 return result;
2478 /** Return bw*1000, unless bw*1000 would overflow, in which case return
2479 * INT32_MAX. */
2480 static inline int32_t
2481 kb_to_bytes(uint32_t bw)
2483 return (bw > (INT32_MAX/1000)) ? INT32_MAX : bw*1000;
2486 /** Helper function:
2487 * choose a random element of smartlist <b>sl</b> of nodes, weighted by
2488 * the advertised bandwidth of each element using the consensus
2489 * bandwidth weights.
2491 * If <b>rule</b>==WEIGHT_FOR_EXIT. we're picking an exit node: consider all
2492 * nodes' bandwidth equally regardless of their Exit status, since there may
2493 * be some in the list because they exit to obscure ports. If
2494 * <b>rule</b>==NO_WEIGHTING, we're picking a non-exit node: weight
2495 * exit-node's bandwidth less depending on the smallness of the fraction of
2496 * Exit-to-total bandwidth. If <b>rule</b>==WEIGHT_FOR_GUARD, we're picking a
2497 * guard node: consider all guard's bandwidth equally. Otherwise, weight
2498 * guards proportionally less.
2500 static const node_t *
2501 smartlist_choose_node_by_bandwidth_weights(const smartlist_t *sl,
2502 bandwidth_weight_rule_t rule)
2504 double *bandwidths_dbl=NULL;
2505 uint64_t *bandwidths_u64=NULL;
2507 if (compute_weighted_bandwidths(sl, rule, &bandwidths_dbl) < 0)
2508 return NULL;
2510 bandwidths_u64 = tor_calloc(smartlist_len(sl), sizeof(uint64_t));
2511 scale_array_elements_to_u64(bandwidths_u64, bandwidths_dbl,
2512 smartlist_len(sl), NULL);
2515 int idx = choose_array_element_by_weight(bandwidths_u64,
2516 smartlist_len(sl));
2517 tor_free(bandwidths_dbl);
2518 tor_free(bandwidths_u64);
2519 return idx < 0 ? NULL : smartlist_get(sl, idx);
2523 /** Given a list of routers and a weighting rule as in
2524 * smartlist_choose_node_by_bandwidth_weights, compute weighted bandwidth
2525 * values for each node and store them in a freshly allocated
2526 * *<b>bandwidths_out</b> of the same length as <b>sl</b>, and holding results
2527 * as doubles. Return 0 on success, -1 on failure. */
2528 static int
2529 compute_weighted_bandwidths(const smartlist_t *sl,
2530 bandwidth_weight_rule_t rule,
2531 double **bandwidths_out)
2533 int64_t weight_scale;
2534 double Wg = -1, Wm = -1, We = -1, Wd = -1;
2535 double Wgb = -1, Wmb = -1, Web = -1, Wdb = -1;
2536 uint64_t weighted_bw = 0;
2537 guardfraction_bandwidth_t guardfraction_bw;
2538 double *bandwidths;
2540 /* Can't choose exit and guard at same time */
2541 tor_assert(rule == NO_WEIGHTING ||
2542 rule == WEIGHT_FOR_EXIT ||
2543 rule == WEIGHT_FOR_GUARD ||
2544 rule == WEIGHT_FOR_MID ||
2545 rule == WEIGHT_FOR_DIR);
2547 if (smartlist_len(sl) == 0) {
2548 log_info(LD_CIRC,
2549 "Empty routerlist passed in to consensus weight node "
2550 "selection for rule %s",
2551 bandwidth_weight_rule_to_string(rule));
2552 return -1;
2555 weight_scale = networkstatus_get_weight_scale_param(NULL);
2557 if (rule == WEIGHT_FOR_GUARD) {
2558 Wg = networkstatus_get_bw_weight(NULL, "Wgg", -1);
2559 Wm = networkstatus_get_bw_weight(NULL, "Wgm", -1); /* Bridges */
2560 We = 0;
2561 Wd = networkstatus_get_bw_weight(NULL, "Wgd", -1);
2563 Wgb = networkstatus_get_bw_weight(NULL, "Wgb", -1);
2564 Wmb = networkstatus_get_bw_weight(NULL, "Wmb", -1);
2565 Web = networkstatus_get_bw_weight(NULL, "Web", -1);
2566 Wdb = networkstatus_get_bw_weight(NULL, "Wdb", -1);
2567 } else if (rule == WEIGHT_FOR_MID) {
2568 Wg = networkstatus_get_bw_weight(NULL, "Wmg", -1);
2569 Wm = networkstatus_get_bw_weight(NULL, "Wmm", -1);
2570 We = networkstatus_get_bw_weight(NULL, "Wme", -1);
2571 Wd = networkstatus_get_bw_weight(NULL, "Wmd", -1);
2573 Wgb = networkstatus_get_bw_weight(NULL, "Wgb", -1);
2574 Wmb = networkstatus_get_bw_weight(NULL, "Wmb", -1);
2575 Web = networkstatus_get_bw_weight(NULL, "Web", -1);
2576 Wdb = networkstatus_get_bw_weight(NULL, "Wdb", -1);
2577 } else if (rule == WEIGHT_FOR_EXIT) {
2578 // Guards CAN be exits if they have weird exit policies
2579 // They are d then I guess...
2580 We = networkstatus_get_bw_weight(NULL, "Wee", -1);
2581 Wm = networkstatus_get_bw_weight(NULL, "Wem", -1); /* Odd exit policies */
2582 Wd = networkstatus_get_bw_weight(NULL, "Wed", -1);
2583 Wg = networkstatus_get_bw_weight(NULL, "Weg", -1); /* Odd exit policies */
2585 Wgb = networkstatus_get_bw_weight(NULL, "Wgb", -1);
2586 Wmb = networkstatus_get_bw_weight(NULL, "Wmb", -1);
2587 Web = networkstatus_get_bw_weight(NULL, "Web", -1);
2588 Wdb = networkstatus_get_bw_weight(NULL, "Wdb", -1);
2589 } else if (rule == WEIGHT_FOR_DIR) {
2590 We = networkstatus_get_bw_weight(NULL, "Wbe", -1);
2591 Wm = networkstatus_get_bw_weight(NULL, "Wbm", -1);
2592 Wd = networkstatus_get_bw_weight(NULL, "Wbd", -1);
2593 Wg = networkstatus_get_bw_weight(NULL, "Wbg", -1);
2595 Wgb = Wmb = Web = Wdb = weight_scale;
2596 } else if (rule == NO_WEIGHTING) {
2597 Wg = Wm = We = Wd = weight_scale;
2598 Wgb = Wmb = Web = Wdb = weight_scale;
2601 if (Wg < 0 || Wm < 0 || We < 0 || Wd < 0 || Wgb < 0 || Wmb < 0 || Wdb < 0
2602 || Web < 0) {
2603 log_debug(LD_CIRC,
2604 "Got negative bandwidth weights. Defaulting to naive selection"
2605 " algorithm.");
2606 Wg = Wm = We = Wd = weight_scale;
2607 Wgb = Wmb = Web = Wdb = weight_scale;
2610 Wg /= weight_scale;
2611 Wm /= weight_scale;
2612 We /= weight_scale;
2613 Wd /= weight_scale;
2615 Wgb /= weight_scale;
2616 Wmb /= weight_scale;
2617 Web /= weight_scale;
2618 Wdb /= weight_scale;
2620 bandwidths = tor_calloc(smartlist_len(sl), sizeof(double));
2622 // Cycle through smartlist and total the bandwidth.
2623 static int warned_missing_bw = 0;
2624 SMARTLIST_FOREACH_BEGIN(sl, const node_t *, node) {
2625 int is_exit = 0, is_guard = 0, is_dir = 0, this_bw = 0;
2626 double weight = 1;
2627 double weight_without_guard_flag = 0; /* Used for guardfraction */
2628 double final_weight = 0;
2629 is_exit = node->is_exit && ! node->is_bad_exit;
2630 is_guard = node->is_possible_guard;
2631 is_dir = node_is_dir(node);
2632 if (node->rs) {
2633 if (!node->rs->has_bandwidth) {
2634 /* This should never happen, unless all the authorites downgrade
2635 * to 0.2.0 or rogue routerstatuses get inserted into our consensus. */
2636 if (! warned_missing_bw) {
2637 log_warn(LD_BUG,
2638 "Consensus is missing some bandwidths. Using a naive "
2639 "router selection algorithm");
2640 warned_missing_bw = 1;
2642 this_bw = 30000; /* Chosen arbitrarily */
2643 } else {
2644 this_bw = kb_to_bytes(node->rs->bandwidth_kb);
2646 } else if (node->ri) {
2647 /* bridge or other descriptor not in our consensus */
2648 this_bw = bridge_get_advertised_bandwidth_bounded(node->ri);
2649 } else {
2650 /* We can't use this one. */
2651 continue;
2654 if (is_guard && is_exit) {
2655 weight = (is_dir ? Wdb*Wd : Wd);
2656 weight_without_guard_flag = (is_dir ? Web*We : We);
2657 } else if (is_guard) {
2658 weight = (is_dir ? Wgb*Wg : Wg);
2659 weight_without_guard_flag = (is_dir ? Wmb*Wm : Wm);
2660 } else if (is_exit) {
2661 weight = (is_dir ? Web*We : We);
2662 } else { // middle
2663 weight = (is_dir ? Wmb*Wm : Wm);
2665 /* These should be impossible; but overflows here would be bad, so let's
2666 * make sure. */
2667 if (this_bw < 0)
2668 this_bw = 0;
2669 if (weight < 0.0)
2670 weight = 0.0;
2671 if (weight_without_guard_flag < 0.0)
2672 weight_without_guard_flag = 0.0;
2674 /* If guardfraction information is available in the consensus, we
2675 * want to calculate this router's bandwidth according to its
2676 * guardfraction. Quoting from proposal236:
2678 * Let Wpf denote the weight from the 'bandwidth-weights' line a
2679 * client would apply to N for position p if it had the guard
2680 * flag, Wpn the weight if it did not have the guard flag, and B the
2681 * measured bandwidth of N in the consensus. Then instead of choosing
2682 * N for position p proportionally to Wpf*B or Wpn*B, clients should
2683 * choose N proportionally to F*Wpf*B + (1-F)*Wpn*B.
2685 if (node->rs && node->rs->has_guardfraction && rule != WEIGHT_FOR_GUARD) {
2686 /* XXX The assert should actually check for is_guard. However,
2687 * that crashes dirauths because of #13297. This should be
2688 * equivalent: */
2689 tor_assert(node->rs->is_possible_guard);
2691 guard_get_guardfraction_bandwidth(&guardfraction_bw,
2692 this_bw,
2693 node->rs->guardfraction_percentage);
2695 /* Calculate final_weight = F*Wpf*B + (1-F)*Wpn*B */
2696 final_weight =
2697 guardfraction_bw.guard_bw * weight +
2698 guardfraction_bw.non_guard_bw * weight_without_guard_flag;
2700 log_debug(LD_GENERAL, "%s: Guardfraction weight %f instead of %f (%s)",
2701 node->rs->nickname, final_weight, weight*this_bw,
2702 bandwidth_weight_rule_to_string(rule));
2703 } else { /* no guardfraction information. calculate the weight normally. */
2704 final_weight = weight*this_bw;
2707 bandwidths[node_sl_idx] = final_weight + 0.5;
2708 } SMARTLIST_FOREACH_END(node);
2710 log_debug(LD_CIRC, "Generated weighted bandwidths for rule %s based "
2711 "on weights "
2712 "Wg=%f Wm=%f We=%f Wd=%f with total bw "U64_FORMAT,
2713 bandwidth_weight_rule_to_string(rule),
2714 Wg, Wm, We, Wd, U64_PRINTF_ARG(weighted_bw));
2716 *bandwidths_out = bandwidths;
2718 return 0;
2721 /** For all nodes in <b>sl</b>, return the fraction of those nodes, weighted
2722 * by their weighted bandwidths with rule <b>rule</b>, for which we have
2723 * descriptors. */
2724 double
2725 frac_nodes_with_descriptors(const smartlist_t *sl,
2726 bandwidth_weight_rule_t rule)
2728 double *bandwidths = NULL;
2729 double total, present;
2731 if (smartlist_len(sl) == 0)
2732 return 0.0;
2734 if (compute_weighted_bandwidths(sl, rule, &bandwidths) < 0) {
2735 int n_with_descs = 0;
2736 SMARTLIST_FOREACH(sl, const node_t *, node, {
2737 if (node_has_descriptor(node))
2738 n_with_descs++;
2740 return ((double)n_with_descs) / (double)smartlist_len(sl);
2743 total = present = 0.0;
2744 SMARTLIST_FOREACH_BEGIN(sl, const node_t *, node) {
2745 const double bw = bandwidths[node_sl_idx];
2746 total += bw;
2747 if (node_has_descriptor(node))
2748 present += bw;
2749 } SMARTLIST_FOREACH_END(node);
2751 tor_free(bandwidths);
2753 if (total < 1.0)
2754 return 0;
2756 return present / total;
2759 /** Choose a random element of status list <b>sl</b>, weighted by
2760 * the advertised bandwidth of each node */
2761 const node_t *
2762 node_sl_choose_by_bandwidth(const smartlist_t *sl,
2763 bandwidth_weight_rule_t rule)
2764 { /*XXXX MOVE */
2765 return smartlist_choose_node_by_bandwidth_weights(sl, rule);
2768 /** Return a random running node from the nodelist. Never
2769 * pick a node that is in
2770 * <b>excludedsmartlist</b>, or which matches <b>excludedset</b>,
2771 * even if they are the only nodes available.
2772 * If <b>CRN_NEED_UPTIME</b> is set in flags and any router has more than
2773 * a minimum uptime, return one of those.
2774 * If <b>CRN_NEED_CAPACITY</b> is set in flags, weight your choice by the
2775 * advertised capacity of each router.
2776 * If <b>CRN_ALLOW_INVALID</b> is not set in flags, consider only Valid
2777 * routers.
2778 * If <b>CRN_NEED_GUARD</b> is set in flags, consider only Guard routers.
2779 * If <b>CRN_WEIGHT_AS_EXIT</b> is set in flags, we weight bandwidths as if
2780 * picking an exit node, otherwise we weight bandwidths for picking a relay
2781 * node (that is, possibly discounting exit nodes).
2782 * If <b>CRN_NEED_DESC</b> is set in flags, we only consider nodes that
2783 * have a routerinfo or microdescriptor -- that is, enough info to be
2784 * used to build a circuit.
2785 * If <b>CRN_PREF_ADDR</b> is set in flags, we only consider nodes that
2786 * have an address that is preferred by the ClientPreferIPv6ORPort setting
2787 * (regardless of this flag, we exclude nodes that aren't allowed by the
2788 * firewall, including ClientUseIPv4 0 and fascist_firewall_use_ipv6() == 0).
2790 const node_t *
2791 router_choose_random_node(smartlist_t *excludedsmartlist,
2792 routerset_t *excludedset,
2793 router_crn_flags_t flags)
2794 { /* XXXX MOVE */
2795 const int need_uptime = (flags & CRN_NEED_UPTIME) != 0;
2796 const int need_capacity = (flags & CRN_NEED_CAPACITY) != 0;
2797 const int need_guard = (flags & CRN_NEED_GUARD) != 0;
2798 const int allow_invalid = (flags & CRN_ALLOW_INVALID) != 0;
2799 const int weight_for_exit = (flags & CRN_WEIGHT_AS_EXIT) != 0;
2800 const int need_desc = (flags & CRN_NEED_DESC) != 0;
2801 const int pref_addr = (flags & CRN_PREF_ADDR) != 0;
2802 const int direct_conn = (flags & CRN_DIRECT_CONN) != 0;
2804 smartlist_t *sl=smartlist_new(),
2805 *excludednodes=smartlist_new();
2806 const node_t *choice = NULL;
2807 const routerinfo_t *r;
2808 bandwidth_weight_rule_t rule;
2810 tor_assert(!(weight_for_exit && need_guard));
2811 rule = weight_for_exit ? WEIGHT_FOR_EXIT :
2812 (need_guard ? WEIGHT_FOR_GUARD : WEIGHT_FOR_MID);
2814 /* Exclude relays that allow single hop exit circuits, if the user
2815 * wants to (such relays might be risky) */
2816 if (get_options()->ExcludeSingleHopRelays) {
2817 SMARTLIST_FOREACH(nodelist_get_list(), node_t *, node,
2818 if (node_allows_single_hop_exits(node)) {
2819 smartlist_add(excludednodes, node);
2823 if ((r = routerlist_find_my_routerinfo()))
2824 routerlist_add_node_and_family(excludednodes, r);
2826 router_add_running_nodes_to_smartlist(sl, allow_invalid,
2827 need_uptime, need_capacity,
2828 need_guard, need_desc, pref_addr,
2829 direct_conn);
2830 log_debug(LD_CIRC,
2831 "We found %d running nodes.",
2832 smartlist_len(sl));
2834 smartlist_subtract(sl,excludednodes);
2835 log_debug(LD_CIRC,
2836 "We removed %d excludednodes, leaving %d nodes.",
2837 smartlist_len(excludednodes),
2838 smartlist_len(sl));
2840 if (excludedsmartlist) {
2841 smartlist_subtract(sl,excludedsmartlist);
2842 log_debug(LD_CIRC,
2843 "We removed %d excludedsmartlist, leaving %d nodes.",
2844 smartlist_len(excludedsmartlist),
2845 smartlist_len(sl));
2847 if (excludedset) {
2848 routerset_subtract_nodes(sl,excludedset);
2849 log_debug(LD_CIRC,
2850 "We removed excludedset, leaving %d nodes.",
2851 smartlist_len(sl));
2854 // Always weight by bandwidth
2855 choice = node_sl_choose_by_bandwidth(sl, rule);
2857 smartlist_free(sl);
2858 if (!choice && (need_uptime || need_capacity || need_guard || pref_addr)) {
2859 /* try once more -- recurse but with fewer restrictions. */
2860 log_info(LD_CIRC,
2861 "We couldn't find any live%s%s%s routers; falling back "
2862 "to list of all routers.",
2863 need_capacity?", fast":"",
2864 need_uptime?", stable":"",
2865 need_guard?", guard":"");
2866 flags &= ~ (CRN_NEED_UPTIME|CRN_NEED_CAPACITY|CRN_NEED_GUARD|
2867 CRN_PREF_ADDR);
2868 choice = router_choose_random_node(
2869 excludedsmartlist, excludedset, flags);
2871 smartlist_free(excludednodes);
2872 if (!choice) {
2873 log_warn(LD_CIRC,
2874 "No available nodes when trying to choose node. Failing.");
2876 return choice;
2879 /** Helper: given an extended nickname in <b>hexdigest</b> try to decode it.
2880 * Return 0 on success, -1 on failure. Store the result into the
2881 * DIGEST_LEN-byte buffer at <b>digest_out</b>, the single character at
2882 * <b>nickname_qualifier_char_out</b>, and the MAXNICKNAME_LEN+1-byte buffer
2883 * at <b>nickname_out</b>.
2885 * The recognized format is:
2886 * HexName = Dollar? HexDigest NamePart?
2887 * Dollar = '?'
2888 * HexDigest = HexChar*20
2889 * HexChar = 'a'..'f' | 'A'..'F' | '0'..'9'
2890 * NamePart = QualChar Name
2891 * QualChar = '=' | '~'
2892 * Name = NameChar*(1..MAX_NICKNAME_LEN)
2893 * NameChar = Any ASCII alphanumeric character
2896 hex_digest_nickname_decode(const char *hexdigest,
2897 char *digest_out,
2898 char *nickname_qualifier_char_out,
2899 char *nickname_out)
2901 size_t len;
2903 tor_assert(hexdigest);
2904 if (hexdigest[0] == '$')
2905 ++hexdigest;
2907 len = strlen(hexdigest);
2908 if (len < HEX_DIGEST_LEN) {
2909 return -1;
2910 } else if (len > HEX_DIGEST_LEN && (hexdigest[HEX_DIGEST_LEN] == '=' ||
2911 hexdigest[HEX_DIGEST_LEN] == '~') &&
2912 len <= HEX_DIGEST_LEN+1+MAX_NICKNAME_LEN) {
2913 *nickname_qualifier_char_out = hexdigest[HEX_DIGEST_LEN];
2914 strlcpy(nickname_out, hexdigest+HEX_DIGEST_LEN+1 , MAX_NICKNAME_LEN+1);
2915 } else if (len == HEX_DIGEST_LEN) {
2917 } else {
2918 return -1;
2921 if (base16_decode(digest_out, DIGEST_LEN,
2922 hexdigest, HEX_DIGEST_LEN) != DIGEST_LEN)
2923 return -1;
2924 return 0;
2927 /** Helper: Return true iff the <b>identity_digest</b> and <b>nickname</b>
2928 * combination of a router, encoded in hexadecimal, matches <b>hexdigest</b>
2929 * (which is optionally prefixed with a single dollar sign). Return false if
2930 * <b>hexdigest</b> is malformed, or it doesn't match. */
2932 hex_digest_nickname_matches(const char *hexdigest, const char *identity_digest,
2933 const char *nickname, int is_named)
2935 char digest[DIGEST_LEN];
2936 char nn_char='\0';
2937 char nn_buf[MAX_NICKNAME_LEN+1];
2939 if (hex_digest_nickname_decode(hexdigest, digest, &nn_char, nn_buf) == -1)
2940 return 0;
2942 if (nn_char == '=' || nn_char == '~') {
2943 if (!nickname)
2944 return 0;
2945 if (strcasecmp(nn_buf, nickname))
2946 return 0;
2947 if (nn_char == '=' && !is_named)
2948 return 0;
2951 return tor_memeq(digest, identity_digest, DIGEST_LEN);
2954 /** Return true iff <b>router</b> is listed as named in the current
2955 * consensus. */
2957 router_is_named(const routerinfo_t *router)
2959 const char *digest =
2960 networkstatus_get_router_digest_by_nickname(router->nickname);
2962 return (digest &&
2963 tor_memeq(digest, router->cache_info.identity_digest, DIGEST_LEN));
2966 /** Return true iff <b>digest</b> is the digest of the identity key of a
2967 * trusted directory matching at least one bit of <b>type</b>. If <b>type</b>
2968 * is zero (NO_DIRINFO), or ALL_DIRINFO, any authority is okay. */
2970 router_digest_is_trusted_dir_type(const char *digest, dirinfo_type_t type)
2972 if (!trusted_dir_servers)
2973 return 0;
2974 if (authdir_mode(get_options()) && router_digest_is_me(digest))
2975 return 1;
2976 SMARTLIST_FOREACH(trusted_dir_servers, dir_server_t *, ent,
2977 if (tor_memeq(digest, ent->digest, DIGEST_LEN)) {
2978 return (!type) || ((type & ent->type) != 0);
2980 return 0;
2983 /** If hexdigest is correctly formed, base16_decode it into
2984 * digest, which must have DIGEST_LEN space in it.
2985 * Return 0 on success, -1 on failure.
2988 hexdigest_to_digest(const char *hexdigest, char *digest)
2990 if (hexdigest[0]=='$')
2991 ++hexdigest;
2992 if (strlen(hexdigest) < HEX_DIGEST_LEN ||
2993 base16_decode(digest,DIGEST_LEN,hexdigest,HEX_DIGEST_LEN) != DIGEST_LEN)
2994 return -1;
2995 return 0;
2998 /** As router_get_by_id_digest,but return a pointer that you're allowed to
2999 * modify */
3000 routerinfo_t *
3001 router_get_mutable_by_digest(const char *digest)
3003 tor_assert(digest);
3005 if (!routerlist) return NULL;
3007 // routerlist_assert_ok(routerlist);
3009 return rimap_get(routerlist->identity_map, digest);
3012 /** Return the router in our routerlist whose 20-byte key digest
3013 * is <b>digest</b>. Return NULL if no such router is known. */
3014 const routerinfo_t *
3015 router_get_by_id_digest(const char *digest)
3017 return router_get_mutable_by_digest(digest);
3020 /** Return the router in our routerlist whose 20-byte descriptor
3021 * is <b>digest</b>. Return NULL if no such router is known. */
3022 signed_descriptor_t *
3023 router_get_by_descriptor_digest(const char *digest)
3025 tor_assert(digest);
3027 if (!routerlist) return NULL;
3029 return sdmap_get(routerlist->desc_digest_map, digest);
3032 /** Return the signed descriptor for the router in our routerlist whose
3033 * 20-byte extra-info digest is <b>digest</b>. Return NULL if no such router
3034 * is known. */
3035 MOCK_IMPL(signed_descriptor_t *,
3036 router_get_by_extrainfo_digest,(const char *digest))
3038 tor_assert(digest);
3040 if (!routerlist) return NULL;
3042 return sdmap_get(routerlist->desc_by_eid_map, digest);
3045 /** Return the signed descriptor for the extrainfo_t in our routerlist whose
3046 * extra-info-digest is <b>digest</b>. Return NULL if no such extra-info
3047 * document is known. */
3048 signed_descriptor_t *
3049 extrainfo_get_by_descriptor_digest(const char *digest)
3051 extrainfo_t *ei;
3052 tor_assert(digest);
3053 if (!routerlist) return NULL;
3054 ei = eimap_get(routerlist->extra_info_map, digest);
3055 return ei ? &ei->cache_info : NULL;
3058 /** Return a pointer to the signed textual representation of a descriptor.
3059 * The returned string is not guaranteed to be NUL-terminated: the string's
3060 * length will be in desc-\>signed_descriptor_len.
3062 * If <b>with_annotations</b> is set, the returned string will include
3063 * the annotations
3064 * (if any) preceding the descriptor. This will increase the length of the
3065 * string by desc-\>annotations_len.
3067 * The caller must not free the string returned.
3069 static const char *
3070 signed_descriptor_get_body_impl(const signed_descriptor_t *desc,
3071 int with_annotations)
3073 const char *r = NULL;
3074 size_t len = desc->signed_descriptor_len;
3075 off_t offset = desc->saved_offset;
3076 if (with_annotations)
3077 len += desc->annotations_len;
3078 else
3079 offset += desc->annotations_len;
3081 tor_assert(len > 32);
3082 if (desc->saved_location == SAVED_IN_CACHE && routerlist) {
3083 desc_store_t *store = desc_get_store(router_get_routerlist(), desc);
3084 if (store && store->mmap) {
3085 tor_assert(desc->saved_offset + len <= store->mmap->size);
3086 r = store->mmap->data + offset;
3087 } else if (store) {
3088 log_err(LD_DIR, "We couldn't read a descriptor that is supposedly "
3089 "mmaped in our cache. Is another process running in our data "
3090 "directory? Exiting.");
3091 exit(1);
3094 if (!r) /* no mmap, or not in cache. */
3095 r = desc->signed_descriptor_body +
3096 (with_annotations ? 0 : desc->annotations_len);
3098 tor_assert(r);
3099 if (!with_annotations) {
3100 if (fast_memcmp("router ", r, 7) && fast_memcmp("extra-info ", r, 11)) {
3101 char *cp = tor_strndup(r, 64);
3102 log_err(LD_DIR, "descriptor at %p begins with unexpected string %s. "
3103 "Is another process running in our data directory? Exiting.",
3104 desc, escaped(cp));
3105 exit(1);
3109 return r;
3112 /** Return a pointer to the signed textual representation of a descriptor.
3113 * The returned string is not guaranteed to be NUL-terminated: the string's
3114 * length will be in desc-\>signed_descriptor_len.
3116 * The caller must not free the string returned.
3118 const char *
3119 signed_descriptor_get_body(const signed_descriptor_t *desc)
3121 return signed_descriptor_get_body_impl(desc, 0);
3124 /** As signed_descriptor_get_body(), but points to the beginning of the
3125 * annotations section rather than the beginning of the descriptor. */
3126 const char *
3127 signed_descriptor_get_annotations(const signed_descriptor_t *desc)
3129 return signed_descriptor_get_body_impl(desc, 1);
3132 /** Return the current list of all known routers. */
3133 routerlist_t *
3134 router_get_routerlist(void)
3136 if (PREDICT_UNLIKELY(!routerlist)) {
3137 routerlist = tor_malloc_zero(sizeof(routerlist_t));
3138 routerlist->routers = smartlist_new();
3139 routerlist->old_routers = smartlist_new();
3140 routerlist->identity_map = rimap_new();
3141 routerlist->desc_digest_map = sdmap_new();
3142 routerlist->desc_by_eid_map = sdmap_new();
3143 routerlist->extra_info_map = eimap_new();
3145 routerlist->desc_store.fname_base = "cached-descriptors";
3146 routerlist->extrainfo_store.fname_base = "cached-extrainfo";
3148 routerlist->desc_store.type = ROUTER_STORE;
3149 routerlist->extrainfo_store.type = EXTRAINFO_STORE;
3151 routerlist->desc_store.description = "router descriptors";
3152 routerlist->extrainfo_store.description = "extra-info documents";
3154 return routerlist;
3157 /** Free all storage held by <b>router</b>. */
3158 void
3159 routerinfo_free(routerinfo_t *router)
3161 if (!router)
3162 return;
3164 tor_free(router->cache_info.signed_descriptor_body);
3165 tor_free(router->nickname);
3166 tor_free(router->platform);
3167 tor_free(router->protocol_list);
3168 tor_free(router->contact_info);
3169 if (router->onion_pkey)
3170 crypto_pk_free(router->onion_pkey);
3171 tor_free(router->onion_curve25519_pkey);
3172 if (router->identity_pkey)
3173 crypto_pk_free(router->identity_pkey);
3174 tor_cert_free(router->cache_info.signing_key_cert);
3175 if (router->declared_family) {
3176 SMARTLIST_FOREACH(router->declared_family, char *, s, tor_free(s));
3177 smartlist_free(router->declared_family);
3179 addr_policy_list_free(router->exit_policy);
3180 short_policy_free(router->ipv6_exit_policy);
3182 memset(router, 77, sizeof(routerinfo_t));
3184 tor_free(router);
3187 /** Release all storage held by <b>extrainfo</b> */
3188 void
3189 extrainfo_free(extrainfo_t *extrainfo)
3191 if (!extrainfo)
3192 return;
3193 tor_cert_free(extrainfo->cache_info.signing_key_cert);
3194 tor_free(extrainfo->cache_info.signed_descriptor_body);
3195 tor_free(extrainfo->pending_sig);
3197 memset(extrainfo, 88, sizeof(extrainfo_t)); /* debug bad memory usage */
3198 tor_free(extrainfo);
3201 /** Release storage held by <b>sd</b>. */
3202 static void
3203 signed_descriptor_free(signed_descriptor_t *sd)
3205 if (!sd)
3206 return;
3208 tor_free(sd->signed_descriptor_body);
3209 tor_cert_free(sd->signing_key_cert);
3211 memset(sd, 99, sizeof(signed_descriptor_t)); /* Debug bad mem usage */
3212 tor_free(sd);
3215 /** Reset the given signed descriptor <b>sd</b> by freeing the allocated
3216 * memory inside the object and by zeroing its content. */
3217 static void
3218 signed_descriptor_reset(signed_descriptor_t *sd)
3220 tor_assert(sd);
3221 tor_free(sd->signed_descriptor_body);
3222 tor_cert_free(sd->signing_key_cert);
3223 memset(sd, 0, sizeof(*sd));
3226 /** Copy src into dest, and steal all references inside src so that when
3227 * we free src, we don't mess up dest. */
3228 static void
3229 signed_descriptor_move(signed_descriptor_t *dest,
3230 signed_descriptor_t *src)
3232 tor_assert(dest != src);
3233 /* Cleanup destination object before overwriting it.*/
3234 signed_descriptor_reset(dest);
3235 memcpy(dest, src, sizeof(signed_descriptor_t));
3236 src->signed_descriptor_body = NULL;
3237 src->signing_key_cert = NULL;
3238 dest->routerlist_index = -1;
3241 /** Extract a signed_descriptor_t from a general routerinfo, and free the
3242 * routerinfo.
3244 static signed_descriptor_t *
3245 signed_descriptor_from_routerinfo(routerinfo_t *ri)
3247 signed_descriptor_t *sd;
3248 tor_assert(ri->purpose == ROUTER_PURPOSE_GENERAL);
3249 sd = tor_malloc_zero(sizeof(signed_descriptor_t));
3250 signed_descriptor_move(sd, &ri->cache_info);
3251 routerinfo_free(ri);
3252 return sd;
3255 /** Helper: free the storage held by the extrainfo_t in <b>e</b>. */
3256 static void
3257 extrainfo_free_(void *e)
3259 extrainfo_free(e);
3262 /** Free all storage held by a routerlist <b>rl</b>. */
3263 void
3264 routerlist_free(routerlist_t *rl)
3266 if (!rl)
3267 return;
3268 rimap_free(rl->identity_map, NULL);
3269 sdmap_free(rl->desc_digest_map, NULL);
3270 sdmap_free(rl->desc_by_eid_map, NULL);
3271 eimap_free(rl->extra_info_map, extrainfo_free_);
3272 SMARTLIST_FOREACH(rl->routers, routerinfo_t *, r,
3273 routerinfo_free(r));
3274 SMARTLIST_FOREACH(rl->old_routers, signed_descriptor_t *, sd,
3275 signed_descriptor_free(sd));
3276 smartlist_free(rl->routers);
3277 smartlist_free(rl->old_routers);
3278 if (rl->desc_store.mmap) {
3279 int res = tor_munmap_file(routerlist->desc_store.mmap);
3280 if (res != 0) {
3281 log_warn(LD_FS, "Failed to munmap routerlist->desc_store.mmap");
3284 if (rl->extrainfo_store.mmap) {
3285 int res = tor_munmap_file(routerlist->extrainfo_store.mmap);
3286 if (res != 0) {
3287 log_warn(LD_FS, "Failed to munmap routerlist->extrainfo_store.mmap");
3290 tor_free(rl);
3292 router_dir_info_changed();
3295 /** Log information about how much memory is being used for routerlist,
3296 * at log level <b>severity</b>. */
3297 void
3298 dump_routerlist_mem_usage(int severity)
3300 uint64_t livedescs = 0;
3301 uint64_t olddescs = 0;
3302 if (!routerlist)
3303 return;
3304 SMARTLIST_FOREACH(routerlist->routers, routerinfo_t *, r,
3305 livedescs += r->cache_info.signed_descriptor_len);
3306 SMARTLIST_FOREACH(routerlist->old_routers, signed_descriptor_t *, sd,
3307 olddescs += sd->signed_descriptor_len);
3309 tor_log(severity, LD_DIR,
3310 "In %d live descriptors: "U64_FORMAT" bytes. "
3311 "In %d old descriptors: "U64_FORMAT" bytes.",
3312 smartlist_len(routerlist->routers), U64_PRINTF_ARG(livedescs),
3313 smartlist_len(routerlist->old_routers), U64_PRINTF_ARG(olddescs));
3316 /** Debugging helper: If <b>idx</b> is nonnegative, assert that <b>ri</b> is
3317 * in <b>sl</b> at position <b>idx</b>. Otherwise, search <b>sl</b> for
3318 * <b>ri</b>. Return the index of <b>ri</b> in <b>sl</b>, or -1 if <b>ri</b>
3319 * is not in <b>sl</b>. */
3320 static inline int
3321 routerlist_find_elt_(smartlist_t *sl, void *ri, int idx)
3323 if (idx < 0) {
3324 idx = -1;
3325 SMARTLIST_FOREACH(sl, routerinfo_t *, r,
3326 if (r == ri) {
3327 idx = r_sl_idx;
3328 break;
3330 } else {
3331 tor_assert(idx < smartlist_len(sl));
3332 tor_assert(smartlist_get(sl, idx) == ri);
3334 return idx;
3337 /** Insert an item <b>ri</b> into the routerlist <b>rl</b>, updating indices
3338 * as needed. There must be no previous member of <b>rl</b> with the same
3339 * identity digest as <b>ri</b>: If there is, call routerlist_replace
3340 * instead.
3342 static void
3343 routerlist_insert(routerlist_t *rl, routerinfo_t *ri)
3345 routerinfo_t *ri_old;
3346 signed_descriptor_t *sd_old;
3348 const routerinfo_t *ri_generated = router_get_my_routerinfo();
3349 tor_assert(ri_generated != ri);
3351 tor_assert(ri->cache_info.routerlist_index == -1);
3353 ri_old = rimap_set(rl->identity_map, ri->cache_info.identity_digest, ri);
3354 tor_assert(!ri_old);
3356 sd_old = sdmap_set(rl->desc_digest_map,
3357 ri->cache_info.signed_descriptor_digest,
3358 &(ri->cache_info));
3359 if (sd_old) {
3360 int idx = sd_old->routerlist_index;
3361 sd_old->routerlist_index = -1;
3362 smartlist_del(rl->old_routers, idx);
3363 if (idx < smartlist_len(rl->old_routers)) {
3364 signed_descriptor_t *d = smartlist_get(rl->old_routers, idx);
3365 d->routerlist_index = idx;
3367 rl->desc_store.bytes_dropped += sd_old->signed_descriptor_len;
3368 sdmap_remove(rl->desc_by_eid_map, sd_old->extra_info_digest);
3369 signed_descriptor_free(sd_old);
3372 if (!tor_digest_is_zero(ri->cache_info.extra_info_digest))
3373 sdmap_set(rl->desc_by_eid_map, ri->cache_info.extra_info_digest,
3374 &ri->cache_info);
3375 smartlist_add(rl->routers, ri);
3376 ri->cache_info.routerlist_index = smartlist_len(rl->routers) - 1;
3377 nodelist_set_routerinfo(ri, NULL);
3378 router_dir_info_changed();
3379 #ifdef DEBUG_ROUTERLIST
3380 routerlist_assert_ok(rl);
3381 #endif
3384 /** Adds the extrainfo_t <b>ei</b> to the routerlist <b>rl</b>, if there is a
3385 * corresponding router in rl-\>routers or rl-\>old_routers. Return the status
3386 * of inserting <b>ei</b>. Free <b>ei</b> if it isn't inserted. */
3387 MOCK_IMPL(STATIC was_router_added_t,
3388 extrainfo_insert,(routerlist_t *rl, extrainfo_t *ei, int warn_if_incompatible))
3390 was_router_added_t r;
3391 const char *compatibility_error_msg;
3392 routerinfo_t *ri = rimap_get(rl->identity_map,
3393 ei->cache_info.identity_digest);
3394 signed_descriptor_t *sd =
3395 sdmap_get(rl->desc_by_eid_map, ei->cache_info.signed_descriptor_digest);
3396 extrainfo_t *ei_tmp;
3397 const int severity = warn_if_incompatible ? LOG_WARN : LOG_INFO;
3400 extrainfo_t *ei_generated = router_get_my_extrainfo();
3401 tor_assert(ei_generated != ei);
3404 if (!ri) {
3405 /* This router is unknown; we can't even verify the signature. Give up.*/
3406 r = ROUTER_NOT_IN_CONSENSUS;
3407 goto done;
3409 if (! sd) {
3410 /* The extrainfo router doesn't have a known routerdesc to attach it to.
3411 * This just won't work. */;
3412 static ratelim_t no_sd_ratelim = RATELIM_INIT(1800);
3413 r = ROUTER_BAD_EI;
3414 log_fn_ratelim(&no_sd_ratelim, severity, LD_BUG,
3415 "No entry found in extrainfo map.");
3416 goto done;
3418 if (tor_memneq(ei->cache_info.signed_descriptor_digest,
3419 sd->extra_info_digest, DIGEST_LEN)) {
3420 static ratelim_t digest_mismatch_ratelim = RATELIM_INIT(1800);
3421 /* The sd we got from the map doesn't match the digest we used to look
3422 * it up. This makes no sense. */
3423 r = ROUTER_BAD_EI;
3424 log_fn_ratelim(&digest_mismatch_ratelim, severity, LD_BUG,
3425 "Mismatch in digest in extrainfo map.");
3426 goto done;
3428 if (routerinfo_incompatible_with_extrainfo(ri->identity_pkey, ei, sd,
3429 &compatibility_error_msg)) {
3430 char d1[HEX_DIGEST_LEN+1], d2[HEX_DIGEST_LEN+1];
3431 r = (ri->cache_info.extrainfo_is_bogus) ?
3432 ROUTER_BAD_EI : ROUTER_NOT_IN_CONSENSUS;
3434 base16_encode(d1, sizeof(d1), ri->cache_info.identity_digest, DIGEST_LEN);
3435 base16_encode(d2, sizeof(d2), ei->cache_info.identity_digest, DIGEST_LEN);
3437 log_fn(severity,LD_DIR,
3438 "router info incompatible with extra info (ri id: %s, ei id %s, "
3439 "reason: %s)", d1, d2, compatibility_error_msg);
3441 goto done;
3444 /* Okay, if we make it here, we definitely have a router corresponding to
3445 * this extrainfo. */
3447 ei_tmp = eimap_set(rl->extra_info_map,
3448 ei->cache_info.signed_descriptor_digest,
3449 ei);
3450 r = ROUTER_ADDED_SUCCESSFULLY;
3451 if (ei_tmp) {
3452 rl->extrainfo_store.bytes_dropped +=
3453 ei_tmp->cache_info.signed_descriptor_len;
3454 extrainfo_free(ei_tmp);
3457 done:
3458 if (r != ROUTER_ADDED_SUCCESSFULLY)
3459 extrainfo_free(ei);
3461 #ifdef DEBUG_ROUTERLIST
3462 routerlist_assert_ok(rl);
3463 #endif
3464 return r;
3467 #define should_cache_old_descriptors() \
3468 directory_caches_dir_info(get_options())
3470 /** If we're a directory cache and routerlist <b>rl</b> doesn't have
3471 * a copy of router <b>ri</b> yet, add it to the list of old (not
3472 * recommended but still served) descriptors. Else free it. */
3473 static void
3474 routerlist_insert_old(routerlist_t *rl, routerinfo_t *ri)
3477 const routerinfo_t *ri_generated = router_get_my_routerinfo();
3478 tor_assert(ri_generated != ri);
3480 tor_assert(ri->cache_info.routerlist_index == -1);
3482 if (should_cache_old_descriptors() &&
3483 ri->purpose == ROUTER_PURPOSE_GENERAL &&
3484 !sdmap_get(rl->desc_digest_map,
3485 ri->cache_info.signed_descriptor_digest)) {
3486 signed_descriptor_t *sd = signed_descriptor_from_routerinfo(ri);
3487 sdmap_set(rl->desc_digest_map, sd->signed_descriptor_digest, sd);
3488 smartlist_add(rl->old_routers, sd);
3489 sd->routerlist_index = smartlist_len(rl->old_routers)-1;
3490 if (!tor_digest_is_zero(sd->extra_info_digest))
3491 sdmap_set(rl->desc_by_eid_map, sd->extra_info_digest, sd);
3492 } else {
3493 routerinfo_free(ri);
3495 #ifdef DEBUG_ROUTERLIST
3496 routerlist_assert_ok(rl);
3497 #endif
3500 /** Remove an item <b>ri</b> from the routerlist <b>rl</b>, updating indices
3501 * as needed. If <b>idx</b> is nonnegative and smartlist_get(rl-&gt;routers,
3502 * idx) == ri, we don't need to do a linear search over the list to decide
3503 * which to remove. We fill the gap in rl-&gt;routers with a later element in
3504 * the list, if any exists. <b>ri</b> is freed.
3506 * If <b>make_old</b> is true, instead of deleting the router, we try adding
3507 * it to rl-&gt;old_routers. */
3508 void
3509 routerlist_remove(routerlist_t *rl, routerinfo_t *ri, int make_old, time_t now)
3511 routerinfo_t *ri_tmp;
3512 extrainfo_t *ei_tmp;
3513 int idx = ri->cache_info.routerlist_index;
3514 tor_assert(0 <= idx && idx < smartlist_len(rl->routers));
3515 tor_assert(smartlist_get(rl->routers, idx) == ri);
3517 nodelist_remove_routerinfo(ri);
3519 /* make sure the rephist module knows that it's not running */
3520 rep_hist_note_router_unreachable(ri->cache_info.identity_digest, now);
3522 ri->cache_info.routerlist_index = -1;
3523 smartlist_del(rl->routers, idx);
3524 if (idx < smartlist_len(rl->routers)) {
3525 routerinfo_t *r = smartlist_get(rl->routers, idx);
3526 r->cache_info.routerlist_index = idx;
3529 ri_tmp = rimap_remove(rl->identity_map, ri->cache_info.identity_digest);
3530 router_dir_info_changed();
3531 tor_assert(ri_tmp == ri);
3533 if (make_old && should_cache_old_descriptors() &&
3534 ri->purpose == ROUTER_PURPOSE_GENERAL) {
3535 signed_descriptor_t *sd;
3536 sd = signed_descriptor_from_routerinfo(ri);
3537 smartlist_add(rl->old_routers, sd);
3538 sd->routerlist_index = smartlist_len(rl->old_routers)-1;
3539 sdmap_set(rl->desc_digest_map, sd->signed_descriptor_digest, sd);
3540 if (!tor_digest_is_zero(sd->extra_info_digest))
3541 sdmap_set(rl->desc_by_eid_map, sd->extra_info_digest, sd);
3542 } else {
3543 signed_descriptor_t *sd_tmp;
3544 sd_tmp = sdmap_remove(rl->desc_digest_map,
3545 ri->cache_info.signed_descriptor_digest);
3546 tor_assert(sd_tmp == &(ri->cache_info));
3547 rl->desc_store.bytes_dropped += ri->cache_info.signed_descriptor_len;
3548 ei_tmp = eimap_remove(rl->extra_info_map,
3549 ri->cache_info.extra_info_digest);
3550 if (ei_tmp) {
3551 rl->extrainfo_store.bytes_dropped +=
3552 ei_tmp->cache_info.signed_descriptor_len;
3553 extrainfo_free(ei_tmp);
3555 if (!tor_digest_is_zero(ri->cache_info.extra_info_digest))
3556 sdmap_remove(rl->desc_by_eid_map, ri->cache_info.extra_info_digest);
3557 routerinfo_free(ri);
3559 #ifdef DEBUG_ROUTERLIST
3560 routerlist_assert_ok(rl);
3561 #endif
3564 /** Remove a signed_descriptor_t <b>sd</b> from <b>rl</b>-\>old_routers, and
3565 * adjust <b>rl</b> as appropriate. <b>idx</b> is -1, or the index of
3566 * <b>sd</b>. */
3567 static void
3568 routerlist_remove_old(routerlist_t *rl, signed_descriptor_t *sd, int idx)
3570 signed_descriptor_t *sd_tmp;
3571 extrainfo_t *ei_tmp;
3572 desc_store_t *store;
3573 if (idx == -1) {
3574 idx = sd->routerlist_index;
3576 tor_assert(0 <= idx && idx < smartlist_len(rl->old_routers));
3577 /* XXXX edmanm's bridge relay triggered the following assert while
3578 * running 0.2.0.12-alpha. If anybody triggers this again, see if we
3579 * can get a backtrace. */
3580 tor_assert(smartlist_get(rl->old_routers, idx) == sd);
3581 tor_assert(idx == sd->routerlist_index);
3583 sd->routerlist_index = -1;
3584 smartlist_del(rl->old_routers, idx);
3585 if (idx < smartlist_len(rl->old_routers)) {
3586 signed_descriptor_t *d = smartlist_get(rl->old_routers, idx);
3587 d->routerlist_index = idx;
3589 sd_tmp = sdmap_remove(rl->desc_digest_map,
3590 sd->signed_descriptor_digest);
3591 tor_assert(sd_tmp == sd);
3592 store = desc_get_store(rl, sd);
3593 if (store)
3594 store->bytes_dropped += sd->signed_descriptor_len;
3596 ei_tmp = eimap_remove(rl->extra_info_map,
3597 sd->extra_info_digest);
3598 if (ei_tmp) {
3599 rl->extrainfo_store.bytes_dropped +=
3600 ei_tmp->cache_info.signed_descriptor_len;
3601 extrainfo_free(ei_tmp);
3603 if (!tor_digest_is_zero(sd->extra_info_digest))
3604 sdmap_remove(rl->desc_by_eid_map, sd->extra_info_digest);
3606 signed_descriptor_free(sd);
3607 #ifdef DEBUG_ROUTERLIST
3608 routerlist_assert_ok(rl);
3609 #endif
3612 /** Remove <b>ri_old</b> from the routerlist <b>rl</b>, and replace it with
3613 * <b>ri_new</b>, updating all index info. If <b>idx</b> is nonnegative and
3614 * smartlist_get(rl-&gt;routers, idx) == ri, we don't need to do a linear
3615 * search over the list to decide which to remove. We put ri_new in the same
3616 * index as ri_old, if possible. ri is freed as appropriate.
3618 * If should_cache_descriptors() is true, instead of deleting the router,
3619 * we add it to rl-&gt;old_routers. */
3620 static void
3621 routerlist_replace(routerlist_t *rl, routerinfo_t *ri_old,
3622 routerinfo_t *ri_new)
3624 int idx;
3625 int same_descriptors;
3627 routerinfo_t *ri_tmp;
3628 extrainfo_t *ei_tmp;
3630 const routerinfo_t *ri_generated = router_get_my_routerinfo();
3631 tor_assert(ri_generated != ri_new);
3633 tor_assert(ri_old != ri_new);
3634 tor_assert(ri_new->cache_info.routerlist_index == -1);
3636 idx = ri_old->cache_info.routerlist_index;
3637 tor_assert(0 <= idx && idx < smartlist_len(rl->routers));
3638 tor_assert(smartlist_get(rl->routers, idx) == ri_old);
3641 routerinfo_t *ri_old_tmp=NULL;
3642 nodelist_set_routerinfo(ri_new, &ri_old_tmp);
3643 tor_assert(ri_old == ri_old_tmp);
3646 router_dir_info_changed();
3647 if (idx >= 0) {
3648 smartlist_set(rl->routers, idx, ri_new);
3649 ri_old->cache_info.routerlist_index = -1;
3650 ri_new->cache_info.routerlist_index = idx;
3651 /* Check that ri_old is not in rl->routers anymore: */
3652 tor_assert( routerlist_find_elt_(rl->routers, ri_old, -1) == -1 );
3653 } else {
3654 log_warn(LD_BUG, "Appending entry from routerlist_replace.");
3655 routerlist_insert(rl, ri_new);
3656 return;
3658 if (tor_memneq(ri_old->cache_info.identity_digest,
3659 ri_new->cache_info.identity_digest, DIGEST_LEN)) {
3660 /* digests don't match; digestmap_set won't replace */
3661 rimap_remove(rl->identity_map, ri_old->cache_info.identity_digest);
3663 ri_tmp = rimap_set(rl->identity_map,
3664 ri_new->cache_info.identity_digest, ri_new);
3665 tor_assert(!ri_tmp || ri_tmp == ri_old);
3666 sdmap_set(rl->desc_digest_map,
3667 ri_new->cache_info.signed_descriptor_digest,
3668 &(ri_new->cache_info));
3670 if (!tor_digest_is_zero(ri_new->cache_info.extra_info_digest)) {
3671 sdmap_set(rl->desc_by_eid_map, ri_new->cache_info.extra_info_digest,
3672 &ri_new->cache_info);
3675 same_descriptors = tor_memeq(ri_old->cache_info.signed_descriptor_digest,
3676 ri_new->cache_info.signed_descriptor_digest,
3677 DIGEST_LEN);
3679 if (should_cache_old_descriptors() &&
3680 ri_old->purpose == ROUTER_PURPOSE_GENERAL &&
3681 !same_descriptors) {
3682 /* ri_old is going to become a signed_descriptor_t and go into
3683 * old_routers */
3684 signed_descriptor_t *sd = signed_descriptor_from_routerinfo(ri_old);
3685 smartlist_add(rl->old_routers, sd);
3686 sd->routerlist_index = smartlist_len(rl->old_routers)-1;
3687 sdmap_set(rl->desc_digest_map, sd->signed_descriptor_digest, sd);
3688 if (!tor_digest_is_zero(sd->extra_info_digest))
3689 sdmap_set(rl->desc_by_eid_map, sd->extra_info_digest, sd);
3690 } else {
3691 /* We're dropping ri_old. */
3692 if (!same_descriptors) {
3693 /* digests don't match; The sdmap_set above didn't replace */
3694 sdmap_remove(rl->desc_digest_map,
3695 ri_old->cache_info.signed_descriptor_digest);
3697 if (tor_memneq(ri_old->cache_info.extra_info_digest,
3698 ri_new->cache_info.extra_info_digest, DIGEST_LEN)) {
3699 ei_tmp = eimap_remove(rl->extra_info_map,
3700 ri_old->cache_info.extra_info_digest);
3701 if (ei_tmp) {
3702 rl->extrainfo_store.bytes_dropped +=
3703 ei_tmp->cache_info.signed_descriptor_len;
3704 extrainfo_free(ei_tmp);
3708 if (!tor_digest_is_zero(ri_old->cache_info.extra_info_digest)) {
3709 sdmap_remove(rl->desc_by_eid_map,
3710 ri_old->cache_info.extra_info_digest);
3713 rl->desc_store.bytes_dropped += ri_old->cache_info.signed_descriptor_len;
3714 routerinfo_free(ri_old);
3716 #ifdef DEBUG_ROUTERLIST
3717 routerlist_assert_ok(rl);
3718 #endif
3721 /** Extract the descriptor <b>sd</b> from old_routerlist, and re-parse
3722 * it as a fresh routerinfo_t. */
3723 static routerinfo_t *
3724 routerlist_reparse_old(routerlist_t *rl, signed_descriptor_t *sd)
3726 routerinfo_t *ri;
3727 const char *body;
3729 body = signed_descriptor_get_annotations(sd);
3731 ri = router_parse_entry_from_string(body,
3732 body+sd->signed_descriptor_len+sd->annotations_len,
3733 0, 1, NULL, NULL);
3734 if (!ri)
3735 return NULL;
3736 signed_descriptor_move(&ri->cache_info, sd);
3738 routerlist_remove_old(rl, sd, -1);
3740 return ri;
3743 /** Free all memory held by the routerlist module.
3744 * Note: Calling routerlist_free_all() should always be paired with
3745 * a call to nodelist_free_all(). These should only be called during
3746 * cleanup.
3748 void
3749 routerlist_free_all(void)
3751 routerlist_free(routerlist);
3752 routerlist = NULL;
3753 if (warned_nicknames) {
3754 SMARTLIST_FOREACH(warned_nicknames, char *, cp, tor_free(cp));
3755 smartlist_free(warned_nicknames);
3756 warned_nicknames = NULL;
3758 clear_dir_servers();
3759 smartlist_free(trusted_dir_servers);
3760 smartlist_free(fallback_dir_servers);
3761 trusted_dir_servers = fallback_dir_servers = NULL;
3762 if (trusted_dir_certs) {
3763 digestmap_free(trusted_dir_certs, cert_list_free_);
3764 trusted_dir_certs = NULL;
3768 /** Forget that we have issued any router-related warnings, so that we'll
3769 * warn again if we see the same errors. */
3770 void
3771 routerlist_reset_warnings(void)
3773 if (!warned_nicknames)
3774 warned_nicknames = smartlist_new();
3775 SMARTLIST_FOREACH(warned_nicknames, char *, cp, tor_free(cp));
3776 smartlist_clear(warned_nicknames); /* now the list is empty. */
3778 networkstatus_reset_warnings();
3781 /** Return 1 if the signed descriptor of this router is older than
3782 * <b>seconds</b> seconds. Otherwise return 0. */
3783 MOCK_IMPL(int,
3784 router_descriptor_is_older_than,(const routerinfo_t *router, int seconds))
3786 return router->cache_info.published_on < approx_time() - seconds;
3789 /** Add <b>router</b> to the routerlist, if we don't already have it. Replace
3790 * older entries (if any) with the same key. Note: Callers should not hold
3791 * their pointers to <b>router</b> if this function fails; <b>router</b>
3792 * will either be inserted into the routerlist or freed. Similarly, even
3793 * if this call succeeds, they should not hold their pointers to
3794 * <b>router</b> after subsequent calls with other routerinfo's -- they
3795 * might cause the original routerinfo to get freed.
3797 * Returns the status for the operation. Might set *<b>msg</b> if it wants
3798 * the poster of the router to know something.
3800 * If <b>from_cache</b>, this descriptor came from our disk cache. If
3801 * <b>from_fetch</b>, we received it in response to a request we made.
3802 * (If both are false, that means it was uploaded to us as an auth dir
3803 * server or via the controller.)
3805 * This function should be called *after*
3806 * routers_update_status_from_consensus_networkstatus; subsequently, you
3807 * should call router_rebuild_store and routerlist_descriptors_added.
3809 was_router_added_t
3810 router_add_to_routerlist(routerinfo_t *router, const char **msg,
3811 int from_cache, int from_fetch)
3813 const char *id_digest;
3814 const or_options_t *options = get_options();
3815 int authdir = authdir_mode_handles_descs(options, router->purpose);
3816 int authdir_believes_valid = 0;
3817 routerinfo_t *old_router;
3818 networkstatus_t *consensus =
3819 networkstatus_get_latest_consensus_by_flavor(FLAV_NS);
3820 int in_consensus = 0;
3822 tor_assert(msg);
3824 if (!routerlist)
3825 router_get_routerlist();
3827 id_digest = router->cache_info.identity_digest;
3829 old_router = router_get_mutable_by_digest(id_digest);
3831 /* Make sure that it isn't expired. */
3832 if (router->cert_expiration_time < approx_time()) {
3833 routerinfo_free(router);
3834 *msg = "Some certs on this router are expired.";
3835 return ROUTER_CERTS_EXPIRED;
3838 /* Make sure that we haven't already got this exact descriptor. */
3839 if (sdmap_get(routerlist->desc_digest_map,
3840 router->cache_info.signed_descriptor_digest)) {
3841 /* If we have this descriptor already and the new descriptor is a bridge
3842 * descriptor, replace it. If we had a bridge descriptor before and the
3843 * new one is not a bridge descriptor, don't replace it. */
3845 /* Only members of routerlist->identity_map can be bridges; we don't
3846 * put bridges in old_routers. */
3847 const int was_bridge = old_router &&
3848 old_router->purpose == ROUTER_PURPOSE_BRIDGE;
3850 if (routerinfo_is_a_configured_bridge(router) &&
3851 router->purpose == ROUTER_PURPOSE_BRIDGE &&
3852 !was_bridge) {
3853 log_info(LD_DIR, "Replacing non-bridge descriptor with bridge "
3854 "descriptor for router %s",
3855 router_describe(router));
3856 } else {
3857 log_info(LD_DIR,
3858 "Dropping descriptor that we already have for router %s",
3859 router_describe(router));
3860 *msg = "Router descriptor was not new.";
3861 routerinfo_free(router);
3862 return ROUTER_IS_ALREADY_KNOWN;
3866 if (authdir) {
3867 if (authdir_wants_to_reject_router(router, msg,
3868 !from_cache && !from_fetch,
3869 &authdir_believes_valid)) {
3870 tor_assert(*msg);
3871 routerinfo_free(router);
3872 return ROUTER_AUTHDIR_REJECTS;
3874 } else if (from_fetch) {
3875 /* Only check the descriptor digest against the network statuses when
3876 * we are receiving in response to a fetch. */
3878 if (!signed_desc_digest_is_recognized(&router->cache_info) &&
3879 !routerinfo_is_a_configured_bridge(router)) {
3880 /* We asked for it, so some networkstatus must have listed it when we
3881 * did. Save it if we're a cache in case somebody else asks for it. */
3882 log_info(LD_DIR,
3883 "Received a no-longer-recognized descriptor for router %s",
3884 router_describe(router));
3885 *msg = "Router descriptor is not referenced by any network-status.";
3887 /* Only journal this desc if we want to keep old descriptors */
3888 if (!from_cache && should_cache_old_descriptors())
3889 signed_desc_append_to_journal(&router->cache_info,
3890 &routerlist->desc_store);
3891 routerlist_insert_old(routerlist, router);
3892 return ROUTER_NOT_IN_CONSENSUS_OR_NETWORKSTATUS;
3896 /* We no longer need a router with this descriptor digest. */
3897 if (consensus) {
3898 routerstatus_t *rs = networkstatus_vote_find_mutable_entry(
3899 consensus, id_digest);
3900 if (rs && tor_memeq(rs->descriptor_digest,
3901 router->cache_info.signed_descriptor_digest,
3902 DIGEST_LEN)) {
3903 in_consensus = 1;
3907 if (router->purpose == ROUTER_PURPOSE_GENERAL &&
3908 consensus && !in_consensus && !authdir) {
3909 /* If it's a general router not listed in the consensus, then don't
3910 * consider replacing the latest router with it. */
3911 if (!from_cache && should_cache_old_descriptors())
3912 signed_desc_append_to_journal(&router->cache_info,
3913 &routerlist->desc_store);
3914 routerlist_insert_old(routerlist, router);
3915 *msg = "Skipping router descriptor: not in consensus.";
3916 return ROUTER_NOT_IN_CONSENSUS;
3919 /* If we're reading a bridge descriptor from our cache, and we don't
3920 * recognize it as one of our currently configured bridges, drop the
3921 * descriptor. Otherwise we could end up using it as one of our entry
3922 * guards even if it isn't in our Bridge config lines. */
3923 if (router->purpose == ROUTER_PURPOSE_BRIDGE && from_cache &&
3924 !authdir_mode_bridge(options) &&
3925 !routerinfo_is_a_configured_bridge(router)) {
3926 log_info(LD_DIR, "Dropping bridge descriptor for %s because we have "
3927 "no bridge configured at that address.",
3928 safe_str_client(router_describe(router)));
3929 *msg = "Router descriptor was not a configured bridge.";
3930 routerinfo_free(router);
3931 return ROUTER_WAS_NOT_WANTED;
3934 /* If we have a router with the same identity key, choose the newer one. */
3935 if (old_router) {
3936 if (!in_consensus && (router->cache_info.published_on <=
3937 old_router->cache_info.published_on)) {
3938 /* Same key, but old. This one is not listed in the consensus. */
3939 log_debug(LD_DIR, "Not-new descriptor for router %s",
3940 router_describe(router));
3941 /* Only journal this desc if we'll be serving it. */
3942 if (!from_cache && should_cache_old_descriptors())
3943 signed_desc_append_to_journal(&router->cache_info,
3944 &routerlist->desc_store);
3945 routerlist_insert_old(routerlist, router);
3946 *msg = "Router descriptor was not new.";
3947 return ROUTER_IS_ALREADY_KNOWN;
3948 } else {
3949 /* Same key, and either new, or listed in the consensus. */
3950 log_debug(LD_DIR, "Replacing entry for router %s",
3951 router_describe(router));
3952 routerlist_replace(routerlist, old_router, router);
3953 if (!from_cache) {
3954 signed_desc_append_to_journal(&router->cache_info,
3955 &routerlist->desc_store);
3957 *msg = authdir_believes_valid ? "Valid server updated" :
3958 ("Invalid server updated. (This dirserver is marking your "
3959 "server as unapproved.)");
3960 return ROUTER_ADDED_SUCCESSFULLY;
3964 if (!in_consensus && from_cache &&
3965 router_descriptor_is_older_than(router, OLD_ROUTER_DESC_MAX_AGE)) {
3966 *msg = "Router descriptor was really old.";
3967 routerinfo_free(router);
3968 return ROUTER_WAS_TOO_OLD;
3971 /* We haven't seen a router with this identity before. Add it to the end of
3972 * the list. */
3973 routerlist_insert(routerlist, router);
3974 if (!from_cache) {
3975 signed_desc_append_to_journal(&router->cache_info,
3976 &routerlist->desc_store);
3978 return ROUTER_ADDED_SUCCESSFULLY;
3981 /** Insert <b>ei</b> into the routerlist, or free it. Other arguments are
3982 * as for router_add_to_routerlist(). Return ROUTER_ADDED_SUCCESSFULLY iff
3983 * we actually inserted it, ROUTER_BAD_EI otherwise.
3985 was_router_added_t
3986 router_add_extrainfo_to_routerlist(extrainfo_t *ei, const char **msg,
3987 int from_cache, int from_fetch)
3989 was_router_added_t inserted;
3990 (void)from_fetch;
3991 if (msg) *msg = NULL;
3992 /*XXXX Do something with msg */
3994 inserted = extrainfo_insert(router_get_routerlist(), ei, !from_cache);
3996 if (WRA_WAS_ADDED(inserted) && !from_cache)
3997 signed_desc_append_to_journal(&ei->cache_info,
3998 &routerlist->extrainfo_store);
4000 return inserted;
4003 /** Sorting helper: return &lt;0, 0, or &gt;0 depending on whether the
4004 * signed_descriptor_t* in *<b>a</b> has an identity digest preceding, equal
4005 * to, or later than that of *<b>b</b>. */
4006 static int
4007 compare_old_routers_by_identity_(const void **_a, const void **_b)
4009 int i;
4010 const signed_descriptor_t *r1 = *_a, *r2 = *_b;
4011 if ((i = fast_memcmp(r1->identity_digest, r2->identity_digest, DIGEST_LEN)))
4012 return i;
4013 return (int)(r1->published_on - r2->published_on);
4016 /** Internal type used to represent how long an old descriptor was valid,
4017 * where it appeared in the list of old descriptors, and whether it's extra
4018 * old. Used only by routerlist_remove_old_cached_routers_with_id(). */
4019 struct duration_idx_t {
4020 int duration;
4021 int idx;
4022 int old;
4025 /** Sorting helper: compare two duration_idx_t by their duration. */
4026 static int
4027 compare_duration_idx_(const void *_d1, const void *_d2)
4029 const struct duration_idx_t *d1 = _d1;
4030 const struct duration_idx_t *d2 = _d2;
4031 return d1->duration - d2->duration;
4034 /** The range <b>lo</b> through <b>hi</b> inclusive of routerlist->old_routers
4035 * must contain routerinfo_t with the same identity and with publication time
4036 * in ascending order. Remove members from this range until there are no more
4037 * than max_descriptors_per_router() remaining. Start by removing the oldest
4038 * members from before <b>cutoff</b>, then remove members which were current
4039 * for the lowest amount of time. The order of members of old_routers at
4040 * indices <b>lo</b> or higher may be changed.
4042 static void
4043 routerlist_remove_old_cached_routers_with_id(time_t now,
4044 time_t cutoff, int lo, int hi,
4045 digestset_t *retain)
4047 int i, n = hi-lo+1;
4048 unsigned n_extra, n_rmv = 0;
4049 struct duration_idx_t *lifespans;
4050 uint8_t *rmv, *must_keep;
4051 smartlist_t *lst = routerlist->old_routers;
4052 #if 1
4053 const char *ident;
4054 tor_assert(hi < smartlist_len(lst));
4055 tor_assert(lo <= hi);
4056 ident = ((signed_descriptor_t*)smartlist_get(lst, lo))->identity_digest;
4057 for (i = lo+1; i <= hi; ++i) {
4058 signed_descriptor_t *r = smartlist_get(lst, i);
4059 tor_assert(tor_memeq(ident, r->identity_digest, DIGEST_LEN));
4061 #endif
4062 /* Check whether we need to do anything at all. */
4064 int mdpr = directory_caches_dir_info(get_options()) ? 2 : 1;
4065 if (n <= mdpr)
4066 return;
4067 n_extra = n - mdpr;
4070 lifespans = tor_calloc(n, sizeof(struct duration_idx_t));
4071 rmv = tor_calloc(n, sizeof(uint8_t));
4072 must_keep = tor_calloc(n, sizeof(uint8_t));
4073 /* Set lifespans to contain the lifespan and index of each server. */
4074 /* Set rmv[i-lo]=1 if we're going to remove a server for being too old. */
4075 for (i = lo; i <= hi; ++i) {
4076 signed_descriptor_t *r = smartlist_get(lst, i);
4077 signed_descriptor_t *r_next;
4078 lifespans[i-lo].idx = i;
4079 if (r->last_listed_as_valid_until >= now ||
4080 (retain && digestset_contains(retain, r->signed_descriptor_digest))) {
4081 must_keep[i-lo] = 1;
4083 if (i < hi) {
4084 r_next = smartlist_get(lst, i+1);
4085 tor_assert(r->published_on <= r_next->published_on);
4086 lifespans[i-lo].duration = (int)(r_next->published_on - r->published_on);
4087 } else {
4088 r_next = NULL;
4089 lifespans[i-lo].duration = INT_MAX;
4091 if (!must_keep[i-lo] && r->published_on < cutoff && n_rmv < n_extra) {
4092 ++n_rmv;
4093 lifespans[i-lo].old = 1;
4094 rmv[i-lo] = 1;
4098 if (n_rmv < n_extra) {
4100 * We aren't removing enough servers for being old. Sort lifespans by
4101 * the duration of liveness, and remove the ones we're not already going to
4102 * remove based on how long they were alive.
4104 qsort(lifespans, n, sizeof(struct duration_idx_t), compare_duration_idx_);
4105 for (i = 0; i < n && n_rmv < n_extra; ++i) {
4106 if (!must_keep[lifespans[i].idx-lo] && !lifespans[i].old) {
4107 rmv[lifespans[i].idx-lo] = 1;
4108 ++n_rmv;
4113 i = hi;
4114 do {
4115 if (rmv[i-lo])
4116 routerlist_remove_old(routerlist, smartlist_get(lst, i), i);
4117 } while (--i >= lo);
4118 tor_free(must_keep);
4119 tor_free(rmv);
4120 tor_free(lifespans);
4123 /** Deactivate any routers from the routerlist that are more than
4124 * ROUTER_MAX_AGE seconds old and not recommended by any networkstatuses;
4125 * remove old routers from the list of cached routers if we have too many.
4127 void
4128 routerlist_remove_old_routers(void)
4130 int i, hi=-1;
4131 const char *cur_id = NULL;
4132 time_t now = time(NULL);
4133 time_t cutoff;
4134 routerinfo_t *router;
4135 signed_descriptor_t *sd;
4136 digestset_t *retain;
4137 const networkstatus_t *consensus = networkstatus_get_latest_consensus();
4139 trusted_dirs_remove_old_certs();
4141 if (!routerlist || !consensus)
4142 return;
4144 // routerlist_assert_ok(routerlist);
4146 /* We need to guess how many router descriptors we will wind up wanting to
4147 retain, so that we can be sure to allocate a large enough Bloom filter
4148 to hold the digest set. Overestimating is fine; underestimating is bad.
4151 /* We'll probably retain everything in the consensus. */
4152 int n_max_retain = smartlist_len(consensus->routerstatus_list);
4153 retain = digestset_new(n_max_retain);
4156 cutoff = now - OLD_ROUTER_DESC_MAX_AGE;
4157 /* Retain anything listed in the consensus. */
4158 if (consensus) {
4159 SMARTLIST_FOREACH(consensus->routerstatus_list, routerstatus_t *, rs,
4160 if (rs->published_on >= cutoff)
4161 digestset_add(retain, rs->descriptor_digest));
4164 /* If we have a consensus, we should consider pruning current routers that
4165 * are too old and that nobody recommends. (If we don't have a consensus,
4166 * then we should get one before we decide to kill routers.) */
4168 if (consensus) {
4169 cutoff = now - ROUTER_MAX_AGE;
4170 /* Remove too-old unrecommended members of routerlist->routers. */
4171 for (i = 0; i < smartlist_len(routerlist->routers); ++i) {
4172 router = smartlist_get(routerlist->routers, i);
4173 if (router->cache_info.published_on <= cutoff &&
4174 router->cache_info.last_listed_as_valid_until < now &&
4175 !digestset_contains(retain,
4176 router->cache_info.signed_descriptor_digest)) {
4177 /* Too old: remove it. (If we're a cache, just move it into
4178 * old_routers.) */
4179 log_info(LD_DIR,
4180 "Forgetting obsolete (too old) routerinfo for router %s",
4181 router_describe(router));
4182 routerlist_remove(routerlist, router, 1, now);
4183 i--;
4188 //routerlist_assert_ok(routerlist);
4190 /* Remove far-too-old members of routerlist->old_routers. */
4191 cutoff = now - OLD_ROUTER_DESC_MAX_AGE;
4192 for (i = 0; i < smartlist_len(routerlist->old_routers); ++i) {
4193 sd = smartlist_get(routerlist->old_routers, i);
4194 if (sd->published_on <= cutoff &&
4195 sd->last_listed_as_valid_until < now &&
4196 !digestset_contains(retain, sd->signed_descriptor_digest)) {
4197 /* Too old. Remove it. */
4198 routerlist_remove_old(routerlist, sd, i--);
4202 //routerlist_assert_ok(routerlist);
4204 log_info(LD_DIR, "We have %d live routers and %d old router descriptors.",
4205 smartlist_len(routerlist->routers),
4206 smartlist_len(routerlist->old_routers));
4208 /* Now we might have to look at routerlist->old_routers for extraneous
4209 * members. (We'd keep all the members if we could, but we need to save
4210 * space.) First, check whether we have too many router descriptors, total.
4211 * We're okay with having too many for some given router, so long as the
4212 * total number doesn't approach max_descriptors_per_router()*len(router).
4214 if (smartlist_len(routerlist->old_routers) <
4215 smartlist_len(routerlist->routers))
4216 goto done;
4218 /* Sort by identity, then fix indices. */
4219 smartlist_sort(routerlist->old_routers, compare_old_routers_by_identity_);
4220 /* Fix indices. */
4221 for (i = 0; i < smartlist_len(routerlist->old_routers); ++i) {
4222 signed_descriptor_t *r = smartlist_get(routerlist->old_routers, i);
4223 r->routerlist_index = i;
4226 /* Iterate through the list from back to front, so when we remove descriptors
4227 * we don't mess up groups we haven't gotten to. */
4228 for (i = smartlist_len(routerlist->old_routers)-1; i >= 0; --i) {
4229 signed_descriptor_t *r = smartlist_get(routerlist->old_routers, i);
4230 if (!cur_id) {
4231 cur_id = r->identity_digest;
4232 hi = i;
4234 if (tor_memneq(cur_id, r->identity_digest, DIGEST_LEN)) {
4235 routerlist_remove_old_cached_routers_with_id(now,
4236 cutoff, i+1, hi, retain);
4237 cur_id = r->identity_digest;
4238 hi = i;
4241 if (hi>=0)
4242 routerlist_remove_old_cached_routers_with_id(now, cutoff, 0, hi, retain);
4243 //routerlist_assert_ok(routerlist);
4245 done:
4246 digestset_free(retain);
4247 router_rebuild_store(RRS_DONT_REMOVE_OLD, &routerlist->desc_store);
4248 router_rebuild_store(RRS_DONT_REMOVE_OLD,&routerlist->extrainfo_store);
4251 /** We just added a new set of descriptors. Take whatever extra steps
4252 * we need. */
4253 void
4254 routerlist_descriptors_added(smartlist_t *sl, int from_cache)
4256 tor_assert(sl);
4257 control_event_descriptors_changed(sl);
4258 SMARTLIST_FOREACH_BEGIN(sl, routerinfo_t *, ri) {
4259 if (ri->purpose == ROUTER_PURPOSE_BRIDGE)
4260 learned_bridge_descriptor(ri, from_cache);
4261 if (ri->needs_retest_if_added) {
4262 ri->needs_retest_if_added = 0;
4263 dirserv_single_reachability_test(approx_time(), ri);
4265 } SMARTLIST_FOREACH_END(ri);
4269 * Code to parse a single router descriptor and insert it into the
4270 * routerlist. Return -1 if the descriptor was ill-formed; 0 if the
4271 * descriptor was well-formed but could not be added; and 1 if the
4272 * descriptor was added.
4274 * If we don't add it and <b>msg</b> is not NULL, then assign to
4275 * *<b>msg</b> a static string describing the reason for refusing the
4276 * descriptor.
4278 * This is used only by the controller.
4281 router_load_single_router(const char *s, uint8_t purpose, int cache,
4282 const char **msg)
4284 routerinfo_t *ri;
4285 was_router_added_t r;
4286 smartlist_t *lst;
4287 char annotation_buf[ROUTER_ANNOTATION_BUF_LEN];
4288 tor_assert(msg);
4289 *msg = NULL;
4291 tor_snprintf(annotation_buf, sizeof(annotation_buf),
4292 "@source controller\n"
4293 "@purpose %s\n", router_purpose_to_string(purpose));
4295 if (!(ri = router_parse_entry_from_string(s, NULL, 1, 0,
4296 annotation_buf, NULL))) {
4297 log_warn(LD_DIR, "Error parsing router descriptor; dropping.");
4298 *msg = "Couldn't parse router descriptor.";
4299 return -1;
4301 tor_assert(ri->purpose == purpose);
4302 if (router_is_me(ri)) {
4303 log_warn(LD_DIR, "Router's identity key matches mine; dropping.");
4304 *msg = "Router's identity key matches mine.";
4305 routerinfo_free(ri);
4306 return 0;
4309 if (!cache) /* obey the preference of the controller */
4310 ri->cache_info.do_not_cache = 1;
4312 lst = smartlist_new();
4313 smartlist_add(lst, ri);
4314 routers_update_status_from_consensus_networkstatus(lst, 0);
4316 r = router_add_to_routerlist(ri, msg, 0, 0);
4317 if (!WRA_WAS_ADDED(r)) {
4318 /* we've already assigned to *msg now, and ri is already freed */
4319 tor_assert(*msg);
4320 if (r == ROUTER_AUTHDIR_REJECTS)
4321 log_warn(LD_DIR, "Couldn't add router to list: %s Dropping.", *msg);
4322 smartlist_free(lst);
4323 return 0;
4324 } else {
4325 routerlist_descriptors_added(lst, 0);
4326 smartlist_free(lst);
4327 log_debug(LD_DIR, "Added router to list");
4328 return 1;
4332 /** Given a string <b>s</b> containing some routerdescs, parse it and put the
4333 * routers into our directory. If saved_location is SAVED_NOWHERE, the routers
4334 * are in response to a query to the network: cache them by adding them to
4335 * the journal.
4337 * Return the number of routers actually added.
4339 * If <b>requested_fingerprints</b> is provided, it must contain a list of
4340 * uppercased fingerprints. Do not update any router whose
4341 * fingerprint is not on the list; after updating a router, remove its
4342 * fingerprint from the list.
4344 * If <b>descriptor_digests</b> is non-zero, then the requested_fingerprints
4345 * are descriptor digests. Otherwise they are identity digests.
4348 router_load_routers_from_string(const char *s, const char *eos,
4349 saved_location_t saved_location,
4350 smartlist_t *requested_fingerprints,
4351 int descriptor_digests,
4352 const char *prepend_annotations)
4354 smartlist_t *routers = smartlist_new(), *changed = smartlist_new();
4355 char fp[HEX_DIGEST_LEN+1];
4356 const char *msg;
4357 int from_cache = (saved_location != SAVED_NOWHERE);
4358 int allow_annotations = (saved_location != SAVED_NOWHERE);
4359 int any_changed = 0;
4360 smartlist_t *invalid_digests = smartlist_new();
4362 router_parse_list_from_string(&s, eos, routers, saved_location, 0,
4363 allow_annotations, prepend_annotations,
4364 invalid_digests);
4366 routers_update_status_from_consensus_networkstatus(routers, !from_cache);
4368 log_info(LD_DIR, "%d elements to add", smartlist_len(routers));
4370 SMARTLIST_FOREACH_BEGIN(routers, routerinfo_t *, ri) {
4371 was_router_added_t r;
4372 char d[DIGEST_LEN];
4373 if (requested_fingerprints) {
4374 base16_encode(fp, sizeof(fp), descriptor_digests ?
4375 ri->cache_info.signed_descriptor_digest :
4376 ri->cache_info.identity_digest,
4377 DIGEST_LEN);
4378 if (smartlist_contains_string(requested_fingerprints, fp)) {
4379 smartlist_string_remove(requested_fingerprints, fp);
4380 } else {
4381 char *requested =
4382 smartlist_join_strings(requested_fingerprints," ",0,NULL);
4383 log_warn(LD_DIR,
4384 "We received a router descriptor with a fingerprint (%s) "
4385 "that we never requested. (We asked for: %s.) Dropping.",
4386 fp, requested);
4387 tor_free(requested);
4388 routerinfo_free(ri);
4389 continue;
4393 memcpy(d, ri->cache_info.signed_descriptor_digest, DIGEST_LEN);
4394 r = router_add_to_routerlist(ri, &msg, from_cache, !from_cache);
4395 if (WRA_WAS_ADDED(r)) {
4396 any_changed++;
4397 smartlist_add(changed, ri);
4398 routerlist_descriptors_added(changed, from_cache);
4399 smartlist_clear(changed);
4400 } else if (WRA_NEVER_DOWNLOADABLE(r)) {
4401 download_status_t *dl_status;
4402 dl_status = router_get_dl_status_by_descriptor_digest(d);
4403 if (dl_status) {
4404 log_info(LD_GENERAL, "Marking router %s as never downloadable",
4405 hex_str(d, DIGEST_LEN));
4406 download_status_mark_impossible(dl_status);
4409 } SMARTLIST_FOREACH_END(ri);
4411 SMARTLIST_FOREACH_BEGIN(invalid_digests, const uint8_t *, bad_digest) {
4412 /* This digest is never going to be parseable. */
4413 base16_encode(fp, sizeof(fp), (char*)bad_digest, DIGEST_LEN);
4414 if (requested_fingerprints && descriptor_digests) {
4415 if (! smartlist_contains_string(requested_fingerprints, fp)) {
4416 /* But we didn't ask for it, so we should assume shennanegans. */
4417 continue;
4419 smartlist_string_remove(requested_fingerprints, fp);
4421 download_status_t *dls;
4422 dls = router_get_dl_status_by_descriptor_digest((char*)bad_digest);
4423 if (dls) {
4424 log_info(LD_GENERAL, "Marking router with descriptor %s as unparseable, "
4425 "and therefore undownloadable", fp);
4426 download_status_mark_impossible(dls);
4428 } SMARTLIST_FOREACH_END(bad_digest);
4429 SMARTLIST_FOREACH(invalid_digests, uint8_t *, d, tor_free(d));
4430 smartlist_free(invalid_digests);
4432 routerlist_assert_ok(routerlist);
4434 if (any_changed)
4435 router_rebuild_store(0, &routerlist->desc_store);
4437 smartlist_free(routers);
4438 smartlist_free(changed);
4440 return any_changed;
4443 /** Parse one or more extrainfos from <b>s</b> (ending immediately before
4444 * <b>eos</b> if <b>eos</b> is present). Other arguments are as for
4445 * router_load_routers_from_string(). */
4446 void
4447 router_load_extrainfo_from_string(const char *s, const char *eos,
4448 saved_location_t saved_location,
4449 smartlist_t *requested_fingerprints,
4450 int descriptor_digests)
4452 smartlist_t *extrainfo_list = smartlist_new();
4453 const char *msg;
4454 int from_cache = (saved_location != SAVED_NOWHERE);
4455 smartlist_t *invalid_digests = smartlist_new();
4457 router_parse_list_from_string(&s, eos, extrainfo_list, saved_location, 1, 0,
4458 NULL, invalid_digests);
4460 log_info(LD_DIR, "%d elements to add", smartlist_len(extrainfo_list));
4462 SMARTLIST_FOREACH_BEGIN(extrainfo_list, extrainfo_t *, ei) {
4463 uint8_t d[DIGEST_LEN];
4464 memcpy(d, ei->cache_info.signed_descriptor_digest, DIGEST_LEN);
4465 was_router_added_t added =
4466 router_add_extrainfo_to_routerlist(ei, &msg, from_cache, !from_cache);
4467 if (WRA_WAS_ADDED(added) && requested_fingerprints) {
4468 char fp[HEX_DIGEST_LEN+1];
4469 base16_encode(fp, sizeof(fp), descriptor_digests ?
4470 ei->cache_info.signed_descriptor_digest :
4471 ei->cache_info.identity_digest,
4472 DIGEST_LEN);
4473 smartlist_string_remove(requested_fingerprints, fp);
4474 /* We silently let relays stuff us with extrainfos we didn't ask for,
4475 * so long as we would have wanted them anyway. Since we always fetch
4476 * all the extrainfos we want, and we never actually act on them
4477 * inside Tor, this should be harmless. */
4478 } else if (WRA_NEVER_DOWNLOADABLE(added)) {
4479 signed_descriptor_t *sd = router_get_by_extrainfo_digest((char*)d);
4480 if (sd) {
4481 log_info(LD_GENERAL, "Marking extrainfo with descriptor %s as "
4482 "unparseable, and therefore undownloadable",
4483 hex_str((char*)d,DIGEST_LEN));
4484 download_status_mark_impossible(&sd->ei_dl_status);
4487 } SMARTLIST_FOREACH_END(ei);
4489 SMARTLIST_FOREACH_BEGIN(invalid_digests, const uint8_t *, bad_digest) {
4490 /* This digest is never going to be parseable. */
4491 char fp[HEX_DIGEST_LEN+1];
4492 base16_encode(fp, sizeof(fp), (char*)bad_digest, DIGEST_LEN);
4493 if (requested_fingerprints) {
4494 if (! smartlist_contains_string(requested_fingerprints, fp)) {
4495 /* But we didn't ask for it, so we should assume shennanegans. */
4496 continue;
4498 smartlist_string_remove(requested_fingerprints, fp);
4500 signed_descriptor_t *sd =
4501 router_get_by_extrainfo_digest((char*)bad_digest);
4502 if (sd) {
4503 log_info(LD_GENERAL, "Marking extrainfo with descriptor %s as "
4504 "unparseable, and therefore undownloadable", fp);
4505 download_status_mark_impossible(&sd->ei_dl_status);
4507 } SMARTLIST_FOREACH_END(bad_digest);
4508 SMARTLIST_FOREACH(invalid_digests, uint8_t *, d, tor_free(d));
4509 smartlist_free(invalid_digests);
4511 routerlist_assert_ok(routerlist);
4512 router_rebuild_store(0, &router_get_routerlist()->extrainfo_store);
4514 smartlist_free(extrainfo_list);
4517 /** Return true iff the latest ns-flavored consensus includes a descriptor
4518 * whose digest is that of <b>desc</b>. */
4519 static int
4520 signed_desc_digest_is_recognized(signed_descriptor_t *desc)
4522 const routerstatus_t *rs;
4523 networkstatus_t *consensus = networkstatus_get_latest_consensus_by_flavor(
4524 FLAV_NS);
4526 if (consensus) {
4527 rs = networkstatus_vote_find_entry(consensus, desc->identity_digest);
4528 if (rs && tor_memeq(rs->descriptor_digest,
4529 desc->signed_descriptor_digest, DIGEST_LEN))
4530 return 1;
4532 return 0;
4535 /** Update downloads for router descriptors and/or microdescriptors as
4536 * appropriate. */
4537 void
4538 update_all_descriptor_downloads(time_t now)
4540 if (get_options()->DisableNetwork)
4541 return;
4542 update_router_descriptor_downloads(now);
4543 update_microdesc_downloads(now);
4544 launch_dummy_descriptor_download_as_needed(now, get_options());
4547 /** Clear all our timeouts for fetching v3 directory stuff, and then
4548 * give it all a try again. */
4549 void
4550 routerlist_retry_directory_downloads(time_t now)
4552 (void)now;
4554 log_debug(LD_GENERAL,
4555 "In routerlist_retry_directory_downloads()");
4557 router_reset_status_download_failures();
4558 router_reset_descriptor_download_failures();
4559 reschedule_directory_downloads();
4562 /** Return true iff <b>router</b> does not permit exit streams.
4565 router_exit_policy_rejects_all(const routerinfo_t *router)
4567 return router->policy_is_reject_star;
4570 /** Create a directory server at <b>address</b>:<b>port</b>, with OR identity
4571 * key <b>digest</b> which has DIGEST_LEN bytes. If <b>address</b> is NULL,
4572 * add ourself. If <b>is_authority</b>, this is a directory authority. Return
4573 * the new directory server entry on success or NULL on failure. */
4574 static dir_server_t *
4575 dir_server_new(int is_authority,
4576 const char *nickname,
4577 const tor_addr_t *addr,
4578 const char *hostname,
4579 uint16_t dir_port, uint16_t or_port,
4580 const tor_addr_port_t *addrport_ipv6,
4581 const char *digest, const char *v3_auth_digest,
4582 dirinfo_type_t type,
4583 double weight)
4585 dir_server_t *ent;
4586 uint32_t a;
4587 char *hostname_ = NULL;
4589 tor_assert(digest);
4591 if (weight < 0)
4592 return NULL;
4594 if (tor_addr_family(addr) == AF_INET)
4595 a = tor_addr_to_ipv4h(addr);
4596 else
4597 return NULL;
4599 if (!hostname)
4600 hostname_ = tor_addr_to_str_dup(addr);
4601 else
4602 hostname_ = tor_strdup(hostname);
4604 ent = tor_malloc_zero(sizeof(dir_server_t));
4605 ent->nickname = nickname ? tor_strdup(nickname) : NULL;
4606 ent->address = hostname_;
4607 ent->addr = a;
4608 ent->dir_port = dir_port;
4609 ent->or_port = or_port;
4610 ent->is_running = 1;
4611 ent->is_authority = is_authority;
4612 ent->type = type;
4613 ent->weight = weight;
4614 if (addrport_ipv6) {
4615 if (tor_addr_family(&addrport_ipv6->addr) != AF_INET6) {
4616 log_warn(LD_BUG, "Hey, I got a non-ipv6 addr as addrport_ipv6.");
4617 tor_addr_make_unspec(&ent->ipv6_addr);
4618 } else {
4619 tor_addr_copy(&ent->ipv6_addr, &addrport_ipv6->addr);
4620 ent->ipv6_orport = addrport_ipv6->port;
4622 } else {
4623 tor_addr_make_unspec(&ent->ipv6_addr);
4626 memcpy(ent->digest, digest, DIGEST_LEN);
4627 if (v3_auth_digest && (type & V3_DIRINFO))
4628 memcpy(ent->v3_identity_digest, v3_auth_digest, DIGEST_LEN);
4630 if (nickname)
4631 tor_asprintf(&ent->description, "directory server \"%s\" at %s:%d",
4632 nickname, hostname_, (int)dir_port);
4633 else
4634 tor_asprintf(&ent->description, "directory server at %s:%d",
4635 hostname_, (int)dir_port);
4637 ent->fake_status.addr = ent->addr;
4638 tor_addr_copy(&ent->fake_status.ipv6_addr, &ent->ipv6_addr);
4639 memcpy(ent->fake_status.identity_digest, digest, DIGEST_LEN);
4640 if (nickname)
4641 strlcpy(ent->fake_status.nickname, nickname,
4642 sizeof(ent->fake_status.nickname));
4643 else
4644 ent->fake_status.nickname[0] = '\0';
4645 ent->fake_status.dir_port = ent->dir_port;
4646 ent->fake_status.or_port = ent->or_port;
4647 ent->fake_status.ipv6_orport = ent->ipv6_orport;
4649 return ent;
4652 /** Create an authoritative directory server at
4653 * <b>address</b>:<b>port</b>, with identity key <b>digest</b>. If
4654 * <b>address</b> is NULL, add ourself. Return the new trusted directory
4655 * server entry on success or NULL if we couldn't add it. */
4656 dir_server_t *
4657 trusted_dir_server_new(const char *nickname, const char *address,
4658 uint16_t dir_port, uint16_t or_port,
4659 const tor_addr_port_t *ipv6_addrport,
4660 const char *digest, const char *v3_auth_digest,
4661 dirinfo_type_t type, double weight)
4663 uint32_t a;
4664 tor_addr_t addr;
4665 char *hostname=NULL;
4666 dir_server_t *result;
4668 if (!address) { /* The address is us; we should guess. */
4669 if (resolve_my_address(LOG_WARN, get_options(),
4670 &a, NULL, &hostname) < 0) {
4671 log_warn(LD_CONFIG,
4672 "Couldn't find a suitable address when adding ourself as a "
4673 "trusted directory server.");
4674 return NULL;
4676 if (!hostname)
4677 hostname = tor_dup_ip(a);
4678 } else {
4679 if (tor_lookup_hostname(address, &a)) {
4680 log_warn(LD_CONFIG,
4681 "Unable to lookup address for directory server at '%s'",
4682 address);
4683 return NULL;
4685 hostname = tor_strdup(address);
4687 tor_addr_from_ipv4h(&addr, a);
4689 result = dir_server_new(1, nickname, &addr, hostname,
4690 dir_port, or_port,
4691 ipv6_addrport,
4692 digest,
4693 v3_auth_digest, type, weight);
4694 tor_free(hostname);
4695 return result;
4698 /** Return a new dir_server_t for a fallback directory server at
4699 * <b>addr</b>:<b>or_port</b>/<b>dir_port</b>, with identity key digest
4700 * <b>id_digest</b> */
4701 dir_server_t *
4702 fallback_dir_server_new(const tor_addr_t *addr,
4703 uint16_t dir_port, uint16_t or_port,
4704 const tor_addr_port_t *addrport_ipv6,
4705 const char *id_digest, double weight)
4707 return dir_server_new(0, NULL, addr, NULL, dir_port, or_port,
4708 addrport_ipv6,
4709 id_digest,
4710 NULL, ALL_DIRINFO, weight);
4713 /** Add a directory server to the global list(s). */
4714 void
4715 dir_server_add(dir_server_t *ent)
4717 if (!trusted_dir_servers)
4718 trusted_dir_servers = smartlist_new();
4719 if (!fallback_dir_servers)
4720 fallback_dir_servers = smartlist_new();
4722 if (ent->is_authority)
4723 smartlist_add(trusted_dir_servers, ent);
4725 smartlist_add(fallback_dir_servers, ent);
4726 router_dir_info_changed();
4729 /** Free storage held in <b>cert</b>. */
4730 void
4731 authority_cert_free(authority_cert_t *cert)
4733 if (!cert)
4734 return;
4736 tor_free(cert->cache_info.signed_descriptor_body);
4737 crypto_pk_free(cert->signing_key);
4738 crypto_pk_free(cert->identity_key);
4740 tor_free(cert);
4743 /** Free storage held in <b>ds</b>. */
4744 static void
4745 dir_server_free(dir_server_t *ds)
4747 if (!ds)
4748 return;
4750 tor_free(ds->nickname);
4751 tor_free(ds->description);
4752 tor_free(ds->address);
4753 tor_free(ds);
4756 /** Remove all members from the list of dir servers. */
4757 void
4758 clear_dir_servers(void)
4760 if (fallback_dir_servers) {
4761 SMARTLIST_FOREACH(fallback_dir_servers, dir_server_t *, ent,
4762 dir_server_free(ent));
4763 smartlist_clear(fallback_dir_servers);
4764 } else {
4765 fallback_dir_servers = smartlist_new();
4767 if (trusted_dir_servers) {
4768 smartlist_clear(trusted_dir_servers);
4769 } else {
4770 trusted_dir_servers = smartlist_new();
4772 router_dir_info_changed();
4775 /** For every current directory connection whose purpose is <b>purpose</b>,
4776 * and where the resource being downloaded begins with <b>prefix</b>, split
4777 * rest of the resource into base16 fingerprints (or base64 fingerprints if
4778 * purpose==DIR_PURPOSE_FETCH_MICRODESC), decode them, and set the
4779 * corresponding elements of <b>result</b> to a nonzero value.
4781 static void
4782 list_pending_downloads(digestmap_t *result, digest256map_t *result256,
4783 int purpose, const char *prefix)
4785 const size_t p_len = strlen(prefix);
4786 smartlist_t *tmp = smartlist_new();
4787 smartlist_t *conns = get_connection_array();
4788 int flags = DSR_HEX;
4789 if (purpose == DIR_PURPOSE_FETCH_MICRODESC)
4790 flags = DSR_DIGEST256|DSR_BASE64;
4792 tor_assert(result || result256);
4794 SMARTLIST_FOREACH_BEGIN(conns, connection_t *, conn) {
4795 if (conn->type == CONN_TYPE_DIR &&
4796 conn->purpose == purpose &&
4797 !conn->marked_for_close) {
4798 const char *resource = TO_DIR_CONN(conn)->requested_resource;
4799 if (!strcmpstart(resource, prefix))
4800 dir_split_resource_into_fingerprints(resource + p_len,
4801 tmp, NULL, flags);
4803 } SMARTLIST_FOREACH_END(conn);
4805 if (result) {
4806 SMARTLIST_FOREACH(tmp, char *, d,
4808 digestmap_set(result, d, (void*)1);
4809 tor_free(d);
4811 } else if (result256) {
4812 SMARTLIST_FOREACH(tmp, uint8_t *, d,
4814 digest256map_set(result256, d, (void*)1);
4815 tor_free(d);
4818 smartlist_free(tmp);
4821 /** For every router descriptor (or extra-info document if <b>extrainfo</b> is
4822 * true) we are currently downloading by descriptor digest, set result[d] to
4823 * (void*)1. */
4824 static void
4825 list_pending_descriptor_downloads(digestmap_t *result, int extrainfo)
4827 int purpose =
4828 extrainfo ? DIR_PURPOSE_FETCH_EXTRAINFO : DIR_PURPOSE_FETCH_SERVERDESC;
4829 list_pending_downloads(result, NULL, purpose, "d/");
4832 /** For every microdescriptor we are currently downloading by descriptor
4833 * digest, set result[d] to (void*)1.
4835 void
4836 list_pending_microdesc_downloads(digest256map_t *result)
4838 list_pending_downloads(NULL, result, DIR_PURPOSE_FETCH_MICRODESC, "d/");
4841 /** For every certificate we are currently downloading by (identity digest,
4842 * signing key digest) pair, set result[fp_pair] to (void *1).
4844 static void
4845 list_pending_fpsk_downloads(fp_pair_map_t *result)
4847 const char *pfx = "fp-sk/";
4848 smartlist_t *tmp;
4849 smartlist_t *conns;
4850 const char *resource;
4852 tor_assert(result);
4854 tmp = smartlist_new();
4855 conns = get_connection_array();
4857 SMARTLIST_FOREACH_BEGIN(conns, connection_t *, conn) {
4858 if (conn->type == CONN_TYPE_DIR &&
4859 conn->purpose == DIR_PURPOSE_FETCH_CERTIFICATE &&
4860 !conn->marked_for_close) {
4861 resource = TO_DIR_CONN(conn)->requested_resource;
4862 if (!strcmpstart(resource, pfx))
4863 dir_split_resource_into_fingerprint_pairs(resource + strlen(pfx),
4864 tmp);
4866 } SMARTLIST_FOREACH_END(conn);
4868 SMARTLIST_FOREACH_BEGIN(tmp, fp_pair_t *, fp) {
4869 fp_pair_map_set(result, fp, (void*)1);
4870 tor_free(fp);
4871 } SMARTLIST_FOREACH_END(fp);
4873 smartlist_free(tmp);
4876 /** Launch downloads for all the descriptors whose digests or digests256
4877 * are listed as digests[i] for lo <= i < hi. (Lo and hi may be out of
4878 * range.) If <b>source</b> is given, download from <b>source</b>;
4879 * otherwise, download from an appropriate random directory server.
4881 MOCK_IMPL(STATIC void, initiate_descriptor_downloads,
4882 (const routerstatus_t *source, int purpose, smartlist_t *digests,
4883 int lo, int hi, int pds_flags))
4885 char *resource, *cp;
4886 int digest_len, enc_digest_len;
4887 const char *sep;
4888 int b64_256;
4889 smartlist_t *tmp;
4891 if (purpose == DIR_PURPOSE_FETCH_MICRODESC) {
4892 /* Microdescriptors are downloaded by "-"-separated base64-encoded
4893 * 256-bit digests. */
4894 digest_len = DIGEST256_LEN;
4895 enc_digest_len = BASE64_DIGEST256_LEN + 1;
4896 sep = "-";
4897 b64_256 = 1;
4898 } else {
4899 digest_len = DIGEST_LEN;
4900 enc_digest_len = HEX_DIGEST_LEN + 1;
4901 sep = "+";
4902 b64_256 = 0;
4905 if (lo < 0)
4906 lo = 0;
4907 if (hi > smartlist_len(digests))
4908 hi = smartlist_len(digests);
4910 if (hi-lo <= 0)
4911 return;
4913 tmp = smartlist_new();
4915 for (; lo < hi; ++lo) {
4916 cp = tor_malloc(enc_digest_len);
4917 if (b64_256) {
4918 digest256_to_base64(cp, smartlist_get(digests, lo));
4919 } else {
4920 base16_encode(cp, enc_digest_len, smartlist_get(digests, lo),
4921 digest_len);
4923 smartlist_add(tmp, cp);
4926 cp = smartlist_join_strings(tmp, sep, 0, NULL);
4927 tor_asprintf(&resource, "d/%s.z", cp);
4929 SMARTLIST_FOREACH(tmp, char *, cp1, tor_free(cp1));
4930 smartlist_free(tmp);
4931 tor_free(cp);
4933 if (source) {
4934 /* We know which authority or directory mirror we want. */
4935 directory_initiate_command_routerstatus(source, purpose,
4936 ROUTER_PURPOSE_GENERAL,
4937 DIRIND_ONEHOP,
4938 resource, NULL, 0, 0, NULL);
4939 } else {
4940 directory_get_from_dirserver(purpose, ROUTER_PURPOSE_GENERAL, resource,
4941 pds_flags, DL_WANT_ANY_DIRSERVER);
4943 tor_free(resource);
4946 /** Return the max number of hashes to put in a URL for a given request.
4948 static int
4949 max_dl_per_request(const or_options_t *options, int purpose)
4951 /* Since squid does not like URLs >= 4096 bytes we limit it to 96.
4952 * 4096 - strlen(http://[ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff]:65535
4953 * /tor/server/d/.z) == 4026
4954 * 4026/41 (40 for the hash and 1 for the + that separates them) => 98
4955 * So use 96 because it's a nice number.
4957 * For microdescriptors, the calculation is
4958 * 4096 - strlen(http://[ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff]:65535
4959 * /tor/micro/d/.z) == 4027
4960 * 4027/44 (43 for the hash and 1 for the - that separates them) => 91
4961 * So use 90 because it's a nice number.
4963 int max = 96;
4964 if (purpose == DIR_PURPOSE_FETCH_MICRODESC) {
4965 max = 90;
4967 /* If we're going to tunnel our connections, we can ask for a lot more
4968 * in a request. */
4969 if (directory_must_use_begindir(options)) {
4970 max = 500;
4972 return max;
4975 /** Don't split our requests so finely that we are requesting fewer than
4976 * this number per server. */
4977 #define MIN_DL_PER_REQUEST 4
4978 /** To prevent a single screwy cache from confusing us by selective reply,
4979 * try to split our requests into at least this many requests. */
4980 #define MIN_REQUESTS 3
4981 /** If we want fewer than this many descriptors, wait until we
4982 * want more, or until TestingClientMaxIntervalWithoutRequest has passed. */
4983 #define MAX_DL_TO_DELAY 16
4985 /** Given a <b>purpose</b> (FETCH_MICRODESC or FETCH_SERVERDESC) and a list of
4986 * router descriptor digests or microdescriptor digest256s in
4987 * <b>downloadable</b>, decide whether to delay fetching until we have more.
4988 * If we don't want to delay, launch one or more requests to the appropriate
4989 * directory authorities.
4991 void
4992 launch_descriptor_downloads(int purpose,
4993 smartlist_t *downloadable,
4994 const routerstatus_t *source, time_t now)
4996 const or_options_t *options = get_options();
4997 const char *descname;
4998 const int fetch_microdesc = (purpose == DIR_PURPOSE_FETCH_MICRODESC);
4999 int n_downloadable = smartlist_len(downloadable);
5001 int i, n_per_request, max_dl_per_req;
5002 const char *req_plural = "", *rtr_plural = "";
5003 int pds_flags = PDS_RETRY_IF_NO_SERVERS;
5005 tor_assert(fetch_microdesc || purpose == DIR_PURPOSE_FETCH_SERVERDESC);
5006 descname = fetch_microdesc ? "microdesc" : "routerdesc";
5008 if (!n_downloadable)
5009 return;
5011 if (!directory_fetches_dir_info_early(options)) {
5012 if (n_downloadable >= MAX_DL_TO_DELAY) {
5013 log_debug(LD_DIR,
5014 "There are enough downloadable %ss to launch requests.",
5015 descname);
5016 } else {
5018 /* should delay */
5019 if ((last_descriptor_download_attempted +
5020 options->TestingClientMaxIntervalWithoutRequest) > now)
5021 return;
5023 if (last_descriptor_download_attempted) {
5024 log_info(LD_DIR,
5025 "There are not many downloadable %ss, but we've "
5026 "been waiting long enough (%d seconds). Downloading.",
5027 descname,
5028 (int)(now-last_descriptor_download_attempted));
5029 } else {
5030 log_info(LD_DIR,
5031 "There are not many downloadable %ss, but we haven't "
5032 "tried downloading descriptors recently. Downloading.",
5033 descname);
5038 if (!authdir_mode_any_nonhidserv(options)) {
5039 /* If we wind up going to the authorities, we want to only open one
5040 * connection to each authority at a time, so that we don't overload
5041 * them. We do this by setting PDS_NO_EXISTING_SERVERDESC_FETCH
5042 * regardless of whether we're a cache or not.
5044 * Setting this flag can make initiate_descriptor_downloads() ignore
5045 * requests. We need to make sure that we do in fact call
5046 * update_router_descriptor_downloads() later on, once the connections
5047 * have succeeded or failed.
5049 pds_flags |= fetch_microdesc ?
5050 PDS_NO_EXISTING_MICRODESC_FETCH :
5051 PDS_NO_EXISTING_SERVERDESC_FETCH;
5054 n_per_request = CEIL_DIV(n_downloadable, MIN_REQUESTS);
5055 max_dl_per_req = max_dl_per_request(options, purpose);
5057 if (n_per_request > max_dl_per_req)
5058 n_per_request = max_dl_per_req;
5060 if (n_per_request < MIN_DL_PER_REQUEST)
5061 n_per_request = MIN_DL_PER_REQUEST;
5063 if (n_downloadable > n_per_request)
5064 req_plural = rtr_plural = "s";
5065 else if (n_downloadable > 1)
5066 rtr_plural = "s";
5068 log_info(LD_DIR,
5069 "Launching %d request%s for %d %s%s, %d at a time",
5070 CEIL_DIV(n_downloadable, n_per_request), req_plural,
5071 n_downloadable, descname, rtr_plural, n_per_request);
5072 smartlist_sort_digests(downloadable);
5073 for (i=0; i < n_downloadable; i += n_per_request) {
5074 initiate_descriptor_downloads(source, purpose,
5075 downloadable, i, i+n_per_request,
5076 pds_flags);
5078 last_descriptor_download_attempted = now;
5081 /** For any descriptor that we want that's currently listed in
5082 * <b>consensus</b>, download it as appropriate. */
5083 void
5084 update_consensus_router_descriptor_downloads(time_t now, int is_vote,
5085 networkstatus_t *consensus)
5087 const or_options_t *options = get_options();
5088 digestmap_t *map = NULL;
5089 smartlist_t *no_longer_old = smartlist_new();
5090 smartlist_t *downloadable = smartlist_new();
5091 routerstatus_t *source = NULL;
5092 int authdir = authdir_mode(options);
5093 int n_delayed=0, n_have=0, n_would_reject=0, n_wouldnt_use=0,
5094 n_inprogress=0, n_in_oldrouters=0;
5096 if (directory_too_idle_to_fetch_descriptors(options, now))
5097 goto done;
5098 if (!consensus)
5099 goto done;
5101 if (is_vote) {
5102 /* where's it from, so we know whom to ask for descriptors */
5103 dir_server_t *ds;
5104 networkstatus_voter_info_t *voter = smartlist_get(consensus->voters, 0);
5105 tor_assert(voter);
5106 ds = trusteddirserver_get_by_v3_auth_digest(voter->identity_digest);
5107 if (ds)
5108 source = &(ds->fake_status);
5109 else
5110 log_warn(LD_DIR, "couldn't lookup source from vote?");
5113 map = digestmap_new();
5114 list_pending_descriptor_downloads(map, 0);
5115 SMARTLIST_FOREACH_BEGIN(consensus->routerstatus_list, void *, rsp) {
5116 routerstatus_t *rs =
5117 is_vote ? &(((vote_routerstatus_t *)rsp)->status) : rsp;
5118 signed_descriptor_t *sd;
5119 if ((sd = router_get_by_descriptor_digest(rs->descriptor_digest))) {
5120 const routerinfo_t *ri;
5121 ++n_have;
5122 if (!(ri = router_get_by_id_digest(rs->identity_digest)) ||
5123 tor_memneq(ri->cache_info.signed_descriptor_digest,
5124 sd->signed_descriptor_digest, DIGEST_LEN)) {
5125 /* We have a descriptor with this digest, but either there is no
5126 * entry in routerlist with the same ID (!ri), or there is one,
5127 * but the identity digest differs (memneq).
5129 smartlist_add(no_longer_old, sd);
5130 ++n_in_oldrouters; /* We have it in old_routers. */
5132 continue; /* We have it already. */
5134 if (digestmap_get(map, rs->descriptor_digest)) {
5135 ++n_inprogress;
5136 continue; /* We have an in-progress download. */
5138 if (!download_status_is_ready(&rs->dl_status, now,
5139 options->TestingDescriptorMaxDownloadTries)) {
5140 ++n_delayed; /* Not ready for retry. */
5141 continue;
5143 if (authdir && dirserv_would_reject_router(rs)) {
5144 ++n_would_reject;
5145 continue; /* We would throw it out immediately. */
5147 if (!we_want_to_fetch_flavor(options, consensus->flavor) &&
5148 !client_would_use_router(rs, now, options)) {
5149 ++n_wouldnt_use;
5150 continue; /* We would never use it ourself. */
5152 if (is_vote && source) {
5153 char time_bufnew[ISO_TIME_LEN+1];
5154 char time_bufold[ISO_TIME_LEN+1];
5155 const routerinfo_t *oldrouter;
5156 oldrouter = router_get_by_id_digest(rs->identity_digest);
5157 format_iso_time(time_bufnew, rs->published_on);
5158 if (oldrouter)
5159 format_iso_time(time_bufold, oldrouter->cache_info.published_on);
5160 log_info(LD_DIR, "Learned about %s (%s vs %s) from %s's vote (%s)",
5161 routerstatus_describe(rs),
5162 time_bufnew,
5163 oldrouter ? time_bufold : "none",
5164 source->nickname, oldrouter ? "known" : "unknown");
5166 smartlist_add(downloadable, rs->descriptor_digest);
5167 } SMARTLIST_FOREACH_END(rsp);
5169 if (!authdir_mode_handles_descs(options, ROUTER_PURPOSE_GENERAL)
5170 && smartlist_len(no_longer_old)) {
5171 routerlist_t *rl = router_get_routerlist();
5172 log_info(LD_DIR, "%d router descriptors listed in consensus are "
5173 "currently in old_routers; making them current.",
5174 smartlist_len(no_longer_old));
5175 SMARTLIST_FOREACH_BEGIN(no_longer_old, signed_descriptor_t *, sd) {
5176 const char *msg;
5177 was_router_added_t r;
5178 routerinfo_t *ri = routerlist_reparse_old(rl, sd);
5179 if (!ri) {
5180 log_warn(LD_BUG, "Failed to re-parse a router.");
5181 continue;
5183 r = router_add_to_routerlist(ri, &msg, 1, 0);
5184 if (WRA_WAS_OUTDATED(r)) {
5185 log_warn(LD_DIR, "Couldn't add re-parsed router: %s",
5186 msg?msg:"???");
5188 } SMARTLIST_FOREACH_END(sd);
5189 routerlist_assert_ok(rl);
5192 log_info(LD_DIR,
5193 "%d router descriptors downloadable. %d delayed; %d present "
5194 "(%d of those were in old_routers); %d would_reject; "
5195 "%d wouldnt_use; %d in progress.",
5196 smartlist_len(downloadable), n_delayed, n_have, n_in_oldrouters,
5197 n_would_reject, n_wouldnt_use, n_inprogress);
5199 launch_descriptor_downloads(DIR_PURPOSE_FETCH_SERVERDESC,
5200 downloadable, source, now);
5202 digestmap_free(map, NULL);
5203 done:
5204 smartlist_free(downloadable);
5205 smartlist_free(no_longer_old);
5208 /** How often should we launch a server/authority request to be sure of getting
5209 * a guess for our IP? */
5210 /*XXXX+ this info should come from netinfo cells or something, or we should
5211 * do this only when we aren't seeing incoming data. see bug 652. */
5212 #define DUMMY_DOWNLOAD_INTERVAL (20*60)
5214 /** As needed, launch a dummy router descriptor fetch to see if our
5215 * address has changed. */
5216 static void
5217 launch_dummy_descriptor_download_as_needed(time_t now,
5218 const or_options_t *options)
5220 static time_t last_dummy_download = 0;
5221 /* XXXX+ we could be smarter here; see notes on bug 652. */
5222 /* If we're a server that doesn't have a configured address, we rely on
5223 * directory fetches to learn when our address changes. So if we haven't
5224 * tried to get any routerdescs in a long time, try a dummy fetch now. */
5225 if (!options->Address &&
5226 server_mode(options) &&
5227 last_descriptor_download_attempted + DUMMY_DOWNLOAD_INTERVAL < now &&
5228 last_dummy_download + DUMMY_DOWNLOAD_INTERVAL < now) {
5229 last_dummy_download = now;
5230 /* XX/teor - do we want an authority here, because they are less likely
5231 * to give us the wrong address? (See #17782)
5232 * I'm leaving the previous behaviour intact, because I don't like
5233 * the idea of some relays contacting an authority every 20 minutes. */
5234 directory_get_from_dirserver(DIR_PURPOSE_FETCH_SERVERDESC,
5235 ROUTER_PURPOSE_GENERAL, "authority.z",
5236 PDS_RETRY_IF_NO_SERVERS,
5237 DL_WANT_ANY_DIRSERVER);
5241 /** Launch downloads for router status as needed. */
5242 void
5243 update_router_descriptor_downloads(time_t now)
5245 const or_options_t *options = get_options();
5246 if (should_delay_dir_fetches(options, NULL))
5247 return;
5248 if (!we_fetch_router_descriptors(options))
5249 return;
5251 update_consensus_router_descriptor_downloads(now, 0,
5252 networkstatus_get_reasonably_live_consensus(now, FLAV_NS));
5255 /** Launch extrainfo downloads as needed. */
5256 void
5257 update_extrainfo_downloads(time_t now)
5259 const or_options_t *options = get_options();
5260 routerlist_t *rl;
5261 smartlist_t *wanted;
5262 digestmap_t *pending;
5263 int old_routers, i, max_dl_per_req;
5264 int n_no_ei = 0, n_pending = 0, n_have = 0, n_delay = 0, n_bogus[2] = {0,0};
5265 if (! options->DownloadExtraInfo)
5266 return;
5267 if (should_delay_dir_fetches(options, NULL))
5268 return;
5269 if (!router_have_minimum_dir_info())
5270 return;
5272 pending = digestmap_new();
5273 list_pending_descriptor_downloads(pending, 1);
5274 rl = router_get_routerlist();
5275 wanted = smartlist_new();
5276 for (old_routers = 0; old_routers < 2; ++old_routers) {
5277 smartlist_t *lst = old_routers ? rl->old_routers : rl->routers;
5278 for (i = 0; i < smartlist_len(lst); ++i) {
5279 signed_descriptor_t *sd;
5280 char *d;
5281 if (old_routers)
5282 sd = smartlist_get(lst, i);
5283 else
5284 sd = &((routerinfo_t*)smartlist_get(lst, i))->cache_info;
5285 if (sd->is_extrainfo)
5286 continue; /* This should never happen. */
5287 if (old_routers && !router_get_by_id_digest(sd->identity_digest))
5288 continue; /* Couldn't check the signature if we got it. */
5289 if (sd->extrainfo_is_bogus)
5290 continue;
5291 d = sd->extra_info_digest;
5292 if (tor_digest_is_zero(d)) {
5293 ++n_no_ei;
5294 continue;
5296 if (eimap_get(rl->extra_info_map, d)) {
5297 ++n_have;
5298 continue;
5300 if (!download_status_is_ready(&sd->ei_dl_status, now,
5301 options->TestingDescriptorMaxDownloadTries)) {
5302 ++n_delay;
5303 continue;
5305 if (digestmap_get(pending, d)) {
5306 ++n_pending;
5307 continue;
5310 const signed_descriptor_t *sd2 = router_get_by_extrainfo_digest(d);
5311 if (sd2 != sd) {
5312 if (sd2 != NULL) {
5313 char d1[HEX_DIGEST_LEN+1], d2[HEX_DIGEST_LEN+1];
5314 char d3[HEX_DIGEST_LEN+1], d4[HEX_DIGEST_LEN+1];
5315 base16_encode(d1, sizeof(d1), sd->identity_digest, DIGEST_LEN);
5316 base16_encode(d2, sizeof(d2), sd2->identity_digest, DIGEST_LEN);
5317 base16_encode(d3, sizeof(d3), d, DIGEST_LEN);
5318 base16_encode(d4, sizeof(d3), sd2->extra_info_digest, DIGEST_LEN);
5320 log_info(LD_DIR, "Found an entry in %s with mismatched "
5321 "router_get_by_extrainfo_digest() value. This has ID %s "
5322 "but the entry in the map has ID %s. This has EI digest "
5323 "%s and the entry in the map has EI digest %s.",
5324 old_routers?"old_routers":"routers",
5325 d1, d2, d3, d4);
5326 } else {
5327 char d1[HEX_DIGEST_LEN+1], d2[HEX_DIGEST_LEN+1];
5328 base16_encode(d1, sizeof(d1), sd->identity_digest, DIGEST_LEN);
5329 base16_encode(d2, sizeof(d2), d, DIGEST_LEN);
5331 log_info(LD_DIR, "Found an entry in %s with NULL "
5332 "router_get_by_extrainfo_digest() value. This has ID %s "
5333 "and EI digest %s.",
5334 old_routers?"old_routers":"routers",
5335 d1, d2);
5337 ++n_bogus[old_routers];
5338 continue;
5340 smartlist_add(wanted, d);
5343 digestmap_free(pending, NULL);
5345 log_info(LD_DIR, "Extrainfo download status: %d router with no ei, %d "
5346 "with present ei, %d delaying, %d pending, %d downloadable, %d "
5347 "bogus in routers, %d bogus in old_routers",
5348 n_no_ei, n_have, n_delay, n_pending, smartlist_len(wanted),
5349 n_bogus[0], n_bogus[1]);
5351 smartlist_shuffle(wanted);
5353 max_dl_per_req = max_dl_per_request(options, DIR_PURPOSE_FETCH_EXTRAINFO);
5354 for (i = 0; i < smartlist_len(wanted); i += max_dl_per_req) {
5355 initiate_descriptor_downloads(NULL, DIR_PURPOSE_FETCH_EXTRAINFO,
5356 wanted, i, i+max_dl_per_req,
5357 PDS_RETRY_IF_NO_SERVERS|PDS_NO_EXISTING_SERVERDESC_FETCH);
5360 smartlist_free(wanted);
5363 /** Reset the descriptor download failure count on all routers, so that we
5364 * can retry any long-failed routers immediately.
5366 void
5367 router_reset_descriptor_download_failures(void)
5369 log_debug(LD_GENERAL,
5370 "In router_reset_descriptor_download_failures()");
5372 networkstatus_reset_download_failures();
5373 last_descriptor_download_attempted = 0;
5374 if (!routerlist)
5375 return;
5376 SMARTLIST_FOREACH(routerlist->routers, routerinfo_t *, ri,
5378 download_status_reset(&ri->cache_info.ei_dl_status);
5380 SMARTLIST_FOREACH(routerlist->old_routers, signed_descriptor_t *, sd,
5382 download_status_reset(&sd->ei_dl_status);
5386 /** Any changes in a router descriptor's publication time larger than this are
5387 * automatically non-cosmetic. */
5388 #define ROUTER_MAX_COSMETIC_TIME_DIFFERENCE (2*60*60)
5390 /** We allow uptime to vary from how much it ought to be by this much. */
5391 #define ROUTER_ALLOW_UPTIME_DRIFT (6*60*60)
5393 /** Return true iff the only differences between r1 and r2 are such that
5394 * would not cause a recent (post 0.1.1.6) dirserver to republish.
5397 router_differences_are_cosmetic(const routerinfo_t *r1, const routerinfo_t *r2)
5399 time_t r1pub, r2pub;
5400 long time_difference;
5401 tor_assert(r1 && r2);
5403 /* r1 should be the one that was published first. */
5404 if (r1->cache_info.published_on > r2->cache_info.published_on) {
5405 const routerinfo_t *ri_tmp = r2;
5406 r2 = r1;
5407 r1 = ri_tmp;
5410 /* If any key fields differ, they're different. */
5411 if (r1->addr != r2->addr ||
5412 strcasecmp(r1->nickname, r2->nickname) ||
5413 r1->or_port != r2->or_port ||
5414 !tor_addr_eq(&r1->ipv6_addr, &r2->ipv6_addr) ||
5415 r1->ipv6_orport != r2->ipv6_orport ||
5416 r1->dir_port != r2->dir_port ||
5417 r1->purpose != r2->purpose ||
5418 !crypto_pk_eq_keys(r1->onion_pkey, r2->onion_pkey) ||
5419 !crypto_pk_eq_keys(r1->identity_pkey, r2->identity_pkey) ||
5420 strcasecmp(r1->platform, r2->platform) ||
5421 (r1->contact_info && !r2->contact_info) || /* contact_info is optional */
5422 (!r1->contact_info && r2->contact_info) ||
5423 (r1->contact_info && r2->contact_info &&
5424 strcasecmp(r1->contact_info, r2->contact_info)) ||
5425 r1->is_hibernating != r2->is_hibernating ||
5426 ! addr_policies_eq(r1->exit_policy, r2->exit_policy) ||
5427 (r1->supports_tunnelled_dir_requests !=
5428 r2->supports_tunnelled_dir_requests))
5429 return 0;
5430 if ((r1->declared_family == NULL) != (r2->declared_family == NULL))
5431 return 0;
5432 if (r1->declared_family && r2->declared_family) {
5433 int i, n;
5434 if (smartlist_len(r1->declared_family)!=smartlist_len(r2->declared_family))
5435 return 0;
5436 n = smartlist_len(r1->declared_family);
5437 for (i=0; i < n; ++i) {
5438 if (strcasecmp(smartlist_get(r1->declared_family, i),
5439 smartlist_get(r2->declared_family, i)))
5440 return 0;
5444 /* Did bandwidth change a lot? */
5445 if ((r1->bandwidthcapacity < r2->bandwidthcapacity/2) ||
5446 (r2->bandwidthcapacity < r1->bandwidthcapacity/2))
5447 return 0;
5449 /* Did the bandwidthrate or bandwidthburst change? */
5450 if ((r1->bandwidthrate != r2->bandwidthrate) ||
5451 (r1->bandwidthburst != r2->bandwidthburst))
5452 return 0;
5454 /* Did more than 12 hours pass? */
5455 if (r1->cache_info.published_on + ROUTER_MAX_COSMETIC_TIME_DIFFERENCE
5456 < r2->cache_info.published_on)
5457 return 0;
5459 /* Did uptime fail to increase by approximately the amount we would think,
5460 * give or take some slop? */
5461 r1pub = r1->cache_info.published_on;
5462 r2pub = r2->cache_info.published_on;
5463 time_difference = labs(r2->uptime - (r1->uptime + (r2pub - r1pub)));
5464 if (time_difference > ROUTER_ALLOW_UPTIME_DRIFT &&
5465 time_difference > r1->uptime * .05 &&
5466 time_difference > r2->uptime * .05)
5467 return 0;
5469 /* Otherwise, the difference is cosmetic. */
5470 return 1;
5473 /** Check whether <b>sd</b> describes a router descriptor compatible with the
5474 * extrainfo document <b>ei</b>.
5476 * <b>identity_pkey</b> (which must also be provided) is RSA1024 identity key
5477 * for the router. We use it to check the signature of the extrainfo document,
5478 * if it has not already been checked.
5480 * If no router is compatible with <b>ei</b>, <b>ei</b> should be
5481 * dropped. Return 0 for "compatible", return 1 for "reject, and inform
5482 * whoever uploaded <b>ei</b>, and return -1 for "reject silently.". If
5483 * <b>msg</b> is present, set *<b>msg</b> to a description of the
5484 * incompatibility (if any).
5486 * Set the extrainfo_is_bogus field in <b>sd</b> if the digests matched
5487 * but the extrainfo was nonetheless incompatible.
5490 routerinfo_incompatible_with_extrainfo(const crypto_pk_t *identity_pkey,
5491 extrainfo_t *ei,
5492 signed_descriptor_t *sd,
5493 const char **msg)
5495 int digest_matches, digest256_matches, r=1;
5496 tor_assert(identity_pkey);
5497 tor_assert(sd);
5498 tor_assert(ei);
5500 if (ei->bad_sig) {
5501 if (msg) *msg = "Extrainfo signature was bad, or signed with wrong key.";
5502 return 1;
5505 digest_matches = tor_memeq(ei->cache_info.signed_descriptor_digest,
5506 sd->extra_info_digest, DIGEST_LEN);
5507 /* Set digest256_matches to 1 if the digest is correct, or if no
5508 * digest256 was in the ri. */
5509 digest256_matches = tor_memeq(ei->digest256,
5510 sd->extra_info_digest256, DIGEST256_LEN);
5511 digest256_matches |=
5512 tor_mem_is_zero(sd->extra_info_digest256, DIGEST256_LEN);
5514 /* The identity must match exactly to have been generated at the same time
5515 * by the same router. */
5516 if (tor_memneq(sd->identity_digest,
5517 ei->cache_info.identity_digest,
5518 DIGEST_LEN)) {
5519 if (msg) *msg = "Extrainfo nickname or identity did not match routerinfo";
5520 goto err; /* different servers */
5523 if (! tor_cert_opt_eq(sd->signing_key_cert,
5524 ei->cache_info.signing_key_cert)) {
5525 if (msg) *msg = "Extrainfo signing key cert didn't match routerinfo";
5526 goto err; /* different servers */
5529 if (ei->pending_sig) {
5530 char signed_digest[128];
5531 if (crypto_pk_public_checksig(identity_pkey,
5532 signed_digest, sizeof(signed_digest),
5533 ei->pending_sig, ei->pending_sig_len) != DIGEST_LEN ||
5534 tor_memneq(signed_digest, ei->cache_info.signed_descriptor_digest,
5535 DIGEST_LEN)) {
5536 ei->bad_sig = 1;
5537 tor_free(ei->pending_sig);
5538 if (msg) *msg = "Extrainfo signature bad, or signed with wrong key";
5539 goto err; /* Bad signature, or no match. */
5542 ei->cache_info.send_unencrypted = sd->send_unencrypted;
5543 tor_free(ei->pending_sig);
5546 if (ei->cache_info.published_on < sd->published_on) {
5547 if (msg) *msg = "Extrainfo published time did not match routerdesc";
5548 goto err;
5549 } else if (ei->cache_info.published_on > sd->published_on) {
5550 if (msg) *msg = "Extrainfo published time did not match routerdesc";
5551 r = -1;
5552 goto err;
5555 if (!digest256_matches && !digest_matches) {
5556 if (msg) *msg = "Neither digest256 or digest matched "
5557 "digest from routerdesc";
5558 goto err;
5561 if (!digest256_matches) {
5562 if (msg) *msg = "Extrainfo digest did not match digest256 from routerdesc";
5563 goto err; /* Digest doesn't match declared value. */
5566 if (!digest_matches) {
5567 if (msg) *msg = "Extrainfo digest did not match value from routerdesc";
5568 goto err; /* Digest doesn't match declared value. */
5571 return 0;
5572 err:
5573 if (digest_matches) {
5574 /* This signature was okay, and the digest was right: This is indeed the
5575 * corresponding extrainfo. But insanely, it doesn't match the routerinfo
5576 * that lists it. Don't try to fetch this one again. */
5577 sd->extrainfo_is_bogus = 1;
5580 return r;
5583 /* Does ri have a valid ntor onion key?
5584 * Valid ntor onion keys exist and have at least one non-zero byte. */
5586 routerinfo_has_curve25519_onion_key(const routerinfo_t *ri)
5588 if (!ri) {
5589 return 0;
5592 if (!ri->onion_curve25519_pkey) {
5593 return 0;
5596 if (tor_mem_is_zero((const char*)ri->onion_curve25519_pkey->public_key,
5597 CURVE25519_PUBKEY_LEN)) {
5598 return 0;
5601 return 1;
5604 /* Is rs running a tor version known to support EXTEND2 cells?
5605 * If allow_unknown_versions is true, return true if we can't tell
5606 * (from a versions line or a protocols line) whether it supports extend2
5607 * cells.
5608 * Otherwise, return false if the version is unknown. */
5610 routerstatus_version_supports_extend2_cells(const routerstatus_t *rs,
5611 int allow_unknown_versions)
5613 if (!rs) {
5614 return allow_unknown_versions;
5617 if (!rs->protocols_known) {
5618 return allow_unknown_versions;
5621 return rs->supports_extend2_cells;
5624 /** Assert that the internal representation of <b>rl</b> is
5625 * self-consistent. */
5626 void
5627 routerlist_assert_ok(const routerlist_t *rl)
5629 routerinfo_t *r2;
5630 signed_descriptor_t *sd2;
5631 if (!rl)
5632 return;
5633 SMARTLIST_FOREACH_BEGIN(rl->routers, routerinfo_t *, r) {
5634 r2 = rimap_get(rl->identity_map, r->cache_info.identity_digest);
5635 tor_assert(r == r2);
5636 sd2 = sdmap_get(rl->desc_digest_map,
5637 r->cache_info.signed_descriptor_digest);
5638 tor_assert(&(r->cache_info) == sd2);
5639 tor_assert(r->cache_info.routerlist_index == r_sl_idx);
5640 /* XXXX
5642 * Hoo boy. We need to fix this one, and the fix is a bit tricky, so
5643 * commenting this out is just a band-aid.
5645 * The problem is that, although well-behaved router descriptors
5646 * should never have the same value for their extra_info_digest, it's
5647 * possible for ill-behaved routers to claim whatever they like there.
5649 * The real answer is to trash desc_by_eid_map and instead have
5650 * something that indicates for a given extra-info digest we want,
5651 * what its download status is. We'll do that as a part of routerlist
5652 * refactoring once consensus directories are in. For now,
5653 * this rep violation is probably harmless: an adversary can make us
5654 * reset our retry count for an extrainfo, but that's not the end
5655 * of the world. Changing the representation in 0.2.0.x would just
5656 * destabilize the codebase.
5657 if (!tor_digest_is_zero(r->cache_info.extra_info_digest)) {
5658 signed_descriptor_t *sd3 =
5659 sdmap_get(rl->desc_by_eid_map, r->cache_info.extra_info_digest);
5660 tor_assert(sd3 == &(r->cache_info));
5663 } SMARTLIST_FOREACH_END(r);
5664 SMARTLIST_FOREACH_BEGIN(rl->old_routers, signed_descriptor_t *, sd) {
5665 r2 = rimap_get(rl->identity_map, sd->identity_digest);
5666 tor_assert(!r2 || sd != &(r2->cache_info));
5667 sd2 = sdmap_get(rl->desc_digest_map, sd->signed_descriptor_digest);
5668 tor_assert(sd == sd2);
5669 tor_assert(sd->routerlist_index == sd_sl_idx);
5670 /* XXXX see above.
5671 if (!tor_digest_is_zero(sd->extra_info_digest)) {
5672 signed_descriptor_t *sd3 =
5673 sdmap_get(rl->desc_by_eid_map, sd->extra_info_digest);
5674 tor_assert(sd3 == sd);
5677 } SMARTLIST_FOREACH_END(sd);
5679 RIMAP_FOREACH(rl->identity_map, d, r) {
5680 tor_assert(tor_memeq(r->cache_info.identity_digest, d, DIGEST_LEN));
5681 } DIGESTMAP_FOREACH_END;
5682 SDMAP_FOREACH(rl->desc_digest_map, d, sd) {
5683 tor_assert(tor_memeq(sd->signed_descriptor_digest, d, DIGEST_LEN));
5684 } DIGESTMAP_FOREACH_END;
5685 SDMAP_FOREACH(rl->desc_by_eid_map, d, sd) {
5686 tor_assert(!tor_digest_is_zero(d));
5687 tor_assert(sd);
5688 tor_assert(tor_memeq(sd->extra_info_digest, d, DIGEST_LEN));
5689 } DIGESTMAP_FOREACH_END;
5690 EIMAP_FOREACH(rl->extra_info_map, d, ei) {
5691 signed_descriptor_t *sd;
5692 tor_assert(tor_memeq(ei->cache_info.signed_descriptor_digest,
5693 d, DIGEST_LEN));
5694 sd = sdmap_get(rl->desc_by_eid_map,
5695 ei->cache_info.signed_descriptor_digest);
5696 // tor_assert(sd); // XXXX see above
5697 if (sd) {
5698 tor_assert(tor_memeq(ei->cache_info.signed_descriptor_digest,
5699 sd->extra_info_digest, DIGEST_LEN));
5701 } DIGESTMAP_FOREACH_END;
5704 /** Allocate and return a new string representing the contact info
5705 * and platform string for <b>router</b>,
5706 * surrounded by quotes and using standard C escapes.
5708 * THIS FUNCTION IS NOT REENTRANT. Don't call it from outside the main
5709 * thread. Also, each call invalidates the last-returned value, so don't
5710 * try log_warn(LD_GENERAL, "%s %s", esc_router_info(a), esc_router_info(b));
5712 * If <b>router</b> is NULL, it just frees its internal memory and returns.
5714 const char *
5715 esc_router_info(const routerinfo_t *router)
5717 static char *info=NULL;
5718 char *esc_contact, *esc_platform;
5719 tor_free(info);
5721 if (!router)
5722 return NULL; /* we're exiting; just free the memory we use */
5724 esc_contact = esc_for_log(router->contact_info);
5725 esc_platform = esc_for_log(router->platform);
5727 tor_asprintf(&info, "Contact %s, Platform %s", esc_contact, esc_platform);
5728 tor_free(esc_contact);
5729 tor_free(esc_platform);
5731 return info;
5734 /** Helper for sorting: compare two routerinfos by their identity
5735 * digest. */
5736 static int
5737 compare_routerinfo_by_id_digest_(const void **a, const void **b)
5739 routerinfo_t *first = *(routerinfo_t **)a, *second = *(routerinfo_t **)b;
5740 return fast_memcmp(first->cache_info.identity_digest,
5741 second->cache_info.identity_digest,
5742 DIGEST_LEN);
5745 /** Sort a list of routerinfo_t in ascending order of identity digest. */
5746 void
5747 routers_sort_by_identity(smartlist_t *routers)
5749 smartlist_sort(routers, compare_routerinfo_by_id_digest_);
5752 /** Called when we change a node set, or when we reload the geoip IPv4 list:
5753 * recompute all country info in all configuration node sets and in the
5754 * routerlist. */
5755 void
5756 refresh_all_country_info(void)
5758 const or_options_t *options = get_options();
5760 if (options->EntryNodes)
5761 routerset_refresh_countries(options->EntryNodes);
5762 if (options->ExitNodes)
5763 routerset_refresh_countries(options->ExitNodes);
5764 if (options->ExcludeNodes)
5765 routerset_refresh_countries(options->ExcludeNodes);
5766 if (options->ExcludeExitNodes)
5767 routerset_refresh_countries(options->ExcludeExitNodes);
5768 if (options->ExcludeExitNodesUnion_)
5769 routerset_refresh_countries(options->ExcludeExitNodesUnion_);
5771 nodelist_refresh_countries();