avoid calling smartlist_get(..., -1) if we have a consensus but no
[tor.git] / src / or / routerlist.c
blob76365b5dfdd5ca586273ec066295a1a27e3e6e8e
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, The Tor Project, Inc. */
5 /* See LICENSE for licensing information */
6 /* $Id$ */
7 const char routerlist_c_id[] =
8 "$Id$";
10 /**
11 * \file routerlist.c
12 * \brief Code to
13 * maintain and access the global list of routerinfos for known
14 * servers.
15 **/
17 #include "or.h"
19 // #define DEBUG_ROUTERLIST
21 /****************************************************************************/
23 /* static function prototypes */
24 static routerstatus_t *router_pick_directory_server_impl(
25 authority_type_t auth, int flags);
26 static routerstatus_t *router_pick_trusteddirserver_impl(
27 authority_type_t auth, int flags);
28 static void mark_all_trusteddirservers_up(void);
29 static int router_nickname_matches(routerinfo_t *router, const char *nickname);
30 static void trusted_dir_server_free(trusted_dir_server_t *ds);
31 static void launch_router_descriptor_downloads(smartlist_t *downloadable,
32 time_t now);
33 static void update_consensus_router_descriptor_downloads(time_t now);
34 static int signed_desc_digest_is_recognized(signed_descriptor_t *desc);
35 static void update_router_have_minimum_dir_info(void);
36 static const char *signed_descriptor_get_body_impl(signed_descriptor_t *desc,
37 int with_annotations);
38 static void list_pending_downloads(digestmap_t *result,
39 int purpose, const char *prefix);
41 DECLARE_TYPED_DIGESTMAP_FNS(sdmap_, digest_sd_map_t, signed_descriptor_t)
42 DECLARE_TYPED_DIGESTMAP_FNS(rimap_, digest_ri_map_t, routerinfo_t)
43 DECLARE_TYPED_DIGESTMAP_FNS(eimap_, digest_ei_map_t, extrainfo_t)
45 /****************************************************************************/
47 /** Global list of a trusted_dir_server_t object for each trusted directory
48 * server. */
49 static smartlist_t *trusted_dir_servers = NULL;
50 /** True iff the key certificate in at least one member of
51 * <b>trusted_dir_server_t</b> has changed since we last flushed the
52 * certificates to disk. */
53 static int trusted_dir_servers_certs_changed = 0;
55 /** Global list of all of the routers that we know about. */
56 static routerlist_t *routerlist = NULL;
58 /** List of strings for nicknames we've already warned about and that are
59 * still unknown / unavailable. */
60 static smartlist_t *warned_nicknames = NULL;
62 /** The last time we tried to download any routerdesc, or 0 for "never". We
63 * use this to rate-limit download attempts when the number of routerdescs to
64 * download is low. */
65 static time_t last_routerdesc_download_attempted = 0;
67 /** Return the number of directory authorities whose type matches some bit set
68 * in <b>type</b> */
69 int
70 get_n_authorities(authority_type_t type)
72 int n = 0;
73 if (!trusted_dir_servers)
74 return 0;
75 SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, ds,
76 if (ds->type & type)
77 ++n);
78 return n;
81 #define get_n_v2_authorities() get_n_authorities(V2_AUTHORITY)
83 /** Reload the cached v3 key certificates from the cached-certs file in
84 * the data directory. Return 0 on success, -1 on failure. */
85 int
86 trusted_dirs_reload_certs(void)
88 char *filename;
89 char *contents;
90 int r;
92 filename = get_datadir_fname("cached-certs");
93 contents = read_file_to_str(filename, RFTS_IGNORE_MISSING, NULL);
94 tor_free(filename);
95 if (!contents)
96 return 0;
97 r = trusted_dirs_load_certs_from_string(contents, 1);
98 tor_free(contents);
99 return r;
102 /** Load a bunch of new key certificates from the string <b>contents</b>. If
103 * <b>from_store</b> is true, the certificates are from the cache, and we
104 * don't need to flush them to disk. If <b>from_store</b> is false, we need
105 * to flush any changed certificates to disk. Return 0 on success, -1 on
106 * failure. */
108 trusted_dirs_load_certs_from_string(const char *contents, int from_store)
110 trusted_dir_server_t *ds;
111 const char *s, *eos;
113 for (s = contents; *s; s = eos) {
114 authority_cert_t *cert = authority_cert_parse_from_string(s, &eos);
115 int found = 0;
116 if (!cert)
117 break;
118 ds = trusteddirserver_get_by_v3_auth_digest(
119 cert->cache_info.identity_digest);
120 if (!ds) {
121 log_info(LD_DIR, "Found %s certificate whose key didn't match "
122 "any v3 authority we recognized; skipping.",
123 from_store ? "cached" : "downloaded");
124 authority_cert_free(cert);
125 continue;
127 if (!ds->v3_certs)
128 ds->v3_certs = smartlist_create();
130 SMARTLIST_FOREACH(ds->v3_certs, authority_cert_t *, c,
132 if (!memcmp(c->cache_info.signed_descriptor_digest,
133 cert->cache_info.signed_descriptor_digest,
134 DIGEST_LEN)) {
135 /* we already have this one. continue. */
136 log_info(LD_DIR, "Skipping %s certificate for %s that we "
137 "already have.",
138 from_store ? "cached" : "downloaded", ds->nickname);
139 authority_cert_free(cert);
140 found = 1;
141 break;
145 if (found)
146 continue;
148 log_info(LD_DIR, "Adding %s certificate for directory authority %s with "
149 "signing key %s", from_store ? "cached" : "downloaded",
150 ds->nickname, hex_str(cert->signing_key_digest,DIGEST_LEN));
152 smartlist_add(ds->v3_certs, cert);
153 if (cert->cache_info.published_on > ds->addr_current_at) {
154 /* Check to see whether we should update our view of the authority's
155 * address. */
156 if (cert->addr && cert->dir_port &&
157 (ds->addr != cert->addr ||
158 ds->dir_port != cert->dir_port)) {
159 char *a = tor_dup_addr(cert->addr);
160 log_notice(LD_DIR, "Updating address for directory authority %s "
161 "from %s:%d to %s:%d based on in certificate.",
162 ds->nickname, ds->address, (int)ds->dir_port,
163 a, cert->dir_port);
164 tor_free(a);
165 ds->addr = cert->addr;
166 ds->dir_port = cert->dir_port;
168 ds->addr_current_at = cert->cache_info.published_on;
171 if (!from_store)
172 trusted_dir_servers_certs_changed = 1;
175 trusted_dirs_flush_certs_to_disk();
177 networkstatus_note_certs_arrived();
178 return 0;
181 /** Save all v3 key certifiacates to the cached-certs file. */
182 void
183 trusted_dirs_flush_certs_to_disk(void)
185 char *filename;
186 smartlist_t *chunks;
188 if (!trusted_dir_servers_certs_changed)
189 return;
191 chunks = smartlist_create();
193 SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, ds,
195 if (ds->v3_certs) {
196 SMARTLIST_FOREACH(ds->v3_certs, authority_cert_t *, cert,
198 sized_chunk_t *c = tor_malloc(sizeof(sized_chunk_t));
199 c->bytes = cert->cache_info.signed_descriptor_body;
200 c->len = cert->cache_info.signed_descriptor_len;
201 smartlist_add(chunks, c);
205 filename = get_datadir_fname("cached-certs");
206 if (write_chunks_to_file(filename, chunks, 0)) {
207 log_warn(LD_FS, "Error writing certificates to disk.");
209 tor_free(filename);
210 SMARTLIST_FOREACH(chunks, sized_chunk_t *, c, tor_free(c));
211 smartlist_free(chunks);
213 trusted_dir_servers_certs_changed = 0;
216 /** Remove all v3 authority certificates that have been superseded for more
217 * than 48 hours. (If the most recent cert was published more than 48 hours
218 * ago, then we aren't going to get any consensuses signed with older
219 * keys.) */
220 static void
221 trusted_dirs_remove_old_certs(void)
223 #define OLD_CERT_LIFETIME (48*60*60)
224 SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, ds,
226 authority_cert_t *newest = NULL;
227 if (!ds->v3_certs)
228 continue;
229 SMARTLIST_FOREACH(ds->v3_certs, authority_cert_t *, cert,
230 if (!newest || (cert->cache_info.published_on >
231 newest->cache_info.published_on))
232 newest = cert);
233 SMARTLIST_FOREACH(ds->v3_certs, authority_cert_t *, cert,
234 if (newest && (newest->cache_info.published_on >
235 cert->cache_info.published_on + OLD_CERT_LIFETIME)) {
236 SMARTLIST_DEL_CURRENT(ds->v3_certs, cert);
237 authority_cert_free(cert);
238 trusted_dir_servers_certs_changed = 1;
241 #undef OLD_CERT_LIFETIME
243 trusted_dirs_flush_certs_to_disk();
246 /** Return the newest v3 authority certificate whose v3 authority identity key
247 * has digest <b>id_digest</b>. Return NULL if no such authority is known,
248 * or it has no certificate. */
249 authority_cert_t *
250 authority_cert_get_newest_by_id(const char *id_digest)
252 trusted_dir_server_t *ds = trusteddirserver_get_by_v3_auth_digest(id_digest);
253 authority_cert_t *best = NULL;
254 if (!ds || !ds->v3_certs)
255 return NULL;
256 SMARTLIST_FOREACH(ds->v3_certs, authority_cert_t *, cert,
258 if (!best || cert->cache_info.published_on > best->cache_info.published_on)
259 best = cert;
261 return best;
264 /** Return the newest v3 authority certificate whose directory signing key has
265 * giest <sk_digest</b>. Return NULL if no such certificate is known.
267 authority_cert_t *
268 authority_cert_get_by_sk_digest(const char *sk_digest)
270 if (!trusted_dir_servers)
271 return NULL;
272 SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, ds,
274 if (!ds->v3_certs)
275 continue;
276 SMARTLIST_FOREACH(ds->v3_certs, authority_cert_t *, cert,
278 if (!memcmp(cert->signing_key_digest, sk_digest, DIGEST_LEN))
279 return cert;
282 return NULL;
285 /** Return the v3 authority certificate with signing key matching
286 * <b>sk_digest</b>, for the authority with identity digest <b>id_digest</b>.
287 * Return NULL if no such authority is known. */
288 authority_cert_t *
289 authority_cert_get_by_digests(const char *id_digest,
290 const char *sk_digest)
292 trusted_dir_server_t *ds = trusteddirserver_get_by_v3_auth_digest(id_digest);
294 if (!ds || !ds->v3_certs)
295 return NULL;
296 SMARTLIST_FOREACH(ds->v3_certs, authority_cert_t *, cert,
297 if (!memcmp(cert->signing_key_digest, sk_digest, DIGEST_LEN))
298 return cert; );
300 return NULL;
303 /** How many times will we try to fetch a certificate before giving up? */
304 #define MAX_CERT_DL_FAILURES 8
306 /** Try to download any v3 authority certificates that we may be missing. If
307 * <b>status</b> is provided, try to get all the ones that were used to sign
308 * <b>status</b>. Additionally, try to have a non-expired certificate for
309 * every V3 authority in trusted_dir_servers. Don't fetch certificates we
310 * already have.
312 void
313 authority_certs_fetch_missing(networkstatus_vote_t *status, time_t now)
315 digestmap_t *pending;
316 smartlist_t *missing_digests;
317 char *resource = NULL;
319 if (should_delay_dir_fetches(get_options()))
320 return;
322 pending = digestmap_new();
323 missing_digests = smartlist_create();
325 list_pending_downloads(pending, DIR_PURPOSE_FETCH_CERTIFICATE, "fp/");
326 if (status) {
327 SMARTLIST_FOREACH(status->voters, networkstatus_voter_info_t *, voter,
329 trusted_dir_server_t *ds
330 = trusteddirserver_get_by_v3_auth_digest(voter->identity_digest);
331 if (!ds) /* XXXX020 This is wrong!! If we're a cache, we should
332 * download unrecognized signing keys so we can serve
333 * them. */
334 continue;
335 if (tor_digest_is_zero(voter->signing_key_digest))
336 continue; /* This authority never signed this consensus, so don't
337 * go looking for a cert with key digest 0000000000. */
338 if (authority_cert_get_by_digests(voter->identity_digest,
339 voter->signing_key_digest)) {
340 download_status_reset(&ds->cert_dl_status);
341 continue;
343 if (download_status_is_ready(&ds->cert_dl_status, now,
344 MAX_CERT_DL_FAILURES)) {
345 log_notice(LD_DIR, "We're missing a certificate from authority %s "
346 "with signing key %s: launching request.", ds->nickname,
347 hex_str(voter->signing_key_digest, DIGEST_LEN));
348 smartlist_add(missing_digests, voter->identity_digest);
352 SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, ds,
354 int found = 0;
355 if (!(ds->type & V3_AUTHORITY))
356 continue;
357 if (smartlist_digest_isin(missing_digests, ds->v3_identity_digest))
358 continue;
359 if (!ds->v3_certs)
360 ds->v3_certs = smartlist_create();
361 SMARTLIST_FOREACH(ds->v3_certs, authority_cert_t *, cert,
363 if (!ftime_definitely_after(now, cert->expires)) {
364 /* It's not expired, and we weren't looking for something to
365 * verify a consensus with. Call it done. */
366 download_status_reset(&ds->cert_dl_status);
367 found = 1;
368 break;
371 if (!found && download_status_is_ready(&ds->cert_dl_status, now,
372 MAX_CERT_DL_FAILURES)) {
373 log_notice(LD_DIR, "No current certificate known for authority %s; "
374 "launching request.", ds->nickname);
375 smartlist_add(missing_digests, ds->v3_identity_digest);
379 if (!smartlist_len(missing_digests)) {
380 goto done;
381 } else {
382 smartlist_t *fps = smartlist_create();
383 smartlist_add(fps, tor_strdup("fp/"));
384 SMARTLIST_FOREACH(missing_digests, const char *, d, {
385 char *fp;
386 if (digestmap_get(pending, d))
387 continue;
388 fp = tor_malloc(HEX_DIGEST_LEN+2);
389 base16_encode(fp, HEX_DIGEST_LEN+1, d, DIGEST_LEN);
390 fp[HEX_DIGEST_LEN] = '+';
391 fp[HEX_DIGEST_LEN+1] = '\0';
392 smartlist_add(fps, fp);
394 if (smartlist_len(fps) == 1) {
395 /* we didn't add any: they were all pending */
396 SMARTLIST_FOREACH(fps, char *, cp, tor_free(cp));
397 smartlist_free(fps);
398 goto done;
400 resource = smartlist_join_strings(fps, "", 0, NULL);
401 resource[strlen(resource)-1] = '\0';
402 SMARTLIST_FOREACH(fps, char *, cp, tor_free(cp));
403 smartlist_free(fps);
405 directory_get_from_dirserver(DIR_PURPOSE_FETCH_CERTIFICATE, 0,
406 resource, 1);
408 done:
409 tor_free(resource);
410 smartlist_free(missing_digests);
411 digestmap_free(pending, NULL);
414 /* Router descriptor storage.
416 * Routerdescs are stored in a big file, named "cached-descriptors". As new
417 * routerdescs arrive, we append them to a journal file named
418 * "cached-descriptors.new".
420 * From time to time, we replace "cached-descriptors" with a new file
421 * containing only the live, non-superseded descriptors, and clear
422 * cached-routers.new.
424 * On startup, we read both files.
427 /** Helper: return 1 iff the router log is so big we want to rebuild the
428 * store. */
429 static int
430 router_should_rebuild_store(desc_store_t *store)
432 if (store->store_len > (1<<16))
433 return (store->journal_len > store->store_len / 2 ||
434 store->bytes_dropped > store->store_len / 2);
435 else
436 return store->journal_len > (1<<15);
439 static INLINE desc_store_t *
440 desc_get_store(routerlist_t *rl, signed_descriptor_t *sd)
442 if (sd->is_extrainfo)
443 return &rl->extrainfo_store;
444 else
445 return &rl->desc_store;
448 /** Add the signed_descriptor_t in <b>desc</b> to the router
449 * journal; change its saved_location to SAVED_IN_JOURNAL and set its
450 * offset appropriately. */
451 static int
452 signed_desc_append_to_journal(signed_descriptor_t *desc,
453 desc_store_t *store)
455 char *fname = get_datadir_fname_suffix(store->fname_base, ".new");
456 const char *body = signed_descriptor_get_body_impl(desc,1);
457 size_t len = desc->signed_descriptor_len + desc->annotations_len;
459 tor_assert(len == strlen(body));
461 if (append_bytes_to_file(fname, body, len, 1)) {
462 log_warn(LD_FS, "Unable to store router descriptor");
463 tor_free(fname);
464 return -1;
466 desc->saved_location = SAVED_IN_JOURNAL;
467 tor_free(fname);
469 desc->saved_offset = store->journal_len;
470 store->journal_len += len;
472 return 0;
475 /** Sorting helper: return &lt;0, 0, or &gt;0 depending on whether the
476 * signed_descriptor_t* in *<b>a</b> is older, the same age as, or newer than
477 * the signed_descriptor_t* in *<b>b</b>. */
478 static int
479 _compare_signed_descriptors_by_age(const void **_a, const void **_b)
481 const signed_descriptor_t *r1 = *_a, *r2 = *_b;
482 return r1->published_on - r2->published_on;
485 /** If the journal is too long, or if <b>force</b> is true, then atomically
486 * replace the router store with the routers currently in our routerlist, and
487 * clear the journal. Return 0 on success, -1 on failure.
489 * If <b>extrainfo</b> is true, rebuild the extrainfo store; else rebuild the
490 * router descriptor store.
492 static int
493 router_rebuild_store(int force, desc_store_t *store)
495 smartlist_t *chunk_list = NULL;
496 char *fname = NULL, *fname_tmp = NULL;
497 int r = -1;
498 off_t offset = 0;
499 smartlist_t *signed_descriptors = NULL;
500 int nocache=0;
501 size_t total_expected_len = 0;
502 int had_any;
504 if (!force && !router_should_rebuild_store(store))
505 return 0;
506 if (!routerlist)
507 return 0;
509 if (store->type == EXTRAINFO_STORE)
510 had_any = !eimap_isempty(routerlist->extra_info_map);
511 else
512 had_any = (smartlist_len(routerlist->routers)+
513 smartlist_len(routerlist->old_routers))>0;
515 /* Don't save deadweight. */
516 routerlist_remove_old_routers();
518 log_info(LD_DIR, "Rebuilding %s cache", store->description);
520 fname = get_datadir_fname(store->fname_base);
521 fname_tmp = get_datadir_fname_suffix(store->fname_base, ".tmp");
523 chunk_list = smartlist_create();
525 /* We sort the routers by age to enhance locality on disk. */
526 signed_descriptors = smartlist_create();
527 if (store->type == EXTRAINFO_STORE) {
528 eimap_iter_t *iter;
529 for (iter = eimap_iter_init(routerlist->extra_info_map);
530 !eimap_iter_done(iter);
531 iter = eimap_iter_next(routerlist->extra_info_map, iter)) {
532 const char *key;
533 extrainfo_t *ei;
534 eimap_iter_get(iter, &key, &ei);
535 smartlist_add(signed_descriptors, &ei->cache_info);
537 } else {
538 SMARTLIST_FOREACH(routerlist->old_routers, signed_descriptor_t *, sd,
539 smartlist_add(signed_descriptors, sd));
540 SMARTLIST_FOREACH(routerlist->routers, routerinfo_t *, ri,
541 smartlist_add(signed_descriptors, &ri->cache_info));
544 smartlist_sort(signed_descriptors, _compare_signed_descriptors_by_age);
546 /* Now, add the appropriate members to chunk_list */
547 SMARTLIST_FOREACH(signed_descriptors, signed_descriptor_t *, sd,
549 sized_chunk_t *c;
550 const char *body = signed_descriptor_get_body_impl(sd, 1);
551 if (!body) {
552 log_warn(LD_BUG, "No descriptor available for router.");
553 goto done;
555 if (sd->do_not_cache) {
556 ++nocache;
557 continue;
559 c = tor_malloc(sizeof(sized_chunk_t));
560 c->bytes = body;
561 c->len = sd->signed_descriptor_len + sd->annotations_len;
562 total_expected_len += c->len;
563 smartlist_add(chunk_list, c);
566 if (write_chunks_to_file(fname_tmp, chunk_list, 1)<0) {
567 log_warn(LD_FS, "Error writing router store to disk.");
568 goto done;
571 /* Our mmap is now invalid. */
572 if (store->mmap) {
573 tor_munmap_file(store->mmap);
574 store->mmap = NULL;
577 if (replace_file(fname_tmp, fname)<0) {
578 log_warn(LD_FS, "Error replacing old router store.");
579 goto done;
582 errno = 0;
583 store->mmap = tor_mmap_file(fname);
584 if (! store->mmap) {
585 if (errno == ERANGE) {
586 /* empty store.*/
587 if (total_expected_len) {
588 log_warn(LD_FS, "We wrote some bytes to a new descriptor file at '%s',"
589 " but when we went to mmap it, it was empty!", fname);
590 } else if (had_any) {
591 log_notice(LD_FS, "We just removed every descriptor in '%s'. This is "
592 "okay if we're just starting up after a long time. "
593 "Otherwise, it's a bug.",
594 fname);
595 /* XXX020 should we reduce the severity of the above log
596 * message? I don't think we see it much in practice. -RD */
598 } else {
599 log_warn(LD_FS, "Unable to mmap new descriptor file at '%s'.",fname);
603 log_info(LD_DIR, "Reconstructing pointers into cache");
605 offset = 0;
606 SMARTLIST_FOREACH(signed_descriptors, signed_descriptor_t *, sd,
608 if (sd->do_not_cache)
609 continue;
610 sd->saved_location = SAVED_IN_CACHE;
611 if (store->mmap) {
612 tor_free(sd->signed_descriptor_body); // sets it to null
613 sd->saved_offset = offset;
615 offset += sd->signed_descriptor_len + sd->annotations_len;
616 signed_descriptor_get_body(sd); /* reconstruct and assert */
619 tor_free(fname);
620 fname = get_datadir_fname_suffix(store->fname_base, ".new");
621 write_str_to_file(fname, "", 1);
623 r = 0;
624 store->store_len = (size_t) offset;
625 store->journal_len = 0;
626 store->bytes_dropped = 0;
627 done:
628 if (signed_descriptors)
629 smartlist_free(signed_descriptors);
630 tor_free(fname);
631 tor_free(fname_tmp);
632 SMARTLIST_FOREACH(chunk_list, sized_chunk_t *, c, tor_free(c));
633 smartlist_free(chunk_list);
635 return r;
638 /** Helper: Reload a cache file and its associated journal, setting metadata
639 * appropriately. If <b>extrainfo</b> is true, reload the extrainfo store;
640 * else reload the router descriptor store. */
641 static int
642 router_reload_router_list_impl(desc_store_t *store)
644 char *fname = NULL, *altname = NULL, *contents = NULL;
645 struct stat st;
646 int read_from_old_location = 0;
647 int extrainfo = (store->type == EXTRAINFO_STORE);
648 time_t now = time(NULL);
649 store->journal_len = store->store_len = 0;
651 fname = get_datadir_fname(store->fname_base);
652 if (store->fname_alt_base)
653 altname = get_datadir_fname(store->fname_alt_base);
655 if (store->mmap) /* get rid of it first */
656 tor_munmap_file(store->mmap);
657 store->mmap = NULL;
659 store->mmap = tor_mmap_file(fname);
660 if (!store->mmap && altname && file_status(altname) == FN_FILE) {
661 read_from_old_location = 1;
662 log_notice(LD_DIR, "Couldn't read %s; trying to load routers from old "
663 "location %s.", fname, altname);
664 if ((store->mmap = tor_mmap_file(altname)))
665 read_from_old_location = 1;
667 if (altname && !read_from_old_location) {
668 remove_file_if_very_old(altname, now);
670 if (store->mmap) {
671 store->store_len = store->mmap->size;
672 if (extrainfo)
673 router_load_extrainfo_from_string(store->mmap->data,
674 store->mmap->data+store->mmap->size,
675 SAVED_IN_CACHE, NULL, 0);
676 else
677 router_load_routers_from_string(store->mmap->data,
678 store->mmap->data+store->mmap->size,
679 SAVED_IN_CACHE, NULL, 0, NULL);
682 tor_free(fname);
683 fname = get_datadir_fname_suffix(store->fname_base, ".new");
684 if (file_status(fname) == FN_FILE)
685 contents = read_file_to_str(fname, RFTS_BIN|RFTS_IGNORE_MISSING, &st);
686 if (read_from_old_location) {
687 tor_free(altname);
688 altname = get_datadir_fname_suffix(store->fname_alt_base, ".new");
689 if (!contents)
690 contents = read_file_to_str(altname, RFTS_BIN|RFTS_IGNORE_MISSING, &st);
691 else
692 remove_file_if_very_old(altname, now);
694 if (contents) {
695 if (extrainfo)
696 router_load_extrainfo_from_string(contents, NULL,SAVED_IN_JOURNAL,
697 NULL, 0);
698 else
699 router_load_routers_from_string(contents, NULL, SAVED_IN_JOURNAL,
700 NULL, 0, NULL);
701 store->journal_len = (size_t) st.st_size;
702 tor_free(contents);
705 tor_free(fname);
706 tor_free(altname);
708 if (store->journal_len || read_from_old_location) {
709 /* Always clear the journal on startup.*/
710 router_rebuild_store(1, store);
711 } else if (!extrainfo) {
712 /* Don't cache expired routers. (This is in an else because
713 * router_rebuild_store() also calls remove_old_routers().) */
714 routerlist_remove_old_routers();
717 return 0;
720 /** Load all cached router descriptors and extra-info documents from the
721 * store. Return 0 on success and -1 on failure.
724 router_reload_router_list(void)
726 routerlist_t *rl = router_get_routerlist();
727 if (router_reload_router_list_impl(&rl->desc_store))
728 return -1;
729 if (router_reload_router_list_impl(&rl->extrainfo_store))
730 return -1;
731 return 0;
734 /** Return a smartlist containing a list of trusted_dir_server_t * for all
735 * known trusted dirservers. Callers must not modify the list or its
736 * contents.
738 smartlist_t *
739 router_get_trusted_dir_servers(void)
741 if (!trusted_dir_servers)
742 trusted_dir_servers = smartlist_create();
744 return trusted_dir_servers;
747 /** Try to find a running dirserver that supports operations of <b>type</b>.
749 * If there are no running dirservers in our routerlist and the
750 * <b>PDS_RETRY_IF_NO_SERVERS</b> flag is set, set all the authoritative ones
751 * as running again, and pick one.
753 * If the <b>PDS_IGNORE_FASCISTFIREWALL</b> flag is set, then include
754 * dirservers that we can't reach.
756 * If the <b>PDS_ALLOW_SELF</b> flag is not set, then don't include ourself
757 * (if we're a dirserver).
759 * Don't pick an authority if any non-authority is viable; try to avoid using
760 * servers that have returned 503 recently.
762 routerstatus_t *
763 router_pick_directory_server(authority_type_t type, int flags)
765 routerstatus_t *choice;
766 if (get_options()->PreferTunneledDirConns)
767 flags |= _PDS_PREFER_TUNNELED_DIR_CONNS;
769 if (!routerlist)
770 return NULL;
772 choice = router_pick_directory_server_impl(type, flags);
773 if (choice || !(flags & PDS_RETRY_IF_NO_SERVERS))
774 return choice;
776 log_info(LD_DIR,
777 "No reachable router entries for dirservers. "
778 "Trying them all again.");
779 /* mark all authdirservers as up again */
780 mark_all_trusteddirservers_up();
781 /* try again */
782 choice = router_pick_directory_server_impl(type, flags);
783 if (choice)
784 return choice;
786 /* XXXX020 what's the point of *reloading* and trying again?? -NM */
787 log_info(LD_DIR,"Still no %s router entries. Reloading and trying again.",
788 (flags & PDS_IGNORE_FASCISTFIREWALL) ? "known" : "reachable");
789 if (router_reload_router_list()) {
790 return NULL;
792 /* give it one last try */
793 choice = router_pick_directory_server_impl(type, flags);
794 return choice;
797 /** Return the trusted_dir_server_t for the directory authority whose identity
798 * key hashes to <b>digest</b>, or NULL if no such authority is known.
800 trusted_dir_server_t *
801 router_get_trusteddirserver_by_digest(const char *digest)
803 if (!trusted_dir_servers)
804 return NULL;
806 SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, ds,
808 if (!memcmp(ds->digest, digest, DIGEST_LEN))
809 return ds;
812 return NULL;
815 /** Return the trusted_dir_server_t for the directory authority whose identity
816 * key hashes to <b>digest</b>, or NULL if no such authority is known.
818 trusted_dir_server_t *
819 trusteddirserver_get_by_v3_auth_digest(const char *digest)
821 if (!trusted_dir_servers)
822 return NULL;
824 SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, ds,
826 if (!memcmp(ds->v3_identity_digest, digest, DIGEST_LEN) &&
827 (ds->type & V3_AUTHORITY))
828 return ds;
831 return NULL;
834 /** Try to find a running trusted dirserver. Flags are as for
835 * router_pick_directory_server.
837 routerstatus_t *
838 router_pick_trusteddirserver(authority_type_t type, int flags)
840 routerstatus_t *choice;
841 if (get_options()->PreferTunneledDirConns)
842 flags |= _PDS_PREFER_TUNNELED_DIR_CONNS;
844 choice = router_pick_trusteddirserver_impl(type, flags);
845 if (choice || !(flags & PDS_RETRY_IF_NO_SERVERS))
846 return choice;
848 log_info(LD_DIR,
849 "No trusted dirservers are reachable. Trying them all again.");
850 mark_all_trusteddirservers_up();
851 return router_pick_trusteddirserver_impl(type, flags);
854 /** How long do we avoid using a directory server after it's given us a 503? */
855 #define DIR_503_TIMEOUT (60*60)
857 /** Pick a random running valid directory server/mirror from our
858 * routerlist. Arguments are as for router_pick_directory_server(), except
859 * that RETRY_IF_NO_SERVERS is ignored, and:
861 * If the _PDS_PREFER_TUNNELED_DIR_CONNS flag is set, prefer directory servers
862 * that we can use with BEGINDIR.
864 static routerstatus_t *
865 router_pick_directory_server_impl(authority_type_t type, int flags)
867 routerstatus_t *result;
868 smartlist_t *direct, *tunnel;
869 smartlist_t *trusted_direct, *trusted_tunnel;
870 smartlist_t *overloaded_direct, *overloaded_tunnel;
871 time_t now = time(NULL);
872 const networkstatus_vote_t *consensus = networkstatus_get_latest_consensus();
873 int requireother = ! (flags & PDS_ALLOW_SELF);
874 int fascistfirewall = ! (flags & PDS_IGNORE_FASCISTFIREWALL);
875 int prefer_tunnel = (flags & _PDS_PREFER_TUNNELED_DIR_CONNS);
877 if (!consensus)
878 return NULL;
880 direct = smartlist_create();
881 tunnel = smartlist_create();
882 trusted_direct = smartlist_create();
883 trusted_tunnel = smartlist_create();
884 overloaded_direct = smartlist_create();
885 overloaded_tunnel = smartlist_create();
887 /* Find all the running dirservers we know about. */
888 SMARTLIST_FOREACH(consensus->routerstatus_list, routerstatus_t *, status,
890 int is_trusted;
891 int is_overloaded = status->last_dir_503_at + DIR_503_TIMEOUT > now;
892 if (!status->is_running || !status->dir_port || !status->is_valid)
893 continue;
894 if (status->is_bad_directory)
895 continue;
896 if (requireother && router_digest_is_me(status->identity_digest))
897 continue;
898 if (type & V3_AUTHORITY) {
899 if (!(status->version_supports_v3_dir ||
900 router_digest_is_trusted_dir_type(status->identity_digest,
901 V3_AUTHORITY)))
902 continue;
904 is_trusted = router_digest_is_trusted_dir(status->identity_digest);
905 if ((type & V2_AUTHORITY) && !(status->is_v2_dir || is_trusted))
906 continue;
907 if ((type & EXTRAINFO_CACHE) &&
908 !router_supports_extrainfo(status->identity_digest, 0))
909 continue;
910 if (prefer_tunnel &&
911 status->version_supports_begindir &&
912 (!fascistfirewall ||
913 fascist_firewall_allows_address_or(status->addr, status->or_port)))
914 smartlist_add(is_trusted ? trusted_tunnel :
915 is_overloaded ? overloaded_tunnel : tunnel, status);
916 else if (!fascistfirewall ||
917 fascist_firewall_allows_address_dir(status->addr,
918 status->dir_port))
919 smartlist_add(is_trusted ? trusted_direct :
920 is_overloaded ? overloaded_direct : direct, status);
923 if (smartlist_len(tunnel)) {
924 result = routerstatus_sl_choose_by_bandwidth(tunnel);
925 } else if (smartlist_len(overloaded_tunnel)) {
926 result = routerstatus_sl_choose_by_bandwidth(overloaded_tunnel);
927 } else if (smartlist_len(trusted_tunnel)) {
928 /* FFFF We don't distinguish between trusteds and overloaded trusteds
929 * yet. Maybe one day we should. */
930 /* FFFF We also don't load balance over authorities yet. I think this
931 * is a feature, but it could easily be a bug. -RD */
932 result = smartlist_choose(trusted_tunnel);
933 } else if (smartlist_len(direct)) {
934 result = routerstatus_sl_choose_by_bandwidth(direct);
935 } else if (smartlist_len(overloaded_direct)) {
936 result = routerstatus_sl_choose_by_bandwidth(overloaded_direct);
937 } else {
938 result = smartlist_choose(trusted_direct);
940 smartlist_free(direct);
941 smartlist_free(tunnel);
942 smartlist_free(trusted_direct);
943 smartlist_free(trusted_tunnel);
944 smartlist_free(overloaded_direct);
945 smartlist_free(overloaded_tunnel);
946 return result;
949 /** Choose randomly from among the trusted dirservers that are up. Flags
950 * are as for router_pick_directory_server_impl().
952 static routerstatus_t *
953 router_pick_trusteddirserver_impl(authority_type_t type, int flags)
955 smartlist_t *direct, *tunnel;
956 smartlist_t *overloaded_direct, *overloaded_tunnel;
957 routerinfo_t *me = router_get_my_routerinfo();
958 routerstatus_t *result;
959 time_t now = time(NULL);
960 int requireother = ! (flags & PDS_ALLOW_SELF);
961 int fascistfirewall = ! (flags & PDS_IGNORE_FASCISTFIREWALL);
962 int prefer_tunnel = (flags & _PDS_PREFER_TUNNELED_DIR_CONNS);
964 if (!trusted_dir_servers)
965 return NULL;
967 direct = smartlist_create();
968 tunnel = smartlist_create();
969 overloaded_direct = smartlist_create();
970 overloaded_tunnel = smartlist_create();
972 SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, d,
974 int is_overloaded =
975 d->fake_status.last_dir_503_at + DIR_503_TIMEOUT > now;
976 if (!d->is_running) continue;
977 if ((type & d->type) == 0)
978 continue;
979 if ((type & EXTRAINFO_CACHE) &&
980 !router_supports_extrainfo(d->digest, 1))
981 continue;
982 if (requireother && me && router_digest_is_me(d->digest))
983 continue;
984 if (prefer_tunnel &&
985 d->or_port &&
986 (!fascistfirewall ||
987 fascist_firewall_allows_address_or(d->addr, d->or_port)))
988 smartlist_add(is_overloaded ? overloaded_tunnel : tunnel,
989 &d->fake_status);
990 else if (!fascistfirewall ||
991 fascist_firewall_allows_address_dir(d->addr, d->dir_port))
992 smartlist_add(is_overloaded ? overloaded_direct : direct,
993 &d->fake_status);
996 if (smartlist_len(tunnel)) {
997 result = smartlist_choose(tunnel);
998 } else if (smartlist_len(overloaded_tunnel)) {
999 result = smartlist_choose(overloaded_tunnel);
1000 } else if (smartlist_len(direct)) {
1001 result = smartlist_choose(direct);
1002 } else {
1003 result = smartlist_choose(overloaded_direct);
1006 smartlist_free(direct);
1007 smartlist_free(tunnel);
1008 smartlist_free(overloaded_direct);
1009 smartlist_free(overloaded_tunnel);
1010 return result;
1013 /** Go through and mark the authoritative dirservers as up. */
1014 static void
1015 mark_all_trusteddirservers_up(void)
1017 if (routerlist) {
1018 SMARTLIST_FOREACH(routerlist->routers, routerinfo_t *, router,
1019 if (router_digest_is_trusted_dir(router->cache_info.identity_digest) &&
1020 router->dir_port > 0) {
1021 router->is_running = 1;
1024 if (trusted_dir_servers) {
1025 SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, dir,
1027 routerstatus_t *rs;
1028 dir->is_running = 1;
1029 download_status_reset(&dir->v2_ns_dl_status);
1030 rs = router_get_consensus_status_by_id(dir->digest);
1031 if (rs && !rs->is_running) {
1032 rs->is_running = 1;
1033 rs->last_dir_503_at = 0;
1034 control_event_networkstatus_changed_single(rs);
1038 router_dir_info_changed();
1041 /** Reset all internal variables used to count failed downloads of network
1042 * status objects. */
1043 void
1044 router_reset_status_download_failures(void)
1046 mark_all_trusteddirservers_up();
1049 /** Return true iff router1 and router2 have the same /16 network. */
1050 static INLINE int
1051 routers_in_same_network_family(routerinfo_t *r1, routerinfo_t *r2)
1053 return (r1->addr & 0xffff0000) == (r2->addr & 0xffff0000);
1056 /** Look through the routerlist and identify routers that
1057 * advertise the same /16 network address as <b>router</b>.
1058 * Add each of them to <b>sl</b>.
1060 static void
1061 routerlist_add_network_family(smartlist_t *sl, routerinfo_t *router)
1063 SMARTLIST_FOREACH(routerlist->routers, routerinfo_t *, r,
1065 if (router != r && routers_in_same_network_family(router, r))
1066 smartlist_add(sl, r);
1070 /** Add all the family of <b>router</b> to the smartlist <b>sl</b>.
1071 * This is used to make sure we don't pick siblings in a single path.
1073 void
1074 routerlist_add_family(smartlist_t *sl, routerinfo_t *router)
1076 routerinfo_t *r;
1077 config_line_t *cl;
1078 or_options_t *options = get_options();
1080 /* First, add any routers with similar network addresses. */
1081 if (options->EnforceDistinctSubnets)
1082 routerlist_add_network_family(sl, router);
1084 if (router->declared_family) {
1085 /* Add every r such that router declares familyness with r, and r
1086 * declares familyhood with router. */
1087 SMARTLIST_FOREACH(router->declared_family, const char *, n,
1089 if (!(r = router_get_by_nickname(n, 0)))
1090 continue;
1091 if (!r->declared_family)
1092 continue;
1093 SMARTLIST_FOREACH(r->declared_family, const char *, n2,
1095 if (router_nickname_matches(router, n2))
1096 smartlist_add(sl, r);
1101 /* If the user declared any families locally, honor those too. */
1102 for (cl = options->NodeFamilies; cl; cl = cl->next) {
1103 if (router_nickname_is_in_list(router, cl->value)) {
1104 add_nickname_list_to_smartlist(sl, cl->value, 0);
1109 /** Return true iff r is named by some nickname in <b>lst</b>. */
1110 static INLINE int
1111 router_in_nickname_smartlist(smartlist_t *lst, routerinfo_t *r)
1113 if (!lst) return 0;
1114 SMARTLIST_FOREACH(lst, const char *, name,
1115 if (router_nickname_matches(r, name))
1116 return 1;);
1117 return 0;
1120 /** Return true iff r1 and r2 are in the same family, but not the same
1121 * router. */
1123 routers_in_same_family(routerinfo_t *r1, routerinfo_t *r2)
1125 or_options_t *options = get_options();
1126 config_line_t *cl;
1128 if (options->EnforceDistinctSubnets && routers_in_same_network_family(r1,r2))
1129 return 1;
1131 if (router_in_nickname_smartlist(r1->declared_family, r2) &&
1132 router_in_nickname_smartlist(r2->declared_family, r1))
1133 return 1;
1135 for (cl = options->NodeFamilies; cl; cl = cl->next) {
1136 if (router_nickname_is_in_list(r1, cl->value) &&
1137 router_nickname_is_in_list(r2, cl->value))
1138 return 1;
1140 return 0;
1143 /** Given a (possibly NULL) comma-and-whitespace separated list of nicknames,
1144 * see which nicknames in <b>list</b> name routers in our routerlist, and add
1145 * the routerinfos for those routers to <b>sl</b>. If <b>must_be_running</b>,
1146 * only include routers that we think are running.
1147 * Warn if any non-Named routers are specified by nickname.
1149 void
1150 add_nickname_list_to_smartlist(smartlist_t *sl, const char *list,
1151 int must_be_running)
1153 routerinfo_t *router;
1154 smartlist_t *nickname_list;
1155 int have_dir_info = router_have_minimum_dir_info();
1157 if (!list)
1158 return; /* nothing to do */
1159 tor_assert(sl);
1161 nickname_list = smartlist_create();
1162 if (!warned_nicknames)
1163 warned_nicknames = smartlist_create();
1165 smartlist_split_string(nickname_list, list, ",",
1166 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
1168 SMARTLIST_FOREACH(nickname_list, const char *, nick, {
1169 int warned;
1170 if (!is_legal_nickname_or_hexdigest(nick)) {
1171 log_warn(LD_CONFIG, "Nickname '%s' is misformed; skipping", nick);
1172 continue;
1174 router = router_get_by_nickname(nick, 1);
1175 warned = smartlist_string_isin(warned_nicknames, nick);
1176 if (router) {
1177 if (!must_be_running || router->is_running) {
1178 smartlist_add(sl,router);
1180 } else if (!router_get_consensus_status_by_nickname(nick,1)) {
1181 if (!warned) {
1182 log_fn(have_dir_info ? LOG_WARN : LOG_INFO, LD_CONFIG,
1183 "Nickname list includes '%s' which isn't a known router.",nick);
1184 smartlist_add(warned_nicknames, tor_strdup(nick));
1188 SMARTLIST_FOREACH(nickname_list, char *, nick, tor_free(nick));
1189 smartlist_free(nickname_list);
1192 /** Return 1 iff any member of the (possibly NULL) comma-separated list
1193 * <b>list</b> is an acceptable nickname or hexdigest for <b>router</b>. Else
1194 * return 0.
1197 router_nickname_is_in_list(routerinfo_t *router, const char *list)
1199 smartlist_t *nickname_list;
1200 int v = 0;
1202 if (!list)
1203 return 0; /* definitely not */
1204 tor_assert(router);
1206 nickname_list = smartlist_create();
1207 smartlist_split_string(nickname_list, list, ",",
1208 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
1209 SMARTLIST_FOREACH(nickname_list, const char *, cp,
1210 if (router_nickname_matches(router, cp)) {v=1;break;});
1211 SMARTLIST_FOREACH(nickname_list, char *, cp, tor_free(cp));
1212 smartlist_free(nickname_list);
1213 return v;
1216 /** Add every suitable router from our routerlist to <b>sl</b>, so that
1217 * we can pick a node for a circuit.
1219 static void
1220 router_add_running_routers_to_smartlist(smartlist_t *sl, int allow_invalid,
1221 int need_uptime, int need_capacity,
1222 int need_guard)
1224 if (!routerlist)
1225 return;
1227 SMARTLIST_FOREACH(routerlist->routers, routerinfo_t *, router,
1229 if (router->is_running &&
1230 router->purpose == ROUTER_PURPOSE_GENERAL &&
1231 (router->is_valid || allow_invalid) &&
1232 !router_is_unreliable(router, need_uptime,
1233 need_capacity, need_guard)) {
1234 /* If it's running, and it's suitable according to the
1235 * other flags we had in mind */
1236 smartlist_add(sl, router);
1241 /** Look through the routerlist until we find a router that has my key.
1242 Return it. */
1243 routerinfo_t *
1244 routerlist_find_my_routerinfo(void)
1246 if (!routerlist)
1247 return NULL;
1249 SMARTLIST_FOREACH(routerlist->routers, routerinfo_t *, router,
1251 if (router_is_me(router))
1252 return router;
1254 return NULL;
1257 /** Find a router that's up, that has this IP address, and
1258 * that allows exit to this address:port, or return NULL if there
1259 * isn't a good one.
1261 routerinfo_t *
1262 router_find_exact_exit_enclave(const char *address, uint16_t port)
1264 uint32_t addr;
1265 struct in_addr in;
1267 if (!tor_inet_aton(address, &in))
1268 return NULL; /* it's not an IP already */
1269 addr = ntohl(in.s_addr);
1271 SMARTLIST_FOREACH(routerlist->routers, routerinfo_t *, router,
1273 if (router->is_running &&
1274 router->addr == addr &&
1275 compare_addr_to_addr_policy(addr, port, router->exit_policy) ==
1276 ADDR_POLICY_ACCEPTED)
1277 return router;
1279 return NULL;
1282 /** Return 1 if <b>router</b> is not suitable for these parameters, else 0.
1283 * If <b>need_uptime</b> is non-zero, we require a minimum uptime.
1284 * If <b>need_capacity</b> is non-zero, we require a minimum advertised
1285 * bandwidth.
1286 * If <b>need_guard</b>, we require that the router is a possible entry guard.
1289 router_is_unreliable(routerinfo_t *router, int need_uptime,
1290 int need_capacity, int need_guard)
1292 if (need_uptime && !router->is_stable)
1293 return 1;
1294 if (need_capacity && !router->is_fast)
1295 return 1;
1296 if (need_guard && !router->is_possible_guard)
1297 return 1;
1298 return 0;
1301 /** Return the smaller of the router's configured BandwidthRate
1302 * and its advertised capacity. */
1303 uint32_t
1304 router_get_advertised_bandwidth(routerinfo_t *router)
1306 if (router->bandwidthcapacity < router->bandwidthrate)
1307 return router->bandwidthcapacity;
1308 return router->bandwidthrate;
1311 /** Do not weight any declared bandwidth more than this much when picking
1312 * routers by bandwidth. */
1313 #define DEFAULT_MAX_BELIEVABLE_BANDWIDTH 10000000 /* 10 MB/sec */
1315 /** Eventually, the number we return will come from the directory
1316 * consensus, so clients can dynamically update to better numbers.
1318 * But for now, or in case there is no consensus available, just return
1319 * a sufficient default. */
1320 static uint32_t
1321 get_max_believable_bandwidth(void)
1323 return DEFAULT_MAX_BELIEVABLE_BANDWIDTH;
1326 /** Helper function:
1327 * choose a random element of smartlist <b>sl</b>, weighted by
1328 * the advertised bandwidth of each element.
1330 * If <b>statuses</b> is zero, then <b>sl</b> is a list of
1331 * routerinfo_t's. Otherwise it's a list of routerstatus_t's.
1333 * If <b>for_exit</b>, we're picking an exit node: consider all nodes'
1334 * bandwidth equally regardless of their Exit status, since there may be
1335 * some in the list because they exit to obscure ports. If not <b>for_exit</b>,
1336 * we're picking a non-exit node: weight exit-node's bandwidth less
1337 * depending on the smallness of the fraction of Exit-to-total bandwidth.
1339 * If <b>for_guard</b>, we're picking a guard node: consider all guard's
1340 * bandwidth equally. Otherwise, weight guards proportionally less.
1343 static void *
1344 smartlist_choose_by_bandwidth(smartlist_t *sl, bandwidth_weight_rule_t rule,
1345 int statuses)
1347 unsigned int i;
1348 routerinfo_t *router;
1349 routerstatus_t *status=NULL;
1350 int32_t *bandwidths;
1351 int is_exit;
1352 int is_guard;
1353 uint64_t total_nonexit_bw = 0, total_exit_bw = 0, total_bw = 0;
1354 uint64_t total_nonguard_bw = 0, total_guard_bw = 0;
1355 uint64_t rand_bw, tmp;
1356 double exit_weight;
1357 double guard_weight;
1358 int n_unknown = 0;
1359 bitarray_t *exit_bits;
1360 bitarray_t *guard_bits;
1361 uint32_t max_believable_bw = get_max_believable_bandwidth();
1363 /* Can't choose exit and guard at same time */
1364 tor_assert(rule == NO_WEIGHTING ||
1365 rule == WEIGHT_FOR_EXIT ||
1366 rule == WEIGHT_FOR_GUARD);
1368 /* First count the total bandwidth weight, and make a list
1369 * of each value. <0 means "unknown; no routerinfo." We use the
1370 * bits of negative values to remember whether the router was fast (-x)&1
1371 * and whether it was an exit (-x)&2 or guard (-x)&4. Yes, it's a hack. */
1372 bandwidths = tor_malloc(sizeof(int32_t)*smartlist_len(sl));
1373 exit_bits = bitarray_init_zero(smartlist_len(sl));
1374 guard_bits = bitarray_init_zero(smartlist_len(sl));
1376 /* Iterate over all the routerinfo_t or routerstatus_t, and */
1377 for (i = 0; i < (unsigned)smartlist_len(sl); ++i) {
1378 /* first, learn what bandwidth we think i has */
1379 int is_known = 1;
1380 int32_t flags = 0;
1381 uint32_t this_bw = 0;
1382 if (statuses) {
1383 /* need to extract router info */
1384 status = smartlist_get(sl, i);
1385 router = router_get_by_digest(status->identity_digest);
1386 is_exit = status->is_exit;
1387 is_guard = status->is_possible_guard;
1388 if (router) {
1389 this_bw = router_get_advertised_bandwidth(router);
1390 } else { /* guess */
1391 is_known = 0;
1392 flags = status->is_fast ? 1 : 0;
1393 flags |= is_exit ? 2 : 0;
1394 flags |= is_guard ? 4 : 0;
1396 } else {
1397 router = smartlist_get(sl, i);
1398 is_exit = router->is_exit;
1399 is_guard = router->is_possible_guard;
1400 this_bw = router_get_advertised_bandwidth(router);
1402 if (is_exit)
1403 bitarray_set(exit_bits, i);
1404 if (is_guard)
1405 bitarray_set(guard_bits, i);
1406 /* if they claim something huge, don't believe it */
1407 if (this_bw > max_believable_bw) {
1408 char fp[HEX_DIGEST_LEN+1];
1409 base16_encode(fp, sizeof(fp), statuses ?
1410 status->identity_digest :
1411 router->cache_info.identity_digest,
1412 DIGEST_LEN);
1413 log_fn(LOG_PROTOCOL_WARN, LD_DIR,
1414 "Bandwidth %d for router %s (%s) exceeds allowed max %d, capping",
1415 this_bw, router ? router->nickname : "(null)",
1416 fp, max_believable_bw);
1417 this_bw = max_believable_bw;
1419 if (is_known) {
1420 bandwidths[i] = (int32_t) this_bw; // safe since MAX_BELIEVABLE<INT32_MAX
1421 if (is_guard)
1422 total_guard_bw += this_bw;
1423 else
1424 total_nonguard_bw += this_bw;
1425 if (is_exit)
1426 total_exit_bw += this_bw;
1427 else
1428 total_nonexit_bw += this_bw;
1429 } else {
1430 ++n_unknown;
1431 bandwidths[i] = -flags;
1435 /* Now, fill in the unknown values. */
1436 if (n_unknown) {
1437 int32_t avg_fast, avg_slow;
1438 if (total_exit_bw+total_nonexit_bw) {
1439 /* if there's some bandwidth, there's at least one known router,
1440 * so no worries about div by 0 here */
1441 int n_known = smartlist_len(sl)-n_unknown;
1442 avg_fast = avg_slow = (int32_t)
1443 ((total_exit_bw+total_nonexit_bw)/((uint64_t) n_known));
1444 } else {
1445 avg_fast = 40000;
1446 avg_slow = 20000;
1448 for (i=0; i<(unsigned)smartlist_len(sl); ++i) {
1449 int32_t bw = bandwidths[i];
1450 if (bw>=0)
1451 continue;
1452 is_exit = ((-bw)&2);
1453 is_guard = ((-bw)&4);
1454 bandwidths[i] = ((-bw)&1) ? avg_fast : avg_slow;
1455 if (is_exit)
1456 total_exit_bw += bandwidths[i];
1457 else
1458 total_nonexit_bw += bandwidths[i];
1459 if (is_guard)
1460 total_guard_bw += bandwidths[i];
1461 else
1462 total_nonguard_bw += bandwidths[i];
1466 /* If there's no bandwidth at all, pick at random. */
1467 if (!(total_exit_bw+total_nonexit_bw)) {
1468 tor_free(bandwidths);
1469 tor_free(exit_bits);
1470 tor_free(guard_bits);
1471 return smartlist_choose(sl);
1474 /* Figure out how to weight exits and guards */
1476 double all_bw = U64_TO_DBL(total_exit_bw+total_nonexit_bw);
1477 double exit_bw = U64_TO_DBL(total_exit_bw);
1478 double guard_bw = U64_TO_DBL(total_guard_bw);
1480 * For detailed derivation of this formula, see
1481 * http://archives.seul.org/or/dev/Jul-2007/msg00056.html
1483 if (rule == WEIGHT_FOR_EXIT)
1484 exit_weight = 1.0;
1485 else
1486 exit_weight = 1.0 - all_bw/(3.0*exit_bw);
1488 if (rule == WEIGHT_FOR_GUARD)
1489 guard_weight = 1.0;
1490 else
1491 guard_weight = 1.0 - all_bw/(3.0*guard_bw);
1493 if (exit_weight <= 0.0)
1494 exit_weight = 0.0;
1496 if (guard_weight <= 0.0)
1497 guard_weight = 0.0;
1499 total_bw = 0;
1500 for (i=0; i < (unsigned)smartlist_len(sl); i++) {
1501 is_exit = bitarray_is_set(exit_bits, i);
1502 is_guard = bitarray_is_set(guard_bits, i);
1503 if (is_exit && is_guard)
1504 total_bw += ((uint64_t)(bandwidths[i] * exit_weight * guard_weight));
1505 else if (is_guard)
1506 total_bw += ((uint64_t)(bandwidths[i] * guard_weight));
1507 else if (is_exit)
1508 total_bw += ((uint64_t)(bandwidths[i] * exit_weight));
1509 else
1510 total_bw += bandwidths[i];
1513 log_debug(LD_CIRC, "Total weighted bw = "U64_FORMAT
1514 ", exit bw = "U64_FORMAT
1515 ", nonexit bw = "U64_FORMAT", exit weight = %lf "
1516 "(for exit == %d)"
1517 ", guard bw = "U64_FORMAT
1518 ", nonguard bw = "U64_FORMAT", guard weight = %lf "
1519 "(for guard == %d)",
1520 U64_PRINTF_ARG(total_bw),
1521 U64_PRINTF_ARG(total_exit_bw), U64_PRINTF_ARG(total_nonexit_bw),
1522 exit_weight, (int)(rule == WEIGHT_FOR_EXIT),
1523 U64_PRINTF_ARG(total_guard_bw), U64_PRINTF_ARG(total_nonguard_bw),
1524 guard_weight, (int)(rule == WEIGHT_FOR_GUARD));
1526 /* Almost done: choose a random value from the bandwidth weights. */
1527 rand_bw = crypto_rand_uint64(total_bw);
1529 /* Last, count through sl until we get to the element we picked */
1530 tmp = 0;
1531 for (i=0; i < (unsigned)smartlist_len(sl); i++) {
1532 is_exit = bitarray_is_set(exit_bits, i);
1533 is_guard = bitarray_is_set(guard_bits, i);
1535 /* Weights can be 0 if not counting guards/exits */
1536 if (is_exit && is_guard)
1537 tmp += ((uint64_t)(bandwidths[i] * exit_weight * guard_weight));
1538 else if (is_guard)
1539 tmp += ((uint64_t)(bandwidths[i] * guard_weight));
1540 else if (is_exit)
1541 tmp += ((uint64_t)(bandwidths[i] * exit_weight));
1542 else
1543 tmp += bandwidths[i];
1545 if (tmp >= rand_bw)
1546 break;
1548 if (i == (unsigned)smartlist_len(sl)) {
1549 /* This was once possible due to round-off error, but shouldn't be able
1550 * to occur any longer. */
1551 tor_fragile_assert();
1552 --i;
1553 log_warn(LD_BUG, "Round-off error in computing bandwidth had an effect on "
1554 " which router we chose. Please tell the developers. "
1555 U64_FORMAT " " U64_FORMAT " " U64_FORMAT, U64_PRINTF_ARG(tmp),
1556 U64_PRINTF_ARG(rand_bw), U64_PRINTF_ARG(total_bw));
1558 tor_free(bandwidths);
1559 tor_free(exit_bits);
1560 tor_free(guard_bits);
1561 return smartlist_get(sl, i);
1564 /** Choose a random element of router list <b>sl</b>, weighted by
1565 * the advertised bandwidth of each router.
1567 routerinfo_t *
1568 routerlist_sl_choose_by_bandwidth(smartlist_t *sl,
1569 bandwidth_weight_rule_t rule)
1571 return smartlist_choose_by_bandwidth(sl, rule, 0);
1574 /** Choose a random element of status list <b>sl</b>, weighted by
1575 * the advertised bandwidth of each status.
1577 routerstatus_t *
1578 routerstatus_sl_choose_by_bandwidth(smartlist_t *sl)
1580 /* We are choosing neither exit nor guard here. Weight accordingly. */
1581 return smartlist_choose_by_bandwidth(sl, NO_WEIGHTING, 1);
1584 /** Return a random running router from the routerlist. If any node
1585 * named in <b>preferred</b> is available, pick one of those. Never
1586 * pick a node named in <b>excluded</b>, or whose routerinfo is in
1587 * <b>excludedsmartlist</b>, even if they are the only nodes
1588 * available. If <b>strict</b> is true, never pick any node besides
1589 * those in <b>preferred</b>.
1590 * If <b>need_uptime</b> is non-zero and any router has more than
1591 * a minimum uptime, return one of those.
1592 * If <b>need_capacity</b> is non-zero, weight your choice by the
1593 * advertised capacity of each router.
1594 * If ! <b>allow_invalid</b>, consider only Valid routers.
1595 * If <b>need_guard</b>, consider only Guard routers.
1596 * If <b>weight_for_exit</b>, we weight bandwidths as if picking an exit node,
1597 * otherwise we weight bandwidths for picking a relay node (that is, possibly
1598 * discounting exit nodes).
1600 routerinfo_t *
1601 router_choose_random_node(const char *preferred,
1602 const char *excluded,
1603 smartlist_t *excludedsmartlist,
1604 int need_uptime, int need_capacity,
1605 int need_guard,
1606 int allow_invalid, int strict,
1607 int weight_for_exit)
1609 smartlist_t *sl, *excludednodes;
1610 routerinfo_t *choice = NULL;
1611 bandwidth_weight_rule_t rule;
1613 tor_assert(!(weight_for_exit && need_guard));
1614 rule = weight_for_exit ? WEIGHT_FOR_EXIT :
1615 (need_guard ? WEIGHT_FOR_GUARD : NO_WEIGHTING);
1617 excludednodes = smartlist_create();
1618 add_nickname_list_to_smartlist(excludednodes,excluded,0);
1620 /* Try the preferred nodes first. Ignore need_uptime and need_capacity
1621 * and need_guard, since the user explicitly asked for these nodes. */
1622 if (preferred) {
1623 sl = smartlist_create();
1624 add_nickname_list_to_smartlist(sl,preferred,1);
1625 smartlist_subtract(sl,excludednodes);
1626 if (excludedsmartlist)
1627 smartlist_subtract(sl,excludedsmartlist);
1628 choice = smartlist_choose(sl);
1629 smartlist_free(sl);
1631 if (!choice && !strict) {
1632 /* Then give up on our preferred choices: any node
1633 * will do that has the required attributes. */
1634 sl = smartlist_create();
1635 router_add_running_routers_to_smartlist(sl, allow_invalid,
1636 need_uptime, need_capacity,
1637 need_guard);
1638 smartlist_subtract(sl,excludednodes);
1639 if (excludedsmartlist)
1640 smartlist_subtract(sl,excludedsmartlist);
1642 if (need_capacity || need_guard)
1643 choice = routerlist_sl_choose_by_bandwidth(sl, rule);
1644 else
1645 choice = smartlist_choose(sl);
1647 smartlist_free(sl);
1648 if (!choice && (need_uptime || need_capacity || need_guard)) {
1649 /* try once more -- recurse but with fewer restrictions. */
1650 log_info(LD_CIRC,
1651 "We couldn't find any live%s%s%s routers; falling back "
1652 "to list of all routers.",
1653 need_capacity?", fast":"",
1654 need_uptime?", stable":"",
1655 need_guard?", guard":"");
1656 choice = router_choose_random_node(
1657 NULL, excluded, excludedsmartlist,
1658 0, 0, 0, allow_invalid, 0, weight_for_exit);
1661 smartlist_free(excludednodes);
1662 if (!choice) {
1663 if (strict) {
1664 log_warn(LD_CIRC, "All preferred nodes were down when trying to choose "
1665 "node, and the Strict[...]Nodes option is set. Failing.");
1666 } else {
1667 log_warn(LD_CIRC,
1668 "No available nodes when trying to choose node. Failing.");
1671 return choice;
1674 /** Return true iff the digest of <b>router</b>'s identity key,
1675 * encoded in hexadecimal, matches <b>hexdigest</b> (which is
1676 * optionally prefixed with a single dollar sign). Return false if
1677 * <b>hexdigest</b> is malformed, or it doesn't match. */
1678 static INLINE int
1679 router_hex_digest_matches(routerinfo_t *router, const char *hexdigest)
1681 char digest[DIGEST_LEN];
1682 size_t len;
1683 tor_assert(hexdigest);
1684 if (hexdigest[0] == '$')
1685 ++hexdigest;
1687 len = strlen(hexdigest);
1688 if (len < HEX_DIGEST_LEN)
1689 return 0;
1690 else if (len > HEX_DIGEST_LEN &&
1691 (hexdigest[HEX_DIGEST_LEN] == '=' ||
1692 hexdigest[HEX_DIGEST_LEN] == '~')) {
1693 if (strcasecmp(hexdigest+HEX_DIGEST_LEN+1, router->nickname))
1694 return 0;
1695 if (hexdigest[HEX_DIGEST_LEN] == '=' && !router->is_named)
1696 return 0;
1699 if (base16_decode(digest, DIGEST_LEN, hexdigest, HEX_DIGEST_LEN)<0)
1700 return 0;
1701 return (!memcmp(digest, router->cache_info.identity_digest, DIGEST_LEN));
1704 /** Return true if <b>router</b>'s nickname matches <b>nickname</b>
1705 * (case-insensitive), or if <b>router's</b> identity key digest
1706 * matches a hexadecimal value stored in <b>nickname</b>. Return
1707 * false otherwise. */
1708 static int
1709 router_nickname_matches(routerinfo_t *router, const char *nickname)
1711 if (nickname[0]!='$' && !strcasecmp(router->nickname, nickname))
1712 return 1;
1713 return router_hex_digest_matches(router, nickname);
1716 /** Return the router in our routerlist whose (case-insensitive)
1717 * nickname or (case-sensitive) hexadecimal key digest is
1718 * <b>nickname</b>. Return NULL if no such router is known.
1720 routerinfo_t *
1721 router_get_by_nickname(const char *nickname, int warn_if_unnamed)
1723 int maybedigest;
1724 char digest[DIGEST_LEN];
1725 routerinfo_t *best_match=NULL;
1726 int n_matches = 0;
1727 const char *named_digest = NULL;
1729 tor_assert(nickname);
1730 if (!routerlist)
1731 return NULL;
1732 if (nickname[0] == '$')
1733 return router_get_by_hexdigest(nickname);
1734 if (!strcasecmp(nickname, UNNAMED_ROUTER_NICKNAME))
1735 return NULL;
1736 if (server_mode(get_options()) &&
1737 !strcasecmp(nickname, get_options()->Nickname))
1738 return router_get_my_routerinfo();
1740 maybedigest = (strlen(nickname) >= HEX_DIGEST_LEN) &&
1741 (base16_decode(digest,DIGEST_LEN,nickname,HEX_DIGEST_LEN) == 0);
1743 if ((named_digest = networkstatus_get_router_digest_by_nickname(nickname))) {
1744 return rimap_get(routerlist->identity_map, named_digest);
1746 if (networkstatus_nickname_is_unnamed(nickname))
1747 return NULL;
1749 /* If we reach this point, there's no canonical value for the nickname. */
1751 SMARTLIST_FOREACH(routerlist->routers, routerinfo_t *, router,
1753 if (!strcasecmp(router->nickname, nickname)) {
1754 ++n_matches;
1755 if (n_matches <= 1 || router->is_running)
1756 best_match = router;
1757 } else if (maybedigest &&
1758 !memcmp(digest, router->cache_info.identity_digest, DIGEST_LEN)
1760 if (router_hex_digest_matches(router, nickname))
1761 return router;
1762 else
1763 best_match = router; // XXXX020 NM not exactly right.
1767 if (best_match) {
1768 if (warn_if_unnamed && n_matches > 1) {
1769 smartlist_t *fps = smartlist_create();
1770 int any_unwarned = 0;
1771 SMARTLIST_FOREACH(routerlist->routers, routerinfo_t *, router,
1773 routerstatus_t *rs;
1774 char *desc;
1775 size_t dlen;
1776 char fp[HEX_DIGEST_LEN+1];
1777 if (strcasecmp(router->nickname, nickname))
1778 continue;
1779 rs = router_get_consensus_status_by_id(
1780 router->cache_info.identity_digest);
1781 if (rs && !rs->name_lookup_warned) {
1782 rs->name_lookup_warned = 1;
1783 any_unwarned = 1;
1785 base16_encode(fp, sizeof(fp),
1786 router->cache_info.identity_digest, DIGEST_LEN);
1787 dlen = 32 + HEX_DIGEST_LEN + strlen(router->address);
1788 desc = tor_malloc(dlen);
1789 tor_snprintf(desc, dlen, "\"$%s\" for the one at %s:%d",
1790 fp, router->address, router->or_port);
1791 smartlist_add(fps, desc);
1793 if (any_unwarned) {
1794 char *alternatives = smartlist_join_strings(fps, "; ",0,NULL);
1795 log_warn(LD_CONFIG,
1796 "There are multiple matches for the nickname \"%s\","
1797 " but none is listed as named by the directory authorities. "
1798 "Choosing one arbitrarily. If you meant one in particular, "
1799 "you should say %s.", nickname, alternatives);
1800 tor_free(alternatives);
1802 SMARTLIST_FOREACH(fps, char *, cp, tor_free(cp));
1803 smartlist_free(fps);
1804 } else if (warn_if_unnamed) {
1805 routerstatus_t *rs = router_get_consensus_status_by_id(
1806 best_match->cache_info.identity_digest);
1807 if (rs && !rs->name_lookup_warned) {
1808 char fp[HEX_DIGEST_LEN+1];
1809 base16_encode(fp, sizeof(fp),
1810 best_match->cache_info.identity_digest, DIGEST_LEN);
1811 log_warn(LD_CONFIG, "You specified a server \"%s\" by name, but this "
1812 "name is not registered, so it could be used by any server, "
1813 "not just the one you meant. "
1814 "To make sure you get the same server in the future, refer to "
1815 "it by key, as \"$%s\".", nickname, fp);
1816 rs->name_lookup_warned = 1;
1819 return best_match;
1822 return NULL;
1825 /** Try to find a routerinfo for <b>digest</b>. If we don't have one,
1826 * return 1. If we do, ask tor_version_as_new_as() for the answer.
1829 router_digest_version_as_new_as(const char *digest, const char *cutoff)
1831 routerinfo_t *router = router_get_by_digest(digest);
1832 if (!router)
1833 return 1;
1834 return tor_version_as_new_as(router->platform, cutoff);
1837 /** Return true iff <b>digest</b> is the digest of the identity key of a
1838 * trusted directory matching at least one bit of <b>type</b>. If <b>type</b>
1839 * is zero, any authority is okay. */
1841 router_digest_is_trusted_dir_type(const char *digest, authority_type_t type)
1843 if (!trusted_dir_servers)
1844 return 0;
1845 if (authdir_mode(get_options()) && router_digest_is_me(digest))
1846 return 1;
1847 SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, ent,
1848 if (!memcmp(digest, ent->digest, DIGEST_LEN)) {
1849 return (!type) || ((type & ent->type) != 0);
1851 return 0;
1854 /** Return true iff <b>addr</b> is the address of one of our trusted
1855 * directory authorities. */
1857 router_addr_is_trusted_dir(uint32_t addr)
1859 if (!trusted_dir_servers)
1860 return 0;
1861 SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, ent,
1862 if (ent->addr == addr)
1863 return 1;
1865 return 0;
1868 /** If hexdigest is correctly formed, base16_decode it into
1869 * digest, which must have DIGEST_LEN space in it.
1870 * Return 0 on success, -1 on failure.
1873 hexdigest_to_digest(const char *hexdigest, char *digest)
1875 if (hexdigest[0]=='$')
1876 ++hexdigest;
1877 if (strlen(hexdigest) < HEX_DIGEST_LEN ||
1878 base16_decode(digest,DIGEST_LEN,hexdigest,HEX_DIGEST_LEN) < 0)
1879 return -1;
1880 return 0;
1883 /** Return the router in our routerlist whose hexadecimal key digest
1884 * is <b>hexdigest</b>. Return NULL if no such router is known. */
1885 routerinfo_t *
1886 router_get_by_hexdigest(const char *hexdigest)
1888 char digest[DIGEST_LEN];
1889 size_t len;
1890 routerinfo_t *ri;
1892 tor_assert(hexdigest);
1893 if (!routerlist)
1894 return NULL;
1895 if (hexdigest[0]=='$')
1896 ++hexdigest;
1897 len = strlen(hexdigest);
1898 if (hexdigest_to_digest(hexdigest, digest) < 0)
1899 return NULL;
1901 ri = router_get_by_digest(digest);
1903 if (ri && len > HEX_DIGEST_LEN) {
1904 if (hexdigest[HEX_DIGEST_LEN] == '=') {
1905 if (strcasecmp(ri->nickname, hexdigest+HEX_DIGEST_LEN+1) ||
1906 !ri->is_named)
1907 return NULL;
1908 } else if (hexdigest[HEX_DIGEST_LEN] == '~') {
1909 if (strcasecmp(ri->nickname, hexdigest+HEX_DIGEST_LEN+1))
1910 return NULL;
1911 } else {
1912 return NULL;
1916 return ri;
1919 /** Return the router in our routerlist whose 20-byte key digest
1920 * is <b>digest</b>. Return NULL if no such router is known. */
1921 routerinfo_t *
1922 router_get_by_digest(const char *digest)
1924 tor_assert(digest);
1926 if (!routerlist) return NULL;
1928 // routerlist_assert_ok(routerlist);
1930 return rimap_get(routerlist->identity_map, digest);
1933 /** Return the router in our routerlist whose 20-byte descriptor
1934 * is <b>digest</b>. Return NULL if no such router is known. */
1935 signed_descriptor_t *
1936 router_get_by_descriptor_digest(const char *digest)
1938 tor_assert(digest);
1940 if (!routerlist) return NULL;
1942 return sdmap_get(routerlist->desc_digest_map, digest);
1945 /** Return the signed descriptor for the router in our routerlist whose
1946 * 20-byte extra-info digest is <b>digest</b>. Return NULL if no such router
1947 * is known. */
1948 signed_descriptor_t *
1949 router_get_by_extrainfo_digest(const char *digest)
1951 tor_assert(digest);
1953 if (!routerlist) return NULL;
1955 return sdmap_get(routerlist->desc_by_eid_map, digest);
1958 /** Return the signed descriptor for the extrainfo_t in our routerlist whose
1959 * extra-info-digest is <b>digest</b>. Return NULL if no such extra-info
1960 * document is known. */
1961 signed_descriptor_t *
1962 extrainfo_get_by_descriptor_digest(const char *digest)
1964 extrainfo_t *ei;
1965 tor_assert(digest);
1966 if (!routerlist) return NULL;
1967 ei = eimap_get(routerlist->extra_info_map, digest);
1968 return ei ? &ei->cache_info : NULL;
1971 /** Return a pointer to the signed textual representation of a descriptor.
1972 * The returned string is not guaranteed to be NUL-terminated: the string's
1973 * length will be in desc-\>signed_descriptor_len.
1975 * If <b>with_annotations</b> is set, the returned string will include
1976 * the annotations
1977 * (if any) preceding the descriptor. This will increase the length of the
1978 * string by desc-\>annotations_len.
1980 * The caller must not free the string returned.
1982 static const char *
1983 signed_descriptor_get_body_impl(signed_descriptor_t *desc,
1984 int with_annotations)
1986 const char *r = NULL;
1987 size_t len = desc->signed_descriptor_len;
1988 off_t offset = desc->saved_offset;
1989 if (with_annotations)
1990 len += desc->annotations_len;
1991 else
1992 offset += desc->annotations_len;
1994 tor_assert(len > 32);
1995 if (desc->saved_location == SAVED_IN_CACHE && routerlist) {
1996 desc_store_t *store = desc_get_store(router_get_routerlist(), desc);
1997 if (store && store->mmap) {
1998 tor_assert(desc->saved_offset + len <= store->mmap->size);
1999 r = store->mmap->data + offset;
2002 if (!r) /* no mmap, or not in cache. */
2003 r = desc->signed_descriptor_body +
2004 (with_annotations ? 0 : desc->annotations_len);
2006 tor_assert(r);
2007 if (!with_annotations) {
2008 if (memcmp("router ", r, 7) && memcmp("extra-info ", r, 11)) {
2009 char *cp = tor_strndup(r, 64);
2010 log_err(LD_DIR, "descriptor at %p begins with unexpected string %s",
2011 desc, escaped(cp));
2012 tor_free(cp);
2014 tor_assert(!memcmp("router ", r, 7) || !memcmp("extra-info ", r, 11));
2017 return r;
2020 /** Return a pointer to the signed textual representation of a descriptor.
2021 * The returned string is not guaranteed to be NUL-terminated: the string's
2022 * length will be in desc-\>signed_descriptor_len.
2024 * The caller must not free the string returned.
2026 const char *
2027 signed_descriptor_get_body(signed_descriptor_t *desc)
2029 return signed_descriptor_get_body_impl(desc, 0);
2032 /** As signed_descriptor_get_body(), but points to the beginning of the
2033 * annotations section rather than the beginning of the descriptor. */
2034 const char *
2035 signed_descriptor_get_annotations(signed_descriptor_t *desc)
2037 return signed_descriptor_get_body_impl(desc, 1);
2040 /** Return the current list of all known routers. */
2041 routerlist_t *
2042 router_get_routerlist(void)
2044 if (PREDICT_UNLIKELY(!routerlist)) {
2045 routerlist = tor_malloc_zero(sizeof(routerlist_t));
2046 routerlist->routers = smartlist_create();
2047 routerlist->old_routers = smartlist_create();
2048 routerlist->identity_map = rimap_new();
2049 routerlist->desc_digest_map = sdmap_new();
2050 routerlist->desc_by_eid_map = sdmap_new();
2051 routerlist->extra_info_map = eimap_new();
2053 routerlist->desc_store.fname_base = "cached-descriptors";
2054 routerlist->desc_store.fname_alt_base = "cached-routers";
2055 routerlist->extrainfo_store.fname_base = "cached-extrainfo";
2057 routerlist->desc_store.type = ROUTER_STORE;
2058 routerlist->extrainfo_store.type = EXTRAINFO_STORE;
2060 routerlist->desc_store.description = "router descriptors";
2061 routerlist->extrainfo_store.description = "extra-info documents";
2063 return routerlist;
2066 /** Free all storage held by <b>router</b>. */
2067 void
2068 routerinfo_free(routerinfo_t *router)
2070 if (!router)
2071 return;
2073 tor_free(router->cache_info.signed_descriptor_body);
2074 tor_free(router->address);
2075 tor_free(router->nickname);
2076 tor_free(router->platform);
2077 tor_free(router->contact_info);
2078 if (router->onion_pkey)
2079 crypto_free_pk_env(router->onion_pkey);
2080 if (router->identity_pkey)
2081 crypto_free_pk_env(router->identity_pkey);
2082 if (router->declared_family) {
2083 SMARTLIST_FOREACH(router->declared_family, char *, s, tor_free(s));
2084 smartlist_free(router->declared_family);
2086 addr_policy_list_free(router->exit_policy);
2088 /* XXXX020 Remove once 414/417 is fixed. But I have a hunch... */
2089 memset(router, 77, sizeof(routerinfo_t));
2091 tor_free(router);
2094 /** Release all storage held by <b>extrainfo</b> */
2095 void
2096 extrainfo_free(extrainfo_t *extrainfo)
2098 if (!extrainfo)
2099 return;
2100 tor_free(extrainfo->cache_info.signed_descriptor_body);
2101 tor_free(extrainfo->pending_sig);
2103 /* XXXX020 remove this once more bugs go away. */
2104 memset(extrainfo, 88, sizeof(extrainfo_t)); /* debug bad memory usage */
2105 tor_free(extrainfo);
2108 /** Release storage held by <b>sd</b>. */
2109 static void
2110 signed_descriptor_free(signed_descriptor_t *sd)
2112 tor_free(sd->signed_descriptor_body);
2114 /* XXXX020 remove this once more bugs go away. */
2115 memset(sd, 99, sizeof(signed_descriptor_t)); /* Debug bad mem usage */
2116 tor_free(sd);
2119 /** Extract a signed_descriptor_t from a routerinfo, and free the routerinfo.
2121 static signed_descriptor_t *
2122 signed_descriptor_from_routerinfo(routerinfo_t *ri)
2124 signed_descriptor_t *sd = tor_malloc_zero(sizeof(signed_descriptor_t));
2125 memcpy(sd, &(ri->cache_info), sizeof(signed_descriptor_t));
2126 sd->routerlist_index = -1;
2127 ri->cache_info.signed_descriptor_body = NULL;
2128 routerinfo_free(ri);
2129 return sd;
2132 /** Helper: free the storage held by the extrainfo_t in <b>e</b>. */
2133 static void
2134 _extrainfo_free(void *e)
2136 extrainfo_free(e);
2139 /** Free all storage held by a routerlist <b>rl</b>. */
2140 void
2141 routerlist_free(routerlist_t *rl)
2143 tor_assert(rl);
2144 rimap_free(rl->identity_map, NULL);
2145 sdmap_free(rl->desc_digest_map, NULL);
2146 sdmap_free(rl->desc_by_eid_map, NULL);
2147 eimap_free(rl->extra_info_map, _extrainfo_free);
2148 SMARTLIST_FOREACH(rl->routers, routerinfo_t *, r,
2149 routerinfo_free(r));
2150 SMARTLIST_FOREACH(rl->old_routers, signed_descriptor_t *, sd,
2151 signed_descriptor_free(sd));
2152 smartlist_free(rl->routers);
2153 smartlist_free(rl->old_routers);
2154 if (routerlist->desc_store.mmap)
2155 tor_munmap_file(routerlist->desc_store.mmap);
2156 if (routerlist->extrainfo_store.mmap)
2157 tor_munmap_file(routerlist->extrainfo_store.mmap);
2158 tor_free(rl);
2160 router_dir_info_changed();
2163 /** Log information about how much memory is being used for routerlist,
2164 * at log level <b>severity</b>. */
2165 void
2166 dump_routerlist_mem_usage(int severity)
2168 uint64_t livedescs = 0;
2169 uint64_t olddescs = 0;
2170 if (!routerlist)
2171 return;
2172 SMARTLIST_FOREACH(routerlist->routers, routerinfo_t *, r,
2173 livedescs += r->cache_info.signed_descriptor_len);
2174 SMARTLIST_FOREACH(routerlist->old_routers, signed_descriptor_t *, sd,
2175 olddescs += sd->signed_descriptor_len);
2177 log(severity, LD_GENERAL,
2178 "In %d live descriptors: "U64_FORMAT" bytes. "
2179 "In %d old descriptors: "U64_FORMAT" bytes.",
2180 smartlist_len(routerlist->routers), U64_PRINTF_ARG(livedescs),
2181 smartlist_len(routerlist->old_routers), U64_PRINTF_ARG(olddescs));
2184 static INLINE int
2185 _routerlist_find_elt(smartlist_t *sl, void *ri, int idx)
2187 if (idx < 0) {
2188 idx = -1;
2189 SMARTLIST_FOREACH(sl, routerinfo_t *, r,
2190 if (r == ri) {
2191 idx = r_sl_idx;
2192 break;
2194 } else {
2195 tor_assert(idx < smartlist_len(sl));
2196 tor_assert(smartlist_get(sl, idx) == ri);
2198 return idx;
2201 /** Insert an item <b>ri</b> into the routerlist <b>rl</b>, updating indices
2202 * as needed. There must be no previous member of <b>rl</b> with the same
2203 * identity digest as <b>ri</b>: If there is, call routerlist_replace
2204 * instead.
2206 static void
2207 routerlist_insert(routerlist_t *rl, routerinfo_t *ri)
2209 routerinfo_t *ri_old;
2211 /* XXXX020 remove this code once bug 417/404 is fixed. */
2212 routerinfo_t *ri_generated = router_get_my_routerinfo();
2213 tor_assert(ri_generated != ri);
2215 tor_assert(ri->cache_info.routerlist_index == -1);
2217 ri_old = rimap_set(rl->identity_map, ri->cache_info.identity_digest, ri);
2218 tor_assert(!ri_old);
2219 sdmap_set(rl->desc_digest_map, ri->cache_info.signed_descriptor_digest,
2220 &(ri->cache_info));
2221 if (!tor_digest_is_zero(ri->cache_info.extra_info_digest))
2222 sdmap_set(rl->desc_by_eid_map, ri->cache_info.extra_info_digest,
2223 &ri->cache_info);
2224 smartlist_add(rl->routers, ri);
2225 ri->cache_info.routerlist_index = smartlist_len(rl->routers) - 1;
2226 router_dir_info_changed();
2227 #ifdef DEBUG_ROUTERLIST
2228 routerlist_assert_ok(rl);
2229 #endif
2232 /** Adds the extrainfo_t <b>ei</b> to the routerlist <b>rl</b>, if there is a
2233 * corresponding router in rl-\>routers or rl-\>old_routers. Return true iff
2234 * we actually inserted <b>ei</b>. Free <b>ei</b> if it isn't inserted. */
2235 static int
2236 extrainfo_insert(routerlist_t *rl, extrainfo_t *ei)
2238 int r = 0;
2239 routerinfo_t *ri = rimap_get(rl->identity_map,
2240 ei->cache_info.identity_digest);
2241 signed_descriptor_t *sd =
2242 sdmap_get(rl->desc_by_eid_map, ei->cache_info.signed_descriptor_digest);
2243 extrainfo_t *ei_tmp;
2246 /* XXXX020 remove this code once bug 417/404 is fixed. */
2247 extrainfo_t *ei_generated = router_get_my_extrainfo();
2248 tor_assert(ei_generated != ei);
2251 if (!ri) {
2252 /* This router is unknown; we can't even verify the signature. Give up.*/
2253 goto done;
2255 if (routerinfo_incompatible_with_extrainfo(ri, ei, sd, NULL)) {
2256 goto done;
2259 /* Okay, if we make it here, we definitely have a router corresponding to
2260 * this extrainfo. */
2262 ei_tmp = eimap_set(rl->extra_info_map,
2263 ei->cache_info.signed_descriptor_digest,
2264 ei);
2265 r = 1;
2266 if (ei_tmp) {
2267 rl->extrainfo_store.bytes_dropped +=
2268 ei_tmp->cache_info.signed_descriptor_len;
2269 extrainfo_free(ei_tmp);
2272 done:
2273 if (r == 0)
2274 extrainfo_free(ei);
2276 #ifdef DEBUG_ROUTERLIST
2277 routerlist_assert_ok(rl);
2278 #endif
2279 return r;
2282 #define should_cache_old_descriptors() \
2283 directory_caches_dir_info(get_options())
2285 /** If we're a directory cache and routerlist <b>rl</b> doesn't have
2286 * a copy of router <b>ri</b> yet, add it to the list of old (not
2287 * recommended but still served) descriptors. Else free it. */
2288 static void
2289 routerlist_insert_old(routerlist_t *rl, routerinfo_t *ri)
2292 /* XXXX020 remove this code once bug 417/404 is fixed. */
2293 routerinfo_t *ri_generated = router_get_my_routerinfo();
2294 tor_assert(ri_generated != ri);
2296 tor_assert(ri->cache_info.routerlist_index == -1);
2298 if (should_cache_old_descriptors() &&
2299 ri->purpose == ROUTER_PURPOSE_GENERAL &&
2300 !sdmap_get(rl->desc_digest_map,
2301 ri->cache_info.signed_descriptor_digest)) {
2302 signed_descriptor_t *sd = signed_descriptor_from_routerinfo(ri);
2303 sdmap_set(rl->desc_digest_map, sd->signed_descriptor_digest, sd);
2304 smartlist_add(rl->old_routers, sd);
2305 sd->routerlist_index = smartlist_len(rl->old_routers)-1;
2306 if (!tor_digest_is_zero(sd->extra_info_digest))
2307 sdmap_set(rl->desc_by_eid_map, sd->extra_info_digest, sd);
2308 } else {
2309 routerinfo_free(ri);
2311 #ifdef DEBUG_ROUTERLIST
2312 routerlist_assert_ok(rl);
2313 #endif
2316 /** Remove an item <b>ri</b> from the routerlist <b>rl</b>, updating indices
2317 * as needed. If <b>idx</b> is nonnegative and smartlist_get(rl-&gt;routers,
2318 * idx) == ri, we don't need to do a linear search over the list to decide
2319 * which to remove. We fill the gap in rl-&gt;routers with a later element in
2320 * the list, if any exists. <b>ri</b> is freed.
2322 * If <b>make_old</b> is true, instead of deleting the router, we try adding
2323 * it to rl-&gt;old_routers. */
2324 void
2325 routerlist_remove(routerlist_t *rl, routerinfo_t *ri, int make_old)
2327 routerinfo_t *ri_tmp;
2328 extrainfo_t *ei_tmp;
2329 int idx = ri->cache_info.routerlist_index;
2330 tor_assert(0 <= idx && idx < smartlist_len(rl->routers));
2331 tor_assert(smartlist_get(rl->routers, idx) == ri);
2333 ri->cache_info.routerlist_index = -1;
2334 smartlist_del(rl->routers, idx);
2335 if (idx < smartlist_len(rl->routers)) {
2336 routerinfo_t *r = smartlist_get(rl->routers, idx);
2337 r->cache_info.routerlist_index = idx;
2340 ri_tmp = rimap_remove(rl->identity_map, ri->cache_info.identity_digest);
2341 router_dir_info_changed();
2342 tor_assert(ri_tmp == ri);
2344 if (make_old && should_cache_old_descriptors() &&
2345 ri->purpose == ROUTER_PURPOSE_GENERAL) {
2346 signed_descriptor_t *sd;
2347 sd = signed_descriptor_from_routerinfo(ri);
2348 smartlist_add(rl->old_routers, sd);
2349 sd->routerlist_index = smartlist_len(rl->old_routers)-1;
2350 sdmap_set(rl->desc_digest_map, sd->signed_descriptor_digest, sd);
2351 if (!tor_digest_is_zero(sd->extra_info_digest))
2352 sdmap_set(rl->desc_by_eid_map, sd->extra_info_digest, sd);
2353 } else {
2354 signed_descriptor_t *sd_tmp;
2355 sd_tmp = sdmap_remove(rl->desc_digest_map,
2356 ri->cache_info.signed_descriptor_digest);
2357 tor_assert(sd_tmp == &(ri->cache_info));
2358 rl->desc_store.bytes_dropped += ri->cache_info.signed_descriptor_len;
2359 ei_tmp = eimap_remove(rl->extra_info_map,
2360 ri->cache_info.extra_info_digest);
2361 if (ei_tmp) {
2362 rl->extrainfo_store.bytes_dropped +=
2363 ei_tmp->cache_info.signed_descriptor_len;
2364 extrainfo_free(ei_tmp);
2366 if (!tor_digest_is_zero(ri->cache_info.extra_info_digest))
2367 sdmap_remove(rl->desc_by_eid_map, ri->cache_info.extra_info_digest);
2368 routerinfo_free(ri);
2370 #ifdef DEBUG_ROUTERLIST
2371 routerlist_assert_ok(rl);
2372 #endif
2375 /** Remove a signed_descriptor_t <b>sd</b> from <b>rl</b>-\>old_routers, and
2376 * adjust <b>rl</b> as appropriate. <b>idx</i> is -1, or the index of
2377 * <b>sd</b>. */
2378 static void
2379 routerlist_remove_old(routerlist_t *rl, signed_descriptor_t *sd, int idx)
2381 signed_descriptor_t *sd_tmp;
2382 extrainfo_t *ei_tmp;
2383 desc_store_t *store;
2384 if (idx == -1) {
2385 idx = sd->routerlist_index;
2387 tor_assert(0 <= idx && idx < smartlist_len(rl->old_routers));
2388 /* XXX020 edmanm's bridge relay triggered the following assert while
2389 * running 0.2.0.12-alpha: */
2390 tor_assert(smartlist_get(rl->old_routers, idx) == sd);
2391 tor_assert(idx == sd->routerlist_index);
2393 sd->routerlist_index = -1;
2394 smartlist_del(rl->old_routers, idx);
2395 if (idx < smartlist_len(rl->old_routers)) {
2396 signed_descriptor_t *d = smartlist_get(rl->old_routers, idx);
2397 d->routerlist_index = idx;
2399 sd_tmp = sdmap_remove(rl->desc_digest_map,
2400 sd->signed_descriptor_digest);
2401 tor_assert(sd_tmp == sd);
2402 store = desc_get_store(rl, sd);
2403 if (store)
2404 store->bytes_dropped += sd->signed_descriptor_len;
2406 ei_tmp = eimap_remove(rl->extra_info_map,
2407 sd->extra_info_digest);
2408 if (ei_tmp) {
2409 rl->extrainfo_store.bytes_dropped +=
2410 ei_tmp->cache_info.signed_descriptor_len;
2411 extrainfo_free(ei_tmp);
2413 if (!tor_digest_is_zero(sd->extra_info_digest))
2414 sdmap_remove(rl->desc_by_eid_map, sd->extra_info_digest);
2416 signed_descriptor_free(sd);
2417 #ifdef DEBUG_ROUTERLIST
2418 routerlist_assert_ok(rl);
2419 #endif
2422 /** Remove <b>ri_old</b> from the routerlist <b>rl</b>, and replace it with
2423 * <b>ri_new</b>, updating all index info. If <b>idx</b> is nonnegative and
2424 * smartlist_get(rl-&gt;routers, idx) == ri, we don't need to do a linear
2425 * search over the list to decide which to remove. We put ri_new in the same
2426 * index as ri_old, if possible. ri is freed as appropriate.
2428 * If should_cache_descriptors() is true, instead of deleting the router,
2429 * we add it to rl-&gt;old_routers. */
2430 static void
2431 routerlist_replace(routerlist_t *rl, routerinfo_t *ri_old,
2432 routerinfo_t *ri_new)
2434 int idx;
2436 routerinfo_t *ri_tmp;
2437 extrainfo_t *ei_tmp;
2439 /* XXXX020 remove this code once bug 417/404 is fixed. */
2440 routerinfo_t *ri_generated = router_get_my_routerinfo();
2441 tor_assert(ri_generated != ri_new);
2443 tor_assert(ri_old != ri_new);
2444 tor_assert(ri_new->cache_info.routerlist_index == -1);
2446 idx = ri_old->cache_info.routerlist_index;
2447 tor_assert(0 <= idx && idx < smartlist_len(rl->routers));
2448 tor_assert(smartlist_get(rl->routers, idx) == ri_old);
2450 router_dir_info_changed();
2451 if (idx >= 0) {
2452 smartlist_set(rl->routers, idx, ri_new);
2453 ri_old->cache_info.routerlist_index = -1;
2454 ri_new->cache_info.routerlist_index = idx;
2455 /* Check that ri_old is not in rl->routers anymore: */
2456 tor_assert( _routerlist_find_elt(rl->routers, ri_old, -1) == -1 );
2457 } else {
2458 log_warn(LD_BUG, "Appending entry from routerlist_replace.");
2459 routerlist_insert(rl, ri_new);
2460 return;
2462 if (memcmp(ri_old->cache_info.identity_digest,
2463 ri_new->cache_info.identity_digest, DIGEST_LEN)) {
2464 /* digests don't match; digestmap_set won't replace */
2465 rimap_remove(rl->identity_map, ri_old->cache_info.identity_digest);
2467 ri_tmp = rimap_set(rl->identity_map,
2468 ri_new->cache_info.identity_digest, ri_new);
2469 tor_assert(!ri_tmp || ri_tmp == ri_old);
2470 sdmap_set(rl->desc_digest_map,
2471 ri_new->cache_info.signed_descriptor_digest,
2472 &(ri_new->cache_info));
2474 if (!tor_digest_is_zero(ri_new->cache_info.extra_info_digest)) {
2475 sdmap_set(rl->desc_by_eid_map, ri_new->cache_info.extra_info_digest,
2476 &ri_new->cache_info);
2479 if (should_cache_old_descriptors() &&
2480 ri_old->purpose == ROUTER_PURPOSE_GENERAL) {
2481 signed_descriptor_t *sd = signed_descriptor_from_routerinfo(ri_old);
2482 smartlist_add(rl->old_routers, sd);
2483 sd->routerlist_index = smartlist_len(rl->old_routers)-1;
2484 sdmap_set(rl->desc_digest_map, sd->signed_descriptor_digest, sd);
2485 if (!tor_digest_is_zero(sd->extra_info_digest))
2486 sdmap_set(rl->desc_by_eid_map, sd->extra_info_digest, sd);
2487 } else {
2488 if (memcmp(ri_old->cache_info.signed_descriptor_digest,
2489 ri_new->cache_info.signed_descriptor_digest,
2490 DIGEST_LEN)) {
2491 /* digests don't match; digestmap_set didn't replace */
2492 sdmap_remove(rl->desc_digest_map,
2493 ri_old->cache_info.signed_descriptor_digest);
2496 ei_tmp = eimap_remove(rl->extra_info_map,
2497 ri_old->cache_info.extra_info_digest);
2498 if (ei_tmp) {
2499 rl->extrainfo_store.bytes_dropped +=
2500 ei_tmp->cache_info.signed_descriptor_len;
2501 extrainfo_free(ei_tmp);
2503 if (!tor_digest_is_zero(ri_old->cache_info.extra_info_digest)) {
2504 sdmap_remove(rl->desc_by_eid_map,
2505 ri_old->cache_info.extra_info_digest);
2507 rl->desc_store.bytes_dropped += ri_old->cache_info.signed_descriptor_len;
2508 routerinfo_free(ri_old);
2510 #ifdef DEBUG_ROUTERLIST
2511 routerlist_assert_ok(rl);
2512 #endif
2515 /** Extract the descriptor <b>sd</b> from old_routerlist, and re-parse
2516 * it as a fresh routerinfo_t. */
2517 static routerinfo_t *
2518 routerlist_reparse_old(routerlist_t *rl, signed_descriptor_t *sd)
2520 routerinfo_t *ri;
2521 const char *body;
2523 body = signed_descriptor_get_annotations(sd);
2525 ri = router_parse_entry_from_string(body,
2526 body+sd->signed_descriptor_len+sd->annotations_len,
2527 0, 1, NULL);
2528 if (!ri)
2529 return NULL;
2530 memcpy(&ri->cache_info, sd, sizeof(signed_descriptor_t));
2531 sd->signed_descriptor_body = NULL; /* Steal reference. */
2532 ri->cache_info.routerlist_index = -1;
2534 routerlist_remove_old(rl, sd, -1);
2536 return ri;
2539 /** Free all memory held by the routerlist module. */
2540 void
2541 routerlist_free_all(void)
2543 if (routerlist)
2544 routerlist_free(routerlist);
2545 routerlist = NULL;
2546 if (warned_nicknames) {
2547 SMARTLIST_FOREACH(warned_nicknames, char *, cp, tor_free(cp));
2548 smartlist_free(warned_nicknames);
2549 warned_nicknames = NULL;
2551 if (trusted_dir_servers) {
2552 SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, ds,
2553 trusted_dir_server_free(ds));
2554 smartlist_free(trusted_dir_servers);
2555 trusted_dir_servers = NULL;
2559 /** Forget that we have issued any router-related warnings, so that we'll
2560 * warn again if we see the same errors. */
2561 void
2562 routerlist_reset_warnings(void)
2564 if (!warned_nicknames)
2565 warned_nicknames = smartlist_create();
2566 SMARTLIST_FOREACH(warned_nicknames, char *, cp, tor_free(cp));
2567 smartlist_clear(warned_nicknames); /* now the list is empty. */
2569 networkstatus_reset_warnings();
2572 /** Mark the router with ID <b>digest</b> as running or non-running
2573 * in our routerlist. */
2574 void
2575 router_set_status(const char *digest, int up)
2577 routerinfo_t *router;
2578 routerstatus_t *status;
2579 tor_assert(digest);
2581 SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, d,
2582 if (!memcmp(d->digest, digest, DIGEST_LEN))
2583 d->is_running = up);
2585 router = router_get_by_digest(digest);
2586 if (router) {
2587 log_debug(LD_DIR,"Marking router '%s' as %s.",
2588 router->nickname, up ? "up" : "down");
2589 if (!up && router_is_me(router) && !we_are_hibernating())
2590 log_warn(LD_NET, "We just marked ourself as down. Are your external "
2591 "addresses reachable?");
2592 router->is_running = up;
2594 status = router_get_consensus_status_by_id(digest);
2595 if (status && status->is_running != up) {
2596 status->is_running = up;
2597 control_event_networkstatus_changed_single(status);
2599 router_dir_info_changed();
2602 /** Add <b>router</b> to the routerlist, if we don't already have it. Replace
2603 * older entries (if any) with the same key. Note: Callers should not hold
2604 * their pointers to <b>router</b> if this function fails; <b>router</b>
2605 * will either be inserted into the routerlist or freed. Similarly, even
2606 * if this call succeeds, they should not hold their pointers to
2607 * <b>router</b> after subsequent calls with other routerinfo's -- they
2608 * might cause the original routerinfo to get freed.
2610 * Returns >= 0 if the router was added; less than 0 if it was not.
2612 * If we're returning non-zero, then assign to *<b>msg</b> a static string
2613 * describing the reason for not liking the routerinfo.
2615 * If the return value is less than -1, there was a problem with the
2616 * routerinfo. If the return value is equal to -1, then the routerinfo was
2617 * fine, but out-of-date. If the return value is equal to 1, the
2618 * routerinfo was accepted, but we should notify the generator of the
2619 * descriptor using the message *<b>msg</b>.
2621 * If <b>from_cache</b>, this descriptor came from our disk cache. If
2622 * <b>from_fetch</b>, we received it in response to a request we made.
2623 * (If both are false, that means it was uploaded to us as an auth dir
2624 * server or via the controller.)
2626 * This function should be called *after*
2627 * routers_update_status_from_consensus_networkstatus; subsequently, you
2628 * should call router_rebuild_store and routerlist_descriptors_added.
2631 router_add_to_routerlist(routerinfo_t *router, const char **msg,
2632 int from_cache, int from_fetch)
2634 const char *id_digest;
2635 int authdir = authdir_mode_handles_descs(get_options(), router->purpose);
2636 int authdir_believes_valid = 0;
2637 routerinfo_t *old_router;
2638 networkstatus_vote_t *consensus = networkstatus_get_latest_consensus();
2639 const smartlist_t *networkstatus_v2_list = networkstatus_get_v2_list();
2640 int in_consensus = 0;
2642 tor_assert(msg);
2644 if (!routerlist)
2645 router_get_routerlist();
2647 id_digest = router->cache_info.identity_digest;
2649 /* Make sure that we haven't already got this exact descriptor. */
2650 if (sdmap_get(routerlist->desc_digest_map,
2651 router->cache_info.signed_descriptor_digest)) {
2652 log_info(LD_DIR,
2653 "Dropping descriptor that we already have for router '%s'",
2654 router->nickname);
2655 *msg = "Router descriptor was not new.";
2656 routerinfo_free(router);
2657 return -1;
2660 #if 0
2661 if (routerlist_is_overfull(routerlist))
2662 routerlist_remove_old_routers();
2663 #endif
2665 if (authdir) {
2666 if (authdir_wants_to_reject_router(router, msg,
2667 !from_cache && !from_fetch)) {
2668 tor_assert(*msg);
2669 routerinfo_free(router);
2670 return -2;
2672 authdir_believes_valid = router->is_valid;
2673 } else if (from_fetch) {
2674 /* Only check the descriptor digest against the network statuses when
2675 * we are receiving in response to a fetch. */
2677 if (!signed_desc_digest_is_recognized(&router->cache_info) &&
2678 !routerinfo_is_a_configured_bridge(router)) {
2679 /* We asked for it, so some networkstatus must have listed it when we
2680 * did. Save it if we're a cache in case somebody else asks for it. */
2681 log_info(LD_DIR,
2682 "Received a no-longer-recognized descriptor for router '%s'",
2683 router->nickname);
2684 *msg = "Router descriptor is not referenced by any network-status.";
2686 /* Only journal this desc if we'll be serving it. */
2687 if (!from_cache && should_cache_old_descriptors())
2688 signed_desc_append_to_journal(&router->cache_info,
2689 &routerlist->desc_store);
2690 routerlist_insert_old(routerlist, router);
2691 return -1;
2695 /* We no longer need a router with this descriptor digest. */
2696 SMARTLIST_FOREACH(networkstatus_v2_list, networkstatus_v2_t *, ns,
2698 routerstatus_t *rs =
2699 networkstatus_v2_find_entry(ns, router->cache_info.identity_digest);
2700 if (rs && !memcmp(rs->descriptor_digest,
2701 router->cache_info.signed_descriptor_digest,
2702 DIGEST_LEN))
2703 rs->need_to_mirror = 0;
2705 if (consensus) {
2706 routerstatus_t *rs = networkstatus_vote_find_entry(consensus,
2707 router->cache_info.identity_digest);
2708 if (rs && !memcmp(rs->descriptor_digest,
2709 router->cache_info.signed_descriptor_digest,
2710 DIGEST_LEN)) {
2711 in_consensus = 1;
2712 rs->need_to_mirror = 0;
2716 if (router->purpose == ROUTER_PURPOSE_GENERAL &&
2717 consensus && !in_consensus && !authdir) {
2718 /* If it's a general router not listed in the consensus, then don't
2719 * consider replacing the latest router with it. */
2720 if (!from_cache && should_cache_old_descriptors())
2721 signed_desc_append_to_journal(&router->cache_info,
2722 &routerlist->desc_store);
2723 routerlist_insert_old(routerlist, router);
2724 *msg = "Skipping router descriptor: not in consensus.";
2725 return -1;
2728 /* If we have a router with the same identity key, choose the newer one. */
2729 old_router = rimap_get(routerlist->identity_map,
2730 router->cache_info.identity_digest);
2731 if (old_router) {
2732 if (!in_consensus && (router->cache_info.published_on <=
2733 old_router->cache_info.published_on)) {
2734 /* Same key, but old. This one is not listed in the consensus. */
2735 log_debug(LD_DIR, "Skipping not-new descriptor for router '%s'",
2736 router->nickname);
2737 /* Only journal this desc if we'll be serving it. */
2738 if (!from_cache && should_cache_old_descriptors())
2739 signed_desc_append_to_journal(&router->cache_info,
2740 &routerlist->desc_store);
2741 routerlist_insert_old(routerlist, router);
2742 *msg = "Router descriptor was not new.";
2743 return -1;
2744 } else {
2745 /* Same key, and either new, or listed in the consensus. */
2746 log_debug(LD_DIR, "Replacing entry for router '%s/%s' [%s]",
2747 router->nickname, old_router->nickname,
2748 hex_str(id_digest,DIGEST_LEN));
2749 if (router->addr == old_router->addr &&
2750 router->or_port == old_router->or_port) {
2751 /* these carry over when the address and orport are unchanged. */
2752 router->last_reachable = old_router->last_reachable;
2753 router->testing_since = old_router->testing_since;
2755 routerlist_replace(routerlist, old_router, router);
2756 if (!from_cache) {
2757 signed_desc_append_to_journal(&router->cache_info,
2758 &routerlist->desc_store);
2760 directory_set_dirty();
2761 *msg = authdir_believes_valid ? "Valid server updated" :
2762 ("Invalid server updated. (This dirserver is marking your "
2763 "server as unapproved.)");
2764 return 0;
2768 /* We haven't seen a router with this identity before. Add it to the end of
2769 * the list. */
2770 routerlist_insert(routerlist, router);
2771 if (!from_cache)
2772 signed_desc_append_to_journal(&router->cache_info,
2773 &routerlist->desc_store);
2774 directory_set_dirty();
2775 return 0;
2778 /** Insert <b>ei</b> into the routerlist, or free it. Other arguments are
2779 * as for router_add_to_routerlist(). Return true iff we actually inserted
2780 * it.
2783 router_add_extrainfo_to_routerlist(extrainfo_t *ei, const char **msg,
2784 int from_cache, int from_fetch)
2786 int inserted;
2787 (void)from_fetch;
2788 if (msg) *msg = NULL;
2790 inserted = extrainfo_insert(router_get_routerlist(), ei);
2792 if (inserted && !from_cache)
2793 signed_desc_append_to_journal(&ei->cache_info,
2794 &routerlist->extrainfo_store);
2796 return inserted;
2799 /** Sorting helper: return &lt;0, 0, or &gt;0 depending on whether the
2800 * signed_descriptor_t* in *<b>a</b> has an identity digest preceding, equal
2801 * to, or later than that of *<b>b</b>. */
2802 static int
2803 _compare_old_routers_by_identity(const void **_a, const void **_b)
2805 int i;
2806 const signed_descriptor_t *r1 = *_a, *r2 = *_b;
2807 if ((i = memcmp(r1->identity_digest, r2->identity_digest, DIGEST_LEN)))
2808 return i;
2809 return r1->published_on - r2->published_on;
2812 /** Internal type used to represent how long an old descriptor was valid,
2813 * where it appeared in the list of old descriptors, and whether it's extra
2814 * old. Used only by routerlist_remove_old_cached_routers_with_id(). */
2815 struct duration_idx_t {
2816 int duration;
2817 int idx;
2818 int old;
2821 /** Sorting helper: compare two duration_idx_t by their duration. */
2822 static int
2823 _compare_duration_idx(const void *_d1, const void *_d2)
2825 const struct duration_idx_t *d1 = _d1;
2826 const struct duration_idx_t *d2 = _d2;
2827 return d1->duration - d2->duration;
2830 /** The range <b>lo</b> through <b>hi</b> inclusive of routerlist->old_routers
2831 * must contain routerinfo_t with the same identity and with publication time
2832 * in ascending order. Remove members from this range until there are no more
2833 * than max_descriptors_per_router() remaining. Start by removing the oldest
2834 * members from before <b>cutoff</b>, then remove members which were current
2835 * for the lowest amount of time. The order of members of old_routers at
2836 * indices <b>lo</b> or higher may be changed.
2838 static void
2839 routerlist_remove_old_cached_routers_with_id(time_t now,
2840 time_t cutoff, int lo, int hi,
2841 digestmap_t *retain)
2843 int i, n = hi-lo+1;
2844 unsigned n_extra, n_rmv = 0;
2845 struct duration_idx_t *lifespans;
2846 uint8_t *rmv, *must_keep;
2847 smartlist_t *lst = routerlist->old_routers;
2848 #if 1
2849 const char *ident;
2850 tor_assert(hi < smartlist_len(lst));
2851 tor_assert(lo <= hi);
2852 ident = ((signed_descriptor_t*)smartlist_get(lst, lo))->identity_digest;
2853 for (i = lo+1; i <= hi; ++i) {
2854 signed_descriptor_t *r = smartlist_get(lst, i);
2855 tor_assert(!memcmp(ident, r->identity_digest, DIGEST_LEN));
2857 #endif
2859 /* Check whether we need to do anything at all. */
2861 int mdpr = directory_caches_dir_info(get_options()) ? 5 : 2;
2862 if (n <= mdpr)
2863 return;
2864 n_extra = n - mdpr;
2867 lifespans = tor_malloc_zero(sizeof(struct duration_idx_t)*n);
2868 rmv = tor_malloc_zero(sizeof(uint8_t)*n);
2869 must_keep = tor_malloc_zero(sizeof(uint8_t)*n);
2870 /* Set lifespans to contain the lifespan and index of each server. */
2871 /* Set rmv[i-lo]=1 if we're going to remove a server for being too old. */
2872 for (i = lo; i <= hi; ++i) {
2873 signed_descriptor_t *r = smartlist_get(lst, i);
2874 signed_descriptor_t *r_next;
2875 lifespans[i-lo].idx = i;
2876 if (r->last_listed_as_valid_until >= now ||
2877 (retain && digestmap_get(retain, r->signed_descriptor_digest))) {
2878 must_keep[i-lo] = 1;
2880 if (i < hi) {
2881 r_next = smartlist_get(lst, i+1);
2882 tor_assert(r->published_on <= r_next->published_on);
2883 lifespans[i-lo].duration = (r_next->published_on - r->published_on);
2884 } else {
2885 r_next = NULL;
2886 lifespans[i-lo].duration = INT_MAX;
2888 if (!must_keep[i-lo] && r->published_on < cutoff && n_rmv < n_extra) {
2889 ++n_rmv;
2890 lifespans[i-lo].old = 1;
2891 rmv[i-lo] = 1;
2895 if (n_rmv < n_extra) {
2897 * We aren't removing enough servers for being old. Sort lifespans by
2898 * the duration of liveness, and remove the ones we're not already going to
2899 * remove based on how long they were alive.
2901 qsort(lifespans, n, sizeof(struct duration_idx_t), _compare_duration_idx);
2902 for (i = 0; i < n && n_rmv < n_extra; ++i) {
2903 if (!must_keep[lifespans[i].idx-lo] && !lifespans[i].old) {
2904 rmv[lifespans[i].idx-lo] = 1;
2905 ++n_rmv;
2910 i = hi;
2911 do {
2912 if (rmv[i-lo])
2913 routerlist_remove_old(routerlist, smartlist_get(lst, i), i);
2914 } while (--i >= lo);
2915 tor_free(must_keep);
2916 tor_free(rmv);
2917 tor_free(lifespans);
2920 /** Deactivate any routers from the routerlist that are more than
2921 * ROUTER_MAX_AGE seconds old and not recommended by any networkstatuses;
2922 * remove old routers from the list of cached routers if we have too many.
2924 void
2925 routerlist_remove_old_routers(void)
2927 int i, hi=-1;
2928 const char *cur_id = NULL;
2929 time_t now = time(NULL);
2930 time_t cutoff;
2931 routerinfo_t *router;
2932 signed_descriptor_t *sd;
2933 digestmap_t *retain;
2934 int caches = directory_caches_dir_info(get_options());
2935 const networkstatus_vote_t *consensus = networkstatus_get_latest_consensus();
2936 const smartlist_t *networkstatus_v2_list = networkstatus_get_v2_list();
2938 trusted_dirs_remove_old_certs();
2940 if (!routerlist || !consensus)
2941 return;
2943 // routerlist_assert_ok(routerlist);
2945 retain = digestmap_new();
2946 cutoff = now - OLD_ROUTER_DESC_MAX_AGE;
2947 /* Build a list of all the descriptors that _anybody_ lists. */
2948 if (caches) {
2949 SMARTLIST_FOREACH(networkstatus_v2_list, networkstatus_v2_t *, ns,
2951 /* XXXX The inner loop here gets pretty expensive, and actually shows up
2952 * on some profiles. It may be the reason digestmap_set shows up in
2953 * profiles too. If instead we kept a per-descriptor digest count of
2954 * how many networkstatuses recommended each descriptor, and changed
2955 * that only when the networkstatuses changed, that would be a speed
2956 * improvement, possibly 1-4% if it also removes digestmap_set from the
2957 * profile. Not worth it for 0.1.2.x, though. The new directory
2958 * system will obsolete this whole thing in 0.2.0.x. */
2959 SMARTLIST_FOREACH(ns->entries, routerstatus_t *, rs,
2960 if (rs->published_on >= cutoff)
2961 digestmap_set(retain, rs->descriptor_digest, (void*)1));
2965 /* Retain anything listed in the consensus. */
2966 if (consensus) {
2967 SMARTLIST_FOREACH(consensus->routerstatus_list, routerstatus_t *, rs,
2968 if (rs->published_on >= cutoff)
2969 digestmap_set(retain, rs->descriptor_digest, (void*)1));
2972 /* If we have a bunch of networkstatuses, we should consider pruning current
2973 * routers that are too old and that nobody recommends. (If we don't have
2974 * enough networkstatuses, then we should get more before we decide to kill
2975 * routers.) */
2976 if (!caches ||
2977 smartlist_len(networkstatus_v2_list) > get_n_v2_authorities() / 2) {
2978 cutoff = now - ROUTER_MAX_AGE;
2979 /* Remove too-old unrecommended members of routerlist->routers. */
2980 for (i = 0; i < smartlist_len(routerlist->routers); ++i) {
2981 router = smartlist_get(routerlist->routers, i);
2982 if (router->cache_info.published_on <= cutoff &&
2983 router->cache_info.last_listed_as_valid_until < now &&
2984 !digestmap_get(retain,router->cache_info.signed_descriptor_digest)) {
2985 /* Too old: remove it. (If we're a cache, just move it into
2986 * old_routers.) */
2987 log_info(LD_DIR,
2988 "Forgetting obsolete (too old) routerinfo for router '%s'",
2989 router->nickname);
2990 routerlist_remove(routerlist, router, 1);
2991 i--;
2996 //routerlist_assert_ok(routerlist);
2998 /* Remove far-too-old members of routerlist->old_routers. */
2999 cutoff = now - OLD_ROUTER_DESC_MAX_AGE;
3000 for (i = 0; i < smartlist_len(routerlist->old_routers); ++i) {
3001 sd = smartlist_get(routerlist->old_routers, i);
3002 if (sd->published_on <= cutoff &&
3003 sd->last_listed_as_valid_until < now &&
3004 !digestmap_get(retain, sd->signed_descriptor_digest)) {
3005 /* Too old. Remove it. */
3006 routerlist_remove_old(routerlist, sd, i--);
3010 //routerlist_assert_ok(routerlist);
3012 log_info(LD_DIR, "We have %d live routers and %d old router descriptors. "
3013 "At most %d must be retained because of networkstatuses.",
3014 smartlist_len(routerlist->routers),
3015 smartlist_len(routerlist->old_routers),
3016 digestmap_size(retain));
3018 /* Now we might have to look at routerlist->old_routers for extraneous
3019 * members. (We'd keep all the members if we could, but we need to save
3020 * space.) First, check whether we have too many router descriptors, total.
3021 * We're okay with having too many for some given router, so long as the
3022 * total number doesn't approach max_descriptors_per_router()*len(router).
3024 if (smartlist_len(routerlist->old_routers) <
3025 smartlist_len(routerlist->routers) * (caches?4:2))
3026 goto done;
3028 smartlist_sort(routerlist->old_routers, _compare_old_routers_by_identity);
3029 /* Fix indices. */
3030 for (i = 0; i < smartlist_len(routerlist->old_routers); ++i) {
3031 signed_descriptor_t *r = smartlist_get(routerlist->old_routers, i);
3032 r->routerlist_index = i;
3035 /* Iterate through the list from back to front, so when we remove descriptors
3036 * we don't mess up groups we haven't gotten to. */
3037 for (i = smartlist_len(routerlist->old_routers)-1; i >= 0; --i) {
3038 signed_descriptor_t *r = smartlist_get(routerlist->old_routers, i);
3039 if (!cur_id) {
3040 cur_id = r->identity_digest;
3041 hi = i;
3043 if (memcmp(cur_id, r->identity_digest, DIGEST_LEN)) {
3044 routerlist_remove_old_cached_routers_with_id(now,
3045 cutoff, i+1, hi, retain);
3046 cur_id = r->identity_digest;
3047 hi = i;
3050 if (hi>=0)
3051 routerlist_remove_old_cached_routers_with_id(now, cutoff, 0, hi, retain);
3052 //routerlist_assert_ok(routerlist);
3054 done:
3055 digestmap_free(retain, NULL);
3058 /** We just added a new set of descriptors. Take whatever extra steps
3059 * we need. */
3060 static void
3061 routerlist_descriptors_added(smartlist_t *sl, int from_cache)
3063 tor_assert(sl);
3064 control_event_descriptors_changed(sl);
3065 SMARTLIST_FOREACH(sl, routerinfo_t *, ri,
3066 if (ri->purpose == ROUTER_PURPOSE_BRIDGE)
3067 learned_bridge_descriptor(ri, from_cache);
3072 * Code to parse a single router descriptor and insert it into the
3073 * routerlist. Return -1 if the descriptor was ill-formed; 0 if the
3074 * descriptor was well-formed but could not be added; and 1 if the
3075 * descriptor was added.
3077 * If we don't add it and <b>msg</b> is not NULL, then assign to
3078 * *<b>msg</b> a static string describing the reason for refusing the
3079 * descriptor.
3081 * This is used only by the controller.
3084 router_load_single_router(const char *s, uint8_t purpose, int cache,
3085 const char **msg)
3087 routerinfo_t *ri;
3088 int r;
3089 smartlist_t *lst;
3090 char annotation_buf[ROUTER_ANNOTATION_BUF_LEN];
3091 tor_assert(msg);
3092 *msg = NULL;
3094 tor_snprintf(annotation_buf, sizeof(annotation_buf),
3095 "@source controller\n"
3096 "@purpose %s\n", router_purpose_to_string(purpose));
3098 if (!(ri = router_parse_entry_from_string(s, NULL, 1, 0, annotation_buf))) {
3099 log_warn(LD_DIR, "Error parsing router descriptor; dropping.");
3100 *msg = "Couldn't parse router descriptor.";
3101 return -1;
3103 tor_assert(ri->purpose == purpose);
3104 if (router_is_me(ri)) {
3105 log_warn(LD_DIR, "Router's identity key matches mine; dropping.");
3106 *msg = "Router's identity key matches mine.";
3107 routerinfo_free(ri);
3108 return 0;
3111 if (!cache) /* obey the preference of the controller */
3112 ri->cache_info.do_not_cache = 1;
3114 lst = smartlist_create();
3115 smartlist_add(lst, ri);
3116 routers_update_status_from_consensus_networkstatus(lst, 0);
3118 if ((r=router_add_to_routerlist(ri, msg, 0, 0))<0) {
3119 /* we've already assigned to *msg now, and ri is already freed */
3120 tor_assert(*msg);
3121 if (r < -1)
3122 log_warn(LD_DIR, "Couldn't add router to list: %s Dropping.", *msg);
3123 smartlist_free(lst);
3124 return 0;
3125 } else {
3126 routerlist_descriptors_added(lst, 0);
3127 smartlist_free(lst);
3128 log_debug(LD_DIR, "Added router to list");
3129 return 1;
3133 /** Given a string <b>s</b> containing some routerdescs, parse it and put the
3134 * routers into our directory. If saved_location is SAVED_NOWHERE, the routers
3135 * are in response to a query to the network: cache them by adding them to
3136 * the journal.
3138 * If <b>requested_fingerprints</b> is provided, it must contain a list of
3139 * uppercased fingerprints. Do not update any router whose
3140 * fingerprint is not on the list; after updating a router, remove its
3141 * fingerprint from the list.
3143 * If <b>descriptor_digests</b> is non-zero, then the requested_fingerprints
3144 * are descriptor digests. Otherwise they are identity digests.
3146 void
3147 router_load_routers_from_string(const char *s, const char *eos,
3148 saved_location_t saved_location,
3149 smartlist_t *requested_fingerprints,
3150 int descriptor_digests,
3151 const char *prepend_annotations)
3153 smartlist_t *routers = smartlist_create(), *changed = smartlist_create();
3154 char fp[HEX_DIGEST_LEN+1];
3155 const char *msg;
3156 int from_cache = (saved_location != SAVED_NOWHERE);
3157 int allow_annotations = (saved_location != SAVED_NOWHERE);
3158 int any_changed = 0;
3160 router_parse_list_from_string(&s, eos, routers, saved_location, 0,
3161 allow_annotations, prepend_annotations);
3163 routers_update_status_from_consensus_networkstatus(routers, !from_cache);
3165 log_info(LD_DIR, "%d elements to add", smartlist_len(routers));
3167 SMARTLIST_FOREACH(routers, routerinfo_t *, ri,
3169 if (requested_fingerprints) {
3170 base16_encode(fp, sizeof(fp), descriptor_digests ?
3171 ri->cache_info.signed_descriptor_digest :
3172 ri->cache_info.identity_digest,
3173 DIGEST_LEN);
3174 if (smartlist_string_isin(requested_fingerprints, fp)) {
3175 smartlist_string_remove(requested_fingerprints, fp);
3176 } else {
3177 char *requested =
3178 smartlist_join_strings(requested_fingerprints," ",0,NULL);
3179 log_warn(LD_DIR,
3180 "We received a router descriptor with a fingerprint (%s) "
3181 "that we never requested. (We asked for: %s.) Dropping.",
3182 fp, requested);
3183 tor_free(requested);
3184 routerinfo_free(ri);
3185 continue;
3189 if (router_add_to_routerlist(ri, &msg, from_cache, !from_cache) >= 0) {
3190 any_changed = 1;
3191 smartlist_add(changed, ri);
3192 routerlist_descriptors_added(changed, from_cache);
3193 smartlist_clear(changed);
3197 routerlist_assert_ok(routerlist);
3199 if (any_changed)
3200 router_rebuild_store(0, &routerlist->desc_store);
3202 smartlist_free(routers);
3203 smartlist_free(changed);
3206 /** Parse one or more extrainfos from <b>s</b> (ending immediately before
3207 * <b>eos</b> if <b>eos</b> is present). Other arguments are as for
3208 * router_load_routers_from_string(). */
3209 void
3210 router_load_extrainfo_from_string(const char *s, const char *eos,
3211 saved_location_t saved_location,
3212 smartlist_t *requested_fingerprints,
3213 int descriptor_digests)
3215 smartlist_t *extrainfo_list = smartlist_create();
3216 const char *msg;
3217 int from_cache = (saved_location != SAVED_NOWHERE);
3219 router_parse_list_from_string(&s, eos, extrainfo_list, saved_location, 1, 0,
3220 NULL);
3222 log_info(LD_DIR, "%d elements to add", smartlist_len(extrainfo_list));
3224 SMARTLIST_FOREACH(extrainfo_list, extrainfo_t *, ei, {
3225 int added =
3226 router_add_extrainfo_to_routerlist(ei, &msg, from_cache, !from_cache);
3227 if (added && requested_fingerprints) {
3228 char fp[HEX_DIGEST_LEN+1];
3229 base16_encode(fp, sizeof(fp), descriptor_digests ?
3230 ei->cache_info.signed_descriptor_digest :
3231 ei->cache_info.identity_digest,
3232 DIGEST_LEN);
3233 smartlist_string_remove(requested_fingerprints, fp);
3234 /* XXX020 We silently let people stuff us with extrainfos we
3235 * didn't ask for. Is this a problem? -RD */
3239 routerlist_assert_ok(routerlist);
3240 router_rebuild_store(0, &router_get_routerlist()->extrainfo_store);
3242 smartlist_free(extrainfo_list);
3245 /** Return true iff any networkstatus includes a descriptor whose digest
3246 * is that of <b>desc</b>. */
3247 static int
3248 signed_desc_digest_is_recognized(signed_descriptor_t *desc)
3250 routerstatus_t *rs;
3251 networkstatus_vote_t *consensus = networkstatus_get_latest_consensus();
3252 int caches = directory_caches_dir_info(get_options());
3253 const smartlist_t *networkstatus_v2_list = networkstatus_get_v2_list();
3255 if (consensus) {
3256 rs = networkstatus_vote_find_entry(consensus, desc->identity_digest);
3257 if (rs && !memcmp(rs->descriptor_digest,
3258 desc->signed_descriptor_digest, DIGEST_LEN))
3259 return 1;
3261 if (caches && networkstatus_v2_list) {
3262 SMARTLIST_FOREACH(networkstatus_v2_list, networkstatus_v2_t *, ns,
3264 if (!(rs = networkstatus_v2_find_entry(ns, desc->identity_digest)))
3265 continue;
3266 if (!memcmp(rs->descriptor_digest,
3267 desc->signed_descriptor_digest, DIGEST_LEN))
3268 return 1;
3271 return 0;
3274 /** Clear all our timeouts for fetching v2 and v3 directory stuff, and then
3275 * give it all a try again. */
3276 void
3277 routerlist_retry_directory_downloads(time_t now)
3279 router_reset_status_download_failures();
3280 router_reset_descriptor_download_failures();
3281 update_networkstatus_downloads(now);
3282 update_router_descriptor_downloads(now);
3285 /** Return 1 if all running sufficiently-stable routers will reject
3286 * addr:port, return 0 if any might accept it. */
3288 router_exit_policy_all_routers_reject(uint32_t addr, uint16_t port,
3289 int need_uptime)
3291 addr_policy_result_t r;
3292 if (!routerlist) return 1;
3294 SMARTLIST_FOREACH(routerlist->routers, routerinfo_t *, router,
3296 if (router->is_running &&
3297 !router_is_unreliable(router, need_uptime, 0, 0)) {
3298 r = compare_addr_to_addr_policy(addr, port, router->exit_policy);
3299 if (r != ADDR_POLICY_REJECTED && r != ADDR_POLICY_PROBABLY_REJECTED)
3300 return 0; /* this one could be ok. good enough. */
3303 return 1; /* all will reject. */
3306 /** Return true iff <b>router</b> does not permit exit streams.
3309 router_exit_policy_rejects_all(routerinfo_t *router)
3311 return compare_addr_to_addr_policy(0, 0, router->exit_policy)
3312 == ADDR_POLICY_REJECTED;
3315 /** Add to the list of authorized directory servers one at
3316 * <b>address</b>:<b>port</b>, with identity key <b>digest</b>. If
3317 * <b>address</b> is NULL, add ourself. */
3318 void
3319 add_trusted_dir_server(const char *nickname, const char *address,
3320 uint16_t dir_port, uint16_t or_port,
3321 const char *digest, const char *v3_auth_digest,
3322 authority_type_t type)
3324 trusted_dir_server_t *ent;
3325 uint32_t a;
3326 char *hostname = NULL;
3327 size_t dlen;
3328 if (!trusted_dir_servers)
3329 trusted_dir_servers = smartlist_create();
3331 if (!address) { /* The address is us; we should guess. */
3332 if (resolve_my_address(LOG_WARN, get_options(), &a, &hostname) < 0) {
3333 log_warn(LD_CONFIG,
3334 "Couldn't find a suitable address when adding ourself as a "
3335 "trusted directory server.");
3336 return;
3338 } else {
3339 if (tor_lookup_hostname(address, &a)) {
3340 log_warn(LD_CONFIG,
3341 "Unable to lookup address for directory server at '%s'",
3342 address);
3343 return;
3345 hostname = tor_strdup(address);
3348 ent = tor_malloc_zero(sizeof(trusted_dir_server_t));
3349 ent->nickname = nickname ? tor_strdup(nickname) : NULL;
3350 ent->address = hostname;
3351 ent->addr = a;
3352 ent->dir_port = dir_port;
3353 ent->or_port = or_port;
3354 ent->is_running = 1;
3355 ent->type = type;
3356 memcpy(ent->digest, digest, DIGEST_LEN);
3357 if (v3_auth_digest && (type & V3_AUTHORITY))
3358 memcpy(ent->v3_identity_digest, v3_auth_digest, DIGEST_LEN);
3360 dlen = 64 + strlen(hostname) + (nickname?strlen(nickname):0);
3361 ent->description = tor_malloc(dlen);
3362 if (nickname)
3363 tor_snprintf(ent->description, dlen, "directory server \"%s\" at %s:%d",
3364 nickname, hostname, (int)dir_port);
3365 else
3366 tor_snprintf(ent->description, dlen, "directory server at %s:%d",
3367 hostname, (int)dir_port);
3369 ent->fake_status.addr = ent->addr;
3370 memcpy(ent->fake_status.identity_digest, digest, DIGEST_LEN);
3371 if (nickname)
3372 strlcpy(ent->fake_status.nickname, nickname,
3373 sizeof(ent->fake_status.nickname));
3374 else
3375 ent->fake_status.nickname[0] = '\0';
3376 ent->fake_status.dir_port = ent->dir_port;
3377 ent->fake_status.or_port = ent->or_port;
3379 if (ent->or_port)
3380 ent->fake_status.version_supports_begindir = 1;
3382 smartlist_add(trusted_dir_servers, ent);
3383 router_dir_info_changed();
3386 /** Free storage held in <b>cert</b>. */
3387 void
3388 authority_cert_free(authority_cert_t *cert)
3390 if (!cert)
3391 return;
3393 tor_free(cert->cache_info.signed_descriptor_body);
3394 if (cert->signing_key)
3395 crypto_free_pk_env(cert->signing_key);
3396 if (cert->identity_key)
3397 crypto_free_pk_env(cert->identity_key);
3399 tor_free(cert);
3402 /** Free storage held in <b>ds</b>. */
3403 static void
3404 trusted_dir_server_free(trusted_dir_server_t *ds)
3406 if (ds->v3_certs) {
3407 SMARTLIST_FOREACH(ds->v3_certs, authority_cert_t *, cert,
3408 authority_cert_free(cert));
3409 smartlist_free(ds->v3_certs);
3411 tor_free(ds->nickname);
3412 tor_free(ds->description);
3413 tor_free(ds->address);
3414 tor_free(ds);
3417 /** Remove all members from the list of trusted dir servers. */
3418 void
3419 clear_trusted_dir_servers(void)
3421 if (trusted_dir_servers) {
3422 SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, ent,
3423 trusted_dir_server_free(ent));
3424 smartlist_clear(trusted_dir_servers);
3425 } else {
3426 trusted_dir_servers = smartlist_create();
3428 router_dir_info_changed();
3431 /** Return 1 if any trusted dir server supports v1 directories,
3432 * else return 0. */
3434 any_trusted_dir_is_v1_authority(void)
3436 if (trusted_dir_servers)
3437 return get_n_authorities(V1_AUTHORITY) > 0;
3439 return 0;
3442 /** For every current directory connection whose purpose is <b>purpose</b>,
3443 * and where the resource being downloaded begins with <b>prefix</b>, split
3444 * rest of the resource into base16 fingerprints, decode them, and set the
3445 * corresponding elements of <b>result</b> to a nonzero value. */
3446 static void
3447 list_pending_downloads(digestmap_t *result,
3448 int purpose, const char *prefix)
3450 const size_t p_len = strlen(prefix);
3451 smartlist_t *tmp = smartlist_create();
3452 smartlist_t *conns = get_connection_array();
3454 tor_assert(result);
3456 SMARTLIST_FOREACH(conns, connection_t *, conn,
3458 if (conn->type == CONN_TYPE_DIR &&
3459 conn->purpose == purpose &&
3460 !conn->marked_for_close) {
3461 const char *resource = TO_DIR_CONN(conn)->requested_resource;
3462 if (!strcmpstart(resource, prefix))
3463 dir_split_resource_into_fingerprints(resource + p_len,
3464 tmp, NULL, 1, 0);
3467 SMARTLIST_FOREACH(tmp, char *, d,
3469 digestmap_set(result, d, (void*)1);
3470 tor_free(d);
3472 smartlist_free(tmp);
3475 /** For every router descriptor (or extra-info document if <b>extrainfo</b> is
3476 * true) we are currently downloading by descriptor digest, set result[d] to
3477 * (void*)1. */
3478 static void
3479 list_pending_descriptor_downloads(digestmap_t *result, int extrainfo)
3481 int purpose =
3482 extrainfo ? DIR_PURPOSE_FETCH_EXTRAINFO : DIR_PURPOSE_FETCH_SERVERDESC;
3483 list_pending_downloads(result, purpose, "d/");
3486 /** Launch downloads for all the descriptors whose digests are listed
3487 * as digests[i] for lo <= i < hi. (Lo and hi may be out of range.)
3488 * If <b>source</b> is given, download from <b>source</b>; otherwise,
3489 * download from an appropriate random directory server.
3491 static void
3492 initiate_descriptor_downloads(routerstatus_t *source,
3493 int purpose,
3494 smartlist_t *digests,
3495 int lo, int hi)
3497 int i, n = hi-lo;
3498 char *resource, *cp;
3499 size_t r_len;
3500 if (n <= 0)
3501 return;
3502 if (lo < 0)
3503 lo = 0;
3504 if (hi > smartlist_len(digests))
3505 hi = smartlist_len(digests);
3507 r_len = 8 + (HEX_DIGEST_LEN+1)*n;
3508 cp = resource = tor_malloc(r_len);
3509 memcpy(cp, "d/", 2);
3510 cp += 2;
3511 for (i = lo; i < hi; ++i) {
3512 base16_encode(cp, r_len-(cp-resource),
3513 smartlist_get(digests,i), DIGEST_LEN);
3514 cp += HEX_DIGEST_LEN;
3515 *cp++ = '+';
3517 memcpy(cp-1, ".z", 3);
3519 if (source) {
3520 /* We know which authority we want. */
3521 directory_initiate_command_routerstatus(source, purpose,
3522 ROUTER_PURPOSE_GENERAL,
3523 0, /* not private */
3524 resource, NULL, 0, 0);
3525 } else {
3526 directory_get_from_dirserver(purpose, ROUTER_PURPOSE_GENERAL, resource, 1);
3528 tor_free(resource);
3531 /** Clients don't download any descriptor this recent, since it will probably
3532 * not have propagated to enough caches. */
3533 #define ESTIMATED_PROPAGATION_TIME (10*60)
3535 /** Return 0 if this routerstatus is obsolete, too new, isn't
3536 * running, or otherwise not a descriptor that we would make any
3537 * use of even if we had it. Else return 1. */
3538 static INLINE int
3539 client_would_use_router(routerstatus_t *rs, time_t now, or_options_t *options)
3541 if (!rs->is_running && !options->FetchUselessDescriptors) {
3542 /* If we had this router descriptor, we wouldn't even bother using it.
3543 * But, if we want to have a complete list, fetch it anyway. */
3544 return 0;
3546 if (rs->published_on + ESTIMATED_PROPAGATION_TIME > now) {
3547 /* Most caches probably don't have this descriptor yet. */
3548 return 0;
3550 if (rs->published_on + OLD_ROUTER_DESC_MAX_AGE < now) {
3551 /* We'd drop it immediately for being too old. */
3552 return 0;
3554 return 1;
3557 /** Max amount of hashes to download per request.
3558 * Since squid does not like URLs >= 4096 bytes we limit it to 96.
3559 * 4096 - strlen(http://255.255.255.255/tor/server/d/.z) == 4058
3560 * 4058/41 (40 for the hash and 1 for the + that separates them) => 98
3561 * So use 96 because it's a nice number.
3563 #define MAX_DL_PER_REQUEST 96
3564 /** Don't split our requests so finely that we are requesting fewer than
3565 * this number per server. */
3566 #define MIN_DL_PER_REQUEST 4
3567 /** To prevent a single screwy cache from confusing us by selective reply,
3568 * try to split our requests into at least this this many requests. */
3569 #define MIN_REQUESTS 3
3570 /** If we want fewer than this many descriptors, wait until we
3571 * want more, or until MAX_CLIENT_INTERVAL_WITHOUT_REQUEST has
3572 * passed. */
3573 #define MAX_DL_TO_DELAY 16
3574 /** When directory clients have only a few servers to request, they batch
3575 * them until they have more, or until this amount of time has passed. */
3576 #define MAX_CLIENT_INTERVAL_WITHOUT_REQUEST (10*60)
3578 /** Given a list of router descriptor digests in <b>downloadable</b>, decide
3579 * whether to delay fetching until we have more. If we don't want to delay,
3580 * launch one or more requests to the appropriate directory authorities. */
3581 static void
3582 launch_router_descriptor_downloads(smartlist_t *downloadable, time_t now)
3584 int should_delay = 0, n_downloadable;
3585 or_options_t *options = get_options();
3587 n_downloadable = smartlist_len(downloadable);
3588 if (!directory_fetches_dir_info_early(options)) {
3589 if (n_downloadable >= MAX_DL_TO_DELAY) {
3590 log_debug(LD_DIR,
3591 "There are enough downloadable routerdescs to launch requests.");
3592 should_delay = 0;
3593 } else {
3594 should_delay = (last_routerdesc_download_attempted +
3595 MAX_CLIENT_INTERVAL_WITHOUT_REQUEST) > now;
3596 if (!should_delay && n_downloadable) {
3597 if (last_routerdesc_download_attempted) {
3598 log_info(LD_DIR,
3599 "There are not many downloadable routerdescs, but we've "
3600 "been waiting long enough (%d seconds). Downloading.",
3601 (int)(now-last_routerdesc_download_attempted));
3602 } else {
3603 log_info(LD_DIR,
3604 "There are not many downloadable routerdescs, but we haven't "
3605 "tried downloading descriptors recently. Downloading.");
3610 /* XXX020 should we consider having even the dir mirrors delay
3611 * a little bit, so we don't load the authorities as much? -RD */
3613 if (! should_delay && n_downloadable) {
3614 int i, n_per_request;
3615 const char *req_plural = "", *rtr_plural = "";
3616 n_per_request = (n_downloadable+MIN_REQUESTS-1) / MIN_REQUESTS;
3617 if (n_per_request > MAX_DL_PER_REQUEST)
3618 n_per_request = MAX_DL_PER_REQUEST;
3619 if (n_per_request < MIN_DL_PER_REQUEST)
3620 n_per_request = MIN_DL_PER_REQUEST;
3622 if (n_downloadable > n_per_request)
3623 req_plural = rtr_plural = "s";
3624 else if (n_downloadable > 1)
3625 rtr_plural = "s";
3627 log_info(LD_DIR,
3628 "Launching %d request%s for %d router%s, %d at a time",
3629 (n_downloadable+n_per_request-1)/n_per_request,
3630 req_plural, n_downloadable, rtr_plural, n_per_request);
3631 smartlist_sort_digests(downloadable);
3632 for (i=0; i < n_downloadable; i += n_per_request) {
3633 initiate_descriptor_downloads(NULL, DIR_PURPOSE_FETCH_SERVERDESC,
3634 downloadable, i, i+n_per_request);
3636 last_routerdesc_download_attempted = now;
3640 /** Launch downloads for router status as needed, using the strategy used by
3641 * authorities and caches: based on the v2 networkstatuses we have, download
3642 * every descriptor we don't have but would serve, from a random authority
3643 * that lists it. */
3644 static void
3645 update_router_descriptor_cache_downloads_v2(time_t now)
3647 smartlist_t **downloadable; /* For each authority, what can we dl from it? */
3648 smartlist_t **download_from; /* ... and, what will we dl from it? */
3649 digestmap_t *map; /* Which descs are in progress, or assigned? */
3650 int i, j, n;
3651 int n_download;
3652 or_options_t *options = get_options();
3653 const smartlist_t *networkstatus_v2_list = networkstatus_get_v2_list();
3655 if (! directory_fetches_dir_info_early(options)) {
3656 log_warn(LD_BUG, "Called update_router_descriptor_cache_downloads_v2() "
3657 "on a non-dir-mirror?");
3660 if (!networkstatus_v2_list || !smartlist_len(networkstatus_v2_list))
3661 return;
3663 map = digestmap_new();
3664 n = smartlist_len(networkstatus_v2_list);
3666 downloadable = tor_malloc_zero(sizeof(smartlist_t*) * n);
3667 download_from = tor_malloc_zero(sizeof(smartlist_t*) * n);
3669 /* Set map[d]=1 for the digest of every descriptor that we are currently
3670 * downloading. */
3671 list_pending_descriptor_downloads(map, 0);
3673 /* For the digest of every descriptor that we don't have, and that we aren't
3674 * downloading, add d to downloadable[i] if the i'th networkstatus knows
3675 * about that descriptor, and we haven't already failed to get that
3676 * descriptor from the corresponding authority.
3678 n_download = 0;
3679 SMARTLIST_FOREACH(networkstatus_v2_list, networkstatus_v2_t *, ns,
3681 trusted_dir_server_t *ds;
3682 smartlist_t *dl;
3683 dl = downloadable[ns_sl_idx] = smartlist_create();
3684 download_from[ns_sl_idx] = smartlist_create();
3685 if (ns->published_on + MAX_NETWORKSTATUS_AGE+10*60 < now) {
3686 /* Don't download if the networkstatus is almost ancient. */
3687 /* Actually, I suspect what's happening here is that we ask
3688 * for the descriptor when we have a given networkstatus,
3689 * and then we get a newer networkstatus, and then we receive
3690 * the descriptor. Having a networkstatus actually expire is
3691 * probably a rare event, and we'll probably be happiest if
3692 * we take this clause out. -RD */
3693 continue;
3696 /* Don't try dirservers that we think are down -- we might have
3697 * just tried them and just marked them as down. */
3698 ds = router_get_trusteddirserver_by_digest(ns->identity_digest);
3699 if (ds && !ds->is_running)
3700 continue;
3702 SMARTLIST_FOREACH(ns->entries, routerstatus_t * , rs,
3704 if (!rs->need_to_mirror)
3705 continue;
3706 if (router_get_by_descriptor_digest(rs->descriptor_digest)) {
3707 log_warn(LD_BUG,
3708 "We have a router descriptor, but need_to_mirror=1.");
3709 rs->need_to_mirror = 0;
3710 continue;
3712 if (authdir_mode(options) && dirserv_would_reject_router(rs)) {
3713 rs->need_to_mirror = 0;
3714 continue;
3716 if (digestmap_get(map, rs->descriptor_digest)) {
3717 /* We're downloading it already. */
3718 continue;
3719 } else {
3720 /* We could download it from this guy. */
3721 smartlist_add(dl, rs->descriptor_digest);
3722 ++n_download;
3727 /* At random, assign descriptors to authorities such that:
3728 * - if d is a member of some downloadable[x], d is a member of some
3729 * download_from[y]. (Everything we want to download, we try to download
3730 * from somebody.)
3731 * - If d is a member of download_from[y], d is a member of downloadable[y].
3732 * (We only try to download descriptors from authorities who claim to have
3733 * them.)
3734 * - No d is a member of download_from[x] and download_from[y] s.t. x != y.
3735 * (We don't try to download anything from two authorities concurrently.)
3737 while (n_download) {
3738 int which_ns = crypto_rand_int(n);
3739 smartlist_t *dl = downloadable[which_ns];
3740 int idx;
3741 char *d;
3742 if (!smartlist_len(dl))
3743 continue;
3744 idx = crypto_rand_int(smartlist_len(dl));
3745 d = smartlist_get(dl, idx);
3746 if (! digestmap_get(map, d)) {
3747 smartlist_add(download_from[which_ns], d);
3748 digestmap_set(map, d, (void*) 1);
3750 smartlist_del(dl, idx);
3751 --n_download;
3754 /* Now, we can actually launch our requests. */
3755 for (i=0; i<n; ++i) {
3756 networkstatus_v2_t *ns = smartlist_get(networkstatus_v2_list, i);
3757 trusted_dir_server_t *ds =
3758 router_get_trusteddirserver_by_digest(ns->identity_digest);
3759 smartlist_t *dl = download_from[i];
3760 if (!ds) {
3761 log_warn(LD_BUG, "Networkstatus with no corresponding authority!");
3762 continue;
3764 if (! smartlist_len(dl))
3765 continue;
3766 log_info(LD_DIR, "Requesting %d descriptors from authority \"%s\"",
3767 smartlist_len(dl), ds->nickname);
3768 for (j=0; j < smartlist_len(dl); j += MAX_DL_PER_REQUEST) {
3769 initiate_descriptor_downloads(&(ds->fake_status),
3770 DIR_PURPOSE_FETCH_SERVERDESC, dl, j,
3771 j+MAX_DL_PER_REQUEST);
3775 for (i=0; i<n; ++i) {
3776 smartlist_free(download_from[i]);
3777 smartlist_free(downloadable[i]);
3779 tor_free(download_from);
3780 tor_free(downloadable);
3781 digestmap_free(map,NULL);
3784 /** For any descriptor that we want that's currently listed in the live
3785 * consensus, download it as appropriate. */
3786 static void
3787 update_consensus_router_descriptor_downloads(time_t now)
3789 or_options_t *options = get_options();
3790 digestmap_t *map = NULL;
3791 smartlist_t *no_longer_old = smartlist_create();
3792 smartlist_t *downloadable = smartlist_create();
3793 int authdir = authdir_mode(options);
3794 networkstatus_vote_t *consensus =
3795 networkstatus_get_reasonably_live_consensus(now);
3796 int n_delayed=0, n_have=0, n_would_reject=0, n_wouldnt_use=0,
3797 n_inprogress=0, n_in_oldrouters=0;
3799 if (directory_too_idle_to_fetch_descriptors(options, now))
3800 goto done;
3801 if (!consensus)
3802 goto done;
3804 map = digestmap_new();
3805 list_pending_descriptor_downloads(map, 0);
3806 SMARTLIST_FOREACH(consensus->routerstatus_list, routerstatus_t *, rs,
3808 signed_descriptor_t *sd;
3809 if ((sd = router_get_by_descriptor_digest(rs->descriptor_digest))) {
3810 routerinfo_t *ri;
3811 ++n_have;
3812 if (!(ri = router_get_by_digest(rs->identity_digest)) ||
3813 memcmp(ri->cache_info.signed_descriptor_digest,
3814 sd->signed_descriptor_digest, DIGEST_LEN)) {
3815 /* We have a descriptor with this digest, but either there is no
3816 * entry in routerlist with the same ID (!ri), or there is one,
3817 * but the identity digest differs (memcmp).
3819 smartlist_add(no_longer_old, sd);
3820 ++n_in_oldrouters; /* We have it in old_routers. */
3822 continue; /* We have it already. */
3824 if (digestmap_get(map, rs->descriptor_digest)) {
3825 ++n_inprogress;
3826 continue; /* We have an in-progress download. */
3828 if (!download_status_is_ready(&rs->dl_status, now,
3829 MAX_ROUTERDESC_DOWNLOAD_FAILURES)) {
3830 ++n_delayed; /* Not ready for retry. */
3831 continue;
3833 if (authdir && dirserv_would_reject_router(rs)) {
3834 ++n_would_reject;
3835 continue; /* We would throw it out immediately. */
3837 if (!directory_caches_dir_info(options) &&
3838 !client_would_use_router(rs, now, options)) {
3839 ++n_wouldnt_use;
3840 continue; /* We would never use it ourself. */
3842 smartlist_add(downloadable, rs->descriptor_digest);
3845 if (!authdir_mode_handles_descs(options, ROUTER_PURPOSE_GENERAL)
3846 && smartlist_len(no_longer_old)) {
3847 routerlist_t *rl = router_get_routerlist();
3848 log_info(LD_DIR, "%d router descriptors listed in consensus are "
3849 "currently in old_routers; making them current.",
3850 smartlist_len(no_longer_old));
3851 SMARTLIST_FOREACH(no_longer_old, signed_descriptor_t *, sd, {
3852 const char *msg;
3853 int r;
3854 routerinfo_t *ri = routerlist_reparse_old(rl, sd);
3855 if (!ri) {
3856 log_warn(LD_BUG, "Failed to re-parse a router.");
3857 continue;
3859 r = router_add_to_routerlist(ri, &msg, 1, 0);
3860 if (r == -1) {
3861 log_warn(LD_DIR, "Couldn't add re-parsed router: %s",
3862 msg?msg:"???");
3865 routerlist_assert_ok(rl);
3868 log_info(LD_DIR,
3869 "%d router descriptors downloadable. %d delayed; %d present "
3870 "(%d of those were in old_routers); %d would_reject; "
3871 "%d wouldnt_use, %d in progress.",
3872 smartlist_len(downloadable), n_delayed, n_have, n_in_oldrouters,
3873 n_would_reject, n_wouldnt_use, n_inprogress);
3875 launch_router_descriptor_downloads(downloadable, now);
3877 digestmap_free(map, NULL);
3878 done:
3879 smartlist_free(downloadable);
3880 smartlist_free(no_longer_old);
3883 /** Launch downloads for router status as needed. */
3884 void
3885 update_router_descriptor_downloads(time_t now)
3887 or_options_t *options = get_options();
3888 if (should_delay_dir_fetches(options))
3889 return;
3890 if (directory_fetches_dir_info_early(options)) {
3891 update_router_descriptor_cache_downloads_v2(now);
3893 update_consensus_router_descriptor_downloads(now);
3896 /** Launch extrainfo downloads as needed. */
3897 void
3898 update_extrainfo_downloads(time_t now)
3900 or_options_t *options = get_options();
3901 routerlist_t *rl;
3902 smartlist_t *wanted;
3903 digestmap_t *pending;
3904 int old_routers, i;
3905 int n_no_ei = 0, n_pending = 0, n_have = 0, n_delay = 0;
3906 if (! options->DownloadExtraInfo)
3907 return;
3908 if (should_delay_dir_fetches(options))
3909 return;
3910 if (!router_have_minimum_dir_info())
3911 return;
3913 pending = digestmap_new();
3914 list_pending_descriptor_downloads(pending, 1);
3915 rl = router_get_routerlist();
3916 wanted = smartlist_create();
3917 for (old_routers = 0; old_routers < 2; ++old_routers) {
3918 smartlist_t *lst = old_routers ? rl->old_routers : rl->routers;
3919 for (i = 0; i < smartlist_len(lst); ++i) {
3920 signed_descriptor_t *sd;
3921 char *d;
3922 if (old_routers)
3923 sd = smartlist_get(lst, i);
3924 else
3925 sd = &((routerinfo_t*)smartlist_get(lst, i))->cache_info;
3926 if (sd->is_extrainfo)
3927 continue; /* This should never happen. */
3928 if (old_routers && !router_get_by_digest(sd->identity_digest))
3929 continue; /* Couldn't check the signature if we got it. */
3930 if (sd->extrainfo_is_bogus)
3931 continue;
3932 d = sd->extra_info_digest;
3933 if (tor_digest_is_zero(d)) {
3934 ++n_no_ei;
3935 continue;
3937 if (eimap_get(rl->extra_info_map, d)) {
3938 ++n_have;
3939 continue;
3941 if (!download_status_is_ready(&sd->ei_dl_status, now,
3942 MAX_ROUTERDESC_DOWNLOAD_FAILURES)) {
3943 ++n_delay;
3944 continue;
3946 if (digestmap_get(pending, d)) {
3947 ++n_pending;
3948 continue;
3950 smartlist_add(wanted, d);
3953 digestmap_free(pending, NULL);
3955 log_info(LD_DIR, "Extrainfo download status: %d router with no ei, %d "
3956 "with present ei, %d delaying, %d pending, %d downloadable.",
3957 n_no_ei, n_have, n_delay, n_pending, smartlist_len(wanted));
3959 smartlist_shuffle(wanted);
3960 for (i = 0; i < smartlist_len(wanted); i += MAX_DL_PER_REQUEST) {
3961 initiate_descriptor_downloads(NULL, DIR_PURPOSE_FETCH_EXTRAINFO,
3962 wanted, i, i + MAX_DL_PER_REQUEST);
3965 smartlist_free(wanted);
3968 /** True iff, the last time we checked whether we had enough directory info
3969 * to build circuits, the answer was "yes". */
3970 static int have_min_dir_info = 0;
3971 /** True iff enough has changed since the last time we checked whether we had
3972 * enough directory info to build circuits that our old answer can no longer
3973 * be trusted. */
3974 static int need_to_update_have_min_dir_info = 1;
3975 /** String describing what we're missing before we have enough directory
3976 * info. */
3977 static char dir_info_status[128] = "";
3979 /** Return true iff we have enough networkstatus and router information to
3980 * start building circuits. Right now, this means "more than half the
3981 * networkstatus documents, and at least 1/4 of expected routers." */
3982 //XXX should consider whether we have enough exiting nodes here.
3984 router_have_minimum_dir_info(void)
3986 if (PREDICT_UNLIKELY(need_to_update_have_min_dir_info)) {
3987 update_router_have_minimum_dir_info();
3988 need_to_update_have_min_dir_info = 0;
3990 return have_min_dir_info;
3993 /** Called when our internal view of the directory has changed. This can be
3994 * when the authorities change, networkstatuses change, the list of routerdescs
3995 * changes, or number of running routers changes.
3997 void
3998 router_dir_info_changed(void)
4000 need_to_update_have_min_dir_info = 1;
4003 /** Return a string describing what we're missing before we have enough
4004 * directory info. */
4005 const char *
4006 get_dir_info_status_string(void)
4008 return dir_info_status;
4011 /** Change the value of have_min_dir_info, setting it true iff we have enough
4012 * network and router information to build circuits. Clear the value of
4013 * need_to_update_have_min_dir_info. */
4014 static void
4015 update_router_have_minimum_dir_info(void)
4017 int num_present = 0, num_usable=0;
4018 time_t now = time(NULL);
4019 int res;
4020 or_options_t *options = get_options();
4021 const networkstatus_vote_t *consensus =
4022 networkstatus_get_reasonably_live_consensus(now);
4024 if (!consensus) {
4025 if (!networkstatus_get_latest_consensus())
4026 strlcpy(dir_info_status, "We have no network-status consensus.",
4027 sizeof(dir_info_status));
4028 else
4029 strlcpy(dir_info_status, "We have no recent network-status consensus.",
4030 sizeof(dir_info_status));
4031 res = 0;
4032 goto done;
4035 if (should_delay_dir_fetches(get_options())) {
4036 log_notice(LD_DIR, "no known bridge descriptors running yet; stalling");
4037 strlcpy(dir_info_status, "No live bridge descriptors.",
4038 sizeof(dir_info_status));
4039 res = 0;
4040 goto done;
4043 SMARTLIST_FOREACH(consensus->routerstatus_list, routerstatus_t *, rs,
4045 if (client_would_use_router(rs, now, options)) {
4046 ++num_usable;
4047 if (router_get_by_digest(rs->identity_digest)) {
4048 ++num_present;
4053 if (num_present < num_usable/4) {
4054 tor_snprintf(dir_info_status, sizeof(dir_info_status),
4055 "We have only %d/%d usable descriptors.", num_present, num_usable);
4056 res = 0;
4057 } else if (num_usable < 2) {
4058 tor_snprintf(dir_info_status, sizeof(dir_info_status),
4059 "Only %d usable descriptor%s known!", num_usable,
4060 num_usable ? "" : "s");
4061 res = 0;
4062 } else {
4063 res = 1;
4066 done:
4067 if (res && !have_min_dir_info) {
4068 log(LOG_NOTICE, LD_DIR,
4069 "We now have enough directory information to build circuits.");
4070 control_event_client_status(LOG_NOTICE, "ENOUGH_DIR_INFO");
4072 if (!res && have_min_dir_info) {
4073 log(LOG_NOTICE, LD_DIR,"Our directory information is no longer up-to-date "
4074 "enough to build circuits.%s",
4075 num_usable > 2 ? "" : " (Not enough servers seem reachable -- "
4076 "is your network connection down?)");
4077 control_event_client_status(LOG_NOTICE, "NOT_ENOUGH_DIR_INFO");
4079 have_min_dir_info = res;
4080 need_to_update_have_min_dir_info = 0;
4083 /** Reset the descriptor download failure count on all routers, so that we
4084 * can retry any long-failed routers immediately.
4086 void
4087 router_reset_descriptor_download_failures(void)
4089 networkstatus_reset_download_failures();
4090 last_routerdesc_download_attempted = 0;
4091 if (!routerlist)
4092 return;
4093 SMARTLIST_FOREACH(routerlist->routers, routerinfo_t *, ri,
4095 download_status_reset(&ri->cache_info.ei_dl_status);
4097 SMARTLIST_FOREACH(routerlist->old_routers, signed_descriptor_t *, sd,
4099 download_status_reset(&sd->ei_dl_status);
4103 /** Any changes in a router descriptor's publication time larger than this are
4104 * automatically non-cosmetic. */
4105 #define ROUTER_MAX_COSMETIC_TIME_DIFFERENCE (12*60*60)
4107 /** We allow uptime to vary from how much it ought to be by this much. */
4108 #define ROUTER_ALLOW_UPTIME_DRIFT (6*60*60)
4110 /** Return true iff the only differences between r1 and r2 are such that
4111 * would not cause a recent (post 0.1.1.6) dirserver to republish.
4114 router_differences_are_cosmetic(routerinfo_t *r1, routerinfo_t *r2)
4116 time_t r1pub, r2pub;
4117 int time_difference;
4118 tor_assert(r1 && r2);
4120 /* r1 should be the one that was published first. */
4121 if (r1->cache_info.published_on > r2->cache_info.published_on) {
4122 routerinfo_t *ri_tmp = r2;
4123 r2 = r1;
4124 r1 = ri_tmp;
4127 /* If any key fields differ, they're different. */
4128 if (strcasecmp(r1->address, r2->address) ||
4129 strcasecmp(r1->nickname, r2->nickname) ||
4130 r1->or_port != r2->or_port ||
4131 r1->dir_port != r2->dir_port ||
4132 r1->purpose != r2->purpose ||
4133 crypto_pk_cmp_keys(r1->onion_pkey, r2->onion_pkey) ||
4134 crypto_pk_cmp_keys(r1->identity_pkey, r2->identity_pkey) ||
4135 strcasecmp(r1->platform, r2->platform) ||
4136 (r1->contact_info && !r2->contact_info) || /* contact_info is optional */
4137 (!r1->contact_info && r2->contact_info) ||
4138 (r1->contact_info && r2->contact_info &&
4139 strcasecmp(r1->contact_info, r2->contact_info)) ||
4140 r1->is_hibernating != r2->is_hibernating ||
4141 r1->has_old_dnsworkers != r2->has_old_dnsworkers ||
4142 cmp_addr_policies(r1->exit_policy, r2->exit_policy))
4143 return 0;
4144 if ((r1->declared_family == NULL) != (r2->declared_family == NULL))
4145 return 0;
4146 if (r1->declared_family && r2->declared_family) {
4147 int i, n;
4148 if (smartlist_len(r1->declared_family)!=smartlist_len(r2->declared_family))
4149 return 0;
4150 n = smartlist_len(r1->declared_family);
4151 for (i=0; i < n; ++i) {
4152 if (strcasecmp(smartlist_get(r1->declared_family, i),
4153 smartlist_get(r2->declared_family, i)))
4154 return 0;
4158 /* Did bandwidth change a lot? */
4159 if ((r1->bandwidthcapacity < r2->bandwidthcapacity/2) ||
4160 (r2->bandwidthcapacity < r1->bandwidthcapacity/2))
4161 return 0;
4163 /* Did more than 12 hours pass? */
4164 if (r1->cache_info.published_on + ROUTER_MAX_COSMETIC_TIME_DIFFERENCE
4165 < r2->cache_info.published_on)
4166 return 0;
4168 /* Did uptime fail to increase by approximately the amount we would think,
4169 * give or take some slop? */
4170 r1pub = r1->cache_info.published_on;
4171 r2pub = r2->cache_info.published_on;
4172 time_difference = abs(r2->uptime - (r1->uptime + (r2pub - r1pub)));
4173 if (time_difference > ROUTER_ALLOW_UPTIME_DRIFT &&
4174 time_difference > r1->uptime * .05 &&
4175 time_difference > r2->uptime * .05)
4176 return 0;
4178 /* Otherwise, the difference is cosmetic. */
4179 return 1;
4182 /** Check whether <b>ri</b> (a.k.a. sd) is a router compatible with the
4183 * extrainfo document
4184 * <b>ei</b>. If no router is compatible with <b>ei</b>, <b>ei</b> should be
4185 * dropped. Return 0 for "compatible", return 1 for "reject, and inform
4186 * whoever uploaded <b>ei</b>, and return -1 for "reject silently.". If
4187 * <b>msg</b> is present, set *<b>msg</b> to a description of the
4188 * incompatibility (if any).
4191 routerinfo_incompatible_with_extrainfo(routerinfo_t *ri, extrainfo_t *ei,
4192 signed_descriptor_t *sd,
4193 const char **msg)
4195 int digest_matches, r=1;
4196 tor_assert(ri);
4197 tor_assert(ei);
4198 if (!sd)
4199 sd = &ri->cache_info;
4201 if (ei->bad_sig) {
4202 if (msg) *msg = "Extrainfo signature was bad, or signed with wrong key.";
4203 return 1;
4206 digest_matches = !memcmp(ei->cache_info.signed_descriptor_digest,
4207 sd->extra_info_digest, DIGEST_LEN);
4209 /* The identity must match exactly to have been generated at the same time
4210 * by the same router. */
4211 if (memcmp(ri->cache_info.identity_digest, ei->cache_info.identity_digest,
4212 DIGEST_LEN)) {
4213 if (msg) *msg = "Extrainfo nickname or identity did not match routerinfo";
4214 goto err; /* different servers */
4217 if (ei->pending_sig) {
4218 char signed_digest[128];
4219 if (crypto_pk_public_checksig(ri->identity_pkey, signed_digest,
4220 ei->pending_sig, ei->pending_sig_len) != DIGEST_LEN ||
4221 memcmp(signed_digest, ei->cache_info.signed_descriptor_digest,
4222 DIGEST_LEN)) {
4223 ei->bad_sig = 1;
4224 tor_free(ei->pending_sig);
4225 if (msg) *msg = "Extrainfo signature bad, or signed with wrong key";
4226 goto err; /* Bad signature, or no match. */
4229 ei->cache_info.send_unencrypted = ri->cache_info.send_unencrypted;
4230 tor_free(ei->pending_sig);
4233 if (ei->cache_info.published_on < sd->published_on) {
4234 if (msg) *msg = "Extrainfo published time did not match routerdesc";
4235 goto err;
4236 } else if (ei->cache_info.published_on > sd->published_on) {
4237 if (msg) *msg = "Extrainfo published time did not match routerdesc";
4238 r = -1;
4239 goto err;
4242 if (!digest_matches) {
4243 if (msg) *msg = "Extrainfo digest did not match value from routerdesc";
4244 goto err; /* Digest doesn't match declared value. */
4247 return 0;
4248 err:
4249 if (digest_matches) {
4250 /* This signature was okay, and the digest was right: This is indeed the
4251 * corresponding extrainfo. But insanely, it doesn't match the routerinfo
4252 * that lists it. Don't try to fetch this one again. */
4253 sd->extrainfo_is_bogus = 1;
4256 return r;
4259 /** Assert that the internal representation of <b>rl</b> is
4260 * self-consistent. */
4261 void
4262 routerlist_assert_ok(routerlist_t *rl)
4264 digestmap_iter_t *iter; /* XXXX020 use the appropriate iter type. */
4265 routerinfo_t *r2;
4266 signed_descriptor_t *sd2;
4267 if (!rl)
4268 return;
4269 SMARTLIST_FOREACH(rl->routers, routerinfo_t *, r,
4271 r2 = rimap_get(rl->identity_map, r->cache_info.identity_digest);
4272 tor_assert(r == r2);
4273 sd2 = sdmap_get(rl->desc_digest_map,
4274 r->cache_info.signed_descriptor_digest);
4275 tor_assert(&(r->cache_info) == sd2);
4276 tor_assert(r->cache_info.routerlist_index == r_sl_idx);
4277 #if 0
4278 /* XXXX020.
4280 * Hoo boy. We need to fix this one, and the fix is a bit tricky, so
4281 * commenting this out is just a band-aid.
4283 * The problem is that, although well-behaved router descriptors
4284 * should never have the same value for their extra_info_digest, it's
4285 * possible for ill-behaved routers to claim whatever they like there.
4287 * The real answer is to trash desc_by_eid_map and instead have
4288 * something that indicates for a given extra-info digest we want,
4289 * what its download status is. We'll do that as a part of routerlist
4290 * refactoring once consensus directories are in. For now,
4291 * this rep violation is probably harmless: an adversary can make us
4292 * reset our retry count for an extrainfo, but that's not the end
4293 * of the world.
4295 if (!tor_digest_is_zero(r->cache_info.extra_info_digest)) {
4296 signed_descriptor_t *sd3 =
4297 sdmap_get(rl->desc_by_eid_map, r->cache_info.extra_info_digest);
4298 tor_assert(sd3 == &(r->cache_info));
4300 #endif
4302 SMARTLIST_FOREACH(rl->old_routers, signed_descriptor_t *, sd,
4304 r2 = rimap_get(rl->identity_map, sd->identity_digest);
4305 tor_assert(sd != &(r2->cache_info));
4306 sd2 = sdmap_get(rl->desc_digest_map, sd->signed_descriptor_digest);
4307 tor_assert(sd == sd2);
4308 tor_assert(sd->routerlist_index == sd_sl_idx);
4309 #if 0
4310 /* XXXX020 see above. */
4311 if (!tor_digest_is_zero(sd->extra_info_digest)) {
4312 signed_descriptor_t *sd3 =
4313 sdmap_get(rl->desc_by_eid_map, sd->extra_info_digest);
4314 tor_assert(sd3 == sd);
4316 #endif
4319 iter = digestmap_iter_init((digestmap_t*)rl->identity_map);
4320 while (!digestmap_iter_done(iter)) {
4321 const char *d;
4322 void *_r;
4323 routerinfo_t *r;
4324 digestmap_iter_get(iter, &d, &_r);
4325 r = _r;
4326 tor_assert(!memcmp(r->cache_info.identity_digest, d, DIGEST_LEN));
4327 iter = digestmap_iter_next((digestmap_t*)rl->identity_map, iter);
4329 iter = digestmap_iter_init((digestmap_t*)rl->desc_digest_map);
4330 while (!digestmap_iter_done(iter)) {
4331 const char *d;
4332 void *_sd;
4333 signed_descriptor_t *sd;
4334 digestmap_iter_get(iter, &d, &_sd);
4335 sd = _sd;
4336 tor_assert(!memcmp(sd->signed_descriptor_digest, d, DIGEST_LEN));
4337 iter = digestmap_iter_next((digestmap_t*)rl->desc_digest_map, iter);
4339 iter = digestmap_iter_init((digestmap_t*)rl->desc_by_eid_map);
4340 while (!digestmap_iter_done(iter)) {
4341 const char *d;
4342 void *_sd;
4343 signed_descriptor_t *sd;
4344 digestmap_iter_get(iter, &d, &_sd);
4345 sd = _sd;
4346 tor_assert(!tor_digest_is_zero(d));
4347 tor_assert(sd);
4348 tor_assert(!memcmp(sd->extra_info_digest, d, DIGEST_LEN));
4349 iter = digestmap_iter_next((digestmap_t*)rl->desc_by_eid_map, iter);
4351 iter = digestmap_iter_init((digestmap_t*)rl->extra_info_map);
4352 while (!digestmap_iter_done(iter)) {
4353 const char *d;
4354 void *_ei;
4355 extrainfo_t *ei;
4356 signed_descriptor_t *sd;
4357 digestmap_iter_get(iter, &d, &_ei);
4358 ei = _ei;
4359 tor_assert(!memcmp(ei->cache_info.signed_descriptor_digest,
4360 d, DIGEST_LEN));
4361 sd = sdmap_get(rl->desc_by_eid_map,
4362 ei->cache_info.signed_descriptor_digest);
4363 // tor_assert(sd); // XXXX020 see above
4364 if (sd) {
4365 tor_assert(!memcmp(ei->cache_info.signed_descriptor_digest,
4366 sd->extra_info_digest, DIGEST_LEN));
4368 iter = digestmap_iter_next((digestmap_t*)rl->extra_info_map, iter);
4372 /** Allocate and return a new string representing the contact info
4373 * and platform string for <b>router</b>,
4374 * surrounded by quotes and using standard C escapes.
4376 * THIS FUNCTION IS NOT REENTRANT. Don't call it from outside the main
4377 * thread. Also, each call invalidates the last-returned value, so don't
4378 * try log_warn(LD_GENERAL, "%s %s", esc_router_info(a), esc_router_info(b));
4380 * If <b>router</b> is NULL, it just frees its internal memory and returns.
4382 const char *
4383 esc_router_info(routerinfo_t *router)
4385 static char *info=NULL;
4386 char *esc_contact, *esc_platform;
4387 size_t len;
4388 if (info)
4389 tor_free(info);
4390 if (!router)
4391 return NULL; /* we're exiting; just free the memory we use */
4393 esc_contact = esc_for_log(router->contact_info);
4394 esc_platform = esc_for_log(router->platform);
4396 len = strlen(esc_contact)+strlen(esc_platform)+32;
4397 info = tor_malloc(len);
4398 tor_snprintf(info, len, "Contact %s, Platform %s", esc_contact,
4399 esc_platform);
4400 tor_free(esc_contact);
4401 tor_free(esc_platform);
4403 return info;
4406 /** Helper for sorting: compare two routerinfos by their identity
4407 * digest. */
4408 static int
4409 _compare_routerinfo_by_id_digest(const void **a, const void **b)
4411 routerinfo_t *first = *(routerinfo_t **)a, *second = *(routerinfo_t **)b;
4412 return memcmp(first->cache_info.identity_digest,
4413 second->cache_info.identity_digest,
4414 DIGEST_LEN);
4417 /** Sort a list of routerinfo_t in ascending order of identity digest. */
4418 void
4419 routers_sort_by_identity(smartlist_t *routers)
4421 smartlist_sort(routers, _compare_routerinfo_by_id_digest);
4424 /** Determine the routers that are responsible for <b>id</b> (binary) and
4425 * add pointers to those routers' routerstatus_t to <b>responsible_dirs</b>.
4426 * If we don't have a consensus, return -1, else 0. */
4428 hid_serv_get_responsible_directories(smartlist_t *responsible_dirs,
4429 const char *id)
4431 int start, found, n_added = 0, i;
4432 networkstatus_vote_t *c = networkstatus_get_latest_consensus();
4433 if (!c || !smartlist_len(c->routerstatus_list)) {
4434 log_warn(LD_REND, "We don't have a consensus, so we can't perform v2 "
4435 "rendezvous operations.");
4436 return -1;
4438 tor_assert(id);
4439 start = networkstatus_vote_find_entry_idx(c, id, &found);
4440 if (start == smartlist_len(c->routerstatus_list)) start = 0;
4441 i = start;
4442 do {
4443 routerstatus_t *r = smartlist_get(c->routerstatus_list, i);
4444 if (r->is_hs_dir) {
4445 smartlist_add(responsible_dirs, r);
4446 if (++n_added == REND_NUMBER_OF_CONSECUTIVE_REPLICAS)
4447 return 0;
4449 if (++i == smartlist_len(c->routerstatus_list))
4450 i = 0;
4451 } while (i != start);
4453 /* Even though we don't have the desired number of hidden service
4454 * directories, we are happy with what we got. */
4455 return 0;
4458 /** Return true if this node is currently acting as hidden service
4459 * directory, false otherwise. */
4461 hid_serv_acting_as_directory(void)
4463 routerinfo_t *me = router_get_my_routerinfo();
4464 networkstatus_vote_t *c;
4465 routerstatus_t *rs;
4466 if (!me)
4467 return 0;
4468 if (!get_options()->HidServDirectoryV2) {
4469 log_info(LD_REND, "We are not acting as hidden service directory, "
4470 "because we have not been configured as such.");
4471 return 0;
4473 if (!(c = networkstatus_get_latest_consensus())) {
4474 log_info(LD_REND, "There's no consensus, so I can't tell if I'm a hidden "
4475 "service directory");
4476 return 0;
4478 rs = networkstatus_vote_find_entry(c, me->cache_info.identity_digest);
4479 if (!rs) {
4480 log_info(LD_REND, "We're not listed in the consensus, so we're not "
4481 "being a hidden service directory.");
4482 return 0;
4484 if (!rs->is_hs_dir) {
4485 log_info(LD_REND, "We're not listed as a hidden service directory in "
4486 "the consensus, so we won't be one.");
4487 return 0;
4489 return 1;
4492 /** Return true if this node is responsible for storing the descriptor ID
4493 * in <b>query</b> and false otherwise. */
4495 hid_serv_responsible_for_desc_id(const char *query)
4497 routerinfo_t *me;
4498 routerstatus_t *last_rs;
4499 const char *my_id, *last_id;
4500 int result;
4501 smartlist_t *responsible;
4502 if (!hid_serv_acting_as_directory())
4503 return 0;
4504 if (!(me = router_get_my_routerinfo()))
4505 return 0; /* This is redundant, but let's be paranoid. */
4506 my_id = me->cache_info.identity_digest;
4507 responsible = smartlist_create();
4508 (int) hid_serv_get_responsible_directories(responsible, query);
4509 if (!smartlist_len(responsible)) {
4510 smartlist_free(responsible);
4511 return 0;
4513 last_rs = smartlist_get(responsible, smartlist_len(responsible)-1);
4514 last_id = last_rs->identity_digest;
4515 result = rend_id_is_in_interval(my_id, query, last_id);
4516 smartlist_free(responsible);
4517 return result;