don't use old non-configured bridges (bug 2511)
[tor.git] / src / or / routerlist.c
blobbbd08f39ef89ee39a4bbca38c3956ad3d4e370da
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-2011, The Tor Project, Inc. */
5 /* See LICENSE for licensing information */
7 /**
8 * \file routerlist.c
9 * \brief Code to
10 * maintain and access the global list of routerinfos for known
11 * servers.
12 **/
14 #include "or.h"
15 #include "circuitbuild.h"
16 #include "config.h"
17 #include "connection.h"
18 #include "control.h"
19 #include "directory.h"
20 #include "dirserv.h"
21 #include "dirvote.h"
22 #include "geoip.h"
23 #include "hibernate.h"
24 #include "main.h"
25 #include "networkstatus.h"
26 #include "policies.h"
27 #include "reasons.h"
28 #include "rendcommon.h"
29 #include "rendservice.h"
30 #include "rephist.h"
31 #include "router.h"
32 #include "routerlist.h"
33 #include "routerparse.h"
35 // #define DEBUG_ROUTERLIST
37 /****************************************************************************/
39 /* static function prototypes */
40 static routerstatus_t *router_pick_directory_server_impl(
41 authority_type_t auth, int flags);
42 static routerstatus_t *router_pick_trusteddirserver_impl(
43 authority_type_t auth, int flags, int *n_busy_out);
44 static void mark_all_trusteddirservers_up(void);
45 static int router_nickname_matches(routerinfo_t *router, const char *nickname);
46 static void trusted_dir_server_free(trusted_dir_server_t *ds);
47 static void launch_router_descriptor_downloads(smartlist_t *downloadable,
48 routerstatus_t *source,
49 time_t now);
50 static int signed_desc_digest_is_recognized(signed_descriptor_t *desc);
51 static void update_router_have_minimum_dir_info(void);
52 static const char *signed_descriptor_get_body_impl(signed_descriptor_t *desc,
53 int with_annotations);
54 static void list_pending_downloads(digestmap_t *result,
55 int purpose, const char *prefix);
57 DECLARE_TYPED_DIGESTMAP_FNS(sdmap_, digest_sd_map_t, signed_descriptor_t)
58 DECLARE_TYPED_DIGESTMAP_FNS(rimap_, digest_ri_map_t, routerinfo_t)
59 DECLARE_TYPED_DIGESTMAP_FNS(eimap_, digest_ei_map_t, extrainfo_t)
60 #define SDMAP_FOREACH(map, keyvar, valvar) \
61 DIGESTMAP_FOREACH(sdmap_to_digestmap(map), keyvar, signed_descriptor_t *, \
62 valvar)
63 #define RIMAP_FOREACH(map, keyvar, valvar) \
64 DIGESTMAP_FOREACH(rimap_to_digestmap(map), keyvar, routerinfo_t *, valvar)
65 #define EIMAP_FOREACH(map, keyvar, valvar) \
66 DIGESTMAP_FOREACH(eimap_to_digestmap(map), keyvar, extrainfo_t *, valvar)
68 /****************************************************************************/
70 /** Global list of a trusted_dir_server_t object for each trusted directory
71 * server. */
72 static smartlist_t *trusted_dir_servers = NULL;
74 /** List of for a given authority, and download status for latest certificate.
76 typedef struct cert_list_t {
77 download_status_t dl_status;
78 smartlist_t *certs;
79 } cert_list_t;
80 /** Map from v3 identity key digest to cert_list_t. */
81 static digestmap_t *trusted_dir_certs = NULL;
82 /** True iff any key certificate in at least one member of
83 * <b>trusted_dir_certs</b> has changed since we last flushed the
84 * certificates to disk. */
85 static int trusted_dir_servers_certs_changed = 0;
87 /** Global list of all of the routers that we know about. */
88 static routerlist_t *routerlist = NULL;
90 /** List of strings for nicknames we've already warned about and that are
91 * still unknown / unavailable. */
92 static smartlist_t *warned_nicknames = NULL;
94 /** The last time we tried to download any routerdesc, or 0 for "never". We
95 * use this to rate-limit download attempts when the number of routerdescs to
96 * download is low. */
97 static time_t last_routerdesc_download_attempted = 0;
99 /** When we last computed the weights to use for bandwidths on directory
100 * requests, what were the total weighted bandwidth, and our share of that
101 * bandwidth? Used to determine what fraction of directory requests we should
102 * expect to see. */
103 static uint64_t sl_last_total_weighted_bw = 0,
104 sl_last_weighted_bw_of_me = 0;
106 /** Return the number of directory authorities whose type matches some bit set
107 * in <b>type</b> */
109 get_n_authorities(authority_type_t type)
111 int n = 0;
112 if (!trusted_dir_servers)
113 return 0;
114 SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, ds,
115 if (ds->type & type)
116 ++n);
117 return n;
120 #define get_n_v2_authorities() get_n_authorities(V2_AUTHORITY)
122 /** Helper: Return the cert_list_t for an authority whose authority ID is
123 * <b>id_digest</b>, allocating a new list if necessary. */
124 static cert_list_t *
125 get_cert_list(const char *id_digest)
127 cert_list_t *cl;
128 if (!trusted_dir_certs)
129 trusted_dir_certs = digestmap_new();
130 cl = digestmap_get(trusted_dir_certs, id_digest);
131 if (!cl) {
132 cl = tor_malloc_zero(sizeof(cert_list_t));
133 cl->dl_status.schedule = DL_SCHED_CONSENSUS;
134 cl->certs = smartlist_create();
135 digestmap_set(trusted_dir_certs, id_digest, cl);
137 return cl;
140 /** Reload the cached v3 key certificates from the cached-certs file in
141 * the data directory. Return 0 on success, -1 on failure. */
143 trusted_dirs_reload_certs(void)
145 char *filename;
146 char *contents;
147 int r;
149 filename = get_datadir_fname("cached-certs");
150 contents = read_file_to_str(filename, RFTS_IGNORE_MISSING, NULL);
151 tor_free(filename);
152 if (!contents)
153 return 0;
154 r = trusted_dirs_load_certs_from_string(contents, 1, 1);
155 tor_free(contents);
156 return r;
159 /** Helper: return true iff we already have loaded the exact cert
160 * <b>cert</b>. */
161 static INLINE int
162 already_have_cert(authority_cert_t *cert)
164 cert_list_t *cl = get_cert_list(cert->cache_info.identity_digest);
166 SMARTLIST_FOREACH(cl->certs, authority_cert_t *, c,
168 if (!memcmp(c->cache_info.signed_descriptor_digest,
169 cert->cache_info.signed_descriptor_digest,
170 DIGEST_LEN))
171 return 1;
173 return 0;
176 /** Load a bunch of new key certificates from the string <b>contents</b>. If
177 * <b>from_store</b> is true, the certificates are from the cache, and we
178 * don't need to flush them to disk. If <b>flush</b> is true, we need
179 * to flush any changed certificates to disk now. Return 0 on success, -1
180 * if any certs fail to parse. */
182 trusted_dirs_load_certs_from_string(const char *contents, int from_store,
183 int flush)
185 trusted_dir_server_t *ds;
186 const char *s, *eos;
187 int failure_code = 0;
189 for (s = contents; *s; s = eos) {
190 authority_cert_t *cert = authority_cert_parse_from_string(s, &eos);
191 cert_list_t *cl;
192 if (!cert) {
193 failure_code = -1;
194 break;
196 ds = trusteddirserver_get_by_v3_auth_digest(
197 cert->cache_info.identity_digest);
198 log_debug(LD_DIR, "Parsed certificate for %s",
199 ds ? ds->nickname : "unknown authority");
201 if (already_have_cert(cert)) {
202 /* we already have this one. continue. */
203 log_info(LD_DIR, "Skipping %s certificate for %s that we "
204 "already have.",
205 from_store ? "cached" : "downloaded",
206 ds ? ds->nickname : "an old or new authority");
208 /* a duplicate on a download should be treated as a failure, since it
209 * probably means we wanted a different secret key or we are trying to
210 * replace an expired cert that has not in fact been updated. */
211 if (!from_store) {
212 log_warn(LD_DIR, "Got a certificate for %s, but we already have it. "
213 "Maybe they haven't updated it. Waiting for a while.",
214 ds ? ds->nickname : "an old or new authority");
215 authority_cert_dl_failed(cert->cache_info.identity_digest, 404);
218 authority_cert_free(cert);
219 continue;
222 if (ds) {
223 log_info(LD_DIR, "Adding %s certificate for directory authority %s with "
224 "signing key %s", from_store ? "cached" : "downloaded",
225 ds->nickname, hex_str(cert->signing_key_digest,DIGEST_LEN));
226 } else {
227 int adding = directory_caches_dir_info(get_options());
228 log_info(LD_DIR, "%s %s certificate for unrecognized directory "
229 "authority with signing key %s",
230 adding ? "Adding" : "Not adding",
231 from_store ? "cached" : "downloaded",
232 hex_str(cert->signing_key_digest,DIGEST_LEN));
233 if (!adding) {
234 authority_cert_free(cert);
235 continue;
239 cl = get_cert_list(cert->cache_info.identity_digest);
240 smartlist_add(cl->certs, cert);
241 if (ds && cert->cache_info.published_on > ds->addr_current_at) {
242 /* Check to see whether we should update our view of the authority's
243 * address. */
244 if (cert->addr && cert->dir_port &&
245 (ds->addr != cert->addr ||
246 ds->dir_port != cert->dir_port)) {
247 char *a = tor_dup_ip(cert->addr);
248 log_notice(LD_DIR, "Updating address for directory authority %s "
249 "from %s:%d to %s:%d based on certificate.",
250 ds->nickname, ds->address, (int)ds->dir_port,
251 a, cert->dir_port);
252 tor_free(a);
253 ds->addr = cert->addr;
254 ds->dir_port = cert->dir_port;
256 ds->addr_current_at = cert->cache_info.published_on;
259 if (!from_store)
260 trusted_dir_servers_certs_changed = 1;
263 if (flush)
264 trusted_dirs_flush_certs_to_disk();
266 /* call this even if failure_code is <0, since some certs might have
267 * succeeded. */
268 networkstatus_note_certs_arrived();
270 return failure_code;
273 /** Save all v3 key certificates to the cached-certs file. */
274 void
275 trusted_dirs_flush_certs_to_disk(void)
277 char *filename;
278 smartlist_t *chunks;
280 if (!trusted_dir_servers_certs_changed || !trusted_dir_certs)
281 return;
283 chunks = smartlist_create();
284 DIGESTMAP_FOREACH(trusted_dir_certs, key, cert_list_t *, cl) {
285 SMARTLIST_FOREACH(cl->certs, authority_cert_t *, cert,
287 sized_chunk_t *c = tor_malloc(sizeof(sized_chunk_t));
288 c->bytes = cert->cache_info.signed_descriptor_body;
289 c->len = cert->cache_info.signed_descriptor_len;
290 smartlist_add(chunks, c);
292 } DIGESTMAP_FOREACH_END;
294 filename = get_datadir_fname("cached-certs");
295 if (write_chunks_to_file(filename, chunks, 0)) {
296 log_warn(LD_FS, "Error writing certificates to disk.");
298 tor_free(filename);
299 SMARTLIST_FOREACH(chunks, sized_chunk_t *, c, tor_free(c));
300 smartlist_free(chunks);
302 trusted_dir_servers_certs_changed = 0;
305 /** Remove all v3 authority certificates that have been superseded for more
306 * than 48 hours. (If the most recent cert was published more than 48 hours
307 * ago, then we aren't going to get any consensuses signed with older
308 * keys.) */
309 static void
310 trusted_dirs_remove_old_certs(void)
312 time_t now = time(NULL);
313 #define DEAD_CERT_LIFETIME (2*24*60*60)
314 #define OLD_CERT_LIFETIME (7*24*60*60)
315 if (!trusted_dir_certs)
316 return;
318 DIGESTMAP_FOREACH(trusted_dir_certs, key, cert_list_t *, cl) {
319 authority_cert_t *newest = NULL;
320 SMARTLIST_FOREACH(cl->certs, authority_cert_t *, cert,
321 if (!newest || (cert->cache_info.published_on >
322 newest->cache_info.published_on))
323 newest = cert);
324 if (newest) {
325 const time_t newest_published = newest->cache_info.published_on;
326 SMARTLIST_FOREACH_BEGIN(cl->certs, authority_cert_t *, cert) {
327 int expired;
328 time_t cert_published;
329 if (newest == cert)
330 continue;
331 expired = ftime_definitely_after(now, cert->expires);
332 cert_published = cert->cache_info.published_on;
333 /* Store expired certs for 48 hours after a newer arrives;
335 if (expired ?
336 (newest_published + DEAD_CERT_LIFETIME < now) :
337 (cert_published + OLD_CERT_LIFETIME < newest_published)) {
338 SMARTLIST_DEL_CURRENT(cl->certs, cert);
339 authority_cert_free(cert);
340 trusted_dir_servers_certs_changed = 1;
342 } SMARTLIST_FOREACH_END(cert);
344 } DIGESTMAP_FOREACH_END;
345 #undef OLD_CERT_LIFETIME
347 trusted_dirs_flush_certs_to_disk();
350 /** Return the newest v3 authority certificate whose v3 authority identity key
351 * has digest <b>id_digest</b>. Return NULL if no such authority is known,
352 * or it has no certificate. */
353 authority_cert_t *
354 authority_cert_get_newest_by_id(const char *id_digest)
356 cert_list_t *cl;
357 authority_cert_t *best = NULL;
358 if (!trusted_dir_certs ||
359 !(cl = digestmap_get(trusted_dir_certs, id_digest)))
360 return NULL;
362 SMARTLIST_FOREACH(cl->certs, authority_cert_t *, cert,
364 if (!best || cert->cache_info.published_on > best->cache_info.published_on)
365 best = cert;
367 return best;
370 /** Return the newest v3 authority certificate whose directory signing key has
371 * digest <b>sk_digest</b>. Return NULL if no such certificate is known.
373 authority_cert_t *
374 authority_cert_get_by_sk_digest(const char *sk_digest)
376 authority_cert_t *c;
377 if (!trusted_dir_certs)
378 return NULL;
380 if ((c = get_my_v3_authority_cert()) &&
381 !memcmp(c->signing_key_digest, sk_digest, DIGEST_LEN))
382 return c;
383 if ((c = get_my_v3_legacy_cert()) &&
384 !memcmp(c->signing_key_digest, sk_digest, DIGEST_LEN))
385 return c;
387 DIGESTMAP_FOREACH(trusted_dir_certs, key, cert_list_t *, cl) {
388 SMARTLIST_FOREACH(cl->certs, authority_cert_t *, cert,
390 if (!memcmp(cert->signing_key_digest, sk_digest, DIGEST_LEN))
391 return cert;
393 } DIGESTMAP_FOREACH_END;
394 return NULL;
397 /** Return the v3 authority certificate with signing key matching
398 * <b>sk_digest</b>, for the authority with identity digest <b>id_digest</b>.
399 * Return NULL if no such authority is known. */
400 authority_cert_t *
401 authority_cert_get_by_digests(const char *id_digest,
402 const char *sk_digest)
404 cert_list_t *cl;
405 if (!trusted_dir_certs ||
406 !(cl = digestmap_get(trusted_dir_certs, id_digest)))
407 return NULL;
408 SMARTLIST_FOREACH(cl->certs, authority_cert_t *, cert,
409 if (!memcmp(cert->signing_key_digest, sk_digest, DIGEST_LEN))
410 return cert; );
412 return NULL;
415 /** Add every known authority_cert_t to <b>certs_out</b>. */
416 void
417 authority_cert_get_all(smartlist_t *certs_out)
419 tor_assert(certs_out);
420 if (!trusted_dir_certs)
421 return;
423 DIGESTMAP_FOREACH(trusted_dir_certs, key, cert_list_t *, cl) {
424 SMARTLIST_FOREACH(cl->certs, authority_cert_t *, c,
425 smartlist_add(certs_out, c));
426 } DIGESTMAP_FOREACH_END;
429 /** Called when an attempt to download a certificate with the authority with
430 * ID <b>id_digest</b> fails with HTTP response code <b>status</b>: remember
431 * the failure, so we don't try again immediately. */
432 void
433 authority_cert_dl_failed(const char *id_digest, int status)
435 cert_list_t *cl;
436 if (!trusted_dir_certs ||
437 !(cl = digestmap_get(trusted_dir_certs, id_digest)))
438 return;
440 download_status_failed(&cl->dl_status, status);
443 /** Return true iff when we've been getting enough failures when trying to
444 * download the certificate with ID digest <b>id_digest</b> that we're willing
445 * to start bugging the user about it. */
447 authority_cert_dl_looks_uncertain(const char *id_digest)
449 #define N_AUTH_CERT_DL_FAILURES_TO_BUG_USER 2
450 cert_list_t *cl;
451 int n_failures;
452 if (!trusted_dir_certs ||
453 !(cl = digestmap_get(trusted_dir_certs, id_digest)))
454 return 0;
456 n_failures = download_status_get_n_failures(&cl->dl_status);
457 return n_failures >= N_AUTH_CERT_DL_FAILURES_TO_BUG_USER;
460 /** How many times will we try to fetch a certificate before giving up? */
461 #define MAX_CERT_DL_FAILURES 8
463 /** Try to download any v3 authority certificates that we may be missing. If
464 * <b>status</b> is provided, try to get all the ones that were used to sign
465 * <b>status</b>. Additionally, try to have a non-expired certificate for
466 * every V3 authority in trusted_dir_servers. Don't fetch certificates we
467 * already have.
469 void
470 authority_certs_fetch_missing(networkstatus_t *status, time_t now)
472 digestmap_t *pending;
473 authority_cert_t *cert;
474 smartlist_t *missing_digests;
475 char *resource = NULL;
476 cert_list_t *cl;
477 const int cache = directory_caches_dir_info(get_options());
479 if (should_delay_dir_fetches(get_options()))
480 return;
482 pending = digestmap_new();
483 missing_digests = smartlist_create();
485 list_pending_downloads(pending, DIR_PURPOSE_FETCH_CERTIFICATE, "fp/");
486 if (status) {
487 SMARTLIST_FOREACH_BEGIN(status->voters, networkstatus_voter_info_t *,
488 voter) {
489 if (!smartlist_len(voter->sigs))
490 continue; /* This authority never signed this consensus, so don't
491 * go looking for a cert with key digest 0000000000. */
492 if (!cache &&
493 !trusteddirserver_get_by_v3_auth_digest(voter->identity_digest))
494 continue; /* We are not a cache, and we don't know this authority.*/
495 cl = get_cert_list(voter->identity_digest);
496 SMARTLIST_FOREACH_BEGIN(voter->sigs, document_signature_t *, sig) {
497 cert = authority_cert_get_by_digests(voter->identity_digest,
498 sig->signing_key_digest);
499 if (cert) {
500 if (now < cert->expires)
501 download_status_reset(&cl->dl_status);
502 continue;
504 if (download_status_is_ready(&cl->dl_status, now,
505 MAX_CERT_DL_FAILURES) &&
506 !digestmap_get(pending, voter->identity_digest)) {
507 log_notice(LD_DIR, "We're missing a certificate from authority "
508 "with signing key %s: launching request.",
509 hex_str(sig->signing_key_digest, DIGEST_LEN));
510 smartlist_add(missing_digests, sig->identity_digest);
512 } SMARTLIST_FOREACH_END(sig);
513 } SMARTLIST_FOREACH_END(voter);
515 SMARTLIST_FOREACH_BEGIN(trusted_dir_servers, trusted_dir_server_t *, ds) {
516 int found = 0;
517 if (!(ds->type & V3_AUTHORITY))
518 continue;
519 if (smartlist_digest_isin(missing_digests, ds->v3_identity_digest))
520 continue;
521 cl = get_cert_list(ds->v3_identity_digest);
522 SMARTLIST_FOREACH(cl->certs, authority_cert_t *, cert, {
523 if (!ftime_definitely_after(now, cert->expires)) {
524 /* It's not expired, and we weren't looking for something to
525 * verify a consensus with. Call it done. */
526 download_status_reset(&cl->dl_status);
527 found = 1;
528 break;
531 if (!found &&
532 download_status_is_ready(&cl->dl_status, now,MAX_CERT_DL_FAILURES) &&
533 !digestmap_get(pending, ds->v3_identity_digest)) {
534 log_notice(LD_DIR, "No current certificate known for authority %s; "
535 "launching request.", ds->nickname);
536 smartlist_add(missing_digests, ds->v3_identity_digest);
538 } SMARTLIST_FOREACH_END(ds);
540 if (!smartlist_len(missing_digests)) {
541 goto done;
542 } else {
543 smartlist_t *fps = smartlist_create();
544 smartlist_add(fps, tor_strdup("fp/"));
545 SMARTLIST_FOREACH(missing_digests, const char *, d, {
546 char *fp;
547 if (digestmap_get(pending, d))
548 continue;
549 fp = tor_malloc(HEX_DIGEST_LEN+2);
550 base16_encode(fp, HEX_DIGEST_LEN+1, d, DIGEST_LEN);
551 fp[HEX_DIGEST_LEN] = '+';
552 fp[HEX_DIGEST_LEN+1] = '\0';
553 smartlist_add(fps, fp);
555 if (smartlist_len(fps) == 1) {
556 /* we didn't add any: they were all pending */
557 SMARTLIST_FOREACH(fps, char *, cp, tor_free(cp));
558 smartlist_free(fps);
559 goto done;
561 resource = smartlist_join_strings(fps, "", 0, NULL);
562 resource[strlen(resource)-1] = '\0';
563 SMARTLIST_FOREACH(fps, char *, cp, tor_free(cp));
564 smartlist_free(fps);
566 directory_get_from_dirserver(DIR_PURPOSE_FETCH_CERTIFICATE, 0,
567 resource, PDS_RETRY_IF_NO_SERVERS);
569 done:
570 tor_free(resource);
571 smartlist_free(missing_digests);
572 digestmap_free(pending, NULL);
575 /* Router descriptor storage.
577 * Routerdescs are stored in a big file, named "cached-descriptors". As new
578 * routerdescs arrive, we append them to a journal file named
579 * "cached-descriptors.new".
581 * From time to time, we replace "cached-descriptors" with a new file
582 * containing only the live, non-superseded descriptors, and clear
583 * cached-routers.new.
585 * On startup, we read both files.
588 /** Helper: return 1 iff the router log is so big we want to rebuild the
589 * store. */
590 static int
591 router_should_rebuild_store(desc_store_t *store)
593 if (store->store_len > (1<<16))
594 return (store->journal_len > store->store_len / 2 ||
595 store->bytes_dropped > store->store_len / 2);
596 else
597 return store->journal_len > (1<<15);
600 /** Return the desc_store_t in <b>rl</b> that should be used to store
601 * <b>sd</b>. */
602 static INLINE desc_store_t *
603 desc_get_store(routerlist_t *rl, signed_descriptor_t *sd)
605 if (sd->is_extrainfo)
606 return &rl->extrainfo_store;
607 else
608 return &rl->desc_store;
611 /** Add the signed_descriptor_t in <b>desc</b> to the router
612 * journal; change its saved_location to SAVED_IN_JOURNAL and set its
613 * offset appropriately. */
614 static int
615 signed_desc_append_to_journal(signed_descriptor_t *desc,
616 desc_store_t *store)
618 char *fname = get_datadir_fname_suffix(store->fname_base, ".new");
619 const char *body = signed_descriptor_get_body_impl(desc,1);
620 size_t len = desc->signed_descriptor_len + desc->annotations_len;
622 if (append_bytes_to_file(fname, body, len, 1)) {
623 log_warn(LD_FS, "Unable to store router descriptor");
624 tor_free(fname);
625 return -1;
627 desc->saved_location = SAVED_IN_JOURNAL;
628 tor_free(fname);
630 desc->saved_offset = store->journal_len;
631 store->journal_len += len;
633 return 0;
636 /** Sorting helper: return &lt;0, 0, or &gt;0 depending on whether the
637 * signed_descriptor_t* in *<b>a</b> is older, the same age as, or newer than
638 * the signed_descriptor_t* in *<b>b</b>. */
639 static int
640 _compare_signed_descriptors_by_age(const void **_a, const void **_b)
642 const signed_descriptor_t *r1 = *_a, *r2 = *_b;
643 return (int)(r1->published_on - r2->published_on);
646 #define RRS_FORCE 1
647 #define RRS_DONT_REMOVE_OLD 2
649 /** If the journal of <b>store</b> is too long, or if RRS_FORCE is set in
650 * <b>flags</b>, then atomically replace the saved router store with the
651 * routers currently in our routerlist, and clear the journal. Unless
652 * RRS_DONT_REMOVE_OLD is set in <b>flags</b>, delete expired routers before
653 * rebuilding the store. Return 0 on success, -1 on failure.
655 static int
656 router_rebuild_store(int flags, desc_store_t *store)
658 smartlist_t *chunk_list = NULL;
659 char *fname = NULL, *fname_tmp = NULL;
660 int r = -1;
661 off_t offset = 0;
662 smartlist_t *signed_descriptors = NULL;
663 int nocache=0;
664 size_t total_expected_len = 0;
665 int had_any;
666 int force = flags & RRS_FORCE;
668 if (!force && !router_should_rebuild_store(store)) {
669 r = 0;
670 goto done;
672 if (!routerlist) {
673 r = 0;
674 goto done;
677 if (store->type == EXTRAINFO_STORE)
678 had_any = !eimap_isempty(routerlist->extra_info_map);
679 else
680 had_any = (smartlist_len(routerlist->routers)+
681 smartlist_len(routerlist->old_routers))>0;
683 /* Don't save deadweight. */
684 if (!(flags & RRS_DONT_REMOVE_OLD))
685 routerlist_remove_old_routers();
687 log_info(LD_DIR, "Rebuilding %s cache", store->description);
689 fname = get_datadir_fname(store->fname_base);
690 fname_tmp = get_datadir_fname_suffix(store->fname_base, ".tmp");
692 chunk_list = smartlist_create();
694 /* We sort the routers by age to enhance locality on disk. */
695 signed_descriptors = smartlist_create();
696 if (store->type == EXTRAINFO_STORE) {
697 eimap_iter_t *iter;
698 for (iter = eimap_iter_init(routerlist->extra_info_map);
699 !eimap_iter_done(iter);
700 iter = eimap_iter_next(routerlist->extra_info_map, iter)) {
701 const char *key;
702 extrainfo_t *ei;
703 eimap_iter_get(iter, &key, &ei);
704 smartlist_add(signed_descriptors, &ei->cache_info);
706 } else {
707 SMARTLIST_FOREACH(routerlist->old_routers, signed_descriptor_t *, sd,
708 smartlist_add(signed_descriptors, sd));
709 SMARTLIST_FOREACH(routerlist->routers, routerinfo_t *, ri,
710 smartlist_add(signed_descriptors, &ri->cache_info));
713 smartlist_sort(signed_descriptors, _compare_signed_descriptors_by_age);
715 /* Now, add the appropriate members to chunk_list */
716 SMARTLIST_FOREACH(signed_descriptors, signed_descriptor_t *, sd,
718 sized_chunk_t *c;
719 const char *body = signed_descriptor_get_body_impl(sd, 1);
720 if (!body) {
721 log_warn(LD_BUG, "No descriptor available for router.");
722 goto done;
724 if (sd->do_not_cache) {
725 ++nocache;
726 continue;
728 c = tor_malloc(sizeof(sized_chunk_t));
729 c->bytes = body;
730 c->len = sd->signed_descriptor_len + sd->annotations_len;
731 total_expected_len += c->len;
732 smartlist_add(chunk_list, c);
735 if (write_chunks_to_file(fname_tmp, chunk_list, 1)<0) {
736 log_warn(LD_FS, "Error writing router store to disk.");
737 goto done;
740 /* Our mmap is now invalid. */
741 if (store->mmap) {
742 tor_munmap_file(store->mmap);
743 store->mmap = NULL;
746 if (replace_file(fname_tmp, fname)<0) {
747 log_warn(LD_FS, "Error replacing old router store: %s", strerror(errno));
748 goto done;
751 errno = 0;
752 store->mmap = tor_mmap_file(fname);
753 if (! store->mmap) {
754 if (errno == ERANGE) {
755 /* empty store.*/
756 if (total_expected_len) {
757 log_warn(LD_FS, "We wrote some bytes to a new descriptor file at '%s',"
758 " but when we went to mmap it, it was empty!", fname);
759 } else if (had_any) {
760 log_info(LD_FS, "We just removed every descriptor in '%s'. This is "
761 "okay if we're just starting up after a long time. "
762 "Otherwise, it's a bug.", fname);
764 } else {
765 log_warn(LD_FS, "Unable to mmap new descriptor file at '%s'.",fname);
769 log_info(LD_DIR, "Reconstructing pointers into cache");
771 offset = 0;
772 SMARTLIST_FOREACH(signed_descriptors, signed_descriptor_t *, sd,
774 if (sd->do_not_cache)
775 continue;
776 sd->saved_location = SAVED_IN_CACHE;
777 if (store->mmap) {
778 tor_free(sd->signed_descriptor_body); // sets it to null
779 sd->saved_offset = offset;
781 offset += sd->signed_descriptor_len + sd->annotations_len;
782 signed_descriptor_get_body(sd); /* reconstruct and assert */
785 tor_free(fname);
786 fname = get_datadir_fname_suffix(store->fname_base, ".new");
787 write_str_to_file(fname, "", 1);
789 r = 0;
790 store->store_len = (size_t) offset;
791 store->journal_len = 0;
792 store->bytes_dropped = 0;
793 done:
794 smartlist_free(signed_descriptors);
795 tor_free(fname);
796 tor_free(fname_tmp);
797 if (chunk_list) {
798 SMARTLIST_FOREACH(chunk_list, sized_chunk_t *, c, tor_free(c));
799 smartlist_free(chunk_list);
802 return r;
805 /** Helper: Reload a cache file and its associated journal, setting metadata
806 * appropriately. If <b>extrainfo</b> is true, reload the extrainfo store;
807 * else reload the router descriptor store. */
808 static int
809 router_reload_router_list_impl(desc_store_t *store)
811 char *fname = NULL, *altname = NULL, *contents = NULL;
812 struct stat st;
813 int read_from_old_location = 0;
814 int extrainfo = (store->type == EXTRAINFO_STORE);
815 time_t now = time(NULL);
816 store->journal_len = store->store_len = 0;
818 fname = get_datadir_fname(store->fname_base);
819 if (store->fname_alt_base)
820 altname = get_datadir_fname(store->fname_alt_base);
822 if (store->mmap) /* get rid of it first */
823 tor_munmap_file(store->mmap);
824 store->mmap = NULL;
826 store->mmap = tor_mmap_file(fname);
827 if (!store->mmap && altname && file_status(altname) == FN_FILE) {
828 read_from_old_location = 1;
829 log_notice(LD_DIR, "Couldn't read %s; trying to load routers from old "
830 "location %s.", fname, altname);
831 if ((store->mmap = tor_mmap_file(altname)))
832 read_from_old_location = 1;
834 if (altname && !read_from_old_location) {
835 remove_file_if_very_old(altname, now);
837 if (store->mmap) {
838 store->store_len = store->mmap->size;
839 if (extrainfo)
840 router_load_extrainfo_from_string(store->mmap->data,
841 store->mmap->data+store->mmap->size,
842 SAVED_IN_CACHE, NULL, 0);
843 else
844 router_load_routers_from_string(store->mmap->data,
845 store->mmap->data+store->mmap->size,
846 SAVED_IN_CACHE, NULL, 0, NULL);
849 tor_free(fname);
850 fname = get_datadir_fname_suffix(store->fname_base, ".new");
851 if (file_status(fname) == FN_FILE)
852 contents = read_file_to_str(fname, RFTS_BIN|RFTS_IGNORE_MISSING, &st);
853 if (read_from_old_location) {
854 tor_free(altname);
855 altname = get_datadir_fname_suffix(store->fname_alt_base, ".new");
856 if (!contents)
857 contents = read_file_to_str(altname, RFTS_BIN|RFTS_IGNORE_MISSING, &st);
858 else
859 remove_file_if_very_old(altname, now);
861 if (contents) {
862 if (extrainfo)
863 router_load_extrainfo_from_string(contents, NULL,SAVED_IN_JOURNAL,
864 NULL, 0);
865 else
866 router_load_routers_from_string(contents, NULL, SAVED_IN_JOURNAL,
867 NULL, 0, NULL);
868 store->journal_len = (size_t) st.st_size;
869 tor_free(contents);
872 tor_free(fname);
873 tor_free(altname);
875 if (store->journal_len || read_from_old_location) {
876 /* Always clear the journal on startup.*/
877 router_rebuild_store(RRS_FORCE, store);
878 } else if (!extrainfo) {
879 /* Don't cache expired routers. (This is in an else because
880 * router_rebuild_store() also calls remove_old_routers().) */
881 routerlist_remove_old_routers();
884 return 0;
887 /** Load all cached router descriptors and extra-info documents from the
888 * store. Return 0 on success and -1 on failure.
891 router_reload_router_list(void)
893 routerlist_t *rl = router_get_routerlist();
894 if (router_reload_router_list_impl(&rl->desc_store))
895 return -1;
896 if (router_reload_router_list_impl(&rl->extrainfo_store))
897 return -1;
898 return 0;
901 /** Return a smartlist containing a list of trusted_dir_server_t * for all
902 * known trusted dirservers. Callers must not modify the list or its
903 * contents.
905 smartlist_t *
906 router_get_trusted_dir_servers(void)
908 if (!trusted_dir_servers)
909 trusted_dir_servers = smartlist_create();
911 return trusted_dir_servers;
914 /** Try to find a running dirserver that supports operations of <b>type</b>.
916 * If there are no running dirservers in our routerlist and the
917 * <b>PDS_RETRY_IF_NO_SERVERS</b> flag is set, set all the authoritative ones
918 * as running again, and pick one.
920 * If the <b>PDS_IGNORE_FASCISTFIREWALL</b> flag is set, then include
921 * dirservers that we can't reach.
923 * If the <b>PDS_ALLOW_SELF</b> flag is not set, then don't include ourself
924 * (if we're a dirserver).
926 * Don't pick an authority if any non-authority is viable; try to avoid using
927 * servers that have returned 503 recently.
929 routerstatus_t *
930 router_pick_directory_server(authority_type_t type, int flags)
932 routerstatus_t *choice;
933 if (get_options()->PreferTunneledDirConns)
934 flags |= _PDS_PREFER_TUNNELED_DIR_CONNS;
936 if (!routerlist)
937 return NULL;
939 choice = router_pick_directory_server_impl(type, flags);
940 if (choice || !(flags & PDS_RETRY_IF_NO_SERVERS))
941 return choice;
943 log_info(LD_DIR,
944 "No reachable router entries for dirservers. "
945 "Trying them all again.");
946 /* mark all authdirservers as up again */
947 mark_all_trusteddirservers_up();
948 /* try again */
949 choice = router_pick_directory_server_impl(type, flags);
950 return choice;
953 /** Try to determine which fraction of v2 and v3 directory requests aimed at
954 * caches will be sent to us. Set *<b>v2_share_out</b> and
955 * *<b>v3_share_out</b> to the fractions of v2 and v3 protocol shares we
956 * expect to see, respectively. Return 0 on success, negative on failure. */
958 router_get_my_share_of_directory_requests(double *v2_share_out,
959 double *v3_share_out)
961 routerinfo_t *me = router_get_my_routerinfo();
962 routerstatus_t *rs;
963 const int pds_flags = PDS_ALLOW_SELF|PDS_IGNORE_FASCISTFIREWALL;
964 *v2_share_out = *v3_share_out = 0.0;
965 if (!me)
966 return -1;
967 rs = router_get_consensus_status_by_id(me->cache_info.identity_digest);
968 if (!rs)
969 return -1;
971 /* Calling for side effect */
972 /* XXXX This is a bit of a kludge */
973 if (rs->is_v2_dir) {
974 sl_last_total_weighted_bw = 0;
975 router_pick_directory_server(V2_AUTHORITY, pds_flags);
976 if (sl_last_total_weighted_bw != 0) {
977 *v2_share_out = U64_TO_DBL(sl_last_weighted_bw_of_me) /
978 U64_TO_DBL(sl_last_total_weighted_bw);
982 if (rs->version_supports_v3_dir) {
983 sl_last_total_weighted_bw = 0;
984 router_pick_directory_server(V3_AUTHORITY, pds_flags);
985 if (sl_last_total_weighted_bw != 0) {
986 *v3_share_out = U64_TO_DBL(sl_last_weighted_bw_of_me) /
987 U64_TO_DBL(sl_last_total_weighted_bw);
991 return 0;
994 /** Return the trusted_dir_server_t for the directory authority whose identity
995 * key hashes to <b>digest</b>, or NULL if no such authority is known.
997 trusted_dir_server_t *
998 router_get_trusteddirserver_by_digest(const char *digest)
1000 if (!trusted_dir_servers)
1001 return NULL;
1003 SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, ds,
1005 if (!memcmp(ds->digest, digest, DIGEST_LEN))
1006 return ds;
1009 return NULL;
1012 /** Return the trusted_dir_server_t for the directory authority whose
1013 * v3 identity key hashes to <b>digest</b>, or NULL if no such authority
1014 * is known.
1016 trusted_dir_server_t *
1017 trusteddirserver_get_by_v3_auth_digest(const char *digest)
1019 if (!trusted_dir_servers)
1020 return NULL;
1022 SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, ds,
1024 if (!memcmp(ds->v3_identity_digest, digest, DIGEST_LEN) &&
1025 (ds->type & V3_AUTHORITY))
1026 return ds;
1029 return NULL;
1032 /** Try to find a running trusted dirserver. Flags are as for
1033 * router_pick_directory_server.
1035 routerstatus_t *
1036 router_pick_trusteddirserver(authority_type_t type, int flags)
1038 routerstatus_t *choice;
1039 int busy = 0;
1040 if (get_options()->PreferTunneledDirConns)
1041 flags |= _PDS_PREFER_TUNNELED_DIR_CONNS;
1043 choice = router_pick_trusteddirserver_impl(type, flags, &busy);
1044 if (choice || !(flags & PDS_RETRY_IF_NO_SERVERS))
1045 return choice;
1046 if (busy) {
1047 /* If the reason that we got no server is that servers are "busy",
1048 * we must be excluding good servers because we already have serverdesc
1049 * fetches with them. Do not mark down servers up because of this. */
1050 tor_assert((flags & PDS_NO_EXISTING_SERVERDESC_FETCH));
1051 return NULL;
1054 log_info(LD_DIR,
1055 "No trusted dirservers are reachable. Trying them all again.");
1056 mark_all_trusteddirservers_up();
1057 return router_pick_trusteddirserver_impl(type, flags, NULL);
1060 /** How long do we avoid using a directory server after it's given us a 503? */
1061 #define DIR_503_TIMEOUT (60*60)
1063 /** Pick a random running valid directory server/mirror from our
1064 * routerlist. Arguments are as for router_pick_directory_server(), except
1065 * that RETRY_IF_NO_SERVERS is ignored, and:
1067 * If the _PDS_PREFER_TUNNELED_DIR_CONNS flag is set, prefer directory servers
1068 * that we can use with BEGINDIR.
1070 static routerstatus_t *
1071 router_pick_directory_server_impl(authority_type_t type, int flags)
1073 routerstatus_t *result;
1074 smartlist_t *direct, *tunnel;
1075 smartlist_t *trusted_direct, *trusted_tunnel;
1076 smartlist_t *overloaded_direct, *overloaded_tunnel;
1077 time_t now = time(NULL);
1078 const networkstatus_t *consensus = networkstatus_get_latest_consensus();
1079 int requireother = ! (flags & PDS_ALLOW_SELF);
1080 int fascistfirewall = ! (flags & PDS_IGNORE_FASCISTFIREWALL);
1081 int prefer_tunnel = (flags & _PDS_PREFER_TUNNELED_DIR_CONNS);
1083 if (!consensus)
1084 return NULL;
1086 direct = smartlist_create();
1087 tunnel = smartlist_create();
1088 trusted_direct = smartlist_create();
1089 trusted_tunnel = smartlist_create();
1090 overloaded_direct = smartlist_create();
1091 overloaded_tunnel = smartlist_create();
1093 /* Find all the running dirservers we know about. */
1094 SMARTLIST_FOREACH_BEGIN(consensus->routerstatus_list, routerstatus_t *,
1095 status) {
1096 int is_trusted;
1097 int is_overloaded = status->last_dir_503_at + DIR_503_TIMEOUT > now;
1098 tor_addr_t addr;
1099 if (!status->is_running || !status->dir_port || !status->is_valid)
1100 continue;
1101 if (status->is_bad_directory)
1102 continue;
1103 if (requireother && router_digest_is_me(status->identity_digest))
1104 continue;
1105 if (type & V3_AUTHORITY) {
1106 if (!(status->version_supports_v3_dir ||
1107 router_digest_is_trusted_dir_type(status->identity_digest,
1108 V3_AUTHORITY)))
1109 continue;
1111 is_trusted = router_digest_is_trusted_dir(status->identity_digest);
1112 if ((type & V2_AUTHORITY) && !(status->is_v2_dir || is_trusted))
1113 continue;
1114 if ((type & EXTRAINFO_CACHE) &&
1115 !router_supports_extrainfo(status->identity_digest, 0))
1116 continue;
1118 /* XXXX IP6 proposal 118 */
1119 tor_addr_from_ipv4h(&addr, status->addr);
1121 if (prefer_tunnel &&
1122 status->version_supports_begindir &&
1123 (!fascistfirewall ||
1124 fascist_firewall_allows_address_or(&addr, status->or_port)))
1125 smartlist_add(is_trusted ? trusted_tunnel :
1126 is_overloaded ? overloaded_tunnel : tunnel, status);
1127 else if (!fascistfirewall ||
1128 fascist_firewall_allows_address_dir(&addr, status->dir_port))
1129 smartlist_add(is_trusted ? trusted_direct :
1130 is_overloaded ? overloaded_direct : direct, status);
1131 } SMARTLIST_FOREACH_END(status);
1133 if (smartlist_len(tunnel)) {
1134 result = routerstatus_sl_choose_by_bandwidth(tunnel, WEIGHT_FOR_DIR);
1135 } else if (smartlist_len(overloaded_tunnel)) {
1136 result = routerstatus_sl_choose_by_bandwidth(overloaded_tunnel,
1137 WEIGHT_FOR_DIR);
1138 } else if (smartlist_len(trusted_tunnel)) {
1139 /* FFFF We don't distinguish between trusteds and overloaded trusteds
1140 * yet. Maybe one day we should. */
1141 /* FFFF We also don't load balance over authorities yet. I think this
1142 * is a feature, but it could easily be a bug. -RD */
1143 result = smartlist_choose(trusted_tunnel);
1144 } else if (smartlist_len(direct)) {
1145 result = routerstatus_sl_choose_by_bandwidth(direct, WEIGHT_FOR_DIR);
1146 } else if (smartlist_len(overloaded_direct)) {
1147 result = routerstatus_sl_choose_by_bandwidth(overloaded_direct,
1148 WEIGHT_FOR_DIR);
1149 } else {
1150 result = smartlist_choose(trusted_direct);
1152 smartlist_free(direct);
1153 smartlist_free(tunnel);
1154 smartlist_free(trusted_direct);
1155 smartlist_free(trusted_tunnel);
1156 smartlist_free(overloaded_direct);
1157 smartlist_free(overloaded_tunnel);
1158 return result;
1161 /** Choose randomly from among the trusted dirservers that are up. Flags
1162 * are as for router_pick_directory_server_impl().
1164 static routerstatus_t *
1165 router_pick_trusteddirserver_impl(authority_type_t type, int flags,
1166 int *n_busy_out)
1168 smartlist_t *direct, *tunnel;
1169 smartlist_t *overloaded_direct, *overloaded_tunnel;
1170 routerinfo_t *me = router_get_my_routerinfo();
1171 routerstatus_t *result;
1172 time_t now = time(NULL);
1173 const int requireother = ! (flags & PDS_ALLOW_SELF);
1174 const int fascistfirewall = ! (flags & PDS_IGNORE_FASCISTFIREWALL);
1175 const int prefer_tunnel = (flags & _PDS_PREFER_TUNNELED_DIR_CONNS);
1176 const int no_serverdesc_fetching =(flags & PDS_NO_EXISTING_SERVERDESC_FETCH);
1177 int n_busy = 0;
1179 if (!trusted_dir_servers)
1180 return NULL;
1182 direct = smartlist_create();
1183 tunnel = smartlist_create();
1184 overloaded_direct = smartlist_create();
1185 overloaded_tunnel = smartlist_create();
1187 SMARTLIST_FOREACH_BEGIN(trusted_dir_servers, trusted_dir_server_t *, d)
1189 int is_overloaded =
1190 d->fake_status.last_dir_503_at + DIR_503_TIMEOUT > now;
1191 tor_addr_t addr;
1192 if (!d->is_running) continue;
1193 if ((type & d->type) == 0)
1194 continue;
1195 if ((type & EXTRAINFO_CACHE) &&
1196 !router_supports_extrainfo(d->digest, 1))
1197 continue;
1198 if (requireother && me && router_digest_is_me(d->digest))
1199 continue;
1201 /* XXXX IP6 proposal 118 */
1202 tor_addr_from_ipv4h(&addr, d->addr);
1204 if (no_serverdesc_fetching) {
1205 if (connection_get_by_type_addr_port_purpose(
1206 CONN_TYPE_DIR, &addr, d->dir_port, DIR_PURPOSE_FETCH_SERVERDESC)
1207 || connection_get_by_type_addr_port_purpose(
1208 CONN_TYPE_DIR, &addr, d->dir_port, DIR_PURPOSE_FETCH_EXTRAINFO)) {
1209 //log_debug(LD_DIR, "We have an existing connection to fetch "
1210 // "descriptor from %s; delaying",d->description);
1211 ++n_busy;
1212 continue;
1216 if (prefer_tunnel &&
1217 d->or_port &&
1218 (!fascistfirewall ||
1219 fascist_firewall_allows_address_or(&addr, d->or_port)))
1220 smartlist_add(is_overloaded ? overloaded_tunnel : tunnel,
1221 &d->fake_status);
1222 else if (!fascistfirewall ||
1223 fascist_firewall_allows_address_dir(&addr, d->dir_port))
1224 smartlist_add(is_overloaded ? overloaded_direct : direct,
1225 &d->fake_status);
1227 SMARTLIST_FOREACH_END(d);
1229 if (smartlist_len(tunnel)) {
1230 result = smartlist_choose(tunnel);
1231 } else if (smartlist_len(overloaded_tunnel)) {
1232 result = smartlist_choose(overloaded_tunnel);
1233 } else if (smartlist_len(direct)) {
1234 result = smartlist_choose(direct);
1235 } else {
1236 result = smartlist_choose(overloaded_direct);
1239 if (n_busy_out)
1240 *n_busy_out = n_busy;
1242 smartlist_free(direct);
1243 smartlist_free(tunnel);
1244 smartlist_free(overloaded_direct);
1245 smartlist_free(overloaded_tunnel);
1246 return result;
1249 /** Go through and mark the authoritative dirservers as up. */
1250 static void
1251 mark_all_trusteddirservers_up(void)
1253 if (routerlist) {
1254 SMARTLIST_FOREACH(routerlist->routers, routerinfo_t *, router,
1255 if (router_digest_is_trusted_dir(router->cache_info.identity_digest) &&
1256 router->dir_port > 0) {
1257 router->is_running = 1;
1260 if (trusted_dir_servers) {
1261 SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, dir,
1263 routerstatus_t *rs;
1264 dir->is_running = 1;
1265 download_status_reset(&dir->v2_ns_dl_status);
1266 rs = router_get_consensus_status_by_id(dir->digest);
1267 if (rs && !rs->is_running) {
1268 rs->is_running = 1;
1269 rs->last_dir_503_at = 0;
1270 control_event_networkstatus_changed_single(rs);
1274 router_dir_info_changed();
1277 /** Return true iff r1 and r2 have the same address and OR port. */
1279 routers_have_same_or_addr(const routerinfo_t *r1, const routerinfo_t *r2)
1281 return r1->addr == r2->addr && r1->or_port == r2->or_port;
1284 /** Reset all internal variables used to count failed downloads of network
1285 * status objects. */
1286 void
1287 router_reset_status_download_failures(void)
1289 mark_all_trusteddirservers_up();
1292 /** Return true iff router1 and router2 have the same /16 network. */
1293 static INLINE int
1294 routers_in_same_network_family(routerinfo_t *r1, routerinfo_t *r2)
1296 return (r1->addr & 0xffff0000) == (r2->addr & 0xffff0000);
1299 /** Look through the routerlist and identify routers that
1300 * advertise the same /16 network address as <b>router</b>.
1301 * Add each of them to <b>sl</b>.
1303 static void
1304 routerlist_add_network_family(smartlist_t *sl, routerinfo_t *router)
1306 SMARTLIST_FOREACH(routerlist->routers, routerinfo_t *, r,
1308 if (router != r && routers_in_same_network_family(router, r))
1309 smartlist_add(sl, r);
1313 /** Add all the family of <b>router</b> to the smartlist <b>sl</b>.
1314 * This is used to make sure we don't pick siblings in a single path,
1315 * or pick more than one relay from a family for our entry guard list.
1317 void
1318 routerlist_add_family(smartlist_t *sl, routerinfo_t *router)
1320 routerinfo_t *r;
1321 config_line_t *cl;
1322 or_options_t *options = get_options();
1324 /* First, add any routers with similar network addresses. */
1325 if (options->EnforceDistinctSubnets)
1326 routerlist_add_network_family(sl, router);
1328 if (router->declared_family) {
1329 /* Add every r such that router declares familyness with r, and r
1330 * declares familyhood with router. */
1331 SMARTLIST_FOREACH(router->declared_family, const char *, n,
1333 if (!(r = router_get_by_nickname(n, 0)))
1334 continue;
1335 if (!r->declared_family)
1336 continue;
1337 SMARTLIST_FOREACH(r->declared_family, const char *, n2,
1339 if (router_nickname_matches(router, n2))
1340 smartlist_add(sl, r);
1345 /* If the user declared any families locally, honor those too. */
1346 for (cl = options->NodeFamilies; cl; cl = cl->next) {
1347 if (router_nickname_is_in_list(router, cl->value)) {
1348 add_nickname_list_to_smartlist(sl, cl->value, 0);
1353 /** Return true iff r is named by some nickname in <b>lst</b>. */
1354 static INLINE int
1355 router_in_nickname_smartlist(smartlist_t *lst, routerinfo_t *r)
1357 if (!lst) return 0;
1358 SMARTLIST_FOREACH(lst, const char *, name,
1359 if (router_nickname_matches(r, name))
1360 return 1;);
1361 return 0;
1364 /** Return true iff r1 and r2 are in the same family, but not the same
1365 * router. */
1367 routers_in_same_family(routerinfo_t *r1, routerinfo_t *r2)
1369 or_options_t *options = get_options();
1370 config_line_t *cl;
1372 if (options->EnforceDistinctSubnets && routers_in_same_network_family(r1,r2))
1373 return 1;
1375 if (router_in_nickname_smartlist(r1->declared_family, r2) &&
1376 router_in_nickname_smartlist(r2->declared_family, r1))
1377 return 1;
1379 for (cl = options->NodeFamilies; cl; cl = cl->next) {
1380 if (router_nickname_is_in_list(r1, cl->value) &&
1381 router_nickname_is_in_list(r2, cl->value))
1382 return 1;
1384 return 0;
1387 /** Given a (possibly NULL) comma-and-whitespace separated list of nicknames,
1388 * see which nicknames in <b>list</b> name routers in our routerlist, and add
1389 * the routerinfos for those routers to <b>sl</b>. If <b>must_be_running</b>,
1390 * only include routers that we think are running.
1391 * Warn if any non-Named routers are specified by nickname.
1393 void
1394 add_nickname_list_to_smartlist(smartlist_t *sl, const char *list,
1395 int must_be_running)
1397 routerinfo_t *router;
1398 smartlist_t *nickname_list;
1399 int have_dir_info = router_have_minimum_dir_info();
1401 if (!list)
1402 return; /* nothing to do */
1403 tor_assert(sl);
1405 nickname_list = smartlist_create();
1406 if (!warned_nicknames)
1407 warned_nicknames = smartlist_create();
1409 smartlist_split_string(nickname_list, list, ",",
1410 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
1412 SMARTLIST_FOREACH(nickname_list, const char *, nick, {
1413 int warned;
1414 if (!is_legal_nickname_or_hexdigest(nick)) {
1415 log_warn(LD_CONFIG, "Nickname '%s' is misformed; skipping", nick);
1416 continue;
1418 router = router_get_by_nickname(nick, 1);
1419 warned = smartlist_string_isin(warned_nicknames, nick);
1420 if (router) {
1421 if (!must_be_running || router->is_running) {
1422 smartlist_add(sl,router);
1424 } else if (!router_get_consensus_status_by_nickname(nick,1)) {
1425 if (!warned) {
1426 log_fn(have_dir_info ? LOG_WARN : LOG_INFO, LD_CONFIG,
1427 "Nickname list includes '%s' which isn't a known router.",nick);
1428 smartlist_add(warned_nicknames, tor_strdup(nick));
1432 SMARTLIST_FOREACH(nickname_list, char *, nick, tor_free(nick));
1433 smartlist_free(nickname_list);
1436 /** Return 1 iff any member of the (possibly NULL) comma-separated list
1437 * <b>list</b> is an acceptable nickname or hexdigest for <b>router</b>. Else
1438 * return 0.
1441 router_nickname_is_in_list(routerinfo_t *router, const char *list)
1443 smartlist_t *nickname_list;
1444 int v = 0;
1446 if (!list)
1447 return 0; /* definitely not */
1448 tor_assert(router);
1450 nickname_list = smartlist_create();
1451 smartlist_split_string(nickname_list, list, ",",
1452 SPLIT_SKIP_SPACE|SPLIT_STRIP_SPACE|SPLIT_IGNORE_BLANK, 0);
1453 SMARTLIST_FOREACH(nickname_list, const char *, cp,
1454 if (router_nickname_matches(router, cp)) {v=1;break;});
1455 SMARTLIST_FOREACH(nickname_list, char *, cp, tor_free(cp));
1456 smartlist_free(nickname_list);
1457 return v;
1460 /** Add every suitable router from our routerlist to <b>sl</b>, so that
1461 * we can pick a node for a circuit.
1463 static void
1464 router_add_running_routers_to_smartlist(smartlist_t *sl, int allow_invalid,
1465 int need_uptime, int need_capacity,
1466 int need_guard)
1468 if (!routerlist)
1469 return;
1471 SMARTLIST_FOREACH(routerlist->routers, routerinfo_t *, router,
1473 if (router->is_running &&
1474 router->purpose == ROUTER_PURPOSE_GENERAL &&
1475 (router->is_valid || allow_invalid) &&
1476 !router_is_unreliable(router, need_uptime,
1477 need_capacity, need_guard)) {
1478 /* If it's running, and it's suitable according to the
1479 * other flags we had in mind */
1480 smartlist_add(sl, router);
1485 /** Look through the routerlist until we find a router that has my key.
1486 Return it. */
1487 routerinfo_t *
1488 routerlist_find_my_routerinfo(void)
1490 if (!routerlist)
1491 return NULL;
1493 SMARTLIST_FOREACH(routerlist->routers, routerinfo_t *, router,
1495 if (router_is_me(router))
1496 return router;
1498 return NULL;
1501 /** Find a router that's up, that has this IP address, and
1502 * that allows exit to this address:port, or return NULL if there
1503 * isn't a good one.
1505 routerinfo_t *
1506 router_find_exact_exit_enclave(const char *address, uint16_t port)
1508 uint32_t addr;
1509 struct in_addr in;
1510 tor_addr_t a;
1512 if (!tor_inet_aton(address, &in))
1513 return NULL; /* it's not an IP already */
1514 addr = ntohl(in.s_addr);
1516 tor_addr_from_ipv4h(&a, addr);
1518 SMARTLIST_FOREACH(routerlist->routers, routerinfo_t *, router,
1520 if (router->addr == addr &&
1521 router->is_running &&
1522 compare_tor_addr_to_addr_policy(&a, port, router->exit_policy) ==
1523 ADDR_POLICY_ACCEPTED)
1524 return router;
1526 return NULL;
1529 /** Return 1 if <b>router</b> is not suitable for these parameters, else 0.
1530 * If <b>need_uptime</b> is non-zero, we require a minimum uptime.
1531 * If <b>need_capacity</b> is non-zero, we require a minimum advertised
1532 * bandwidth.
1533 * If <b>need_guard</b>, we require that the router is a possible entry guard.
1536 router_is_unreliable(routerinfo_t *router, int need_uptime,
1537 int need_capacity, int need_guard)
1539 if (need_uptime && !router->is_stable)
1540 return 1;
1541 if (need_capacity && !router->is_fast)
1542 return 1;
1543 if (need_guard && !router->is_possible_guard)
1544 return 1;
1545 return 0;
1548 /** Return the smaller of the router's configured BandwidthRate
1549 * and its advertised capacity. */
1550 uint32_t
1551 router_get_advertised_bandwidth(routerinfo_t *router)
1553 if (router->bandwidthcapacity < router->bandwidthrate)
1554 return router->bandwidthcapacity;
1555 return router->bandwidthrate;
1558 /** Do not weight any declared bandwidth more than this much when picking
1559 * routers by bandwidth. */
1560 #define DEFAULT_MAX_BELIEVABLE_BANDWIDTH 10000000 /* 10 MB/sec */
1562 /** Return the smaller of the router's configured BandwidthRate
1563 * and its advertised capacity, capped by max-believe-bw. */
1564 uint32_t
1565 router_get_advertised_bandwidth_capped(routerinfo_t *router)
1567 uint32_t result = router->bandwidthcapacity;
1568 if (result > router->bandwidthrate)
1569 result = router->bandwidthrate;
1570 if (result > DEFAULT_MAX_BELIEVABLE_BANDWIDTH)
1571 result = DEFAULT_MAX_BELIEVABLE_BANDWIDTH;
1572 return result;
1575 /** When weighting bridges, enforce these values as lower and upper
1576 * bound for believable bandwidth, because there is no way for us
1577 * to verify a bridge's bandwidth currently. */
1578 #define BRIDGE_MIN_BELIEVABLE_BANDWIDTH 20000 /* 20 kB/sec */
1579 #define BRIDGE_MAX_BELIEVABLE_BANDWIDTH 100000 /* 100 kB/sec */
1581 /** Return the smaller of the router's configured BandwidthRate
1582 * and its advertised capacity, making sure to stay within the
1583 * interval between bridge-min-believe-bw and
1584 * bridge-max-believe-bw. */
1585 static uint32_t
1586 bridge_get_advertised_bandwidth_bounded(routerinfo_t *router)
1588 uint32_t result = router->bandwidthcapacity;
1589 if (result > router->bandwidthrate)
1590 result = router->bandwidthrate;
1591 if (result > BRIDGE_MAX_BELIEVABLE_BANDWIDTH)
1592 result = BRIDGE_MAX_BELIEVABLE_BANDWIDTH;
1593 else if (result < BRIDGE_MIN_BELIEVABLE_BANDWIDTH)
1594 result = BRIDGE_MIN_BELIEVABLE_BANDWIDTH;
1595 return result;
1598 /** Return bw*1000, unless bw*1000 would overflow, in which case return
1599 * INT32_MAX. */
1600 static INLINE int32_t
1601 kb_to_bytes(uint32_t bw)
1603 return (bw > (INT32_MAX/1000)) ? INT32_MAX : bw*1000;
1606 /** Helper function:
1607 * choose a random element of smartlist <b>sl</b>, weighted by
1608 * the advertised bandwidth of each element using the consensus
1609 * bandwidth weights.
1611 * If <b>statuses</b> is zero, then <b>sl</b> is a list of
1612 * routerinfo_t's. Otherwise it's a list of routerstatus_t's.
1614 * If <b>rule</b>==WEIGHT_FOR_EXIT. we're picking an exit node: consider all
1615 * nodes' bandwidth equally regardless of their Exit status, since there may
1616 * be some in the list because they exit to obscure ports. If
1617 * <b>rule</b>==NO_WEIGHTING, we're picking a non-exit node: weight
1618 * exit-node's bandwidth less depending on the smallness of the fraction of
1619 * Exit-to-total bandwidth. If <b>rule</b>==WEIGHT_FOR_GUARD, we're picking a
1620 * guard node: consider all guard's bandwidth equally. Otherwise, weight
1621 * guards proportionally less.
1623 static void *
1624 smartlist_choose_by_bandwidth_weights(smartlist_t *sl,
1625 bandwidth_weight_rule_t rule,
1626 int statuses)
1628 int64_t weight_scale;
1629 int64_t rand_bw;
1630 double Wg = -1, Wm = -1, We = -1, Wd = -1;
1631 double Wgb = -1, Wmb = -1, Web = -1, Wdb = -1;
1632 double weighted_bw = 0;
1633 double *bandwidths;
1634 double tmp = 0;
1635 unsigned int i;
1636 int have_unknown = 0; /* true iff sl contains element not in consensus. */
1638 /* Can't choose exit and guard at same time */
1639 tor_assert(rule == NO_WEIGHTING ||
1640 rule == WEIGHT_FOR_EXIT ||
1641 rule == WEIGHT_FOR_GUARD ||
1642 rule == WEIGHT_FOR_MID ||
1643 rule == WEIGHT_FOR_DIR);
1645 if (smartlist_len(sl) == 0) {
1646 log_info(LD_CIRC,
1647 "Empty routerlist passed in to consensus weight node "
1648 "selection for rule %s",
1649 bandwidth_weight_rule_to_string(rule));
1650 return NULL;
1653 weight_scale = circuit_build_times_get_bw_scale(NULL);
1655 if (rule == WEIGHT_FOR_GUARD) {
1656 Wg = networkstatus_get_bw_weight(NULL, "Wgg", -1);
1657 Wm = networkstatus_get_bw_weight(NULL, "Wgm", -1); /* Bridges */
1658 We = 0;
1659 Wd = networkstatus_get_bw_weight(NULL, "Wgd", -1);
1661 Wgb = networkstatus_get_bw_weight(NULL, "Wgb", -1);
1662 Wmb = networkstatus_get_bw_weight(NULL, "Wmb", -1);
1663 Web = networkstatus_get_bw_weight(NULL, "Web", -1);
1664 Wdb = networkstatus_get_bw_weight(NULL, "Wdb", -1);
1665 } else if (rule == WEIGHT_FOR_MID) {
1666 Wg = networkstatus_get_bw_weight(NULL, "Wmg", -1);
1667 Wm = networkstatus_get_bw_weight(NULL, "Wmm", -1);
1668 We = networkstatus_get_bw_weight(NULL, "Wme", -1);
1669 Wd = networkstatus_get_bw_weight(NULL, "Wmd", -1);
1671 Wgb = networkstatus_get_bw_weight(NULL, "Wgb", -1);
1672 Wmb = networkstatus_get_bw_weight(NULL, "Wmb", -1);
1673 Web = networkstatus_get_bw_weight(NULL, "Web", -1);
1674 Wdb = networkstatus_get_bw_weight(NULL, "Wdb", -1);
1675 } else if (rule == WEIGHT_FOR_EXIT) {
1676 // Guards CAN be exits if they have weird exit policies
1677 // They are d then I guess...
1678 We = networkstatus_get_bw_weight(NULL, "Wee", -1);
1679 Wm = networkstatus_get_bw_weight(NULL, "Wem", -1); /* Odd exit policies */
1680 Wd = networkstatus_get_bw_weight(NULL, "Wed", -1);
1681 Wg = networkstatus_get_bw_weight(NULL, "Weg", -1); /* Odd exit policies */
1683 Wgb = networkstatus_get_bw_weight(NULL, "Wgb", -1);
1684 Wmb = networkstatus_get_bw_weight(NULL, "Wmb", -1);
1685 Web = networkstatus_get_bw_weight(NULL, "Web", -1);
1686 Wdb = networkstatus_get_bw_weight(NULL, "Wdb", -1);
1687 } else if (rule == WEIGHT_FOR_DIR) {
1688 We = networkstatus_get_bw_weight(NULL, "Wbe", -1);
1689 Wm = networkstatus_get_bw_weight(NULL, "Wbm", -1);
1690 Wd = networkstatus_get_bw_weight(NULL, "Wbd", -1);
1691 Wg = networkstatus_get_bw_weight(NULL, "Wbg", -1);
1693 Wgb = Wmb = Web = Wdb = weight_scale;
1694 } else if (rule == NO_WEIGHTING) {
1695 Wg = Wm = We = Wd = weight_scale;
1696 Wgb = Wmb = Web = Wdb = weight_scale;
1699 if (Wg < 0 || Wm < 0 || We < 0 || Wd < 0 || Wgb < 0 || Wmb < 0 || Wdb < 0
1700 || Web < 0) {
1701 log_debug(LD_CIRC,
1702 "Got negative bandwidth weights. Defaulting to old selection"
1703 " algorithm.");
1704 return NULL; // Use old algorithm.
1707 Wg /= weight_scale;
1708 Wm /= weight_scale;
1709 We /= weight_scale;
1710 Wd /= weight_scale;
1712 Wgb /= weight_scale;
1713 Wmb /= weight_scale;
1714 Web /= weight_scale;
1715 Wdb /= weight_scale;
1717 bandwidths = tor_malloc_zero(sizeof(double)*smartlist_len(sl));
1719 // Cycle through smartlist and total the bandwidth.
1720 for (i = 0; i < (unsigned)smartlist_len(sl); ++i) {
1721 int is_exit = 0, is_guard = 0, is_dir = 0, this_bw = 0, is_me = 0;
1722 double weight = 1;
1723 if (statuses) {
1724 routerstatus_t *status = smartlist_get(sl, i);
1725 is_exit = status->is_exit && !status->is_bad_exit;
1726 is_guard = status->is_possible_guard;
1727 is_dir = (status->dir_port != 0);
1728 if (!status->has_bandwidth) {
1729 tor_free(bandwidths);
1730 /* This should never happen, unless all the authorites downgrade
1731 * to 0.2.0 or rogue routerstatuses get inserted into our consensus. */
1732 log_warn(LD_BUG,
1733 "Consensus is not listing bandwidths. Defaulting back to "
1734 "old router selection algorithm.");
1735 return NULL;
1737 this_bw = kb_to_bytes(status->bandwidth);
1738 if (router_digest_is_me(status->identity_digest))
1739 is_me = 1;
1740 } else {
1741 routerstatus_t *rs;
1742 routerinfo_t *router = smartlist_get(sl, i);
1743 rs = router_get_consensus_status_by_id(
1744 router->cache_info.identity_digest);
1745 is_exit = router->is_exit && !router->is_bad_exit;
1746 is_guard = router->is_possible_guard;
1747 is_dir = (router->dir_port != 0);
1748 if (rs && rs->has_bandwidth) {
1749 this_bw = kb_to_bytes(rs->bandwidth);
1750 } else { /* bridge or other descriptor not in our consensus */
1751 this_bw = bridge_get_advertised_bandwidth_bounded(router);
1752 have_unknown = 1;
1754 if (router_digest_is_me(router->cache_info.identity_digest))
1755 is_me = 1;
1757 if (is_guard && is_exit) {
1758 weight = (is_dir ? Wdb*Wd : Wd);
1759 } else if (is_guard) {
1760 weight = (is_dir ? Wgb*Wg : Wg);
1761 } else if (is_exit) {
1762 weight = (is_dir ? Web*We : We);
1763 } else { // middle
1764 weight = (is_dir ? Wmb*Wm : Wm);
1767 bandwidths[i] = weight*this_bw;
1768 weighted_bw += weight*this_bw;
1769 if (is_me)
1770 sl_last_weighted_bw_of_me = weight*this_bw;
1773 /* XXXX022 this is a kludge to expose these values. */
1774 sl_last_total_weighted_bw = weighted_bw;
1776 log_debug(LD_CIRC, "Choosing node for rule %s based on weights "
1777 "Wg=%lf Wm=%lf We=%lf Wd=%lf with total bw %lf",
1778 bandwidth_weight_rule_to_string(rule),
1779 Wg, Wm, We, Wd, weighted_bw);
1781 /* If there is no bandwidth, choose at random */
1782 if (DBL_TO_U64(weighted_bw) == 0) {
1783 /* Don't warn when using bridges/relays not in the consensus */
1784 if (!have_unknown)
1785 log_warn(LD_CIRC,
1786 "Weighted bandwidth is %lf in node selection for rule %s",
1787 weighted_bw, bandwidth_weight_rule_to_string(rule));
1788 tor_free(bandwidths);
1789 return smartlist_choose(sl);
1792 rand_bw = crypto_rand_uint64(DBL_TO_U64(weighted_bw));
1793 rand_bw++; /* crypto_rand_uint64() counts from 0, and we need to count
1794 * from 1 below. See bug 1203 for details. */
1796 /* Last, count through sl until we get to the element we picked */
1797 tmp = 0.0;
1798 for (i=0; i < (unsigned)smartlist_len(sl); i++) {
1799 tmp += bandwidths[i];
1800 if (tmp >= rand_bw)
1801 break;
1804 if (i == (unsigned)smartlist_len(sl)) {
1805 /* This was once possible due to round-off error, but shouldn't be able
1806 * to occur any longer. */
1807 tor_fragile_assert();
1808 --i;
1809 log_warn(LD_BUG, "Round-off error in computing bandwidth had an effect on "
1810 " which router we chose. Please tell the developers. "
1811 "%lf " U64_FORMAT " %lf", tmp, U64_PRINTF_ARG(rand_bw),
1812 weighted_bw);
1814 tor_free(bandwidths);
1815 return smartlist_get(sl, i);
1818 /** Helper function:
1819 * choose a random element of smartlist <b>sl</b>, weighted by
1820 * the advertised bandwidth of each element.
1822 * If <b>statuses</b> is zero, then <b>sl</b> is a list of
1823 * routerinfo_t's. Otherwise it's a list of routerstatus_t's.
1825 * If <b>rule</b>==WEIGHT_FOR_EXIT. we're picking an exit node: consider all
1826 * nodes' bandwidth equally regardless of their Exit status, since there may
1827 * be some in the list because they exit to obscure ports. If
1828 * <b>rule</b>==NO_WEIGHTING, we're picking a non-exit node: weight
1829 * exit-node's bandwidth less depending on the smallness of the fraction of
1830 * Exit-to-total bandwidth. If <b>rule</b>==WEIGHT_FOR_GUARD, we're picking a
1831 * guard node: consider all guard's bandwidth equally. Otherwise, weight
1832 * guards proportionally less.
1834 static void *
1835 smartlist_choose_by_bandwidth(smartlist_t *sl, bandwidth_weight_rule_t rule,
1836 int statuses)
1838 unsigned int i;
1839 routerinfo_t *router;
1840 routerstatus_t *status=NULL;
1841 int32_t *bandwidths;
1842 int is_exit;
1843 int is_guard;
1844 uint64_t total_nonexit_bw = 0, total_exit_bw = 0, total_bw = 0;
1845 uint64_t total_nonguard_bw = 0, total_guard_bw = 0;
1846 uint64_t rand_bw, tmp;
1847 double exit_weight;
1848 double guard_weight;
1849 int n_unknown = 0;
1850 bitarray_t *exit_bits;
1851 bitarray_t *guard_bits;
1852 int me_idx = -1;
1854 // This function does not support WEIGHT_FOR_DIR
1855 // or WEIGHT_FOR_MID
1856 if (rule == WEIGHT_FOR_DIR || rule == WEIGHT_FOR_MID) {
1857 rule = NO_WEIGHTING;
1860 /* Can't choose exit and guard at same time */
1861 tor_assert(rule == NO_WEIGHTING ||
1862 rule == WEIGHT_FOR_EXIT ||
1863 rule == WEIGHT_FOR_GUARD);
1865 if (smartlist_len(sl) == 0) {
1866 log_info(LD_CIRC,
1867 "Empty routerlist passed in to old node selection for rule %s",
1868 bandwidth_weight_rule_to_string(rule));
1869 return NULL;
1872 /* First count the total bandwidth weight, and make a list
1873 * of each value. <0 means "unknown; no routerinfo." We use the
1874 * bits of negative values to remember whether the router was fast (-x)&1
1875 * and whether it was an exit (-x)&2 or guard (-x)&4. Yes, it's a hack. */
1876 bandwidths = tor_malloc(sizeof(int32_t)*smartlist_len(sl));
1877 exit_bits = bitarray_init_zero(smartlist_len(sl));
1878 guard_bits = bitarray_init_zero(smartlist_len(sl));
1880 /* Iterate over all the routerinfo_t or routerstatus_t, and */
1881 for (i = 0; i < (unsigned)smartlist_len(sl); ++i) {
1882 /* first, learn what bandwidth we think i has */
1883 int is_known = 1;
1884 int32_t flags = 0;
1885 uint32_t this_bw = 0;
1886 if (statuses) {
1887 status = smartlist_get(sl, i);
1888 if (router_digest_is_me(status->identity_digest))
1889 me_idx = i;
1890 router = router_get_by_digest(status->identity_digest);
1891 is_exit = status->is_exit;
1892 is_guard = status->is_possible_guard;
1893 if (status->has_bandwidth) {
1894 this_bw = kb_to_bytes(status->bandwidth);
1895 } else { /* guess */
1896 /* XXX022 once consensuses always list bandwidths, we can take
1897 * this guessing business out. -RD */
1898 is_known = 0;
1899 flags = status->is_fast ? 1 : 0;
1900 flags |= is_exit ? 2 : 0;
1901 flags |= is_guard ? 4 : 0;
1903 } else {
1904 routerstatus_t *rs;
1905 router = smartlist_get(sl, i);
1906 rs = router_get_consensus_status_by_id(
1907 router->cache_info.identity_digest);
1908 if (router_digest_is_me(router->cache_info.identity_digest))
1909 me_idx = i;
1910 is_exit = router->is_exit;
1911 is_guard = router->is_possible_guard;
1912 if (rs && rs->has_bandwidth) {
1913 this_bw = kb_to_bytes(rs->bandwidth);
1914 } else if (rs) { /* guess; don't trust the descriptor */
1915 /* XXX022 once consensuses always list bandwidths, we can take
1916 * this guessing business out. -RD */
1917 is_known = 0;
1918 flags = router->is_fast ? 1 : 0;
1919 flags |= is_exit ? 2 : 0;
1920 flags |= is_guard ? 4 : 0;
1921 } else /* bridge or other descriptor not in our consensus */
1922 this_bw = bridge_get_advertised_bandwidth_bounded(router);
1924 if (is_exit)
1925 bitarray_set(exit_bits, i);
1926 if (is_guard)
1927 bitarray_set(guard_bits, i);
1928 if (is_known) {
1929 bandwidths[i] = (int32_t) this_bw; // safe since MAX_BELIEVABLE<INT32_MAX
1930 // XXX this is no longer true! We don't always cap the bw anymore. Can
1931 // a consensus make us overflow?-sh
1932 tor_assert(bandwidths[i] >= 0);
1933 if (is_guard)
1934 total_guard_bw += this_bw;
1935 else
1936 total_nonguard_bw += this_bw;
1937 if (is_exit)
1938 total_exit_bw += this_bw;
1939 else
1940 total_nonexit_bw += this_bw;
1941 } else {
1942 ++n_unknown;
1943 bandwidths[i] = -flags;
1947 /* Now, fill in the unknown values. */
1948 if (n_unknown) {
1949 int32_t avg_fast, avg_slow;
1950 if (total_exit_bw+total_nonexit_bw) {
1951 /* if there's some bandwidth, there's at least one known router,
1952 * so no worries about div by 0 here */
1953 int n_known = smartlist_len(sl)-n_unknown;
1954 avg_fast = avg_slow = (int32_t)
1955 ((total_exit_bw+total_nonexit_bw)/((uint64_t) n_known));
1956 } else {
1957 avg_fast = 40000;
1958 avg_slow = 20000;
1960 for (i=0; i<(unsigned)smartlist_len(sl); ++i) {
1961 int32_t bw = bandwidths[i];
1962 if (bw>=0)
1963 continue;
1964 is_exit = ((-bw)&2);
1965 is_guard = ((-bw)&4);
1966 bandwidths[i] = ((-bw)&1) ? avg_fast : avg_slow;
1967 if (is_exit)
1968 total_exit_bw += bandwidths[i];
1969 else
1970 total_nonexit_bw += bandwidths[i];
1971 if (is_guard)
1972 total_guard_bw += bandwidths[i];
1973 else
1974 total_nonguard_bw += bandwidths[i];
1978 /* If there's no bandwidth at all, pick at random. */
1979 if (!(total_exit_bw+total_nonexit_bw)) {
1980 tor_free(bandwidths);
1981 tor_free(exit_bits);
1982 tor_free(guard_bits);
1983 return smartlist_choose(sl);
1986 /* Figure out how to weight exits and guards */
1988 double all_bw = U64_TO_DBL(total_exit_bw+total_nonexit_bw);
1989 double exit_bw = U64_TO_DBL(total_exit_bw);
1990 double guard_bw = U64_TO_DBL(total_guard_bw);
1992 * For detailed derivation of this formula, see
1993 * http://archives.seul.org/or/dev/Jul-2007/msg00056.html
1995 if (rule == WEIGHT_FOR_EXIT || !total_exit_bw)
1996 exit_weight = 1.0;
1997 else
1998 exit_weight = 1.0 - all_bw/(3.0*exit_bw);
2000 if (rule == WEIGHT_FOR_GUARD || !total_guard_bw)
2001 guard_weight = 1.0;
2002 else
2003 guard_weight = 1.0 - all_bw/(3.0*guard_bw);
2005 if (exit_weight <= 0.0)
2006 exit_weight = 0.0;
2008 if (guard_weight <= 0.0)
2009 guard_weight = 0.0;
2011 total_bw = 0;
2012 sl_last_weighted_bw_of_me = 0;
2013 for (i=0; i < (unsigned)smartlist_len(sl); i++) {
2014 uint64_t bw;
2015 is_exit = bitarray_is_set(exit_bits, i);
2016 is_guard = bitarray_is_set(guard_bits, i);
2017 if (is_exit && is_guard)
2018 bw = ((uint64_t)(bandwidths[i] * exit_weight * guard_weight));
2019 else if (is_guard)
2020 bw = ((uint64_t)(bandwidths[i] * guard_weight));
2021 else if (is_exit)
2022 bw = ((uint64_t)(bandwidths[i] * exit_weight));
2023 else
2024 bw = bandwidths[i];
2025 total_bw += bw;
2026 if (i == (unsigned) me_idx)
2027 sl_last_weighted_bw_of_me = bw;
2031 /* XXXX022 this is a kludge to expose these values. */
2032 sl_last_total_weighted_bw = total_bw;
2034 log_debug(LD_CIRC, "Total weighted bw = "U64_FORMAT
2035 ", exit bw = "U64_FORMAT
2036 ", nonexit bw = "U64_FORMAT", exit weight = %lf "
2037 "(for exit == %d)"
2038 ", guard bw = "U64_FORMAT
2039 ", nonguard bw = "U64_FORMAT", guard weight = %lf "
2040 "(for guard == %d)",
2041 U64_PRINTF_ARG(total_bw),
2042 U64_PRINTF_ARG(total_exit_bw), U64_PRINTF_ARG(total_nonexit_bw),
2043 exit_weight, (int)(rule == WEIGHT_FOR_EXIT),
2044 U64_PRINTF_ARG(total_guard_bw), U64_PRINTF_ARG(total_nonguard_bw),
2045 guard_weight, (int)(rule == WEIGHT_FOR_GUARD));
2047 /* Almost done: choose a random value from the bandwidth weights. */
2048 rand_bw = crypto_rand_uint64(total_bw);
2049 rand_bw++; /* crypto_rand_uint64() counts from 0, and we need to count
2050 * from 1 below. See bug 1203 for details. */
2052 /* Last, count through sl until we get to the element we picked */
2053 tmp = 0;
2054 for (i=0; i < (unsigned)smartlist_len(sl); i++) {
2055 is_exit = bitarray_is_set(exit_bits, i);
2056 is_guard = bitarray_is_set(guard_bits, i);
2058 /* Weights can be 0 if not counting guards/exits */
2059 if (is_exit && is_guard)
2060 tmp += ((uint64_t)(bandwidths[i] * exit_weight * guard_weight));
2061 else if (is_guard)
2062 tmp += ((uint64_t)(bandwidths[i] * guard_weight));
2063 else if (is_exit)
2064 tmp += ((uint64_t)(bandwidths[i] * exit_weight));
2065 else
2066 tmp += bandwidths[i];
2068 if (tmp >= rand_bw)
2069 break;
2071 if (i == (unsigned)smartlist_len(sl)) {
2072 /* This was once possible due to round-off error, but shouldn't be able
2073 * to occur any longer. */
2074 tor_fragile_assert();
2075 --i;
2076 log_warn(LD_BUG, "Round-off error in computing bandwidth had an effect on "
2077 " which router we chose. Please tell the developers. "
2078 U64_FORMAT " " U64_FORMAT " " U64_FORMAT, U64_PRINTF_ARG(tmp),
2079 U64_PRINTF_ARG(rand_bw), U64_PRINTF_ARG(total_bw));
2081 tor_free(bandwidths);
2082 tor_free(exit_bits);
2083 tor_free(guard_bits);
2084 return smartlist_get(sl, i);
2087 /** Choose a random element of router list <b>sl</b>, weighted by
2088 * the advertised bandwidth of each router.
2090 routerinfo_t *
2091 routerlist_sl_choose_by_bandwidth(smartlist_t *sl,
2092 bandwidth_weight_rule_t rule)
2094 routerinfo_t *ret;
2095 if ((ret = smartlist_choose_by_bandwidth_weights(sl, rule, 0))) {
2096 return ret;
2097 } else {
2098 return smartlist_choose_by_bandwidth(sl, rule, 0);
2102 /** Choose a random element of status list <b>sl</b>, weighted by
2103 * the advertised bandwidth of each status.
2105 routerstatus_t *
2106 routerstatus_sl_choose_by_bandwidth(smartlist_t *sl,
2107 bandwidth_weight_rule_t rule)
2109 /* We are choosing neither exit nor guard here. Weight accordingly. */
2110 routerstatus_t *ret;
2111 if ((ret = smartlist_choose_by_bandwidth_weights(sl, rule, 1))) {
2112 return ret;
2113 } else {
2114 return smartlist_choose_by_bandwidth(sl, rule, 1);
2118 /** Return a random running router from the routerlist. Never
2119 * pick a node whose routerinfo is in
2120 * <b>excludedsmartlist</b>, or whose routerinfo matches <b>excludedset</b>,
2121 * even if they are the only nodes available.
2122 * If <b>CRN_NEED_UPTIME</b> is set in flags and any router has more than
2123 * a minimum uptime, return one of those.
2124 * If <b>CRN_NEED_CAPACITY</b> is set in flags, weight your choice by the
2125 * advertised capacity of each router.
2126 * If <b>CRN_ALLOW_INVALID</b> is not set in flags, consider only Valid
2127 * routers.
2128 * If <b>CRN_NEED_GUARD</b> is set in flags, consider only Guard routers.
2129 * If <b>CRN_WEIGHT_AS_EXIT</b> is set in flags, we weight bandwidths as if
2130 * picking an exit node, otherwise we weight bandwidths for picking a relay
2131 * node (that is, possibly discounting exit nodes).
2133 routerinfo_t *
2134 router_choose_random_node(smartlist_t *excludedsmartlist,
2135 routerset_t *excludedset,
2136 router_crn_flags_t flags)
2138 const int need_uptime = (flags & CRN_NEED_UPTIME) != 0;
2139 const int need_capacity = (flags & CRN_NEED_CAPACITY) != 0;
2140 const int need_guard = (flags & CRN_NEED_GUARD) != 0;
2141 const int allow_invalid = (flags & CRN_ALLOW_INVALID) != 0;
2142 const int weight_for_exit = (flags & CRN_WEIGHT_AS_EXIT) != 0;
2144 smartlist_t *sl=smartlist_create(),
2145 *excludednodes=smartlist_create();
2146 routerinfo_t *choice = NULL, *r;
2147 bandwidth_weight_rule_t rule;
2149 tor_assert(!(weight_for_exit && need_guard));
2150 rule = weight_for_exit ? WEIGHT_FOR_EXIT :
2151 (need_guard ? WEIGHT_FOR_GUARD : WEIGHT_FOR_MID);
2153 /* Exclude relays that allow single hop exit circuits, if the user
2154 * wants to (such relays might be risky) */
2155 if (get_options()->ExcludeSingleHopRelays) {
2156 routerlist_t *rl = router_get_routerlist();
2157 SMARTLIST_FOREACH(rl->routers, routerinfo_t *, r,
2158 if (r->allow_single_hop_exits) {
2159 smartlist_add(excludednodes, r);
2163 if ((r = routerlist_find_my_routerinfo())) {
2164 smartlist_add(excludednodes, r);
2165 routerlist_add_family(excludednodes, r);
2168 router_add_running_routers_to_smartlist(sl, allow_invalid,
2169 need_uptime, need_capacity,
2170 need_guard);
2171 smartlist_subtract(sl,excludednodes);
2172 if (excludedsmartlist)
2173 smartlist_subtract(sl,excludedsmartlist);
2174 if (excludedset)
2175 routerset_subtract_routers(sl,excludedset);
2177 // Always weight by bandwidth
2178 choice = routerlist_sl_choose_by_bandwidth(sl, rule);
2180 smartlist_free(sl);
2181 if (!choice && (need_uptime || need_capacity || need_guard)) {
2182 /* try once more -- recurse but with fewer restrictions. */
2183 log_info(LD_CIRC,
2184 "We couldn't find any live%s%s%s routers; falling back "
2185 "to list of all routers.",
2186 need_capacity?", fast":"",
2187 need_uptime?", stable":"",
2188 need_guard?", guard":"");
2189 flags &= ~ (CRN_NEED_UPTIME|CRN_NEED_CAPACITY|CRN_NEED_GUARD);
2190 choice = router_choose_random_node(
2191 excludedsmartlist, excludedset, flags);
2193 smartlist_free(excludednodes);
2194 if (!choice) {
2195 log_warn(LD_CIRC,
2196 "No available nodes when trying to choose node. Failing.");
2198 return choice;
2201 /** Helper: Return true iff the <b>identity_digest</b> and <b>nickname</b>
2202 * combination of a router, encoded in hexadecimal, matches <b>hexdigest</b>
2203 * (which is optionally prefixed with a single dollar sign). Return false if
2204 * <b>hexdigest</b> is malformed, or it doesn't match. */
2205 static INLINE int
2206 hex_digest_matches(const char *hexdigest, const char *identity_digest,
2207 const char *nickname, int is_named)
2209 char digest[DIGEST_LEN];
2210 size_t len;
2211 tor_assert(hexdigest);
2212 if (hexdigest[0] == '$')
2213 ++hexdigest;
2215 len = strlen(hexdigest);
2216 if (len < HEX_DIGEST_LEN)
2217 return 0;
2218 else if (len > HEX_DIGEST_LEN &&
2219 (hexdigest[HEX_DIGEST_LEN] == '=' ||
2220 hexdigest[HEX_DIGEST_LEN] == '~')) {
2221 if (strcasecmp(hexdigest+HEX_DIGEST_LEN+1, nickname))
2222 return 0;
2223 if (hexdigest[HEX_DIGEST_LEN] == '=' && !is_named)
2224 return 0;
2227 if (base16_decode(digest, DIGEST_LEN, hexdigest, HEX_DIGEST_LEN)<0)
2228 return 0;
2229 return (!memcmp(digest, identity_digest, DIGEST_LEN));
2232 /** Return true iff the digest of <b>router</b>'s identity key,
2233 * encoded in hexadecimal, matches <b>hexdigest</b> (which is
2234 * optionally prefixed with a single dollar sign). Return false if
2235 * <b>hexdigest</b> is malformed, or it doesn't match. */
2236 static INLINE int
2237 router_hex_digest_matches(routerinfo_t *router, const char *hexdigest)
2239 return hex_digest_matches(hexdigest, router->cache_info.identity_digest,
2240 router->nickname, router->is_named);
2243 /** Return true if <b>router</b>'s nickname matches <b>nickname</b>
2244 * (case-insensitive), or if <b>router's</b> identity key digest
2245 * matches a hexadecimal value stored in <b>nickname</b>. Return
2246 * false otherwise. */
2247 static int
2248 router_nickname_matches(routerinfo_t *router, const char *nickname)
2250 if (nickname[0]!='$' && !strcasecmp(router->nickname, nickname))
2251 return 1;
2252 return router_hex_digest_matches(router, nickname);
2255 /** Return the router in our routerlist whose (case-insensitive)
2256 * nickname or (case-sensitive) hexadecimal key digest is
2257 * <b>nickname</b>. Return NULL if no such router is known.
2259 routerinfo_t *
2260 router_get_by_nickname(const char *nickname, int warn_if_unnamed)
2262 int maybedigest;
2263 char digest[DIGEST_LEN];
2264 routerinfo_t *best_match=NULL;
2265 int n_matches = 0;
2266 const char *named_digest = NULL;
2268 tor_assert(nickname);
2269 if (!routerlist)
2270 return NULL;
2271 if (nickname[0] == '$')
2272 return router_get_by_hexdigest(nickname);
2273 if (!strcasecmp(nickname, UNNAMED_ROUTER_NICKNAME))
2274 return NULL;
2276 maybedigest = (strlen(nickname) >= HEX_DIGEST_LEN) &&
2277 (base16_decode(digest,DIGEST_LEN,nickname,HEX_DIGEST_LEN) == 0);
2279 if ((named_digest = networkstatus_get_router_digest_by_nickname(nickname))) {
2280 return rimap_get(routerlist->identity_map, named_digest);
2282 if (networkstatus_nickname_is_unnamed(nickname))
2283 return NULL;
2285 /* If we reach this point, there's no canonical value for the nickname. */
2287 SMARTLIST_FOREACH(routerlist->routers, routerinfo_t *, router,
2289 if (!strcasecmp(router->nickname, nickname)) {
2290 ++n_matches;
2291 if (n_matches <= 1 || router->is_running)
2292 best_match = router;
2293 } else if (maybedigest &&
2294 !memcmp(digest, router->cache_info.identity_digest, DIGEST_LEN)
2296 if (router_hex_digest_matches(router, nickname))
2297 return router;
2298 /* If we reach this point, we have a ID=name syntax that matches the
2299 * identity but not the name. That isn't an acceptable match. */
2303 if (best_match) {
2304 if (warn_if_unnamed && n_matches > 1) {
2305 smartlist_t *fps = smartlist_create();
2306 int any_unwarned = 0;
2307 SMARTLIST_FOREACH(routerlist->routers, routerinfo_t *, router,
2309 routerstatus_t *rs;
2310 char *desc;
2311 size_t dlen;
2312 char fp[HEX_DIGEST_LEN+1];
2313 if (strcasecmp(router->nickname, nickname))
2314 continue;
2315 rs = router_get_consensus_status_by_id(
2316 router->cache_info.identity_digest);
2317 if (rs && !rs->name_lookup_warned) {
2318 rs->name_lookup_warned = 1;
2319 any_unwarned = 1;
2321 base16_encode(fp, sizeof(fp),
2322 router->cache_info.identity_digest, DIGEST_LEN);
2323 dlen = 32 + HEX_DIGEST_LEN + strlen(router->address);
2324 desc = tor_malloc(dlen);
2325 tor_snprintf(desc, dlen, "\"$%s\" for the one at %s:%d",
2326 fp, router->address, router->or_port);
2327 smartlist_add(fps, desc);
2329 if (any_unwarned) {
2330 char *alternatives = smartlist_join_strings(fps, "; ",0,NULL);
2331 log_warn(LD_CONFIG,
2332 "There are multiple matches for the nickname \"%s\","
2333 " but none is listed as named by the directory authorities. "
2334 "Choosing one arbitrarily. If you meant one in particular, "
2335 "you should say %s.", nickname, alternatives);
2336 tor_free(alternatives);
2338 SMARTLIST_FOREACH(fps, char *, cp, tor_free(cp));
2339 smartlist_free(fps);
2340 } else if (warn_if_unnamed) {
2341 routerstatus_t *rs = router_get_consensus_status_by_id(
2342 best_match->cache_info.identity_digest);
2343 if (rs && !rs->name_lookup_warned) {
2344 char fp[HEX_DIGEST_LEN+1];
2345 base16_encode(fp, sizeof(fp),
2346 best_match->cache_info.identity_digest, DIGEST_LEN);
2347 log_warn(LD_CONFIG, "You specified a server \"%s\" by name, but this "
2348 "name is not registered, so it could be used by any server, "
2349 "not just the one you meant. "
2350 "To make sure you get the same server in the future, refer to "
2351 "it by key, as \"$%s\".", nickname, fp);
2352 rs->name_lookup_warned = 1;
2355 return best_match;
2358 return NULL;
2361 /** Try to find a routerinfo for <b>digest</b>. If we don't have one,
2362 * return 1. If we do, ask tor_version_as_new_as() for the answer.
2365 router_digest_version_as_new_as(const char *digest, const char *cutoff)
2367 routerinfo_t *router = router_get_by_digest(digest);
2368 if (!router)
2369 return 1;
2370 return tor_version_as_new_as(router->platform, cutoff);
2373 /** Return true iff <b>digest</b> is the digest of the identity key of a
2374 * trusted directory matching at least one bit of <b>type</b>. If <b>type</b>
2375 * is zero, any authority is okay. */
2377 router_digest_is_trusted_dir_type(const char *digest, authority_type_t type)
2379 if (!trusted_dir_servers)
2380 return 0;
2381 if (authdir_mode(get_options()) && router_digest_is_me(digest))
2382 return 1;
2383 SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, ent,
2384 if (!memcmp(digest, ent->digest, DIGEST_LEN)) {
2385 return (!type) || ((type & ent->type) != 0);
2387 return 0;
2390 /** Return true iff <b>addr</b> is the address of one of our trusted
2391 * directory authorities. */
2393 router_addr_is_trusted_dir(uint32_t addr)
2395 if (!trusted_dir_servers)
2396 return 0;
2397 SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, ent,
2398 if (ent->addr == addr)
2399 return 1;
2401 return 0;
2404 /** If hexdigest is correctly formed, base16_decode it into
2405 * digest, which must have DIGEST_LEN space in it.
2406 * Return 0 on success, -1 on failure.
2409 hexdigest_to_digest(const char *hexdigest, char *digest)
2411 if (hexdigest[0]=='$')
2412 ++hexdigest;
2413 if (strlen(hexdigest) < HEX_DIGEST_LEN ||
2414 base16_decode(digest,DIGEST_LEN,hexdigest,HEX_DIGEST_LEN) < 0)
2415 return -1;
2416 return 0;
2419 /** Return the router in our routerlist whose hexadecimal key digest
2420 * is <b>hexdigest</b>. Return NULL if no such router is known. */
2421 routerinfo_t *
2422 router_get_by_hexdigest(const char *hexdigest)
2424 char digest[DIGEST_LEN];
2425 size_t len;
2426 routerinfo_t *ri;
2428 tor_assert(hexdigest);
2429 if (!routerlist)
2430 return NULL;
2431 if (hexdigest[0]=='$')
2432 ++hexdigest;
2433 len = strlen(hexdigest);
2434 if (hexdigest_to_digest(hexdigest, digest) < 0)
2435 return NULL;
2437 ri = router_get_by_digest(digest);
2439 if (ri && len > HEX_DIGEST_LEN) {
2440 if (hexdigest[HEX_DIGEST_LEN] == '=') {
2441 if (strcasecmp(ri->nickname, hexdigest+HEX_DIGEST_LEN+1) ||
2442 !ri->is_named)
2443 return NULL;
2444 } else if (hexdigest[HEX_DIGEST_LEN] == '~') {
2445 if (strcasecmp(ri->nickname, hexdigest+HEX_DIGEST_LEN+1))
2446 return NULL;
2447 } else {
2448 return NULL;
2452 return ri;
2455 /** Return the router in our routerlist whose 20-byte key digest
2456 * is <b>digest</b>. Return NULL if no such router is known. */
2457 routerinfo_t *
2458 router_get_by_digest(const char *digest)
2460 tor_assert(digest);
2462 if (!routerlist) return NULL;
2464 // routerlist_assert_ok(routerlist);
2466 return rimap_get(routerlist->identity_map, digest);
2469 /** Return the router in our routerlist whose 20-byte descriptor
2470 * is <b>digest</b>. Return NULL if no such router is known. */
2471 signed_descriptor_t *
2472 router_get_by_descriptor_digest(const char *digest)
2474 tor_assert(digest);
2476 if (!routerlist) return NULL;
2478 return sdmap_get(routerlist->desc_digest_map, digest);
2481 /** Return the signed descriptor for the router in our routerlist whose
2482 * 20-byte extra-info digest is <b>digest</b>. Return NULL if no such router
2483 * is known. */
2484 signed_descriptor_t *
2485 router_get_by_extrainfo_digest(const char *digest)
2487 tor_assert(digest);
2489 if (!routerlist) return NULL;
2491 return sdmap_get(routerlist->desc_by_eid_map, digest);
2494 /** Return the signed descriptor for the extrainfo_t in our routerlist whose
2495 * extra-info-digest is <b>digest</b>. Return NULL if no such extra-info
2496 * document is known. */
2497 signed_descriptor_t *
2498 extrainfo_get_by_descriptor_digest(const char *digest)
2500 extrainfo_t *ei;
2501 tor_assert(digest);
2502 if (!routerlist) return NULL;
2503 ei = eimap_get(routerlist->extra_info_map, digest);
2504 return ei ? &ei->cache_info : NULL;
2507 /** Return a pointer to the signed textual representation of a descriptor.
2508 * The returned string is not guaranteed to be NUL-terminated: the string's
2509 * length will be in desc-\>signed_descriptor_len.
2511 * If <b>with_annotations</b> is set, the returned string will include
2512 * the annotations
2513 * (if any) preceding the descriptor. This will increase the length of the
2514 * string by desc-\>annotations_len.
2516 * The caller must not free the string returned.
2518 static const char *
2519 signed_descriptor_get_body_impl(signed_descriptor_t *desc,
2520 int with_annotations)
2522 const char *r = NULL;
2523 size_t len = desc->signed_descriptor_len;
2524 off_t offset = desc->saved_offset;
2525 if (with_annotations)
2526 len += desc->annotations_len;
2527 else
2528 offset += desc->annotations_len;
2530 tor_assert(len > 32);
2531 if (desc->saved_location == SAVED_IN_CACHE && routerlist) {
2532 desc_store_t *store = desc_get_store(router_get_routerlist(), desc);
2533 if (store && store->mmap) {
2534 tor_assert(desc->saved_offset + len <= store->mmap->size);
2535 r = store->mmap->data + offset;
2536 } else if (store) {
2537 log_err(LD_DIR, "We couldn't read a descriptor that is supposedly "
2538 "mmaped in our cache. Is another process running in our data "
2539 "directory? Exiting.");
2540 exit(1);
2543 if (!r) /* no mmap, or not in cache. */
2544 r = desc->signed_descriptor_body +
2545 (with_annotations ? 0 : desc->annotations_len);
2547 tor_assert(r);
2548 if (!with_annotations) {
2549 if (memcmp("router ", r, 7) && memcmp("extra-info ", r, 11)) {
2550 char *cp = tor_strndup(r, 64);
2551 log_err(LD_DIR, "descriptor at %p begins with unexpected string %s. "
2552 "Is another process running in our data directory? Exiting.",
2553 desc, escaped(cp));
2554 exit(1);
2558 return r;
2561 /** Return a pointer to the signed textual representation of a descriptor.
2562 * The returned string is not guaranteed to be NUL-terminated: the string's
2563 * length will be in desc-\>signed_descriptor_len.
2565 * The caller must not free the string returned.
2567 const char *
2568 signed_descriptor_get_body(signed_descriptor_t *desc)
2570 return signed_descriptor_get_body_impl(desc, 0);
2573 /** As signed_descriptor_get_body(), but points to the beginning of the
2574 * annotations section rather than the beginning of the descriptor. */
2575 const char *
2576 signed_descriptor_get_annotations(signed_descriptor_t *desc)
2578 return signed_descriptor_get_body_impl(desc, 1);
2581 /** Return the current list of all known routers. */
2582 routerlist_t *
2583 router_get_routerlist(void)
2585 if (PREDICT_UNLIKELY(!routerlist)) {
2586 routerlist = tor_malloc_zero(sizeof(routerlist_t));
2587 routerlist->routers = smartlist_create();
2588 routerlist->old_routers = smartlist_create();
2589 routerlist->identity_map = rimap_new();
2590 routerlist->desc_digest_map = sdmap_new();
2591 routerlist->desc_by_eid_map = sdmap_new();
2592 routerlist->extra_info_map = eimap_new();
2594 routerlist->desc_store.fname_base = "cached-descriptors";
2595 routerlist->desc_store.fname_alt_base = "cached-routers";
2596 routerlist->extrainfo_store.fname_base = "cached-extrainfo";
2598 routerlist->desc_store.type = ROUTER_STORE;
2599 routerlist->extrainfo_store.type = EXTRAINFO_STORE;
2601 routerlist->desc_store.description = "router descriptors";
2602 routerlist->extrainfo_store.description = "extra-info documents";
2604 return routerlist;
2607 /** Free all storage held by <b>router</b>. */
2608 void
2609 routerinfo_free(routerinfo_t *router)
2611 if (!router)
2612 return;
2614 tor_free(router->cache_info.signed_descriptor_body);
2615 tor_free(router->address);
2616 tor_free(router->nickname);
2617 tor_free(router->platform);
2618 tor_free(router->contact_info);
2619 if (router->onion_pkey)
2620 crypto_free_pk_env(router->onion_pkey);
2621 if (router->identity_pkey)
2622 crypto_free_pk_env(router->identity_pkey);
2623 if (router->declared_family) {
2624 SMARTLIST_FOREACH(router->declared_family, char *, s, tor_free(s));
2625 smartlist_free(router->declared_family);
2627 addr_policy_list_free(router->exit_policy);
2629 /* XXXX Remove if this turns out to affect performance. */
2630 memset(router, 77, sizeof(routerinfo_t));
2632 tor_free(router);
2635 /** Release all storage held by <b>extrainfo</b> */
2636 void
2637 extrainfo_free(extrainfo_t *extrainfo)
2639 if (!extrainfo)
2640 return;
2641 tor_free(extrainfo->cache_info.signed_descriptor_body);
2642 tor_free(extrainfo->pending_sig);
2644 /* XXXX remove this if it turns out to slow us down. */
2645 memset(extrainfo, 88, sizeof(extrainfo_t)); /* debug bad memory usage */
2646 tor_free(extrainfo);
2649 /** Release storage held by <b>sd</b>. */
2650 static void
2651 signed_descriptor_free(signed_descriptor_t *sd)
2653 if (!sd)
2654 return;
2656 tor_free(sd->signed_descriptor_body);
2658 /* XXXX remove this once more bugs go away. */
2659 memset(sd, 99, sizeof(signed_descriptor_t)); /* Debug bad mem usage */
2660 tor_free(sd);
2663 /** Extract a signed_descriptor_t from a general routerinfo, and free the
2664 * routerinfo.
2666 static signed_descriptor_t *
2667 signed_descriptor_from_routerinfo(routerinfo_t *ri)
2669 signed_descriptor_t *sd;
2670 tor_assert(ri->purpose == ROUTER_PURPOSE_GENERAL);
2671 sd = tor_malloc_zero(sizeof(signed_descriptor_t));
2672 memcpy(sd, &(ri->cache_info), sizeof(signed_descriptor_t));
2673 sd->routerlist_index = -1;
2674 ri->cache_info.signed_descriptor_body = NULL;
2675 routerinfo_free(ri);
2676 return sd;
2679 /** Helper: free the storage held by the extrainfo_t in <b>e</b>. */
2680 static void
2681 _extrainfo_free(void *e)
2683 extrainfo_free(e);
2686 /** Free all storage held by a routerlist <b>rl</b>. */
2687 void
2688 routerlist_free(routerlist_t *rl)
2690 if (!rl)
2691 return;
2692 rimap_free(rl->identity_map, NULL);
2693 sdmap_free(rl->desc_digest_map, NULL);
2694 sdmap_free(rl->desc_by_eid_map, NULL);
2695 eimap_free(rl->extra_info_map, _extrainfo_free);
2696 SMARTLIST_FOREACH(rl->routers, routerinfo_t *, r,
2697 routerinfo_free(r));
2698 SMARTLIST_FOREACH(rl->old_routers, signed_descriptor_t *, sd,
2699 signed_descriptor_free(sd));
2700 smartlist_free(rl->routers);
2701 smartlist_free(rl->old_routers);
2702 if (routerlist->desc_store.mmap)
2703 tor_munmap_file(routerlist->desc_store.mmap);
2704 if (routerlist->extrainfo_store.mmap)
2705 tor_munmap_file(routerlist->extrainfo_store.mmap);
2706 tor_free(rl);
2708 router_dir_info_changed();
2711 /** Log information about how much memory is being used for routerlist,
2712 * at log level <b>severity</b>. */
2713 void
2714 dump_routerlist_mem_usage(int severity)
2716 uint64_t livedescs = 0;
2717 uint64_t olddescs = 0;
2718 if (!routerlist)
2719 return;
2720 SMARTLIST_FOREACH(routerlist->routers, routerinfo_t *, r,
2721 livedescs += r->cache_info.signed_descriptor_len);
2722 SMARTLIST_FOREACH(routerlist->old_routers, signed_descriptor_t *, sd,
2723 olddescs += sd->signed_descriptor_len);
2725 log(severity, LD_DIR,
2726 "In %d live descriptors: "U64_FORMAT" bytes. "
2727 "In %d old descriptors: "U64_FORMAT" bytes.",
2728 smartlist_len(routerlist->routers), U64_PRINTF_ARG(livedescs),
2729 smartlist_len(routerlist->old_routers), U64_PRINTF_ARG(olddescs));
2732 /** Debugging helper: If <b>idx</b> is nonnegative, assert that <b>ri</b> is
2733 * in <b>sl</b> at position <b>idx</b>. Otherwise, search <b>sl</b> for
2734 * <b>ri</b>. Return the index of <b>ri</b> in <b>sl</b>, or -1 if <b>ri</b>
2735 * is not in <b>sl</b>. */
2736 static INLINE int
2737 _routerlist_find_elt(smartlist_t *sl, void *ri, int idx)
2739 if (idx < 0) {
2740 idx = -1;
2741 SMARTLIST_FOREACH(sl, routerinfo_t *, r,
2742 if (r == ri) {
2743 idx = r_sl_idx;
2744 break;
2746 } else {
2747 tor_assert(idx < smartlist_len(sl));
2748 tor_assert(smartlist_get(sl, idx) == ri);
2750 return idx;
2753 /** Insert an item <b>ri</b> into the routerlist <b>rl</b>, updating indices
2754 * as needed. There must be no previous member of <b>rl</b> with the same
2755 * identity digest as <b>ri</b>: If there is, call routerlist_replace
2756 * instead.
2758 static void
2759 routerlist_insert(routerlist_t *rl, routerinfo_t *ri)
2761 routerinfo_t *ri_old;
2762 signed_descriptor_t *sd_old;
2764 /* XXXX Remove if this slows us down. */
2765 routerinfo_t *ri_generated = router_get_my_routerinfo();
2766 tor_assert(ri_generated != ri);
2768 tor_assert(ri->cache_info.routerlist_index == -1);
2770 ri_old = rimap_set(rl->identity_map, ri->cache_info.identity_digest, ri);
2771 tor_assert(!ri_old);
2773 sd_old = sdmap_set(rl->desc_digest_map,
2774 ri->cache_info.signed_descriptor_digest,
2775 &(ri->cache_info));
2776 if (sd_old) {
2777 rl->desc_store.bytes_dropped += sd_old->signed_descriptor_len;
2778 sdmap_remove(rl->desc_by_eid_map, sd_old->extra_info_digest);
2779 signed_descriptor_free(sd_old);
2782 if (!tor_digest_is_zero(ri->cache_info.extra_info_digest))
2783 sdmap_set(rl->desc_by_eid_map, ri->cache_info.extra_info_digest,
2784 &ri->cache_info);
2785 smartlist_add(rl->routers, ri);
2786 ri->cache_info.routerlist_index = smartlist_len(rl->routers) - 1;
2787 router_dir_info_changed();
2788 #ifdef DEBUG_ROUTERLIST
2789 routerlist_assert_ok(rl);
2790 #endif
2793 /** Adds the extrainfo_t <b>ei</b> to the routerlist <b>rl</b>, if there is a
2794 * corresponding router in rl-\>routers or rl-\>old_routers. Return true iff
2795 * we actually inserted <b>ei</b>. Free <b>ei</b> if it isn't inserted. */
2796 static int
2797 extrainfo_insert(routerlist_t *rl, extrainfo_t *ei)
2799 int r = 0;
2800 routerinfo_t *ri = rimap_get(rl->identity_map,
2801 ei->cache_info.identity_digest);
2802 signed_descriptor_t *sd =
2803 sdmap_get(rl->desc_by_eid_map, ei->cache_info.signed_descriptor_digest);
2804 extrainfo_t *ei_tmp;
2807 /* XXXX remove this code if it slows us down. */
2808 extrainfo_t *ei_generated = router_get_my_extrainfo();
2809 tor_assert(ei_generated != ei);
2812 if (!ri) {
2813 /* This router is unknown; we can't even verify the signature. Give up.*/
2814 goto done;
2816 if (routerinfo_incompatible_with_extrainfo(ri, ei, sd, NULL)) {
2817 goto done;
2820 /* Okay, if we make it here, we definitely have a router corresponding to
2821 * this extrainfo. */
2823 ei_tmp = eimap_set(rl->extra_info_map,
2824 ei->cache_info.signed_descriptor_digest,
2825 ei);
2826 r = 1;
2827 if (ei_tmp) {
2828 rl->extrainfo_store.bytes_dropped +=
2829 ei_tmp->cache_info.signed_descriptor_len;
2830 extrainfo_free(ei_tmp);
2833 done:
2834 if (r == 0)
2835 extrainfo_free(ei);
2837 #ifdef DEBUG_ROUTERLIST
2838 routerlist_assert_ok(rl);
2839 #endif
2840 return r;
2843 #define should_cache_old_descriptors() \
2844 directory_caches_dir_info(get_options())
2846 /** If we're a directory cache and routerlist <b>rl</b> doesn't have
2847 * a copy of router <b>ri</b> yet, add it to the list of old (not
2848 * recommended but still served) descriptors. Else free it. */
2849 static void
2850 routerlist_insert_old(routerlist_t *rl, routerinfo_t *ri)
2853 /* XXXX remove this code if it slows us down. */
2854 routerinfo_t *ri_generated = router_get_my_routerinfo();
2855 tor_assert(ri_generated != ri);
2857 tor_assert(ri->cache_info.routerlist_index == -1);
2859 if (should_cache_old_descriptors() &&
2860 ri->purpose == ROUTER_PURPOSE_GENERAL &&
2861 !sdmap_get(rl->desc_digest_map,
2862 ri->cache_info.signed_descriptor_digest)) {
2863 signed_descriptor_t *sd = signed_descriptor_from_routerinfo(ri);
2864 sdmap_set(rl->desc_digest_map, sd->signed_descriptor_digest, sd);
2865 smartlist_add(rl->old_routers, sd);
2866 sd->routerlist_index = smartlist_len(rl->old_routers)-1;
2867 if (!tor_digest_is_zero(sd->extra_info_digest))
2868 sdmap_set(rl->desc_by_eid_map, sd->extra_info_digest, sd);
2869 } else {
2870 routerinfo_free(ri);
2872 #ifdef DEBUG_ROUTERLIST
2873 routerlist_assert_ok(rl);
2874 #endif
2877 /** Remove an item <b>ri</b> from the routerlist <b>rl</b>, updating indices
2878 * as needed. If <b>idx</b> is nonnegative and smartlist_get(rl-&gt;routers,
2879 * idx) == ri, we don't need to do a linear search over the list to decide
2880 * which to remove. We fill the gap in rl-&gt;routers with a later element in
2881 * the list, if any exists. <b>ri</b> is freed.
2883 * If <b>make_old</b> is true, instead of deleting the router, we try adding
2884 * it to rl-&gt;old_routers. */
2885 void
2886 routerlist_remove(routerlist_t *rl, routerinfo_t *ri, int make_old, time_t now)
2888 routerinfo_t *ri_tmp;
2889 extrainfo_t *ei_tmp;
2890 int idx = ri->cache_info.routerlist_index;
2891 tor_assert(0 <= idx && idx < smartlist_len(rl->routers));
2892 tor_assert(smartlist_get(rl->routers, idx) == ri);
2894 /* make sure the rephist module knows that it's not running */
2895 rep_hist_note_router_unreachable(ri->cache_info.identity_digest, now);
2897 ri->cache_info.routerlist_index = -1;
2898 smartlist_del(rl->routers, idx);
2899 if (idx < smartlist_len(rl->routers)) {
2900 routerinfo_t *r = smartlist_get(rl->routers, idx);
2901 r->cache_info.routerlist_index = idx;
2904 ri_tmp = rimap_remove(rl->identity_map, ri->cache_info.identity_digest);
2905 router_dir_info_changed();
2906 tor_assert(ri_tmp == ri);
2908 if (make_old && should_cache_old_descriptors() &&
2909 ri->purpose == ROUTER_PURPOSE_GENERAL) {
2910 signed_descriptor_t *sd;
2911 sd = signed_descriptor_from_routerinfo(ri);
2912 smartlist_add(rl->old_routers, sd);
2913 sd->routerlist_index = smartlist_len(rl->old_routers)-1;
2914 sdmap_set(rl->desc_digest_map, sd->signed_descriptor_digest, sd);
2915 if (!tor_digest_is_zero(sd->extra_info_digest))
2916 sdmap_set(rl->desc_by_eid_map, sd->extra_info_digest, sd);
2917 } else {
2918 signed_descriptor_t *sd_tmp;
2919 sd_tmp = sdmap_remove(rl->desc_digest_map,
2920 ri->cache_info.signed_descriptor_digest);
2921 tor_assert(sd_tmp == &(ri->cache_info));
2922 rl->desc_store.bytes_dropped += ri->cache_info.signed_descriptor_len;
2923 ei_tmp = eimap_remove(rl->extra_info_map,
2924 ri->cache_info.extra_info_digest);
2925 if (ei_tmp) {
2926 rl->extrainfo_store.bytes_dropped +=
2927 ei_tmp->cache_info.signed_descriptor_len;
2928 extrainfo_free(ei_tmp);
2930 if (!tor_digest_is_zero(ri->cache_info.extra_info_digest))
2931 sdmap_remove(rl->desc_by_eid_map, ri->cache_info.extra_info_digest);
2932 routerinfo_free(ri);
2934 #ifdef DEBUG_ROUTERLIST
2935 routerlist_assert_ok(rl);
2936 #endif
2939 /** Remove a signed_descriptor_t <b>sd</b> from <b>rl</b>-\>old_routers, and
2940 * adjust <b>rl</b> as appropriate. <b>idx</b> is -1, or the index of
2941 * <b>sd</b>. */
2942 static void
2943 routerlist_remove_old(routerlist_t *rl, signed_descriptor_t *sd, int idx)
2945 signed_descriptor_t *sd_tmp;
2946 extrainfo_t *ei_tmp;
2947 desc_store_t *store;
2948 if (idx == -1) {
2949 idx = sd->routerlist_index;
2951 tor_assert(0 <= idx && idx < smartlist_len(rl->old_routers));
2952 /* XXXX edmanm's bridge relay triggered the following assert while
2953 * running 0.2.0.12-alpha. If anybody triggers this again, see if we
2954 * can get a backtrace. */
2955 tor_assert(smartlist_get(rl->old_routers, idx) == sd);
2956 tor_assert(idx == sd->routerlist_index);
2958 sd->routerlist_index = -1;
2959 smartlist_del(rl->old_routers, idx);
2960 if (idx < smartlist_len(rl->old_routers)) {
2961 signed_descriptor_t *d = smartlist_get(rl->old_routers, idx);
2962 d->routerlist_index = idx;
2964 sd_tmp = sdmap_remove(rl->desc_digest_map,
2965 sd->signed_descriptor_digest);
2966 tor_assert(sd_tmp == sd);
2967 store = desc_get_store(rl, sd);
2968 if (store)
2969 store->bytes_dropped += sd->signed_descriptor_len;
2971 ei_tmp = eimap_remove(rl->extra_info_map,
2972 sd->extra_info_digest);
2973 if (ei_tmp) {
2974 rl->extrainfo_store.bytes_dropped +=
2975 ei_tmp->cache_info.signed_descriptor_len;
2976 extrainfo_free(ei_tmp);
2978 if (!tor_digest_is_zero(sd->extra_info_digest))
2979 sdmap_remove(rl->desc_by_eid_map, sd->extra_info_digest);
2981 signed_descriptor_free(sd);
2982 #ifdef DEBUG_ROUTERLIST
2983 routerlist_assert_ok(rl);
2984 #endif
2987 /** Remove <b>ri_old</b> from the routerlist <b>rl</b>, and replace it with
2988 * <b>ri_new</b>, updating all index info. If <b>idx</b> is nonnegative and
2989 * smartlist_get(rl-&gt;routers, idx) == ri, we don't need to do a linear
2990 * search over the list to decide which to remove. We put ri_new in the same
2991 * index as ri_old, if possible. ri is freed as appropriate.
2993 * If should_cache_descriptors() is true, instead of deleting the router,
2994 * we add it to rl-&gt;old_routers. */
2995 static void
2996 routerlist_replace(routerlist_t *rl, routerinfo_t *ri_old,
2997 routerinfo_t *ri_new)
2999 int idx;
3000 int same_descriptors;
3002 routerinfo_t *ri_tmp;
3003 extrainfo_t *ei_tmp;
3005 /* XXXX Remove this if it turns out to slow us down. */
3006 routerinfo_t *ri_generated = router_get_my_routerinfo();
3007 tor_assert(ri_generated != ri_new);
3009 tor_assert(ri_old != ri_new);
3010 tor_assert(ri_new->cache_info.routerlist_index == -1);
3012 idx = ri_old->cache_info.routerlist_index;
3013 tor_assert(0 <= idx && idx < smartlist_len(rl->routers));
3014 tor_assert(smartlist_get(rl->routers, idx) == ri_old);
3016 router_dir_info_changed();
3017 if (idx >= 0) {
3018 smartlist_set(rl->routers, idx, ri_new);
3019 ri_old->cache_info.routerlist_index = -1;
3020 ri_new->cache_info.routerlist_index = idx;
3021 /* Check that ri_old is not in rl->routers anymore: */
3022 tor_assert( _routerlist_find_elt(rl->routers, ri_old, -1) == -1 );
3023 } else {
3024 log_warn(LD_BUG, "Appending entry from routerlist_replace.");
3025 routerlist_insert(rl, ri_new);
3026 return;
3028 if (memcmp(ri_old->cache_info.identity_digest,
3029 ri_new->cache_info.identity_digest, DIGEST_LEN)) {
3030 /* digests don't match; digestmap_set won't replace */
3031 rimap_remove(rl->identity_map, ri_old->cache_info.identity_digest);
3033 ri_tmp = rimap_set(rl->identity_map,
3034 ri_new->cache_info.identity_digest, ri_new);
3035 tor_assert(!ri_tmp || ri_tmp == ri_old);
3036 sdmap_set(rl->desc_digest_map,
3037 ri_new->cache_info.signed_descriptor_digest,
3038 &(ri_new->cache_info));
3040 if (!tor_digest_is_zero(ri_new->cache_info.extra_info_digest)) {
3041 sdmap_set(rl->desc_by_eid_map, ri_new->cache_info.extra_info_digest,
3042 &ri_new->cache_info);
3045 same_descriptors = ! memcmp(ri_old->cache_info.signed_descriptor_digest,
3046 ri_new->cache_info.signed_descriptor_digest,
3047 DIGEST_LEN);
3049 if (should_cache_old_descriptors() &&
3050 ri_old->purpose == ROUTER_PURPOSE_GENERAL &&
3051 !same_descriptors) {
3052 /* ri_old is going to become a signed_descriptor_t and go into
3053 * old_routers */
3054 signed_descriptor_t *sd = signed_descriptor_from_routerinfo(ri_old);
3055 smartlist_add(rl->old_routers, sd);
3056 sd->routerlist_index = smartlist_len(rl->old_routers)-1;
3057 sdmap_set(rl->desc_digest_map, sd->signed_descriptor_digest, sd);
3058 if (!tor_digest_is_zero(sd->extra_info_digest))
3059 sdmap_set(rl->desc_by_eid_map, sd->extra_info_digest, sd);
3060 } else {
3061 /* We're dropping ri_old. */
3062 if (!same_descriptors) {
3063 /* digests don't match; The sdmap_set above didn't replace */
3064 sdmap_remove(rl->desc_digest_map,
3065 ri_old->cache_info.signed_descriptor_digest);
3067 if (memcmp(ri_old->cache_info.extra_info_digest,
3068 ri_new->cache_info.extra_info_digest, DIGEST_LEN)) {
3069 ei_tmp = eimap_remove(rl->extra_info_map,
3070 ri_old->cache_info.extra_info_digest);
3071 if (ei_tmp) {
3072 rl->extrainfo_store.bytes_dropped +=
3073 ei_tmp->cache_info.signed_descriptor_len;
3074 extrainfo_free(ei_tmp);
3078 if (!tor_digest_is_zero(ri_old->cache_info.extra_info_digest)) {
3079 sdmap_remove(rl->desc_by_eid_map,
3080 ri_old->cache_info.extra_info_digest);
3083 rl->desc_store.bytes_dropped += ri_old->cache_info.signed_descriptor_len;
3084 routerinfo_free(ri_old);
3086 #ifdef DEBUG_ROUTERLIST
3087 routerlist_assert_ok(rl);
3088 #endif
3091 /** Extract the descriptor <b>sd</b> from old_routerlist, and re-parse
3092 * it as a fresh routerinfo_t. */
3093 static routerinfo_t *
3094 routerlist_reparse_old(routerlist_t *rl, signed_descriptor_t *sd)
3096 routerinfo_t *ri;
3097 const char *body;
3099 body = signed_descriptor_get_annotations(sd);
3101 ri = router_parse_entry_from_string(body,
3102 body+sd->signed_descriptor_len+sd->annotations_len,
3103 0, 1, NULL);
3104 if (!ri)
3105 return NULL;
3106 memcpy(&ri->cache_info, sd, sizeof(signed_descriptor_t));
3107 sd->signed_descriptor_body = NULL; /* Steal reference. */
3108 ri->cache_info.routerlist_index = -1;
3110 routerlist_remove_old(rl, sd, -1);
3112 return ri;
3115 /** Free all memory held by the routerlist module. */
3116 void
3117 routerlist_free_all(void)
3119 routerlist_free(routerlist);
3120 routerlist = NULL;
3121 if (warned_nicknames) {
3122 SMARTLIST_FOREACH(warned_nicknames, char *, cp, tor_free(cp));
3123 smartlist_free(warned_nicknames);
3124 warned_nicknames = NULL;
3126 if (trusted_dir_servers) {
3127 SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, ds,
3128 trusted_dir_server_free(ds));
3129 smartlist_free(trusted_dir_servers);
3130 trusted_dir_servers = NULL;
3132 if (trusted_dir_certs) {
3133 DIGESTMAP_FOREACH(trusted_dir_certs, key, cert_list_t *, cl) {
3134 SMARTLIST_FOREACH(cl->certs, authority_cert_t *, cert,
3135 authority_cert_free(cert));
3136 smartlist_free(cl->certs);
3137 tor_free(cl);
3138 } DIGESTMAP_FOREACH_END;
3139 digestmap_free(trusted_dir_certs, NULL);
3140 trusted_dir_certs = NULL;
3144 /** Forget that we have issued any router-related warnings, so that we'll
3145 * warn again if we see the same errors. */
3146 void
3147 routerlist_reset_warnings(void)
3149 if (!warned_nicknames)
3150 warned_nicknames = smartlist_create();
3151 SMARTLIST_FOREACH(warned_nicknames, char *, cp, tor_free(cp));
3152 smartlist_clear(warned_nicknames); /* now the list is empty. */
3154 networkstatus_reset_warnings();
3157 /** Mark the router with ID <b>digest</b> as running or non-running
3158 * in our routerlist. */
3159 void
3160 router_set_status(const char *digest, int up)
3162 routerinfo_t *router;
3163 routerstatus_t *status;
3164 tor_assert(digest);
3166 SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, d,
3167 if (!memcmp(d->digest, digest, DIGEST_LEN))
3168 d->is_running = up);
3170 router = router_get_by_digest(digest);
3171 if (router) {
3172 log_debug(LD_DIR,"Marking router '%s/%s' as %s.",
3173 router->nickname, router->address, up ? "up" : "down");
3174 if (!up && router_is_me(router) && !we_are_hibernating())
3175 log_warn(LD_NET, "We just marked ourself as down. Are your external "
3176 "addresses reachable?");
3177 router->is_running = up;
3179 status = router_get_consensus_status_by_id(digest);
3180 if (status && status->is_running != up) {
3181 status->is_running = up;
3182 control_event_networkstatus_changed_single(status);
3184 router_dir_info_changed();
3187 /** Add <b>router</b> to the routerlist, if we don't already have it. Replace
3188 * older entries (if any) with the same key. Note: Callers should not hold
3189 * their pointers to <b>router</b> if this function fails; <b>router</b>
3190 * will either be inserted into the routerlist or freed. Similarly, even
3191 * if this call succeeds, they should not hold their pointers to
3192 * <b>router</b> after subsequent calls with other routerinfo's -- they
3193 * might cause the original routerinfo to get freed.
3195 * Returns the status for the operation. Might set *<b>msg</b> if it wants
3196 * the poster of the router to know something.
3198 * If <b>from_cache</b>, this descriptor came from our disk cache. If
3199 * <b>from_fetch</b>, we received it in response to a request we made.
3200 * (If both are false, that means it was uploaded to us as an auth dir
3201 * server or via the controller.)
3203 * This function should be called *after*
3204 * routers_update_status_from_consensus_networkstatus; subsequently, you
3205 * should call router_rebuild_store and routerlist_descriptors_added.
3207 was_router_added_t
3208 router_add_to_routerlist(routerinfo_t *router, const char **msg,
3209 int from_cache, int from_fetch)
3211 const char *id_digest;
3212 int authdir = authdir_mode_handles_descs(get_options(), router->purpose);
3213 int authdir_believes_valid = 0;
3214 routerinfo_t *old_router;
3215 networkstatus_t *consensus = networkstatus_get_latest_consensus();
3216 const smartlist_t *networkstatus_v2_list = networkstatus_get_v2_list();
3217 int in_consensus = 0;
3219 tor_assert(msg);
3221 if (!routerlist)
3222 router_get_routerlist();
3224 id_digest = router->cache_info.identity_digest;
3226 old_router = router_get_by_digest(id_digest);
3228 /* Make sure that we haven't already got this exact descriptor. */
3229 if (sdmap_get(routerlist->desc_digest_map,
3230 router->cache_info.signed_descriptor_digest)) {
3231 /* If we have this descriptor already and the new descriptor is a bridge
3232 * descriptor, replace it. If we had a bridge descriptor before and the
3233 * new one is not a bridge descriptor, don't replace it. */
3235 /* Only members of routerlist->identity_map can be bridges; we don't
3236 * put bridges in old_routers. */
3237 const int was_bridge = old_router &&
3238 old_router->purpose == ROUTER_PURPOSE_BRIDGE;
3240 if (routerinfo_is_a_configured_bridge(router) &&
3241 router->purpose == ROUTER_PURPOSE_BRIDGE &&
3242 !was_bridge) {
3243 log_info(LD_DIR, "Replacing non-bridge descriptor with bridge "
3244 "descriptor for router '%s'", router->nickname);
3245 } else {
3246 log_info(LD_DIR,
3247 "Dropping descriptor that we already have for router '%s'",
3248 router->nickname);
3249 *msg = "Router descriptor was not new.";
3250 routerinfo_free(router);
3251 return ROUTER_WAS_NOT_NEW;
3255 if (authdir) {
3256 if (authdir_wants_to_reject_router(router, msg,
3257 !from_cache && !from_fetch)) {
3258 tor_assert(*msg);
3259 routerinfo_free(router);
3260 return ROUTER_AUTHDIR_REJECTS;
3262 authdir_believes_valid = router->is_valid;
3263 } else if (from_fetch) {
3264 /* Only check the descriptor digest against the network statuses when
3265 * we are receiving in response to a fetch. */
3267 if (!signed_desc_digest_is_recognized(&router->cache_info) &&
3268 !routerinfo_is_a_configured_bridge(router)) {
3269 /* We asked for it, so some networkstatus must have listed it when we
3270 * did. Save it if we're a cache in case somebody else asks for it. */
3271 log_info(LD_DIR,
3272 "Received a no-longer-recognized descriptor for router '%s'",
3273 router->nickname);
3274 *msg = "Router descriptor is not referenced by any network-status.";
3276 /* Only journal this desc if we'll be serving it. */
3277 if (!from_cache && should_cache_old_descriptors())
3278 signed_desc_append_to_journal(&router->cache_info,
3279 &routerlist->desc_store);
3280 routerlist_insert_old(routerlist, router);
3281 return ROUTER_NOT_IN_CONSENSUS_OR_NETWORKSTATUS;
3285 /* We no longer need a router with this descriptor digest. */
3286 SMARTLIST_FOREACH(networkstatus_v2_list, networkstatus_v2_t *, ns,
3288 routerstatus_t *rs =
3289 networkstatus_v2_find_entry(ns, id_digest);
3290 if (rs && !memcmp(rs->descriptor_digest,
3291 router->cache_info.signed_descriptor_digest,
3292 DIGEST_LEN))
3293 rs->need_to_mirror = 0;
3295 if (consensus) {
3296 routerstatus_t *rs = networkstatus_vote_find_entry(consensus, id_digest);
3297 if (rs && !memcmp(rs->descriptor_digest,
3298 router->cache_info.signed_descriptor_digest,
3299 DIGEST_LEN)) {
3300 in_consensus = 1;
3301 rs->need_to_mirror = 0;
3305 if (router->purpose == ROUTER_PURPOSE_GENERAL &&
3306 consensus && !in_consensus && !authdir) {
3307 /* If it's a general router not listed in the consensus, then don't
3308 * consider replacing the latest router with it. */
3309 if (!from_cache && should_cache_old_descriptors())
3310 signed_desc_append_to_journal(&router->cache_info,
3311 &routerlist->desc_store);
3312 routerlist_insert_old(routerlist, router);
3313 *msg = "Skipping router descriptor: not in consensus.";
3314 return ROUTER_NOT_IN_CONSENSUS;
3317 /* If we're reading a bridge descriptor from our cache, and we don't
3318 * recognize it as one of our currently configured bridges, drop the
3319 * descriptor. Otherwise we could end up using it as one of our entry
3320 * guards even if it isn't in our Bridge config lines. */
3321 if (router->purpose == ROUTER_PURPOSE_BRIDGE && from_cache &&
3322 !routerinfo_is_a_configured_bridge(router)) {
3323 log_info(LD_DIR, "Dropping bridge descriptor for '%s' because we have "
3324 "no bridge configured at that address.", router->nickname);
3325 *msg = "Router descriptor was not a configured bridge.";
3326 routerinfo_free(router);
3327 return ROUTER_WAS_NOT_NEW;
3330 /* If we have a router with the same identity key, choose the newer one. */
3331 if (old_router) {
3332 if (!in_consensus && (router->cache_info.published_on <=
3333 old_router->cache_info.published_on)) {
3334 /* Same key, but old. This one is not listed in the consensus. */
3335 log_debug(LD_DIR, "Not-new descriptor for router '%s'",
3336 router->nickname);
3337 /* Only journal this desc if we'll be serving it. */
3338 if (!from_cache && should_cache_old_descriptors())
3339 signed_desc_append_to_journal(&router->cache_info,
3340 &routerlist->desc_store);
3341 routerlist_insert_old(routerlist, router);
3342 *msg = "Router descriptor was not new.";
3343 return ROUTER_WAS_NOT_NEW;
3344 } else {
3345 /* Same key, and either new, or listed in the consensus. */
3346 log_debug(LD_DIR, "Replacing entry for router '%s/%s' [%s]",
3347 router->nickname, old_router->nickname,
3348 hex_str(id_digest,DIGEST_LEN));
3349 if (routers_have_same_or_addr(router, old_router)) {
3350 /* these carry over when the address and orport are unchanged. */
3351 router->last_reachable = old_router->last_reachable;
3352 router->testing_since = old_router->testing_since;
3354 routerlist_replace(routerlist, old_router, router);
3355 if (!from_cache) {
3356 signed_desc_append_to_journal(&router->cache_info,
3357 &routerlist->desc_store);
3359 directory_set_dirty();
3360 *msg = authdir_believes_valid ? "Valid server updated" :
3361 ("Invalid server updated. (This dirserver is marking your "
3362 "server as unapproved.)");
3363 return ROUTER_ADDED_SUCCESSFULLY;
3367 if (!in_consensus && from_cache &&
3368 router->cache_info.published_on < time(NULL) - OLD_ROUTER_DESC_MAX_AGE) {
3369 *msg = "Router descriptor was really old.";
3370 routerinfo_free(router);
3371 return ROUTER_WAS_NOT_NEW;
3374 /* We haven't seen a router with this identity before. Add it to the end of
3375 * the list. */
3376 routerlist_insert(routerlist, router);
3377 if (!from_cache) {
3378 signed_desc_append_to_journal(&router->cache_info,
3379 &routerlist->desc_store);
3381 directory_set_dirty();
3382 return ROUTER_ADDED_SUCCESSFULLY;
3385 /** Insert <b>ei</b> into the routerlist, or free it. Other arguments are
3386 * as for router_add_to_routerlist(). Return ROUTER_ADDED_SUCCESSFULLY iff
3387 * we actually inserted it, ROUTER_BAD_EI otherwise.
3389 was_router_added_t
3390 router_add_extrainfo_to_routerlist(extrainfo_t *ei, const char **msg,
3391 int from_cache, int from_fetch)
3393 int inserted;
3394 (void)from_fetch;
3395 if (msg) *msg = NULL;
3396 /*XXXX022 Do something with msg */
3398 inserted = extrainfo_insert(router_get_routerlist(), ei);
3400 if (inserted && !from_cache)
3401 signed_desc_append_to_journal(&ei->cache_info,
3402 &routerlist->extrainfo_store);
3404 if (inserted)
3405 return ROUTER_ADDED_SUCCESSFULLY;
3406 else
3407 return ROUTER_BAD_EI;
3410 /** Sorting helper: return &lt;0, 0, or &gt;0 depending on whether the
3411 * signed_descriptor_t* in *<b>a</b> has an identity digest preceding, equal
3412 * to, or later than that of *<b>b</b>. */
3413 static int
3414 _compare_old_routers_by_identity(const void **_a, const void **_b)
3416 int i;
3417 const signed_descriptor_t *r1 = *_a, *r2 = *_b;
3418 if ((i = memcmp(r1->identity_digest, r2->identity_digest, DIGEST_LEN)))
3419 return i;
3420 return (int)(r1->published_on - r2->published_on);
3423 /** Internal type used to represent how long an old descriptor was valid,
3424 * where it appeared in the list of old descriptors, and whether it's extra
3425 * old. Used only by routerlist_remove_old_cached_routers_with_id(). */
3426 struct duration_idx_t {
3427 int duration;
3428 int idx;
3429 int old;
3432 /** Sorting helper: compare two duration_idx_t by their duration. */
3433 static int
3434 _compare_duration_idx(const void *_d1, const void *_d2)
3436 const struct duration_idx_t *d1 = _d1;
3437 const struct duration_idx_t *d2 = _d2;
3438 return d1->duration - d2->duration;
3441 /** The range <b>lo</b> through <b>hi</b> inclusive of routerlist->old_routers
3442 * must contain routerinfo_t with the same identity and with publication time
3443 * in ascending order. Remove members from this range until there are no more
3444 * than max_descriptors_per_router() remaining. Start by removing the oldest
3445 * members from before <b>cutoff</b>, then remove members which were current
3446 * for the lowest amount of time. The order of members of old_routers at
3447 * indices <b>lo</b> or higher may be changed.
3449 static void
3450 routerlist_remove_old_cached_routers_with_id(time_t now,
3451 time_t cutoff, int lo, int hi,
3452 digestset_t *retain)
3454 int i, n = hi-lo+1;
3455 unsigned n_extra, n_rmv = 0;
3456 struct duration_idx_t *lifespans;
3457 uint8_t *rmv, *must_keep;
3458 smartlist_t *lst = routerlist->old_routers;
3459 #if 1
3460 const char *ident;
3461 tor_assert(hi < smartlist_len(lst));
3462 tor_assert(lo <= hi);
3463 ident = ((signed_descriptor_t*)smartlist_get(lst, lo))->identity_digest;
3464 for (i = lo+1; i <= hi; ++i) {
3465 signed_descriptor_t *r = smartlist_get(lst, i);
3466 tor_assert(!memcmp(ident, r->identity_digest, DIGEST_LEN));
3468 #endif
3469 /* Check whether we need to do anything at all. */
3471 int mdpr = directory_caches_dir_info(get_options()) ? 2 : 1;
3472 if (n <= mdpr)
3473 return;
3474 n_extra = n - mdpr;
3477 lifespans = tor_malloc_zero(sizeof(struct duration_idx_t)*n);
3478 rmv = tor_malloc_zero(sizeof(uint8_t)*n);
3479 must_keep = tor_malloc_zero(sizeof(uint8_t)*n);
3480 /* Set lifespans to contain the lifespan and index of each server. */
3481 /* Set rmv[i-lo]=1 if we're going to remove a server for being too old. */
3482 for (i = lo; i <= hi; ++i) {
3483 signed_descriptor_t *r = smartlist_get(lst, i);
3484 signed_descriptor_t *r_next;
3485 lifespans[i-lo].idx = i;
3486 if (r->last_listed_as_valid_until >= now ||
3487 (retain && digestset_isin(retain, r->signed_descriptor_digest))) {
3488 must_keep[i-lo] = 1;
3490 if (i < hi) {
3491 r_next = smartlist_get(lst, i+1);
3492 tor_assert(r->published_on <= r_next->published_on);
3493 lifespans[i-lo].duration = (int)(r_next->published_on - r->published_on);
3494 } else {
3495 r_next = NULL;
3496 lifespans[i-lo].duration = INT_MAX;
3498 if (!must_keep[i-lo] && r->published_on < cutoff && n_rmv < n_extra) {
3499 ++n_rmv;
3500 lifespans[i-lo].old = 1;
3501 rmv[i-lo] = 1;
3505 if (n_rmv < n_extra) {
3507 * We aren't removing enough servers for being old. Sort lifespans by
3508 * the duration of liveness, and remove the ones we're not already going to
3509 * remove based on how long they were alive.
3511 qsort(lifespans, n, sizeof(struct duration_idx_t), _compare_duration_idx);
3512 for (i = 0; i < n && n_rmv < n_extra; ++i) {
3513 if (!must_keep[lifespans[i].idx-lo] && !lifespans[i].old) {
3514 rmv[lifespans[i].idx-lo] = 1;
3515 ++n_rmv;
3520 i = hi;
3521 do {
3522 if (rmv[i-lo])
3523 routerlist_remove_old(routerlist, smartlist_get(lst, i), i);
3524 } while (--i >= lo);
3525 tor_free(must_keep);
3526 tor_free(rmv);
3527 tor_free(lifespans);
3530 /** Deactivate any routers from the routerlist that are more than
3531 * ROUTER_MAX_AGE seconds old and not recommended by any networkstatuses;
3532 * remove old routers from the list of cached routers if we have too many.
3534 void
3535 routerlist_remove_old_routers(void)
3537 int i, hi=-1;
3538 const char *cur_id = NULL;
3539 time_t now = time(NULL);
3540 time_t cutoff;
3541 routerinfo_t *router;
3542 signed_descriptor_t *sd;
3543 digestset_t *retain;
3544 int caches = directory_caches_dir_info(get_options());
3545 const networkstatus_t *consensus = networkstatus_get_latest_consensus();
3546 const smartlist_t *networkstatus_v2_list = networkstatus_get_v2_list();
3547 int have_enough_v2;
3549 trusted_dirs_remove_old_certs();
3551 if (!routerlist || !consensus)
3552 return;
3554 // routerlist_assert_ok(routerlist);
3556 /* We need to guess how many router descriptors we will wind up wanting to
3557 retain, so that we can be sure to allocate a large enough Bloom filter
3558 to hold the digest set. Overestimating is fine; underestimating is bad.
3561 /* We'll probably retain everything in the consensus. */
3562 int n_max_retain = smartlist_len(consensus->routerstatus_list);
3563 if (caches && networkstatus_v2_list) {
3564 /* If we care about v2 statuses, we'll retain at most as many as are
3565 listed any of the v2 statues. This will be at least the length of
3566 the largest v2 networkstatus, and in the worst case, this set will be
3567 equal to the sum of the lengths of all v2 consensuses. Take the
3568 worst case.
3570 SMARTLIST_FOREACH(networkstatus_v2_list, networkstatus_v2_t *, ns,
3571 n_max_retain += smartlist_len(ns->entries));
3573 retain = digestset_new(n_max_retain);
3576 cutoff = now - OLD_ROUTER_DESC_MAX_AGE;
3577 /* Build a list of all the descriptors that _anybody_ lists. */
3578 if (caches && networkstatus_v2_list) {
3579 SMARTLIST_FOREACH(networkstatus_v2_list, networkstatus_v2_t *, ns,
3581 /* XXXX The inner loop here gets pretty expensive, and actually shows up
3582 * on some profiles. It may be the reason digestmap_set shows up in
3583 * profiles too. If instead we kept a per-descriptor digest count of
3584 * how many networkstatuses recommended each descriptor, and changed
3585 * that only when the networkstatuses changed, that would be a speed
3586 * improvement, possibly 1-4% if it also removes digestmap_set from the
3587 * profile. Not worth it for 0.1.2.x, though. The new directory
3588 * system will obsolete this whole thing in 0.2.0.x. */
3589 SMARTLIST_FOREACH(ns->entries, routerstatus_t *, rs,
3590 if (rs->published_on >= cutoff)
3591 digestset_add(retain, rs->descriptor_digest));
3595 /* Retain anything listed in the consensus. */
3596 if (consensus) {
3597 SMARTLIST_FOREACH(consensus->routerstatus_list, routerstatus_t *, rs,
3598 if (rs->published_on >= cutoff)
3599 digestset_add(retain, rs->descriptor_digest));
3602 /* If we have a consensus, and nearly as many v2 networkstatuses as we want,
3603 * we should consider pruning current routers that are too old and that
3604 * nobody recommends. (If we don't have a consensus or enough v2
3605 * networkstatuses, then we should get more before we decide to kill
3606 * routers.) */
3607 /* we set this to true iff we don't care about v2 info, or we have enough. */
3608 have_enough_v2 = !caches ||
3609 (networkstatus_v2_list &&
3610 smartlist_len(networkstatus_v2_list) > get_n_v2_authorities() / 2);
3612 if (have_enough_v2 && consensus) {
3613 cutoff = now - ROUTER_MAX_AGE;
3614 /* Remove too-old unrecommended members of routerlist->routers. */
3615 for (i = 0; i < smartlist_len(routerlist->routers); ++i) {
3616 router = smartlist_get(routerlist->routers, i);
3617 if (router->cache_info.published_on <= cutoff &&
3618 router->cache_info.last_listed_as_valid_until < now &&
3619 !digestset_isin(retain,
3620 router->cache_info.signed_descriptor_digest)) {
3621 /* Too old: remove it. (If we're a cache, just move it into
3622 * old_routers.) */
3623 log_info(LD_DIR,
3624 "Forgetting obsolete (too old) routerinfo for router '%s'",
3625 router->nickname);
3626 routerlist_remove(routerlist, router, 1, now);
3627 i--;
3632 //routerlist_assert_ok(routerlist);
3634 /* Remove far-too-old members of routerlist->old_routers. */
3635 cutoff = now - OLD_ROUTER_DESC_MAX_AGE;
3636 for (i = 0; i < smartlist_len(routerlist->old_routers); ++i) {
3637 sd = smartlist_get(routerlist->old_routers, i);
3638 if (sd->published_on <= cutoff &&
3639 sd->last_listed_as_valid_until < now &&
3640 !digestset_isin(retain, sd->signed_descriptor_digest)) {
3641 /* Too old. Remove it. */
3642 routerlist_remove_old(routerlist, sd, i--);
3646 //routerlist_assert_ok(routerlist);
3648 log_info(LD_DIR, "We have %d live routers and %d old router descriptors.",
3649 smartlist_len(routerlist->routers),
3650 smartlist_len(routerlist->old_routers));
3652 /* Now we might have to look at routerlist->old_routers for extraneous
3653 * members. (We'd keep all the members if we could, but we need to save
3654 * space.) First, check whether we have too many router descriptors, total.
3655 * We're okay with having too many for some given router, so long as the
3656 * total number doesn't approach max_descriptors_per_router()*len(router).
3658 if (smartlist_len(routerlist->old_routers) <
3659 smartlist_len(routerlist->routers))
3660 goto done;
3662 /* Sort by identity, then fix indices. */
3663 smartlist_sort(routerlist->old_routers, _compare_old_routers_by_identity);
3664 /* Fix indices. */
3665 for (i = 0; i < smartlist_len(routerlist->old_routers); ++i) {
3666 signed_descriptor_t *r = smartlist_get(routerlist->old_routers, i);
3667 r->routerlist_index = i;
3670 /* Iterate through the list from back to front, so when we remove descriptors
3671 * we don't mess up groups we haven't gotten to. */
3672 for (i = smartlist_len(routerlist->old_routers)-1; i >= 0; --i) {
3673 signed_descriptor_t *r = smartlist_get(routerlist->old_routers, i);
3674 if (!cur_id) {
3675 cur_id = r->identity_digest;
3676 hi = i;
3678 if (memcmp(cur_id, r->identity_digest, DIGEST_LEN)) {
3679 routerlist_remove_old_cached_routers_with_id(now,
3680 cutoff, i+1, hi, retain);
3681 cur_id = r->identity_digest;
3682 hi = i;
3685 if (hi>=0)
3686 routerlist_remove_old_cached_routers_with_id(now, cutoff, 0, hi, retain);
3687 //routerlist_assert_ok(routerlist);
3689 done:
3690 digestset_free(retain);
3691 router_rebuild_store(RRS_DONT_REMOVE_OLD, &routerlist->desc_store);
3692 router_rebuild_store(RRS_DONT_REMOVE_OLD,&routerlist->extrainfo_store);
3695 /** We just added a new set of descriptors. Take whatever extra steps
3696 * we need. */
3697 void
3698 routerlist_descriptors_added(smartlist_t *sl, int from_cache)
3700 tor_assert(sl);
3701 control_event_descriptors_changed(sl);
3702 SMARTLIST_FOREACH_BEGIN(sl, routerinfo_t *, ri) {
3703 if (ri->purpose == ROUTER_PURPOSE_BRIDGE)
3704 learned_bridge_descriptor(ri, from_cache);
3705 if (ri->needs_retest_if_added) {
3706 ri->needs_retest_if_added = 0;
3707 dirserv_single_reachability_test(approx_time(), ri);
3709 } SMARTLIST_FOREACH_END(ri);
3713 * Code to parse a single router descriptor and insert it into the
3714 * routerlist. Return -1 if the descriptor was ill-formed; 0 if the
3715 * descriptor was well-formed but could not be added; and 1 if the
3716 * descriptor was added.
3718 * If we don't add it and <b>msg</b> is not NULL, then assign to
3719 * *<b>msg</b> a static string describing the reason for refusing the
3720 * descriptor.
3722 * This is used only by the controller.
3725 router_load_single_router(const char *s, uint8_t purpose, int cache,
3726 const char **msg)
3728 routerinfo_t *ri;
3729 was_router_added_t r;
3730 smartlist_t *lst;
3731 char annotation_buf[ROUTER_ANNOTATION_BUF_LEN];
3732 tor_assert(msg);
3733 *msg = NULL;
3735 tor_snprintf(annotation_buf, sizeof(annotation_buf),
3736 "@source controller\n"
3737 "@purpose %s\n", router_purpose_to_string(purpose));
3739 if (!(ri = router_parse_entry_from_string(s, NULL, 1, 0, annotation_buf))) {
3740 log_warn(LD_DIR, "Error parsing router descriptor; dropping.");
3741 *msg = "Couldn't parse router descriptor.";
3742 return -1;
3744 tor_assert(ri->purpose == purpose);
3745 if (router_is_me(ri)) {
3746 log_warn(LD_DIR, "Router's identity key matches mine; dropping.");
3747 *msg = "Router's identity key matches mine.";
3748 routerinfo_free(ri);
3749 return 0;
3752 if (!cache) /* obey the preference of the controller */
3753 ri->cache_info.do_not_cache = 1;
3755 lst = smartlist_create();
3756 smartlist_add(lst, ri);
3757 routers_update_status_from_consensus_networkstatus(lst, 0);
3759 r = router_add_to_routerlist(ri, msg, 0, 0);
3760 if (!WRA_WAS_ADDED(r)) {
3761 /* we've already assigned to *msg now, and ri is already freed */
3762 tor_assert(*msg);
3763 if (r == ROUTER_AUTHDIR_REJECTS)
3764 log_warn(LD_DIR, "Couldn't add router to list: %s Dropping.", *msg);
3765 smartlist_free(lst);
3766 return 0;
3767 } else {
3768 routerlist_descriptors_added(lst, 0);
3769 smartlist_free(lst);
3770 log_debug(LD_DIR, "Added router to list");
3771 return 1;
3775 /** Given a string <b>s</b> containing some routerdescs, parse it and put the
3776 * routers into our directory. If saved_location is SAVED_NOWHERE, the routers
3777 * are in response to a query to the network: cache them by adding them to
3778 * the journal.
3780 * Return the number of routers actually added.
3782 * If <b>requested_fingerprints</b> is provided, it must contain a list of
3783 * uppercased fingerprints. Do not update any router whose
3784 * fingerprint is not on the list; after updating a router, remove its
3785 * fingerprint from the list.
3787 * If <b>descriptor_digests</b> is non-zero, then the requested_fingerprints
3788 * are descriptor digests. Otherwise they are identity digests.
3791 router_load_routers_from_string(const char *s, const char *eos,
3792 saved_location_t saved_location,
3793 smartlist_t *requested_fingerprints,
3794 int descriptor_digests,
3795 const char *prepend_annotations)
3797 smartlist_t *routers = smartlist_create(), *changed = smartlist_create();
3798 char fp[HEX_DIGEST_LEN+1];
3799 const char *msg;
3800 int from_cache = (saved_location != SAVED_NOWHERE);
3801 int allow_annotations = (saved_location != SAVED_NOWHERE);
3802 int any_changed = 0;
3804 router_parse_list_from_string(&s, eos, routers, saved_location, 0,
3805 allow_annotations, prepend_annotations);
3807 routers_update_status_from_consensus_networkstatus(routers, !from_cache);
3809 log_info(LD_DIR, "%d elements to add", smartlist_len(routers));
3811 SMARTLIST_FOREACH_BEGIN(routers, routerinfo_t *, ri) {
3812 was_router_added_t r;
3813 char d[DIGEST_LEN];
3814 if (requested_fingerprints) {
3815 base16_encode(fp, sizeof(fp), descriptor_digests ?
3816 ri->cache_info.signed_descriptor_digest :
3817 ri->cache_info.identity_digest,
3818 DIGEST_LEN);
3819 if (smartlist_string_isin(requested_fingerprints, fp)) {
3820 smartlist_string_remove(requested_fingerprints, fp);
3821 } else {
3822 char *requested =
3823 smartlist_join_strings(requested_fingerprints," ",0,NULL);
3824 log_warn(LD_DIR,
3825 "We received a router descriptor with a fingerprint (%s) "
3826 "that we never requested. (We asked for: %s.) Dropping.",
3827 fp, requested);
3828 tor_free(requested);
3829 routerinfo_free(ri);
3830 continue;
3834 memcpy(d, ri->cache_info.signed_descriptor_digest, DIGEST_LEN);
3835 r = router_add_to_routerlist(ri, &msg, from_cache, !from_cache);
3836 if (WRA_WAS_ADDED(r)) {
3837 any_changed++;
3838 smartlist_add(changed, ri);
3839 routerlist_descriptors_added(changed, from_cache);
3840 smartlist_clear(changed);
3841 } else if (WRA_WAS_REJECTED(r)) {
3842 download_status_t *dl_status;
3843 dl_status = router_get_dl_status_by_descriptor_digest(d);
3844 if (dl_status) {
3845 log_info(LD_GENERAL, "Marking router %s as never downloadable",
3846 hex_str(d, DIGEST_LEN));
3847 download_status_mark_impossible(dl_status);
3850 } SMARTLIST_FOREACH_END(ri);
3852 routerlist_assert_ok(routerlist);
3854 if (any_changed)
3855 router_rebuild_store(0, &routerlist->desc_store);
3857 smartlist_free(routers);
3858 smartlist_free(changed);
3860 return any_changed;
3863 /** Parse one or more extrainfos from <b>s</b> (ending immediately before
3864 * <b>eos</b> if <b>eos</b> is present). Other arguments are as for
3865 * router_load_routers_from_string(). */
3866 void
3867 router_load_extrainfo_from_string(const char *s, const char *eos,
3868 saved_location_t saved_location,
3869 smartlist_t *requested_fingerprints,
3870 int descriptor_digests)
3872 smartlist_t *extrainfo_list = smartlist_create();
3873 const char *msg;
3874 int from_cache = (saved_location != SAVED_NOWHERE);
3876 router_parse_list_from_string(&s, eos, extrainfo_list, saved_location, 1, 0,
3877 NULL);
3879 log_info(LD_DIR, "%d elements to add", smartlist_len(extrainfo_list));
3881 SMARTLIST_FOREACH(extrainfo_list, extrainfo_t *, ei, {
3882 was_router_added_t added =
3883 router_add_extrainfo_to_routerlist(ei, &msg, from_cache, !from_cache);
3884 if (WRA_WAS_ADDED(added) && requested_fingerprints) {
3885 char fp[HEX_DIGEST_LEN+1];
3886 base16_encode(fp, sizeof(fp), descriptor_digests ?
3887 ei->cache_info.signed_descriptor_digest :
3888 ei->cache_info.identity_digest,
3889 DIGEST_LEN);
3890 smartlist_string_remove(requested_fingerprints, fp);
3891 /* We silently let people stuff us with extrainfos we didn't ask for,
3892 * so long as we would have wanted them anyway. Since we always fetch
3893 * all the extrainfos we want, and we never actually act on them
3894 * inside Tor, this should be harmless. */
3898 routerlist_assert_ok(routerlist);
3899 router_rebuild_store(0, &router_get_routerlist()->extrainfo_store);
3901 smartlist_free(extrainfo_list);
3904 /** Return true iff any networkstatus includes a descriptor whose digest
3905 * is that of <b>desc</b>. */
3906 static int
3907 signed_desc_digest_is_recognized(signed_descriptor_t *desc)
3909 routerstatus_t *rs;
3910 networkstatus_t *consensus = networkstatus_get_latest_consensus();
3911 int caches = directory_caches_dir_info(get_options());
3912 const smartlist_t *networkstatus_v2_list = networkstatus_get_v2_list();
3914 if (consensus) {
3915 rs = networkstatus_vote_find_entry(consensus, desc->identity_digest);
3916 if (rs && !memcmp(rs->descriptor_digest,
3917 desc->signed_descriptor_digest, DIGEST_LEN))
3918 return 1;
3920 if (caches && networkstatus_v2_list) {
3921 SMARTLIST_FOREACH(networkstatus_v2_list, networkstatus_v2_t *, ns,
3923 if (!(rs = networkstatus_v2_find_entry(ns, desc->identity_digest)))
3924 continue;
3925 if (!memcmp(rs->descriptor_digest,
3926 desc->signed_descriptor_digest, DIGEST_LEN))
3927 return 1;
3930 return 0;
3933 /** Clear all our timeouts for fetching v2 and v3 directory stuff, and then
3934 * give it all a try again. */
3935 void
3936 routerlist_retry_directory_downloads(time_t now)
3938 router_reset_status_download_failures();
3939 router_reset_descriptor_download_failures();
3940 update_networkstatus_downloads(now);
3941 update_router_descriptor_downloads(now);
3944 /** Return 1 if all running sufficiently-stable routers will reject
3945 * addr:port, return 0 if any might accept it. */
3947 router_exit_policy_all_routers_reject(uint32_t addr, uint16_t port,
3948 int need_uptime)
3950 addr_policy_result_t r;
3951 if (!routerlist) return 1;
3953 SMARTLIST_FOREACH(routerlist->routers, routerinfo_t *, router,
3955 if (router->is_running &&
3956 !router_is_unreliable(router, need_uptime, 0, 0)) {
3957 r = compare_addr_to_addr_policy(addr, port, router->exit_policy);
3958 if (r != ADDR_POLICY_REJECTED && r != ADDR_POLICY_PROBABLY_REJECTED)
3959 return 0; /* this one could be ok. good enough. */
3962 return 1; /* all will reject. */
3965 /** Return true iff <b>router</b> does not permit exit streams.
3968 router_exit_policy_rejects_all(routerinfo_t *router)
3970 return router->policy_is_reject_star;
3973 /** Add to the list of authoritative directory servers one at
3974 * <b>address</b>:<b>port</b>, with identity key <b>digest</b>. If
3975 * <b>address</b> is NULL, add ourself. Return the new trusted directory
3976 * server entry on success or NULL if we couldn't add it. */
3977 trusted_dir_server_t *
3978 add_trusted_dir_server(const char *nickname, const char *address,
3979 uint16_t dir_port, uint16_t or_port,
3980 const char *digest, const char *v3_auth_digest,
3981 authority_type_t type)
3983 trusted_dir_server_t *ent;
3984 uint32_t a;
3985 char *hostname = NULL;
3986 size_t dlen;
3987 if (!trusted_dir_servers)
3988 trusted_dir_servers = smartlist_create();
3990 if (!address) { /* The address is us; we should guess. */
3991 if (resolve_my_address(LOG_WARN, get_options(), &a, &hostname) < 0) {
3992 log_warn(LD_CONFIG,
3993 "Couldn't find a suitable address when adding ourself as a "
3994 "trusted directory server.");
3995 return NULL;
3997 } else {
3998 if (tor_lookup_hostname(address, &a)) {
3999 log_warn(LD_CONFIG,
4000 "Unable to lookup address for directory server at '%s'",
4001 address);
4002 return NULL;
4004 hostname = tor_strdup(address);
4007 ent = tor_malloc_zero(sizeof(trusted_dir_server_t));
4008 ent->nickname = nickname ? tor_strdup(nickname) : NULL;
4009 ent->address = hostname;
4010 ent->addr = a;
4011 ent->dir_port = dir_port;
4012 ent->or_port = or_port;
4013 ent->is_running = 1;
4014 ent->type = type;
4015 memcpy(ent->digest, digest, DIGEST_LEN);
4016 if (v3_auth_digest && (type & V3_AUTHORITY))
4017 memcpy(ent->v3_identity_digest, v3_auth_digest, DIGEST_LEN);
4019 dlen = 64 + strlen(hostname) + (nickname?strlen(nickname):0);
4020 ent->description = tor_malloc(dlen);
4021 if (nickname)
4022 tor_snprintf(ent->description, dlen, "directory server \"%s\" at %s:%d",
4023 nickname, hostname, (int)dir_port);
4024 else
4025 tor_snprintf(ent->description, dlen, "directory server at %s:%d",
4026 hostname, (int)dir_port);
4028 ent->fake_status.addr = ent->addr;
4029 memcpy(ent->fake_status.identity_digest, digest, DIGEST_LEN);
4030 if (nickname)
4031 strlcpy(ent->fake_status.nickname, nickname,
4032 sizeof(ent->fake_status.nickname));
4033 else
4034 ent->fake_status.nickname[0] = '\0';
4035 ent->fake_status.dir_port = ent->dir_port;
4036 ent->fake_status.or_port = ent->or_port;
4038 if (ent->or_port)
4039 ent->fake_status.version_supports_begindir = 1;
4041 ent->fake_status.version_supports_conditional_consensus = 1;
4043 smartlist_add(trusted_dir_servers, ent);
4044 router_dir_info_changed();
4045 return ent;
4048 /** Free storage held in <b>cert</b>. */
4049 void
4050 authority_cert_free(authority_cert_t *cert)
4052 if (!cert)
4053 return;
4055 tor_free(cert->cache_info.signed_descriptor_body);
4056 crypto_free_pk_env(cert->signing_key);
4057 crypto_free_pk_env(cert->identity_key);
4059 tor_free(cert);
4062 /** Free storage held in <b>ds</b>. */
4063 static void
4064 trusted_dir_server_free(trusted_dir_server_t *ds)
4066 if (!ds)
4067 return;
4069 tor_free(ds->nickname);
4070 tor_free(ds->description);
4071 tor_free(ds->address);
4072 tor_free(ds);
4075 /** Remove all members from the list of trusted dir servers. */
4076 void
4077 clear_trusted_dir_servers(void)
4079 if (trusted_dir_servers) {
4080 SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, ent,
4081 trusted_dir_server_free(ent));
4082 smartlist_clear(trusted_dir_servers);
4083 } else {
4084 trusted_dir_servers = smartlist_create();
4086 router_dir_info_changed();
4089 /** Return 1 if any trusted dir server supports v1 directories,
4090 * else return 0. */
4092 any_trusted_dir_is_v1_authority(void)
4094 if (trusted_dir_servers)
4095 return get_n_authorities(V1_AUTHORITY) > 0;
4097 return 0;
4100 /** For every current directory connection whose purpose is <b>purpose</b>,
4101 * and where the resource being downloaded begins with <b>prefix</b>, split
4102 * rest of the resource into base16 fingerprints, decode them, and set the
4103 * corresponding elements of <b>result</b> to a nonzero value. */
4104 static void
4105 list_pending_downloads(digestmap_t *result,
4106 int purpose, const char *prefix)
4108 const size_t p_len = strlen(prefix);
4109 smartlist_t *tmp = smartlist_create();
4110 smartlist_t *conns = get_connection_array();
4112 tor_assert(result);
4114 SMARTLIST_FOREACH(conns, connection_t *, conn,
4116 if (conn->type == CONN_TYPE_DIR &&
4117 conn->purpose == purpose &&
4118 !conn->marked_for_close) {
4119 const char *resource = TO_DIR_CONN(conn)->requested_resource;
4120 if (!strcmpstart(resource, prefix))
4121 dir_split_resource_into_fingerprints(resource + p_len,
4122 tmp, NULL, DSR_HEX);
4125 SMARTLIST_FOREACH(tmp, char *, d,
4127 digestmap_set(result, d, (void*)1);
4128 tor_free(d);
4130 smartlist_free(tmp);
4133 /** For every router descriptor (or extra-info document if <b>extrainfo</b> is
4134 * true) we are currently downloading by descriptor digest, set result[d] to
4135 * (void*)1. */
4136 static void
4137 list_pending_descriptor_downloads(digestmap_t *result, int extrainfo)
4139 int purpose =
4140 extrainfo ? DIR_PURPOSE_FETCH_EXTRAINFO : DIR_PURPOSE_FETCH_SERVERDESC;
4141 list_pending_downloads(result, purpose, "d/");
4144 /** Launch downloads for all the descriptors whose digests are listed
4145 * as digests[i] for lo <= i < hi. (Lo and hi may be out of range.)
4146 * If <b>source</b> is given, download from <b>source</b>; otherwise,
4147 * download from an appropriate random directory server.
4149 static void
4150 initiate_descriptor_downloads(routerstatus_t *source,
4151 int purpose,
4152 smartlist_t *digests,
4153 int lo, int hi, int pds_flags)
4155 int i, n = hi-lo;
4156 char *resource, *cp;
4157 size_t r_len;
4158 if (n <= 0)
4159 return;
4160 if (lo < 0)
4161 lo = 0;
4162 if (hi > smartlist_len(digests))
4163 hi = smartlist_len(digests);
4165 r_len = 8 + (HEX_DIGEST_LEN+1)*n;
4166 cp = resource = tor_malloc(r_len);
4167 memcpy(cp, "d/", 2);
4168 cp += 2;
4169 for (i = lo; i < hi; ++i) {
4170 base16_encode(cp, r_len-(cp-resource),
4171 smartlist_get(digests,i), DIGEST_LEN);
4172 cp += HEX_DIGEST_LEN;
4173 *cp++ = '+';
4175 memcpy(cp-1, ".z", 3);
4177 if (source) {
4178 /* We know which authority we want. */
4179 directory_initiate_command_routerstatus(source, purpose,
4180 ROUTER_PURPOSE_GENERAL,
4181 0, /* not private */
4182 resource, NULL, 0, 0);
4183 } else {
4184 directory_get_from_dirserver(purpose, ROUTER_PURPOSE_GENERAL, resource,
4185 pds_flags);
4187 tor_free(resource);
4190 /** Return 0 if this routerstatus is obsolete, too new, isn't
4191 * running, or otherwise not a descriptor that we would make any
4192 * use of even if we had it. Else return 1. */
4193 static INLINE int
4194 client_would_use_router(routerstatus_t *rs, time_t now, or_options_t *options)
4196 if (!rs->is_running && !options->FetchUselessDescriptors) {
4197 /* If we had this router descriptor, we wouldn't even bother using it.
4198 * But, if we want to have a complete list, fetch it anyway. */
4199 return 0;
4201 if (rs->published_on + options->TestingEstimatedDescriptorPropagationTime
4202 > now) {
4203 /* Most caches probably don't have this descriptor yet. */
4204 return 0;
4206 if (rs->published_on + OLD_ROUTER_DESC_MAX_AGE < now) {
4207 /* We'd drop it immediately for being too old. */
4208 return 0;
4210 return 1;
4213 /** Max amount of hashes to download per request.
4214 * Since squid does not like URLs >= 4096 bytes we limit it to 96.
4215 * 4096 - strlen(http://255.255.255.255/tor/server/d/.z) == 4058
4216 * 4058/41 (40 for the hash and 1 for the + that separates them) => 98
4217 * So use 96 because it's a nice number.
4219 #define MAX_DL_PER_REQUEST 96
4220 /** Don't split our requests so finely that we are requesting fewer than
4221 * this number per server. */
4222 #define MIN_DL_PER_REQUEST 4
4223 /** To prevent a single screwy cache from confusing us by selective reply,
4224 * try to split our requests into at least this many requests. */
4225 #define MIN_REQUESTS 3
4226 /** If we want fewer than this many descriptors, wait until we
4227 * want more, or until MAX_CLIENT_INTERVAL_WITHOUT_REQUEST has
4228 * passed. */
4229 #define MAX_DL_TO_DELAY 16
4230 /** When directory clients have only a few servers to request, they batch
4231 * them until they have more, or until this amount of time has passed. */
4232 #define MAX_CLIENT_INTERVAL_WITHOUT_REQUEST (10*60)
4234 /** Given a list of router descriptor digests in <b>downloadable</b>, decide
4235 * whether to delay fetching until we have more. If we don't want to delay,
4236 * launch one or more requests to the appropriate directory authorities. */
4237 static void
4238 launch_router_descriptor_downloads(smartlist_t *downloadable,
4239 routerstatus_t *source, time_t now)
4241 int should_delay = 0, n_downloadable;
4242 or_options_t *options = get_options();
4244 n_downloadable = smartlist_len(downloadable);
4245 if (!directory_fetches_dir_info_early(options)) {
4246 if (n_downloadable >= MAX_DL_TO_DELAY) {
4247 log_debug(LD_DIR,
4248 "There are enough downloadable routerdescs to launch requests.");
4249 should_delay = 0;
4250 } else {
4251 should_delay = (last_routerdesc_download_attempted +
4252 MAX_CLIENT_INTERVAL_WITHOUT_REQUEST) > now;
4253 if (!should_delay && n_downloadable) {
4254 if (last_routerdesc_download_attempted) {
4255 log_info(LD_DIR,
4256 "There are not many downloadable routerdescs, but we've "
4257 "been waiting long enough (%d seconds). Downloading.",
4258 (int)(now-last_routerdesc_download_attempted));
4259 } else {
4260 log_info(LD_DIR,
4261 "There are not many downloadable routerdescs, but we haven't "
4262 "tried downloading descriptors recently. Downloading.");
4267 /* XXX should we consider having even the dir mirrors delay
4268 * a little bit, so we don't load the authorities as much? -RD
4269 * I don't think so. If we do, clients that want those descriptors may
4270 * not actually find them if the caches haven't got them yet. -NM
4273 if (! should_delay && n_downloadable) {
4274 int i, n_per_request;
4275 const char *req_plural = "", *rtr_plural = "";
4276 int pds_flags = PDS_RETRY_IF_NO_SERVERS;
4277 if (! authdir_mode_any_nonhidserv(options)) {
4278 /* If we wind up going to the authorities, we want to only open one
4279 * connection to each authority at a time, so that we don't overload
4280 * them. We do this by setting PDS_NO_EXISTING_SERVERDESC_FETCH
4281 * regardless of whether we're a cache or not; it gets ignored if we're
4282 * not calling router_pick_trusteddirserver.
4284 * Setting this flag can make initiate_descriptor_downloads() ignore
4285 * requests. We need to make sure that we do in fact call
4286 * update_router_descriptor_downloads() later on, once the connections
4287 * have succeeded or failed.
4289 pds_flags |= PDS_NO_EXISTING_SERVERDESC_FETCH;
4292 n_per_request = CEIL_DIV(n_downloadable, MIN_REQUESTS);
4293 if (n_per_request > MAX_DL_PER_REQUEST)
4294 n_per_request = MAX_DL_PER_REQUEST;
4295 if (n_per_request < MIN_DL_PER_REQUEST)
4296 n_per_request = MIN_DL_PER_REQUEST;
4298 if (n_downloadable > n_per_request)
4299 req_plural = rtr_plural = "s";
4300 else if (n_downloadable > 1)
4301 rtr_plural = "s";
4303 log_info(LD_DIR,
4304 "Launching %d request%s for %d router%s, %d at a time",
4305 CEIL_DIV(n_downloadable, n_per_request),
4306 req_plural, n_downloadable, rtr_plural, n_per_request);
4307 smartlist_sort_digests(downloadable);
4308 for (i=0; i < n_downloadable; i += n_per_request) {
4309 initiate_descriptor_downloads(source, DIR_PURPOSE_FETCH_SERVERDESC,
4310 downloadable, i, i+n_per_request,
4311 pds_flags);
4313 last_routerdesc_download_attempted = now;
4317 /** Launch downloads for router status as needed, using the strategy used by
4318 * authorities and caches: based on the v2 networkstatuses we have, download
4319 * every descriptor we don't have but would serve, from a random authority
4320 * that lists it. */
4321 static void
4322 update_router_descriptor_cache_downloads_v2(time_t now)
4324 smartlist_t **downloadable; /* For each authority, what can we dl from it? */
4325 smartlist_t **download_from; /* ... and, what will we dl from it? */
4326 digestmap_t *map; /* Which descs are in progress, or assigned? */
4327 int i, j, n;
4328 int n_download;
4329 or_options_t *options = get_options();
4330 const smartlist_t *networkstatus_v2_list = networkstatus_get_v2_list();
4332 if (! directory_fetches_dir_info_early(options)) {
4333 log_warn(LD_BUG, "Called update_router_descriptor_cache_downloads_v2() "
4334 "on a non-dir-mirror?");
4337 if (!networkstatus_v2_list || !smartlist_len(networkstatus_v2_list))
4338 return;
4340 map = digestmap_new();
4341 n = smartlist_len(networkstatus_v2_list);
4343 downloadable = tor_malloc_zero(sizeof(smartlist_t*) * n);
4344 download_from = tor_malloc_zero(sizeof(smartlist_t*) * n);
4346 /* Set map[d]=1 for the digest of every descriptor that we are currently
4347 * downloading. */
4348 list_pending_descriptor_downloads(map, 0);
4350 /* For the digest of every descriptor that we don't have, and that we aren't
4351 * downloading, add d to downloadable[i] if the i'th networkstatus knows
4352 * about that descriptor, and we haven't already failed to get that
4353 * descriptor from the corresponding authority.
4355 n_download = 0;
4356 SMARTLIST_FOREACH(networkstatus_v2_list, networkstatus_v2_t *, ns,
4358 trusted_dir_server_t *ds;
4359 smartlist_t *dl;
4360 dl = downloadable[ns_sl_idx] = smartlist_create();
4361 download_from[ns_sl_idx] = smartlist_create();
4362 if (ns->published_on + MAX_NETWORKSTATUS_AGE+10*60 < now) {
4363 /* Don't download if the networkstatus is almost ancient. */
4364 /* Actually, I suspect what's happening here is that we ask
4365 * for the descriptor when we have a given networkstatus,
4366 * and then we get a newer networkstatus, and then we receive
4367 * the descriptor. Having a networkstatus actually expire is
4368 * probably a rare event, and we'll probably be happiest if
4369 * we take this clause out. -RD */
4370 continue;
4373 /* Don't try dirservers that we think are down -- we might have
4374 * just tried them and just marked them as down. */
4375 ds = router_get_trusteddirserver_by_digest(ns->identity_digest);
4376 if (ds && !ds->is_running)
4377 continue;
4379 SMARTLIST_FOREACH(ns->entries, routerstatus_t * , rs,
4381 if (!rs->need_to_mirror)
4382 continue;
4383 if (router_get_by_descriptor_digest(rs->descriptor_digest)) {
4384 log_warn(LD_BUG,
4385 "We have a router descriptor, but need_to_mirror=1.");
4386 rs->need_to_mirror = 0;
4387 continue;
4389 if (authdir_mode(options) && dirserv_would_reject_router(rs)) {
4390 rs->need_to_mirror = 0;
4391 continue;
4393 if (digestmap_get(map, rs->descriptor_digest)) {
4394 /* We're downloading it already. */
4395 continue;
4396 } else {
4397 /* We could download it from this guy. */
4398 smartlist_add(dl, rs->descriptor_digest);
4399 ++n_download;
4404 /* At random, assign descriptors to authorities such that:
4405 * - if d is a member of some downloadable[x], d is a member of some
4406 * download_from[y]. (Everything we want to download, we try to download
4407 * from somebody.)
4408 * - If d is a member of download_from[y], d is a member of downloadable[y].
4409 * (We only try to download descriptors from authorities who claim to have
4410 * them.)
4411 * - No d is a member of download_from[x] and download_from[y] s.t. x != y.
4412 * (We don't try to download anything from two authorities concurrently.)
4414 while (n_download) {
4415 int which_ns = crypto_rand_int(n);
4416 smartlist_t *dl = downloadable[which_ns];
4417 int idx;
4418 char *d;
4419 if (!smartlist_len(dl))
4420 continue;
4421 idx = crypto_rand_int(smartlist_len(dl));
4422 d = smartlist_get(dl, idx);
4423 if (! digestmap_get(map, d)) {
4424 smartlist_add(download_from[which_ns], d);
4425 digestmap_set(map, d, (void*) 1);
4427 smartlist_del(dl, idx);
4428 --n_download;
4431 /* Now, we can actually launch our requests. */
4432 for (i=0; i<n; ++i) {
4433 networkstatus_v2_t *ns = smartlist_get(networkstatus_v2_list, i);
4434 trusted_dir_server_t *ds =
4435 router_get_trusteddirserver_by_digest(ns->identity_digest);
4436 smartlist_t *dl = download_from[i];
4437 int pds_flags = PDS_RETRY_IF_NO_SERVERS;
4438 if (! authdir_mode_any_nonhidserv(options))
4439 pds_flags |= PDS_NO_EXISTING_SERVERDESC_FETCH; /* XXXX ignored*/
4441 if (!ds) {
4442 log_info(LD_DIR, "Networkstatus with no corresponding authority!");
4443 continue;
4445 if (! smartlist_len(dl))
4446 continue;
4447 log_info(LD_DIR, "Requesting %d descriptors from authority \"%s\"",
4448 smartlist_len(dl), ds->nickname);
4449 for (j=0; j < smartlist_len(dl); j += MAX_DL_PER_REQUEST) {
4450 initiate_descriptor_downloads(&(ds->fake_status),
4451 DIR_PURPOSE_FETCH_SERVERDESC, dl, j,
4452 j+MAX_DL_PER_REQUEST, pds_flags);
4456 for (i=0; i<n; ++i) {
4457 smartlist_free(download_from[i]);
4458 smartlist_free(downloadable[i]);
4460 tor_free(download_from);
4461 tor_free(downloadable);
4462 digestmap_free(map,NULL);
4465 /** For any descriptor that we want that's currently listed in
4466 * <b>consensus</b>, download it as appropriate. */
4467 void
4468 update_consensus_router_descriptor_downloads(time_t now, int is_vote,
4469 networkstatus_t *consensus)
4471 or_options_t *options = get_options();
4472 digestmap_t *map = NULL;
4473 smartlist_t *no_longer_old = smartlist_create();
4474 smartlist_t *downloadable = smartlist_create();
4475 routerstatus_t *source = NULL;
4476 int authdir = authdir_mode(options);
4477 int n_delayed=0, n_have=0, n_would_reject=0, n_wouldnt_use=0,
4478 n_inprogress=0, n_in_oldrouters=0;
4480 if (directory_too_idle_to_fetch_descriptors(options, now))
4481 goto done;
4482 if (!consensus)
4483 goto done;
4485 if (is_vote) {
4486 /* where's it from, so we know whom to ask for descriptors */
4487 trusted_dir_server_t *ds;
4488 networkstatus_voter_info_t *voter = smartlist_get(consensus->voters, 0);
4489 tor_assert(voter);
4490 ds = trusteddirserver_get_by_v3_auth_digest(voter->identity_digest);
4491 if (ds)
4492 source = &(ds->fake_status);
4493 else
4494 log_warn(LD_DIR, "couldn't lookup source from vote?");
4497 map = digestmap_new();
4498 list_pending_descriptor_downloads(map, 0);
4499 SMARTLIST_FOREACH(consensus->routerstatus_list, void *, rsp,
4501 routerstatus_t *rs =
4502 is_vote ? &(((vote_routerstatus_t *)rsp)->status) : rsp;
4503 signed_descriptor_t *sd;
4504 if ((sd = router_get_by_descriptor_digest(rs->descriptor_digest))) {
4505 routerinfo_t *ri;
4506 ++n_have;
4507 if (!(ri = router_get_by_digest(rs->identity_digest)) ||
4508 memcmp(ri->cache_info.signed_descriptor_digest,
4509 sd->signed_descriptor_digest, DIGEST_LEN)) {
4510 /* We have a descriptor with this digest, but either there is no
4511 * entry in routerlist with the same ID (!ri), or there is one,
4512 * but the identity digest differs (memcmp).
4514 smartlist_add(no_longer_old, sd);
4515 ++n_in_oldrouters; /* We have it in old_routers. */
4517 continue; /* We have it already. */
4519 if (digestmap_get(map, rs->descriptor_digest)) {
4520 ++n_inprogress;
4521 continue; /* We have an in-progress download. */
4523 if (!download_status_is_ready(&rs->dl_status, now,
4524 MAX_ROUTERDESC_DOWNLOAD_FAILURES)) {
4525 ++n_delayed; /* Not ready for retry. */
4526 continue;
4528 if (authdir && dirserv_would_reject_router(rs)) {
4529 ++n_would_reject;
4530 continue; /* We would throw it out immediately. */
4532 if (!directory_caches_dir_info(options) &&
4533 !client_would_use_router(rs, now, options)) {
4534 ++n_wouldnt_use;
4535 continue; /* We would never use it ourself. */
4537 if (is_vote && source) {
4538 char time_bufnew[ISO_TIME_LEN+1];
4539 char time_bufold[ISO_TIME_LEN+1];
4540 routerinfo_t *oldrouter = router_get_by_digest(rs->identity_digest);
4541 format_iso_time(time_bufnew, rs->published_on);
4542 if (oldrouter)
4543 format_iso_time(time_bufold, oldrouter->cache_info.published_on);
4544 log_info(LD_DIR, "Learned about %s (%s vs %s) from %s's vote (%s)",
4545 rs->nickname, time_bufnew,
4546 oldrouter ? time_bufold : "none",
4547 source->nickname, oldrouter ? "known" : "unknown");
4549 smartlist_add(downloadable, rs->descriptor_digest);
4552 if (!authdir_mode_handles_descs(options, ROUTER_PURPOSE_GENERAL)
4553 && smartlist_len(no_longer_old)) {
4554 routerlist_t *rl = router_get_routerlist();
4555 log_info(LD_DIR, "%d router descriptors listed in consensus are "
4556 "currently in old_routers; making them current.",
4557 smartlist_len(no_longer_old));
4558 SMARTLIST_FOREACH(no_longer_old, signed_descriptor_t *, sd, {
4559 const char *msg;
4560 was_router_added_t r;
4561 routerinfo_t *ri = routerlist_reparse_old(rl, sd);
4562 if (!ri) {
4563 log_warn(LD_BUG, "Failed to re-parse a router.");
4564 continue;
4566 r = router_add_to_routerlist(ri, &msg, 1, 0);
4567 if (WRA_WAS_OUTDATED(r)) {
4568 log_warn(LD_DIR, "Couldn't add re-parsed router: %s",
4569 msg?msg:"???");
4572 routerlist_assert_ok(rl);
4575 log_info(LD_DIR,
4576 "%d router descriptors downloadable. %d delayed; %d present "
4577 "(%d of those were in old_routers); %d would_reject; "
4578 "%d wouldnt_use; %d in progress.",
4579 smartlist_len(downloadable), n_delayed, n_have, n_in_oldrouters,
4580 n_would_reject, n_wouldnt_use, n_inprogress);
4582 launch_router_descriptor_downloads(downloadable, source, now);
4584 digestmap_free(map, NULL);
4585 done:
4586 smartlist_free(downloadable);
4587 smartlist_free(no_longer_old);
4590 /** How often should we launch a server/authority request to be sure of getting
4591 * a guess for our IP? */
4592 /*XXXX021 this info should come from netinfo cells or something, or we should
4593 * do this only when we aren't seeing incoming data. see bug 652. */
4594 #define DUMMY_DOWNLOAD_INTERVAL (20*60)
4596 /** Launch downloads for router status as needed. */
4597 void
4598 update_router_descriptor_downloads(time_t now)
4600 or_options_t *options = get_options();
4601 static time_t last_dummy_download = 0;
4602 if (should_delay_dir_fetches(options))
4603 return;
4604 if (directory_fetches_dir_info_early(options)) {
4605 update_router_descriptor_cache_downloads_v2(now);
4607 update_consensus_router_descriptor_downloads(now, 0,
4608 networkstatus_get_reasonably_live_consensus(now));
4610 /* XXXX021 we could be smarter here; see notes on bug 652. */
4611 /* If we're a server that doesn't have a configured address, we rely on
4612 * directory fetches to learn when our address changes. So if we haven't
4613 * tried to get any routerdescs in a long time, try a dummy fetch now. */
4614 if (!options->Address &&
4615 server_mode(options) &&
4616 last_routerdesc_download_attempted + DUMMY_DOWNLOAD_INTERVAL < now &&
4617 last_dummy_download + DUMMY_DOWNLOAD_INTERVAL < now) {
4618 last_dummy_download = now;
4619 directory_get_from_dirserver(DIR_PURPOSE_FETCH_SERVERDESC,
4620 ROUTER_PURPOSE_GENERAL, "authority.z",
4621 PDS_RETRY_IF_NO_SERVERS);
4625 /** Launch extrainfo downloads as needed. */
4626 void
4627 update_extrainfo_downloads(time_t now)
4629 or_options_t *options = get_options();
4630 routerlist_t *rl;
4631 smartlist_t *wanted;
4632 digestmap_t *pending;
4633 int old_routers, i;
4634 int n_no_ei = 0, n_pending = 0, n_have = 0, n_delay = 0;
4635 if (! options->DownloadExtraInfo)
4636 return;
4637 if (should_delay_dir_fetches(options))
4638 return;
4639 if (!router_have_minimum_dir_info())
4640 return;
4642 pending = digestmap_new();
4643 list_pending_descriptor_downloads(pending, 1);
4644 rl = router_get_routerlist();
4645 wanted = smartlist_create();
4646 for (old_routers = 0; old_routers < 2; ++old_routers) {
4647 smartlist_t *lst = old_routers ? rl->old_routers : rl->routers;
4648 for (i = 0; i < smartlist_len(lst); ++i) {
4649 signed_descriptor_t *sd;
4650 char *d;
4651 if (old_routers)
4652 sd = smartlist_get(lst, i);
4653 else
4654 sd = &((routerinfo_t*)smartlist_get(lst, i))->cache_info;
4655 if (sd->is_extrainfo)
4656 continue; /* This should never happen. */
4657 if (old_routers && !router_get_by_digest(sd->identity_digest))
4658 continue; /* Couldn't check the signature if we got it. */
4659 if (sd->extrainfo_is_bogus)
4660 continue;
4661 d = sd->extra_info_digest;
4662 if (tor_digest_is_zero(d)) {
4663 ++n_no_ei;
4664 continue;
4666 if (eimap_get(rl->extra_info_map, d)) {
4667 ++n_have;
4668 continue;
4670 if (!download_status_is_ready(&sd->ei_dl_status, now,
4671 MAX_ROUTERDESC_DOWNLOAD_FAILURES)) {
4672 ++n_delay;
4673 continue;
4675 if (digestmap_get(pending, d)) {
4676 ++n_pending;
4677 continue;
4679 smartlist_add(wanted, d);
4682 digestmap_free(pending, NULL);
4684 log_info(LD_DIR, "Extrainfo download status: %d router with no ei, %d "
4685 "with present ei, %d delaying, %d pending, %d downloadable.",
4686 n_no_ei, n_have, n_delay, n_pending, smartlist_len(wanted));
4688 smartlist_shuffle(wanted);
4689 for (i = 0; i < smartlist_len(wanted); i += MAX_DL_PER_REQUEST) {
4690 initiate_descriptor_downloads(NULL, DIR_PURPOSE_FETCH_EXTRAINFO,
4691 wanted, i, i + MAX_DL_PER_REQUEST,
4692 PDS_RETRY_IF_NO_SERVERS|PDS_NO_EXISTING_SERVERDESC_FETCH);
4695 smartlist_free(wanted);
4698 /** True iff, the last time we checked whether we had enough directory info
4699 * to build circuits, the answer was "yes". */
4700 static int have_min_dir_info = 0;
4701 /** True iff enough has changed since the last time we checked whether we had
4702 * enough directory info to build circuits that our old answer can no longer
4703 * be trusted. */
4704 static int need_to_update_have_min_dir_info = 1;
4705 /** String describing what we're missing before we have enough directory
4706 * info. */
4707 static char dir_info_status[128] = "";
4709 /** Return true iff we have enough networkstatus and router information to
4710 * start building circuits. Right now, this means "more than half the
4711 * networkstatus documents, and at least 1/4 of expected routers." */
4712 //XXX should consider whether we have enough exiting nodes here.
4714 router_have_minimum_dir_info(void)
4716 if (PREDICT_UNLIKELY(need_to_update_have_min_dir_info)) {
4717 update_router_have_minimum_dir_info();
4718 need_to_update_have_min_dir_info = 0;
4720 return have_min_dir_info;
4723 /** Called when our internal view of the directory has changed. This can be
4724 * when the authorities change, networkstatuses change, the list of routerdescs
4725 * changes, or number of running routers changes.
4727 void
4728 router_dir_info_changed(void)
4730 need_to_update_have_min_dir_info = 1;
4731 rend_hsdir_routers_changed();
4734 /** Return a string describing what we're missing before we have enough
4735 * directory info. */
4736 const char *
4737 get_dir_info_status_string(void)
4739 return dir_info_status;
4742 /** Iterate over the servers listed in <b>consensus</b>, and count how many of
4743 * them seem like ones we'd use, and how many of <em>those</em> we have
4744 * descriptors for. Store the former in *<b>num_usable</b> and the latter in
4745 * *<b>num_present</b>. If <b>in_set</b> is non-NULL, only consider those
4746 * routers in <b>in_set</b>.
4748 static void
4749 count_usable_descriptors(int *num_present, int *num_usable,
4750 const networkstatus_t *consensus,
4751 or_options_t *options, time_t now,
4752 routerset_t *in_set)
4754 *num_present = 0, *num_usable=0;
4756 SMARTLIST_FOREACH(consensus->routerstatus_list, routerstatus_t *, rs,
4758 if (in_set && ! routerset_contains_routerstatus(in_set, rs))
4759 continue;
4760 if (client_would_use_router(rs, now, options)) {
4761 ++*num_usable; /* the consensus says we want it. */
4762 if (router_get_by_descriptor_digest(rs->descriptor_digest)) {
4763 /* we have the descriptor listed in the consensus. */
4764 ++*num_present;
4769 log_debug(LD_DIR, "%d usable, %d present.", *num_usable, *num_present);
4772 /** We just fetched a new set of descriptors. Compute how far through
4773 * the "loading descriptors" bootstrapping phase we are, so we can inform
4774 * the controller of our progress. */
4776 count_loading_descriptors_progress(void)
4778 int num_present = 0, num_usable=0;
4779 time_t now = time(NULL);
4780 const networkstatus_t *consensus =
4781 networkstatus_get_reasonably_live_consensus(now);
4782 double fraction;
4784 if (!consensus)
4785 return 0; /* can't count descriptors if we have no list of them */
4787 count_usable_descriptors(&num_present, &num_usable,
4788 consensus, get_options(), now, NULL);
4790 if (num_usable == 0)
4791 return 0; /* don't div by 0 */
4792 fraction = num_present / (num_usable/4.);
4793 if (fraction > 1.0)
4794 return 0; /* it's not the number of descriptors holding us back */
4795 return BOOTSTRAP_STATUS_LOADING_DESCRIPTORS + (int)
4796 (fraction*(BOOTSTRAP_STATUS_CONN_OR-1 -
4797 BOOTSTRAP_STATUS_LOADING_DESCRIPTORS));
4800 /** Change the value of have_min_dir_info, setting it true iff we have enough
4801 * network and router information to build circuits. Clear the value of
4802 * need_to_update_have_min_dir_info. */
4803 static void
4804 update_router_have_minimum_dir_info(void)
4806 int num_present = 0, num_usable=0;
4807 time_t now = time(NULL);
4808 int res;
4809 or_options_t *options = get_options();
4810 const networkstatus_t *consensus =
4811 networkstatus_get_reasonably_live_consensus(now);
4813 if (!consensus) {
4814 if (!networkstatus_get_latest_consensus())
4815 strlcpy(dir_info_status, "We have no network-status consensus.",
4816 sizeof(dir_info_status));
4817 else
4818 strlcpy(dir_info_status, "We have no recent network-status consensus.",
4819 sizeof(dir_info_status));
4820 res = 0;
4821 goto done;
4824 if (should_delay_dir_fetches(get_options())) {
4825 log_notice(LD_DIR, "no known bridge descriptors running yet; stalling");
4826 strlcpy(dir_info_status, "No live bridge descriptors.",
4827 sizeof(dir_info_status));
4828 res = 0;
4829 goto done;
4832 count_usable_descriptors(&num_present, &num_usable, consensus, options, now,
4833 NULL);
4835 if (num_present < num_usable/4) {
4836 tor_snprintf(dir_info_status, sizeof(dir_info_status),
4837 "We have only %d/%d usable descriptors.", num_present, num_usable);
4838 res = 0;
4839 control_event_bootstrap(BOOTSTRAP_STATUS_REQUESTING_DESCRIPTORS, 0);
4840 goto done;
4841 } else if (num_present < 2) {
4842 tor_snprintf(dir_info_status, sizeof(dir_info_status),
4843 "Only %d descriptor%s here and believed reachable!",
4844 num_present, num_present ? "" : "s");
4845 res = 0;
4846 goto done;
4849 /* Check for entry nodes. */
4850 if (options->EntryNodes) {
4851 count_usable_descriptors(&num_present, &num_usable, consensus, options,
4852 now, options->EntryNodes);
4854 if (!num_usable || !num_present) {
4855 tor_snprintf(dir_info_status, sizeof(dir_info_status),
4856 "We have only %d/%d usable entry node descriptors.",
4857 num_present, num_usable);
4858 res = 0;
4859 goto done;
4863 res = 1;
4865 done:
4866 if (res && !have_min_dir_info) {
4867 log(LOG_NOTICE, LD_DIR,
4868 "We now have enough directory information to build circuits.");
4869 control_event_client_status(LOG_NOTICE, "ENOUGH_DIR_INFO");
4870 control_event_bootstrap(BOOTSTRAP_STATUS_CONN_OR, 0);
4872 if (!res && have_min_dir_info) {
4873 int quiet = directory_too_idle_to_fetch_descriptors(options, now);
4874 log(quiet ? LOG_INFO : LOG_NOTICE, LD_DIR,
4875 "Our directory information is no longer up-to-date "
4876 "enough to build circuits: %s", dir_info_status);
4878 /* a) make us log when we next complete a circuit, so we know when Tor
4879 * is back up and usable, and b) disable some activities that Tor
4880 * should only do while circuits are working, like reachability tests
4881 * and fetching bridge descriptors only over circuits. */
4882 can_complete_circuit = 0;
4884 control_event_client_status(LOG_NOTICE, "NOT_ENOUGH_DIR_INFO");
4886 have_min_dir_info = res;
4887 need_to_update_have_min_dir_info = 0;
4890 /** Reset the descriptor download failure count on all routers, so that we
4891 * can retry any long-failed routers immediately.
4893 void
4894 router_reset_descriptor_download_failures(void)
4896 networkstatus_reset_download_failures();
4897 last_routerdesc_download_attempted = 0;
4898 if (!routerlist)
4899 return;
4900 SMARTLIST_FOREACH(routerlist->routers, routerinfo_t *, ri,
4902 download_status_reset(&ri->cache_info.ei_dl_status);
4904 SMARTLIST_FOREACH(routerlist->old_routers, signed_descriptor_t *, sd,
4906 download_status_reset(&sd->ei_dl_status);
4910 /** Any changes in a router descriptor's publication time larger than this are
4911 * automatically non-cosmetic. */
4912 #define ROUTER_MAX_COSMETIC_TIME_DIFFERENCE (12*60*60)
4914 /** We allow uptime to vary from how much it ought to be by this much. */
4915 #define ROUTER_ALLOW_UPTIME_DRIFT (6*60*60)
4917 /** Return true iff the only differences between r1 and r2 are such that
4918 * would not cause a recent (post 0.1.1.6) dirserver to republish.
4921 router_differences_are_cosmetic(routerinfo_t *r1, routerinfo_t *r2)
4923 time_t r1pub, r2pub;
4924 long time_difference;
4925 tor_assert(r1 && r2);
4927 /* r1 should be the one that was published first. */
4928 if (r1->cache_info.published_on > r2->cache_info.published_on) {
4929 routerinfo_t *ri_tmp = r2;
4930 r2 = r1;
4931 r1 = ri_tmp;
4934 /* If any key fields differ, they're different. */
4935 if (strcasecmp(r1->address, r2->address) ||
4936 strcasecmp(r1->nickname, r2->nickname) ||
4937 r1->or_port != r2->or_port ||
4938 r1->dir_port != r2->dir_port ||
4939 r1->purpose != r2->purpose ||
4940 crypto_pk_cmp_keys(r1->onion_pkey, r2->onion_pkey) ||
4941 crypto_pk_cmp_keys(r1->identity_pkey, r2->identity_pkey) ||
4942 strcasecmp(r1->platform, r2->platform) ||
4943 (r1->contact_info && !r2->contact_info) || /* contact_info is optional */
4944 (!r1->contact_info && r2->contact_info) ||
4945 (r1->contact_info && r2->contact_info &&
4946 strcasecmp(r1->contact_info, r2->contact_info)) ||
4947 r1->is_hibernating != r2->is_hibernating ||
4948 r1->has_old_dnsworkers != r2->has_old_dnsworkers ||
4949 cmp_addr_policies(r1->exit_policy, r2->exit_policy))
4950 return 0;
4951 if ((r1->declared_family == NULL) != (r2->declared_family == NULL))
4952 return 0;
4953 if (r1->declared_family && r2->declared_family) {
4954 int i, n;
4955 if (smartlist_len(r1->declared_family)!=smartlist_len(r2->declared_family))
4956 return 0;
4957 n = smartlist_len(r1->declared_family);
4958 for (i=0; i < n; ++i) {
4959 if (strcasecmp(smartlist_get(r1->declared_family, i),
4960 smartlist_get(r2->declared_family, i)))
4961 return 0;
4965 /* Did bandwidth change a lot? */
4966 if ((r1->bandwidthcapacity < r2->bandwidthcapacity/2) ||
4967 (r2->bandwidthcapacity < r1->bandwidthcapacity/2))
4968 return 0;
4970 /* Did the bandwidthrate or bandwidthburst change? */
4971 if ((r1->bandwidthrate != r2->bandwidthrate) ||
4972 (r1->bandwidthburst != r2->bandwidthburst))
4973 return 0;
4975 /* Did more than 12 hours pass? */
4976 if (r1->cache_info.published_on + ROUTER_MAX_COSMETIC_TIME_DIFFERENCE
4977 < r2->cache_info.published_on)
4978 return 0;
4980 /* Did uptime fail to increase by approximately the amount we would think,
4981 * give or take some slop? */
4982 r1pub = r1->cache_info.published_on;
4983 r2pub = r2->cache_info.published_on;
4984 time_difference = labs(r2->uptime - (r1->uptime + (r2pub - r1pub)));
4985 if (time_difference > ROUTER_ALLOW_UPTIME_DRIFT &&
4986 time_difference > r1->uptime * .05 &&
4987 time_difference > r2->uptime * .05)
4988 return 0;
4990 /* Otherwise, the difference is cosmetic. */
4991 return 1;
4994 /** Check whether <b>ri</b> (a.k.a. sd) is a router compatible with the
4995 * extrainfo document
4996 * <b>ei</b>. If no router is compatible with <b>ei</b>, <b>ei</b> should be
4997 * dropped. Return 0 for "compatible", return 1 for "reject, and inform
4998 * whoever uploaded <b>ei</b>, and return -1 for "reject silently.". If
4999 * <b>msg</b> is present, set *<b>msg</b> to a description of the
5000 * incompatibility (if any).
5003 routerinfo_incompatible_with_extrainfo(routerinfo_t *ri, extrainfo_t *ei,
5004 signed_descriptor_t *sd,
5005 const char **msg)
5007 int digest_matches, r=1;
5008 tor_assert(ri);
5009 tor_assert(ei);
5010 if (!sd)
5011 sd = &ri->cache_info;
5013 if (ei->bad_sig) {
5014 if (msg) *msg = "Extrainfo signature was bad, or signed with wrong key.";
5015 return 1;
5018 digest_matches = !memcmp(ei->cache_info.signed_descriptor_digest,
5019 sd->extra_info_digest, DIGEST_LEN);
5021 /* The identity must match exactly to have been generated at the same time
5022 * by the same router. */
5023 if (memcmp(ri->cache_info.identity_digest, ei->cache_info.identity_digest,
5024 DIGEST_LEN)) {
5025 if (msg) *msg = "Extrainfo nickname or identity did not match routerinfo";
5026 goto err; /* different servers */
5029 if (ei->pending_sig) {
5030 char signed_digest[128];
5031 if (crypto_pk_public_checksig(ri->identity_pkey,
5032 signed_digest, sizeof(signed_digest),
5033 ei->pending_sig, ei->pending_sig_len) != DIGEST_LEN ||
5034 memcmp(signed_digest, ei->cache_info.signed_descriptor_digest,
5035 DIGEST_LEN)) {
5036 ei->bad_sig = 1;
5037 tor_free(ei->pending_sig);
5038 if (msg) *msg = "Extrainfo signature bad, or signed with wrong key";
5039 goto err; /* Bad signature, or no match. */
5042 ei->cache_info.send_unencrypted = ri->cache_info.send_unencrypted;
5043 tor_free(ei->pending_sig);
5046 if (ei->cache_info.published_on < sd->published_on) {
5047 if (msg) *msg = "Extrainfo published time did not match routerdesc";
5048 goto err;
5049 } else if (ei->cache_info.published_on > sd->published_on) {
5050 if (msg) *msg = "Extrainfo published time did not match routerdesc";
5051 r = -1;
5052 goto err;
5055 if (!digest_matches) {
5056 if (msg) *msg = "Extrainfo digest did not match value from routerdesc";
5057 goto err; /* Digest doesn't match declared value. */
5060 return 0;
5061 err:
5062 if (digest_matches) {
5063 /* This signature was okay, and the digest was right: This is indeed the
5064 * corresponding extrainfo. But insanely, it doesn't match the routerinfo
5065 * that lists it. Don't try to fetch this one again. */
5066 sd->extrainfo_is_bogus = 1;
5069 return r;
5072 /** Assert that the internal representation of <b>rl</b> is
5073 * self-consistent. */
5074 void
5075 routerlist_assert_ok(routerlist_t *rl)
5077 routerinfo_t *r2;
5078 signed_descriptor_t *sd2;
5079 if (!rl)
5080 return;
5081 SMARTLIST_FOREACH(rl->routers, routerinfo_t *, r,
5083 r2 = rimap_get(rl->identity_map, r->cache_info.identity_digest);
5084 tor_assert(r == r2);
5085 sd2 = sdmap_get(rl->desc_digest_map,
5086 r->cache_info.signed_descriptor_digest);
5087 tor_assert(&(r->cache_info) == sd2);
5088 tor_assert(r->cache_info.routerlist_index == r_sl_idx);
5089 /* XXXX
5091 * Hoo boy. We need to fix this one, and the fix is a bit tricky, so
5092 * commenting this out is just a band-aid.
5094 * The problem is that, although well-behaved router descriptors
5095 * should never have the same value for their extra_info_digest, it's
5096 * possible for ill-behaved routers to claim whatever they like there.
5098 * The real answer is to trash desc_by_eid_map and instead have
5099 * something that indicates for a given extra-info digest we want,
5100 * what its download status is. We'll do that as a part of routerlist
5101 * refactoring once consensus directories are in. For now,
5102 * this rep violation is probably harmless: an adversary can make us
5103 * reset our retry count for an extrainfo, but that's not the end
5104 * of the world. Changing the representation in 0.2.0.x would just
5105 * destabilize the codebase.
5106 if (!tor_digest_is_zero(r->cache_info.extra_info_digest)) {
5107 signed_descriptor_t *sd3 =
5108 sdmap_get(rl->desc_by_eid_map, r->cache_info.extra_info_digest);
5109 tor_assert(sd3 == &(r->cache_info));
5113 SMARTLIST_FOREACH(rl->old_routers, signed_descriptor_t *, sd,
5115 r2 = rimap_get(rl->identity_map, sd->identity_digest);
5116 tor_assert(sd != &(r2->cache_info));
5117 sd2 = sdmap_get(rl->desc_digest_map, sd->signed_descriptor_digest);
5118 tor_assert(sd == sd2);
5119 tor_assert(sd->routerlist_index == sd_sl_idx);
5120 /* XXXX see above.
5121 if (!tor_digest_is_zero(sd->extra_info_digest)) {
5122 signed_descriptor_t *sd3 =
5123 sdmap_get(rl->desc_by_eid_map, sd->extra_info_digest);
5124 tor_assert(sd3 == sd);
5129 RIMAP_FOREACH(rl->identity_map, d, r) {
5130 tor_assert(!memcmp(r->cache_info.identity_digest, d, DIGEST_LEN));
5131 } DIGESTMAP_FOREACH_END;
5132 SDMAP_FOREACH(rl->desc_digest_map, d, sd) {
5133 tor_assert(!memcmp(sd->signed_descriptor_digest, d, DIGEST_LEN));
5134 } DIGESTMAP_FOREACH_END;
5135 SDMAP_FOREACH(rl->desc_by_eid_map, d, sd) {
5136 tor_assert(!tor_digest_is_zero(d));
5137 tor_assert(sd);
5138 tor_assert(!memcmp(sd->extra_info_digest, d, DIGEST_LEN));
5139 } DIGESTMAP_FOREACH_END;
5140 EIMAP_FOREACH(rl->extra_info_map, d, ei) {
5141 signed_descriptor_t *sd;
5142 tor_assert(!memcmp(ei->cache_info.signed_descriptor_digest,
5143 d, DIGEST_LEN));
5144 sd = sdmap_get(rl->desc_by_eid_map,
5145 ei->cache_info.signed_descriptor_digest);
5146 // tor_assert(sd); // XXXX see above
5147 if (sd) {
5148 tor_assert(!memcmp(ei->cache_info.signed_descriptor_digest,
5149 sd->extra_info_digest, DIGEST_LEN));
5151 } DIGESTMAP_FOREACH_END;
5154 /** Allocate and return a new string representing the contact info
5155 * and platform string for <b>router</b>,
5156 * surrounded by quotes and using standard C escapes.
5158 * THIS FUNCTION IS NOT REENTRANT. Don't call it from outside the main
5159 * thread. Also, each call invalidates the last-returned value, so don't
5160 * try log_warn(LD_GENERAL, "%s %s", esc_router_info(a), esc_router_info(b));
5162 * If <b>router</b> is NULL, it just frees its internal memory and returns.
5164 const char *
5165 esc_router_info(routerinfo_t *router)
5167 static char *info=NULL;
5168 char *esc_contact, *esc_platform;
5169 size_t len;
5170 tor_free(info);
5172 if (!router)
5173 return NULL; /* we're exiting; just free the memory we use */
5175 esc_contact = esc_for_log(router->contact_info);
5176 esc_platform = esc_for_log(router->platform);
5178 len = strlen(esc_contact)+strlen(esc_platform)+32;
5179 info = tor_malloc(len);
5180 tor_snprintf(info, len, "Contact %s, Platform %s", esc_contact,
5181 esc_platform);
5182 tor_free(esc_contact);
5183 tor_free(esc_platform);
5185 return info;
5188 /** Helper for sorting: compare two routerinfos by their identity
5189 * digest. */
5190 static int
5191 _compare_routerinfo_by_id_digest(const void **a, const void **b)
5193 routerinfo_t *first = *(routerinfo_t **)a, *second = *(routerinfo_t **)b;
5194 return memcmp(first->cache_info.identity_digest,
5195 second->cache_info.identity_digest,
5196 DIGEST_LEN);
5199 /** Sort a list of routerinfo_t in ascending order of identity digest. */
5200 void
5201 routers_sort_by_identity(smartlist_t *routers)
5203 smartlist_sort(routers, _compare_routerinfo_by_id_digest);
5206 /** A routerset specifies constraints on a set of possible routerinfos, based
5207 * on their names, identities, or addresses. It is optimized for determining
5208 * whether a router is a member or not, in O(1+P) time, where P is the number
5209 * of address policy constraints. */
5210 struct routerset_t {
5211 /** A list of strings for the elements of the policy. Each string is either
5212 * a nickname, a hexadecimal identity fingerprint, or an address policy. A
5213 * router belongs to the set if its nickname OR its identity OR its address
5214 * matches an entry here. */
5215 smartlist_t *list;
5216 /** A map from lowercase nicknames of routers in the set to (void*)1 */
5217 strmap_t *names;
5218 /** A map from identity digests routers in the set to (void*)1 */
5219 digestmap_t *digests;
5220 /** An address policy for routers in the set. For implementation reasons,
5221 * a router belongs to the set if it is _rejected_ by this policy. */
5222 smartlist_t *policies;
5224 /** A human-readable description of what this routerset is for. Used in
5225 * log messages. */
5226 char *description;
5228 /** A list of the country codes in this set. */
5229 smartlist_t *country_names;
5230 /** Total number of countries we knew about when we built <b>countries</b>.*/
5231 int n_countries;
5232 /** Bit array mapping the return value of geoip_get_country() to 1 iff the
5233 * country is a member of this routerset. Note that we MUST call
5234 * routerset_refresh_countries() whenever the geoip country list is
5235 * reloaded. */
5236 bitarray_t *countries;
5239 /** Return a new empty routerset. */
5240 routerset_t *
5241 routerset_new(void)
5243 routerset_t *result = tor_malloc_zero(sizeof(routerset_t));
5244 result->list = smartlist_create();
5245 result->names = strmap_new();
5246 result->digests = digestmap_new();
5247 result->policies = smartlist_create();
5248 result->country_names = smartlist_create();
5249 return result;
5252 /** If <b>c</b> is a country code in the form {cc}, return a newly allocated
5253 * string holding the "cc" part. Else, return NULL. */
5254 static char *
5255 routerset_get_countryname(const char *c)
5257 char *country;
5259 if (strlen(c) < 4 || c[0] !='{' || c[3] !='}')
5260 return NULL;
5262 country = tor_strndup(c+1, 2);
5263 tor_strlower(country);
5264 return country;
5267 #if 0
5268 /** Add the GeoIP database's integer index (+1) of a valid two-character
5269 * country code to the routerset's <b>countries</b> bitarray. Return the
5270 * integer index if the country code is valid, -1 otherwise.*/
5271 static int
5272 routerset_add_country(const char *c)
5274 char country[3];
5275 country_t cc;
5277 /* XXXX: Country codes must be of the form \{[a-z\?]{2}\} but this accepts
5278 \{[.]{2}\}. Do we need to be strict? -RH */
5279 /* Nope; if the country code is bad, we'll get 0 when we look it up. */
5281 if (!geoip_is_loaded()) {
5282 log(LOG_WARN, LD_CONFIG, "GeoIP database not loaded: Cannot add country"
5283 "entry %s, ignoring.", c);
5284 return -1;
5287 memcpy(country, c+1, 2);
5288 country[2] = '\0';
5289 tor_strlower(country);
5291 if ((cc=geoip_get_country(country))==-1) {
5292 log(LOG_WARN, LD_CONFIG, "Country code '%s' is not valid, ignoring.",
5293 country);
5295 return cc;
5297 #endif
5299 /** Update the routerset's <b>countries</b> bitarray_t. Called whenever
5300 * the GeoIP database is reloaded.
5302 void
5303 routerset_refresh_countries(routerset_t *target)
5305 int cc;
5306 bitarray_free(target->countries);
5308 if (!geoip_is_loaded()) {
5309 target->countries = NULL;
5310 target->n_countries = 0;
5311 return;
5313 target->n_countries = geoip_get_n_countries();
5314 target->countries = bitarray_init_zero(target->n_countries);
5315 SMARTLIST_FOREACH_BEGIN(target->country_names, const char *, country) {
5316 cc = geoip_get_country(country);
5317 if (cc >= 0) {
5318 tor_assert(cc < target->n_countries);
5319 bitarray_set(target->countries, cc);
5320 } else {
5321 log(LOG_WARN, LD_CONFIG, "Country code '%s' is not recognized.",
5322 country);
5324 } SMARTLIST_FOREACH_END(country);
5327 /** Parse the string <b>s</b> to create a set of routerset entries, and add
5328 * them to <b>target</b>. In log messages, refer to the string as
5329 * <b>description</b>. Return 0 on success, -1 on failure.
5331 * Three kinds of elements are allowed in routersets: nicknames, IP address
5332 * patterns, and fingerprints. They may be surrounded by optional space, and
5333 * must be separated by commas.
5336 routerset_parse(routerset_t *target, const char *s, const char *description)
5338 int r = 0;
5339 int added_countries = 0;
5340 char *countryname;
5341 smartlist_t *list = smartlist_create();
5342 smartlist_split_string(list, s, ",",
5343 SPLIT_SKIP_SPACE | SPLIT_IGNORE_BLANK, 0);
5344 SMARTLIST_FOREACH_BEGIN(list, char *, nick) {
5345 addr_policy_t *p;
5346 if (is_legal_hexdigest(nick)) {
5347 char d[DIGEST_LEN];
5348 if (*nick == '$')
5349 ++nick;
5350 log_debug(LD_CONFIG, "Adding identity %s to %s", nick, description);
5351 base16_decode(d, sizeof(d), nick, HEX_DIGEST_LEN);
5352 digestmap_set(target->digests, d, (void*)1);
5353 } else if (is_legal_nickname(nick)) {
5354 log_debug(LD_CONFIG, "Adding nickname %s to %s", nick, description);
5355 strmap_set_lc(target->names, nick, (void*)1);
5356 } else if ((countryname = routerset_get_countryname(nick)) != NULL) {
5357 log_debug(LD_CONFIG, "Adding country %s to %s", nick,
5358 description);
5359 smartlist_add(target->country_names, countryname);
5360 added_countries = 1;
5361 } else if ((strchr(nick,'.') || strchr(nick, '*')) &&
5362 (p = router_parse_addr_policy_item_from_string(
5363 nick, ADDR_POLICY_REJECT))) {
5364 log_debug(LD_CONFIG, "Adding address %s to %s", nick, description);
5365 smartlist_add(target->policies, p);
5366 } else {
5367 log_warn(LD_CONFIG, "Entry '%s' in %s is misformed.", nick,
5368 description);
5369 r = -1;
5370 tor_free(nick);
5371 SMARTLIST_DEL_CURRENT(list, nick);
5373 } SMARTLIST_FOREACH_END(nick);
5374 smartlist_add_all(target->list, list);
5375 smartlist_free(list);
5376 if (added_countries)
5377 routerset_refresh_countries(target);
5378 return r;
5381 /** Called when we change a node set, or when we reload the geoip list:
5382 * recompute all country info in all configuration node sets and in the
5383 * routerlist. */
5384 void
5385 refresh_all_country_info(void)
5387 or_options_t *options = get_options();
5389 if (options->EntryNodes)
5390 routerset_refresh_countries(options->EntryNodes);
5391 if (options->ExitNodes)
5392 routerset_refresh_countries(options->ExitNodes);
5393 if (options->ExcludeNodes)
5394 routerset_refresh_countries(options->ExcludeNodes);
5395 if (options->ExcludeExitNodes)
5396 routerset_refresh_countries(options->ExcludeExitNodes);
5397 if (options->_ExcludeExitNodesUnion)
5398 routerset_refresh_countries(options->_ExcludeExitNodesUnion);
5400 routerlist_refresh_countries();
5403 /** Add all members of the set <b>source</b> to <b>target</b>. */
5404 void
5405 routerset_union(routerset_t *target, const routerset_t *source)
5407 char *s;
5408 tor_assert(target);
5409 if (!source || !source->list)
5410 return;
5411 s = routerset_to_string(source);
5412 routerset_parse(target, s, "other routerset");
5413 tor_free(s);
5416 /** Return true iff <b>set</b> lists only nicknames and digests, and includes
5417 * no IP ranges or countries. */
5419 routerset_is_list(const routerset_t *set)
5421 return smartlist_len(set->country_names) == 0 &&
5422 smartlist_len(set->policies) == 0;
5425 /** Return true iff we need a GeoIP IP-to-country database to make sense of
5426 * <b>set</b>. */
5428 routerset_needs_geoip(const routerset_t *set)
5430 return set && smartlist_len(set->country_names);
5433 /** Return true iff there are no entries in <b>set</b>. */
5434 static int
5435 routerset_is_empty(const routerset_t *set)
5437 return !set || smartlist_len(set->list) == 0;
5440 /** Helper. Return true iff <b>set</b> contains a router based on the other
5441 * provided fields. Return higher values for more specific subentries: a
5442 * single router is more specific than an address range of routers, which is
5443 * more specific in turn than a country code.
5445 * (If country is -1, then we take the country
5446 * from addr.) */
5447 static int
5448 routerset_contains(const routerset_t *set, const tor_addr_t *addr,
5449 uint16_t orport,
5450 const char *nickname, const char *id_digest, int is_named,
5451 country_t country)
5453 if (!set || !set->list) return 0;
5454 (void) is_named; /* not supported */
5455 if (nickname && strmap_get_lc(set->names, nickname))
5456 return 4;
5457 if (id_digest && digestmap_get(set->digests, id_digest))
5458 return 4;
5459 if (addr && compare_tor_addr_to_addr_policy(addr, orport, set->policies)
5460 == ADDR_POLICY_REJECTED)
5461 return 3;
5462 if (set->countries) {
5463 if (country < 0 && addr)
5464 country = geoip_get_country_by_ip(tor_addr_to_ipv4h(addr));
5466 if (country >= 0 && country < set->n_countries &&
5467 bitarray_is_set(set->countries, country))
5468 return 2;
5470 return 0;
5473 /** Return true iff we can tell that <b>ei</b> is a member of <b>set</b>. */
5475 routerset_contains_extendinfo(const routerset_t *set, const extend_info_t *ei)
5477 return routerset_contains(set,
5478 &ei->addr,
5479 ei->port,
5480 ei->nickname,
5481 ei->identity_digest,
5482 -1, /*is_named*/
5483 -1 /*country*/);
5486 /** Return true iff <b>ri</b> is in <b>set</b>. */
5488 routerset_contains_router(const routerset_t *set, routerinfo_t *ri)
5490 tor_addr_t addr;
5491 tor_addr_from_ipv4h(&addr, ri->addr);
5492 return routerset_contains(set,
5493 &addr,
5494 ri->or_port,
5495 ri->nickname,
5496 ri->cache_info.identity_digest,
5497 ri->is_named,
5498 ri->country);
5501 /** Return true iff <b>rs</b> is in <b>set</b>. */
5503 routerset_contains_routerstatus(const routerset_t *set, routerstatus_t *rs)
5505 tor_addr_t addr;
5506 tor_addr_from_ipv4h(&addr, rs->addr);
5507 return routerset_contains(set,
5508 &addr,
5509 rs->or_port,
5510 rs->nickname,
5511 rs->identity_digest,
5512 rs->is_named,
5513 -1);
5516 /** Add every known routerinfo_t that is a member of <b>routerset</b> to
5517 * <b>out</b>. If <b>running_only</b>, only add the running ones. */
5518 void
5519 routerset_get_all_routers(smartlist_t *out, const routerset_t *routerset,
5520 int running_only)
5522 tor_assert(out);
5523 if (!routerset || !routerset->list)
5524 return;
5525 if (!warned_nicknames)
5526 warned_nicknames = smartlist_create();
5527 if (routerset_is_list(routerset)) {
5529 /* No routers are specified by type; all are given by name or digest.
5530 * we can do a lookup in O(len(list)). */
5531 SMARTLIST_FOREACH(routerset->list, const char *, name, {
5532 routerinfo_t *router = router_get_by_nickname(name, 1);
5533 if (router) {
5534 if (!running_only || router->is_running)
5535 smartlist_add(out, router);
5538 } else {
5539 /* We need to iterate over the routerlist to get all the ones of the
5540 * right kind. */
5541 routerlist_t *rl = router_get_routerlist();
5542 SMARTLIST_FOREACH(rl->routers, routerinfo_t *, router, {
5543 if (running_only && !router->is_running)
5544 continue;
5545 if (routerset_contains_router(routerset, router))
5546 smartlist_add(out, router);
5551 /** Add to <b>target</b> every routerinfo_t from <b>source</b> except:
5553 * 1) Don't add it if <b>include</b> is non-empty and the relay isn't in
5554 * <b>include</b>; and
5555 * 2) Don't add it if <b>exclude</b> is non-empty and the relay is
5556 * excluded in a more specific fashion by <b>exclude</b>.
5557 * 3) If <b>running_only</b>, don't add non-running routers.
5559 void
5560 routersets_get_disjunction(smartlist_t *target,
5561 const smartlist_t *source,
5562 const routerset_t *include,
5563 const routerset_t *exclude, int running_only)
5565 SMARTLIST_FOREACH(source, routerinfo_t *, router, {
5566 int include_result;
5567 if (running_only && !router->is_running)
5568 continue;
5569 if (!routerset_is_empty(include))
5570 include_result = routerset_contains_router(include, router);
5571 else
5572 include_result = 1;
5574 if (include_result) {
5575 int exclude_result = routerset_contains_router(exclude, router);
5576 if (include_result >= exclude_result)
5577 smartlist_add(target, router);
5582 /** Remove every routerinfo_t from <b>lst</b> that is in <b>routerset</b>. */
5583 void
5584 routerset_subtract_routers(smartlist_t *lst, const routerset_t *routerset)
5586 tor_assert(lst);
5587 if (!routerset)
5588 return;
5589 SMARTLIST_FOREACH(lst, routerinfo_t *, r, {
5590 if (routerset_contains_router(routerset, r)) {
5591 //log_debug(LD_DIR, "Subtracting %s",r->nickname);
5592 SMARTLIST_DEL_CURRENT(lst, r);
5597 /** Return a new string that when parsed by routerset_parse_string() will
5598 * yield <b>set</b>. */
5599 char *
5600 routerset_to_string(const routerset_t *set)
5602 if (!set || !set->list)
5603 return tor_strdup("");
5604 return smartlist_join_strings(set->list, ",", 0, NULL);
5607 /** Helper: return true iff old and new are both NULL, or both non-NULL
5608 * equal routersets. */
5610 routerset_equal(const routerset_t *old, const routerset_t *new)
5612 if (old == NULL && new == NULL)
5613 return 1;
5614 else if (old == NULL || new == NULL)
5615 return 0;
5617 if (smartlist_len(old->list) != smartlist_len(new->list))
5618 return 0;
5620 SMARTLIST_FOREACH(old->list, const char *, cp1, {
5621 const char *cp2 = smartlist_get(new->list, cp1_sl_idx);
5622 if (strcmp(cp1, cp2))
5623 return 0;
5626 return 1;
5629 /** Free all storage held in <b>routerset</b>. */
5630 void
5631 routerset_free(routerset_t *routerset)
5633 if (!routerset)
5634 return;
5636 SMARTLIST_FOREACH(routerset->list, char *, cp, tor_free(cp));
5637 smartlist_free(routerset->list);
5638 SMARTLIST_FOREACH(routerset->policies, addr_policy_t *, p,
5639 addr_policy_free(p));
5640 smartlist_free(routerset->policies);
5641 SMARTLIST_FOREACH(routerset->country_names, char *, cp, tor_free(cp));
5642 smartlist_free(routerset->country_names);
5644 strmap_free(routerset->names, NULL);
5645 digestmap_free(routerset->digests, NULL);
5646 bitarray_free(routerset->countries);
5647 tor_free(routerset);
5650 /** Refresh the country code of <b>ri</b>. This function MUST be called on
5651 * each router when the GeoIP database is reloaded, and on all new routers. */
5652 void
5653 routerinfo_set_country(routerinfo_t *ri)
5655 ri->country = geoip_get_country_by_ip(ri->addr);
5658 /** Set the country code of all routers in the routerlist. */
5659 void
5660 routerlist_refresh_countries(void)
5662 routerlist_t *rl = router_get_routerlist();
5663 SMARTLIST_FOREACH(rl->routers, routerinfo_t *, ri,
5664 routerinfo_set_country(ri));
5667 /** Determine the routers that are responsible for <b>id</b> (binary) and
5668 * add pointers to those routers' routerstatus_t to <b>responsible_dirs</b>.
5669 * Return -1 if we're returning an empty smartlist, else return 0.
5672 hid_serv_get_responsible_directories(smartlist_t *responsible_dirs,
5673 const char *id)
5675 int start, found, n_added = 0, i;
5676 networkstatus_t *c = networkstatus_get_latest_consensus();
5677 int use_begindir = get_options()->TunnelDirConns;
5678 if (!c || !smartlist_len(c->routerstatus_list)) {
5679 log_warn(LD_REND, "We don't have a consensus, so we can't perform v2 "
5680 "rendezvous operations.");
5681 return -1;
5683 tor_assert(id);
5684 start = networkstatus_vote_find_entry_idx(c, id, &found);
5685 if (start == smartlist_len(c->routerstatus_list)) start = 0;
5686 i = start;
5687 do {
5688 routerstatus_t *r = smartlist_get(c->routerstatus_list, i);
5689 if (r->is_hs_dir) {
5690 if (r->dir_port || use_begindir)
5691 smartlist_add(responsible_dirs, r);
5692 else
5693 log_info(LD_REND, "Not adding router '%s' to list of responsible "
5694 "hidden service directories, because we have no way of "
5695 "reaching it.", r->nickname);
5696 if (++n_added == REND_NUMBER_OF_CONSECUTIVE_REPLICAS)
5697 break;
5699 if (++i == smartlist_len(c->routerstatus_list))
5700 i = 0;
5701 } while (i != start);
5703 /* Even though we don't have the desired number of hidden service
5704 * directories, be happy if we got any. */
5705 return smartlist_len(responsible_dirs) ? 0 : -1;
5708 /** Return true if this node is currently acting as hidden service
5709 * directory, false otherwise. */
5711 hid_serv_acting_as_directory(void)
5713 routerinfo_t *me = router_get_my_routerinfo();
5714 networkstatus_t *c;
5715 routerstatus_t *rs;
5716 if (!me)
5717 return 0;
5718 if (!get_options()->HidServDirectoryV2) {
5719 log_info(LD_REND, "We are not acting as hidden service directory, "
5720 "because we have not been configured as such.");
5721 return 0;
5723 if (!(c = networkstatus_get_latest_consensus())) {
5724 log_info(LD_REND, "There's no consensus, so I can't tell if I'm a hidden "
5725 "service directory");
5726 return 0;
5728 rs = networkstatus_vote_find_entry(c, me->cache_info.identity_digest);
5729 if (!rs) {
5730 log_info(LD_REND, "We're not listed in the consensus, so we're not "
5731 "being a hidden service directory.");
5732 return 0;
5734 if (!rs->is_hs_dir) {
5735 log_info(LD_REND, "We're not listed as a hidden service directory in "
5736 "the consensus, so we won't be one.");
5737 return 0;
5739 return 1;
5742 /** Return true if this node is responsible for storing the descriptor ID
5743 * in <b>query</b> and false otherwise. */
5745 hid_serv_responsible_for_desc_id(const char *query)
5747 routerinfo_t *me;
5748 routerstatus_t *last_rs;
5749 const char *my_id, *last_id;
5750 int result;
5751 smartlist_t *responsible;
5752 if (!hid_serv_acting_as_directory())
5753 return 0;
5754 if (!(me = router_get_my_routerinfo()))
5755 return 0; /* This is redundant, but let's be paranoid. */
5756 my_id = me->cache_info.identity_digest;
5757 responsible = smartlist_create();
5758 if (hid_serv_get_responsible_directories(responsible, query) < 0) {
5759 smartlist_free(responsible);
5760 return 0;
5762 last_rs = smartlist_get(responsible, smartlist_len(responsible)-1);
5763 last_id = last_rs->identity_digest;
5764 result = rend_id_is_in_interval(my_id, query, last_id);
5765 smartlist_free(responsible);
5766 return result;