Merge remote branch 'origin/maint-0.2.1' into maint-0.2.2
[tor/rransom.git] / src / or / routerlist.c
blob253b7872175e7b5dfb411e03d9bf00e4c27cea3f
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 = networkstatus_get_param(NULL, "bwweightscale",
1654 BW_WEIGHT_SCALE);
1656 if (rule == WEIGHT_FOR_GUARD) {
1657 Wg = networkstatus_get_bw_weight(NULL, "Wgg", -1);
1658 Wm = networkstatus_get_bw_weight(NULL, "Wgm", -1); /* Bridges */
1659 We = 0;
1660 Wd = networkstatus_get_bw_weight(NULL, "Wgd", -1);
1662 Wgb = networkstatus_get_bw_weight(NULL, "Wgb", -1);
1663 Wmb = networkstatus_get_bw_weight(NULL, "Wmb", -1);
1664 Web = networkstatus_get_bw_weight(NULL, "Web", -1);
1665 Wdb = networkstatus_get_bw_weight(NULL, "Wdb", -1);
1666 } else if (rule == WEIGHT_FOR_MID) {
1667 Wg = networkstatus_get_bw_weight(NULL, "Wmg", -1);
1668 Wm = networkstatus_get_bw_weight(NULL, "Wmm", -1);
1669 We = networkstatus_get_bw_weight(NULL, "Wme", -1);
1670 Wd = networkstatus_get_bw_weight(NULL, "Wmd", -1);
1672 Wgb = networkstatus_get_bw_weight(NULL, "Wgb", -1);
1673 Wmb = networkstatus_get_bw_weight(NULL, "Wmb", -1);
1674 Web = networkstatus_get_bw_weight(NULL, "Web", -1);
1675 Wdb = networkstatus_get_bw_weight(NULL, "Wdb", -1);
1676 } else if (rule == WEIGHT_FOR_EXIT) {
1677 // Guards CAN be exits if they have weird exit policies
1678 // They are d then I guess...
1679 We = networkstatus_get_bw_weight(NULL, "Wee", -1);
1680 Wm = networkstatus_get_bw_weight(NULL, "Wem", -1); /* Odd exit policies */
1681 Wd = networkstatus_get_bw_weight(NULL, "Wed", -1);
1682 Wg = networkstatus_get_bw_weight(NULL, "Weg", -1); /* Odd exit policies */
1684 Wgb = networkstatus_get_bw_weight(NULL, "Wgb", -1);
1685 Wmb = networkstatus_get_bw_weight(NULL, "Wmb", -1);
1686 Web = networkstatus_get_bw_weight(NULL, "Web", -1);
1687 Wdb = networkstatus_get_bw_weight(NULL, "Wdb", -1);
1688 } else if (rule == WEIGHT_FOR_DIR) {
1689 We = networkstatus_get_bw_weight(NULL, "Wbe", -1);
1690 Wm = networkstatus_get_bw_weight(NULL, "Wbm", -1);
1691 Wd = networkstatus_get_bw_weight(NULL, "Wbd", -1);
1692 Wg = networkstatus_get_bw_weight(NULL, "Wbg", -1);
1694 Wgb = Wmb = Web = Wdb = weight_scale;
1695 } else if (rule == NO_WEIGHTING) {
1696 Wg = Wm = We = Wd = weight_scale;
1697 Wgb = Wmb = Web = Wdb = weight_scale;
1700 if (Wg < 0 || Wm < 0 || We < 0 || Wd < 0 || Wgb < 0 || Wmb < 0 || Wdb < 0
1701 || Web < 0) {
1702 log_debug(LD_CIRC,
1703 "Got negative bandwidth weights. Defaulting to old selection"
1704 " algorithm.");
1705 return NULL; // Use old algorithm.
1708 Wg /= weight_scale;
1709 Wm /= weight_scale;
1710 We /= weight_scale;
1711 Wd /= weight_scale;
1713 Wgb /= weight_scale;
1714 Wmb /= weight_scale;
1715 Web /= weight_scale;
1716 Wdb /= weight_scale;
1718 bandwidths = tor_malloc_zero(sizeof(double)*smartlist_len(sl));
1720 // Cycle through smartlist and total the bandwidth.
1721 for (i = 0; i < (unsigned)smartlist_len(sl); ++i) {
1722 int is_exit = 0, is_guard = 0, is_dir = 0, this_bw = 0, is_me = 0;
1723 double weight = 1;
1724 if (statuses) {
1725 routerstatus_t *status = smartlist_get(sl, i);
1726 is_exit = status->is_exit;
1727 is_guard = status->is_possible_guard;
1728 is_dir = (status->dir_port != 0);
1729 if (!status->has_bandwidth) {
1730 tor_free(bandwidths);
1731 /* This should never happen, unless all the authorites downgrade
1732 * to 0.2.0 or rogue routerstatuses get inserted into our consensus. */
1733 log_warn(LD_BUG,
1734 "Consensus is not listing bandwidths. Defaulting back to "
1735 "old router selection algorithm.");
1736 return NULL;
1738 this_bw = kb_to_bytes(status->bandwidth);
1739 if (router_digest_is_me(status->identity_digest))
1740 is_me = 1;
1741 } else {
1742 routerstatus_t *rs;
1743 routerinfo_t *router = smartlist_get(sl, i);
1744 rs = router_get_consensus_status_by_id(
1745 router->cache_info.identity_digest);
1746 is_exit = router->is_exit;
1747 is_guard = router->is_possible_guard;
1748 is_dir = (router->dir_port != 0);
1749 if (rs && rs->has_bandwidth) {
1750 this_bw = kb_to_bytes(rs->bandwidth);
1751 } else { /* bridge or other descriptor not in our consensus */
1752 this_bw = bridge_get_advertised_bandwidth_bounded(router);
1753 have_unknown = 1;
1755 if (router_digest_is_me(router->cache_info.identity_digest))
1756 is_me = 1;
1758 if (is_guard && is_exit) {
1759 weight = (is_dir ? Wdb*Wd : Wd);
1760 } else if (is_guard) {
1761 weight = (is_dir ? Wgb*Wg : Wg);
1762 } else if (is_exit) {
1763 weight = (is_dir ? Web*We : We);
1764 } else { // middle
1765 weight = (is_dir ? Wmb*Wm : Wm);
1768 bandwidths[i] = weight*this_bw;
1769 weighted_bw += weight*this_bw;
1770 if (is_me)
1771 sl_last_weighted_bw_of_me = weight*this_bw;
1774 /* XXXX022 this is a kludge to expose these values. */
1775 sl_last_total_weighted_bw = weighted_bw;
1777 log_debug(LD_CIRC, "Choosing node for rule %s based on weights "
1778 "Wg=%lf Wm=%lf We=%lf Wd=%lf with total bw %lf",
1779 bandwidth_weight_rule_to_string(rule),
1780 Wg, Wm, We, Wd, weighted_bw);
1782 /* If there is no bandwidth, choose at random */
1783 if (DBL_TO_U64(weighted_bw) == 0) {
1784 /* Don't warn when using bridges/relays not in the consensus */
1785 if (!have_unknown)
1786 log_warn(LD_CIRC,
1787 "Weighted bandwidth is %lf in node selection for rule %s",
1788 weighted_bw, bandwidth_weight_rule_to_string(rule));
1789 tor_free(bandwidths);
1790 return smartlist_choose(sl);
1793 rand_bw = crypto_rand_uint64(DBL_TO_U64(weighted_bw));
1794 rand_bw++; /* crypto_rand_uint64() counts from 0, and we need to count
1795 * from 1 below. See bug 1203 for details. */
1797 /* Last, count through sl until we get to the element we picked */
1798 tmp = 0.0;
1799 for (i=0; i < (unsigned)smartlist_len(sl); i++) {
1800 tmp += bandwidths[i];
1801 if (tmp >= rand_bw)
1802 break;
1805 if (i == (unsigned)smartlist_len(sl)) {
1806 /* This was once possible due to round-off error, but shouldn't be able
1807 * to occur any longer. */
1808 tor_fragile_assert();
1809 --i;
1810 log_warn(LD_BUG, "Round-off error in computing bandwidth had an effect on "
1811 " which router we chose. Please tell the developers. "
1812 "%lf " U64_FORMAT " %lf", tmp, U64_PRINTF_ARG(rand_bw),
1813 weighted_bw);
1815 tor_free(bandwidths);
1816 return smartlist_get(sl, i);
1819 /** Helper function:
1820 * choose a random element of smartlist <b>sl</b>, weighted by
1821 * the advertised bandwidth of each element.
1823 * If <b>statuses</b> is zero, then <b>sl</b> is a list of
1824 * routerinfo_t's. Otherwise it's a list of routerstatus_t's.
1826 * If <b>rule</b>==WEIGHT_FOR_EXIT. we're picking an exit node: consider all
1827 * nodes' bandwidth equally regardless of their Exit status, since there may
1828 * be some in the list because they exit to obscure ports. If
1829 * <b>rule</b>==NO_WEIGHTING, we're picking a non-exit node: weight
1830 * exit-node's bandwidth less depending on the smallness of the fraction of
1831 * Exit-to-total bandwidth. If <b>rule</b>==WEIGHT_FOR_GUARD, we're picking a
1832 * guard node: consider all guard's bandwidth equally. Otherwise, weight
1833 * guards proportionally less.
1835 static void *
1836 smartlist_choose_by_bandwidth(smartlist_t *sl, bandwidth_weight_rule_t rule,
1837 int statuses)
1839 unsigned int i;
1840 routerinfo_t *router;
1841 routerstatus_t *status=NULL;
1842 int32_t *bandwidths;
1843 int is_exit;
1844 int is_guard;
1845 uint64_t total_nonexit_bw = 0, total_exit_bw = 0, total_bw = 0;
1846 uint64_t total_nonguard_bw = 0, total_guard_bw = 0;
1847 uint64_t rand_bw, tmp;
1848 double exit_weight;
1849 double guard_weight;
1850 int n_unknown = 0;
1851 bitarray_t *exit_bits;
1852 bitarray_t *guard_bits;
1853 int me_idx = -1;
1855 // This function does not support WEIGHT_FOR_DIR
1856 // or WEIGHT_FOR_MID
1857 if (rule == WEIGHT_FOR_DIR || rule == WEIGHT_FOR_MID) {
1858 rule = NO_WEIGHTING;
1861 /* Can't choose exit and guard at same time */
1862 tor_assert(rule == NO_WEIGHTING ||
1863 rule == WEIGHT_FOR_EXIT ||
1864 rule == WEIGHT_FOR_GUARD);
1866 if (smartlist_len(sl) == 0) {
1867 log_info(LD_CIRC,
1868 "Empty routerlist passed in to old node selection for rule %s",
1869 bandwidth_weight_rule_to_string(rule));
1870 return NULL;
1873 /* First count the total bandwidth weight, and make a list
1874 * of each value. <0 means "unknown; no routerinfo." We use the
1875 * bits of negative values to remember whether the router was fast (-x)&1
1876 * and whether it was an exit (-x)&2 or guard (-x)&4. Yes, it's a hack. */
1877 bandwidths = tor_malloc(sizeof(int32_t)*smartlist_len(sl));
1878 exit_bits = bitarray_init_zero(smartlist_len(sl));
1879 guard_bits = bitarray_init_zero(smartlist_len(sl));
1881 /* Iterate over all the routerinfo_t or routerstatus_t, and */
1882 for (i = 0; i < (unsigned)smartlist_len(sl); ++i) {
1883 /* first, learn what bandwidth we think i has */
1884 int is_known = 1;
1885 int32_t flags = 0;
1886 uint32_t this_bw = 0;
1887 if (statuses) {
1888 status = smartlist_get(sl, i);
1889 if (router_digest_is_me(status->identity_digest))
1890 me_idx = i;
1891 router = router_get_by_digest(status->identity_digest);
1892 is_exit = status->is_exit;
1893 is_guard = status->is_possible_guard;
1894 if (status->has_bandwidth) {
1895 this_bw = kb_to_bytes(status->bandwidth);
1896 } else { /* guess */
1897 /* XXX022 once consensuses always list bandwidths, we can take
1898 * this guessing business out. -RD */
1899 is_known = 0;
1900 flags = status->is_fast ? 1 : 0;
1901 flags |= is_exit ? 2 : 0;
1902 flags |= is_guard ? 4 : 0;
1904 } else {
1905 routerstatus_t *rs;
1906 router = smartlist_get(sl, i);
1907 rs = router_get_consensus_status_by_id(
1908 router->cache_info.identity_digest);
1909 if (router_digest_is_me(router->cache_info.identity_digest))
1910 me_idx = i;
1911 is_exit = router->is_exit;
1912 is_guard = router->is_possible_guard;
1913 if (rs && rs->has_bandwidth) {
1914 this_bw = kb_to_bytes(rs->bandwidth);
1915 } else if (rs) { /* guess; don't trust the descriptor */
1916 /* XXX022 once consensuses always list bandwidths, we can take
1917 * this guessing business out. -RD */
1918 is_known = 0;
1919 flags = router->is_fast ? 1 : 0;
1920 flags |= is_exit ? 2 : 0;
1921 flags |= is_guard ? 4 : 0;
1922 } else /* bridge or other descriptor not in our consensus */
1923 this_bw = bridge_get_advertised_bandwidth_bounded(router);
1925 if (is_exit)
1926 bitarray_set(exit_bits, i);
1927 if (is_guard)
1928 bitarray_set(guard_bits, i);
1929 if (is_known) {
1930 bandwidths[i] = (int32_t) this_bw; // safe since MAX_BELIEVABLE<INT32_MAX
1931 // XXX this is no longer true! We don't always cap the bw anymore. Can
1932 // a consensus make us overflow?-sh
1933 tor_assert(bandwidths[i] >= 0);
1934 if (is_guard)
1935 total_guard_bw += this_bw;
1936 else
1937 total_nonguard_bw += this_bw;
1938 if (is_exit)
1939 total_exit_bw += this_bw;
1940 else
1941 total_nonexit_bw += this_bw;
1942 } else {
1943 ++n_unknown;
1944 bandwidths[i] = -flags;
1948 /* Now, fill in the unknown values. */
1949 if (n_unknown) {
1950 int32_t avg_fast, avg_slow;
1951 if (total_exit_bw+total_nonexit_bw) {
1952 /* if there's some bandwidth, there's at least one known router,
1953 * so no worries about div by 0 here */
1954 int n_known = smartlist_len(sl)-n_unknown;
1955 avg_fast = avg_slow = (int32_t)
1956 ((total_exit_bw+total_nonexit_bw)/((uint64_t) n_known));
1957 } else {
1958 avg_fast = 40000;
1959 avg_slow = 20000;
1961 for (i=0; i<(unsigned)smartlist_len(sl); ++i) {
1962 int32_t bw = bandwidths[i];
1963 if (bw>=0)
1964 continue;
1965 is_exit = ((-bw)&2);
1966 is_guard = ((-bw)&4);
1967 bandwidths[i] = ((-bw)&1) ? avg_fast : avg_slow;
1968 if (is_exit)
1969 total_exit_bw += bandwidths[i];
1970 else
1971 total_nonexit_bw += bandwidths[i];
1972 if (is_guard)
1973 total_guard_bw += bandwidths[i];
1974 else
1975 total_nonguard_bw += bandwidths[i];
1979 /* If there's no bandwidth at all, pick at random. */
1980 if (!(total_exit_bw+total_nonexit_bw)) {
1981 tor_free(bandwidths);
1982 tor_free(exit_bits);
1983 tor_free(guard_bits);
1984 return smartlist_choose(sl);
1987 /* Figure out how to weight exits and guards */
1989 double all_bw = U64_TO_DBL(total_exit_bw+total_nonexit_bw);
1990 double exit_bw = U64_TO_DBL(total_exit_bw);
1991 double guard_bw = U64_TO_DBL(total_guard_bw);
1993 * For detailed derivation of this formula, see
1994 * http://archives.seul.org/or/dev/Jul-2007/msg00056.html
1996 if (rule == WEIGHT_FOR_EXIT || !total_exit_bw)
1997 exit_weight = 1.0;
1998 else
1999 exit_weight = 1.0 - all_bw/(3.0*exit_bw);
2001 if (rule == WEIGHT_FOR_GUARD || !total_guard_bw)
2002 guard_weight = 1.0;
2003 else
2004 guard_weight = 1.0 - all_bw/(3.0*guard_bw);
2006 if (exit_weight <= 0.0)
2007 exit_weight = 0.0;
2009 if (guard_weight <= 0.0)
2010 guard_weight = 0.0;
2012 total_bw = 0;
2013 sl_last_weighted_bw_of_me = 0;
2014 for (i=0; i < (unsigned)smartlist_len(sl); i++) {
2015 uint64_t bw;
2016 is_exit = bitarray_is_set(exit_bits, i);
2017 is_guard = bitarray_is_set(guard_bits, i);
2018 if (is_exit && is_guard)
2019 bw = ((uint64_t)(bandwidths[i] * exit_weight * guard_weight));
2020 else if (is_guard)
2021 bw = ((uint64_t)(bandwidths[i] * guard_weight));
2022 else if (is_exit)
2023 bw = ((uint64_t)(bandwidths[i] * exit_weight));
2024 else
2025 bw = bandwidths[i];
2026 total_bw += bw;
2027 if (i == (unsigned) me_idx)
2028 sl_last_weighted_bw_of_me = bw;
2032 /* XXXX022 this is a kludge to expose these values. */
2033 sl_last_total_weighted_bw = total_bw;
2035 log_debug(LD_CIRC, "Total weighted bw = "U64_FORMAT
2036 ", exit bw = "U64_FORMAT
2037 ", nonexit bw = "U64_FORMAT", exit weight = %lf "
2038 "(for exit == %d)"
2039 ", guard bw = "U64_FORMAT
2040 ", nonguard bw = "U64_FORMAT", guard weight = %lf "
2041 "(for guard == %d)",
2042 U64_PRINTF_ARG(total_bw),
2043 U64_PRINTF_ARG(total_exit_bw), U64_PRINTF_ARG(total_nonexit_bw),
2044 exit_weight, (int)(rule == WEIGHT_FOR_EXIT),
2045 U64_PRINTF_ARG(total_guard_bw), U64_PRINTF_ARG(total_nonguard_bw),
2046 guard_weight, (int)(rule == WEIGHT_FOR_GUARD));
2048 /* Almost done: choose a random value from the bandwidth weights. */
2049 rand_bw = crypto_rand_uint64(total_bw);
2050 rand_bw++; /* crypto_rand_uint64() counts from 0, and we need to count
2051 * from 1 below. See bug 1203 for details. */
2053 /* Last, count through sl until we get to the element we picked */
2054 tmp = 0;
2055 for (i=0; i < (unsigned)smartlist_len(sl); i++) {
2056 is_exit = bitarray_is_set(exit_bits, i);
2057 is_guard = bitarray_is_set(guard_bits, i);
2059 /* Weights can be 0 if not counting guards/exits */
2060 if (is_exit && is_guard)
2061 tmp += ((uint64_t)(bandwidths[i] * exit_weight * guard_weight));
2062 else if (is_guard)
2063 tmp += ((uint64_t)(bandwidths[i] * guard_weight));
2064 else if (is_exit)
2065 tmp += ((uint64_t)(bandwidths[i] * exit_weight));
2066 else
2067 tmp += bandwidths[i];
2069 if (tmp >= rand_bw)
2070 break;
2072 if (i == (unsigned)smartlist_len(sl)) {
2073 /* This was once possible due to round-off error, but shouldn't be able
2074 * to occur any longer. */
2075 tor_fragile_assert();
2076 --i;
2077 log_warn(LD_BUG, "Round-off error in computing bandwidth had an effect on "
2078 " which router we chose. Please tell the developers. "
2079 U64_FORMAT " " U64_FORMAT " " U64_FORMAT, U64_PRINTF_ARG(tmp),
2080 U64_PRINTF_ARG(rand_bw), U64_PRINTF_ARG(total_bw));
2082 tor_free(bandwidths);
2083 tor_free(exit_bits);
2084 tor_free(guard_bits);
2085 return smartlist_get(sl, i);
2088 /** Choose a random element of router list <b>sl</b>, weighted by
2089 * the advertised bandwidth of each router.
2091 routerinfo_t *
2092 routerlist_sl_choose_by_bandwidth(smartlist_t *sl,
2093 bandwidth_weight_rule_t rule)
2095 routerinfo_t *ret;
2096 if ((ret = smartlist_choose_by_bandwidth_weights(sl, rule, 0))) {
2097 return ret;
2098 } else {
2099 return smartlist_choose_by_bandwidth(sl, rule, 0);
2103 /** Choose a random element of status list <b>sl</b>, weighted by
2104 * the advertised bandwidth of each status.
2106 routerstatus_t *
2107 routerstatus_sl_choose_by_bandwidth(smartlist_t *sl,
2108 bandwidth_weight_rule_t rule)
2110 /* We are choosing neither exit nor guard here. Weight accordingly. */
2111 routerstatus_t *ret;
2112 if ((ret = smartlist_choose_by_bandwidth_weights(sl, rule, 1))) {
2113 return ret;
2114 } else {
2115 return smartlist_choose_by_bandwidth(sl, rule, 1);
2119 /** Return a random running router from the routerlist. Never
2120 * pick a node whose routerinfo is in
2121 * <b>excludedsmartlist</b>, or whose routerinfo matches <b>excludedset</b>,
2122 * even if they are the only nodes available.
2123 * If <b>CRN_NEED_UPTIME</b> is set in flags and any router has more than
2124 * a minimum uptime, return one of those.
2125 * If <b>CRN_NEED_CAPACITY</b> is set in flags, weight your choice by the
2126 * advertised capacity of each router.
2127 * If <b>CRN_ALLOW_INVALID</b> is not set in flags, consider only Valid
2128 * routers.
2129 * If <b>CRN_NEED_GUARD</b> is set in flags, consider only Guard routers.
2130 * If <b>CRN_WEIGHT_AS_EXIT</b> is set in flags, we weight bandwidths as if
2131 * picking an exit node, otherwise we weight bandwidths for picking a relay
2132 * node (that is, possibly discounting exit nodes).
2134 routerinfo_t *
2135 router_choose_random_node(smartlist_t *excludedsmartlist,
2136 routerset_t *excludedset,
2137 router_crn_flags_t flags)
2139 const int need_uptime = (flags & CRN_NEED_UPTIME) != 0;
2140 const int need_capacity = (flags & CRN_NEED_CAPACITY) != 0;
2141 const int need_guard = (flags & CRN_NEED_GUARD) != 0;
2142 const int allow_invalid = (flags & CRN_ALLOW_INVALID) != 0;
2143 const int weight_for_exit = (flags & CRN_WEIGHT_AS_EXIT) != 0;
2145 smartlist_t *sl=smartlist_create(),
2146 *excludednodes=smartlist_create();
2147 routerinfo_t *choice = NULL, *r;
2148 bandwidth_weight_rule_t rule;
2150 tor_assert(!(weight_for_exit && need_guard));
2151 rule = weight_for_exit ? WEIGHT_FOR_EXIT :
2152 (need_guard ? WEIGHT_FOR_GUARD : WEIGHT_FOR_MID);
2154 /* Exclude relays that allow single hop exit circuits, if the user
2155 * wants to (such relays might be risky) */
2156 if (get_options()->ExcludeSingleHopRelays) {
2157 routerlist_t *rl = router_get_routerlist();
2158 SMARTLIST_FOREACH(rl->routers, routerinfo_t *, r,
2159 if (r->allow_single_hop_exits) {
2160 smartlist_add(excludednodes, r);
2164 if ((r = routerlist_find_my_routerinfo())) {
2165 smartlist_add(excludednodes, r);
2166 routerlist_add_family(excludednodes, r);
2169 router_add_running_routers_to_smartlist(sl, allow_invalid,
2170 need_uptime, need_capacity,
2171 need_guard);
2172 smartlist_subtract(sl,excludednodes);
2173 if (excludedsmartlist)
2174 smartlist_subtract(sl,excludedsmartlist);
2175 if (excludedset)
2176 routerset_subtract_routers(sl,excludedset);
2178 // Always weight by bandwidth
2179 choice = routerlist_sl_choose_by_bandwidth(sl, rule);
2181 smartlist_free(sl);
2182 if (!choice && (need_uptime || need_capacity || need_guard)) {
2183 /* try once more -- recurse but with fewer restrictions. */
2184 log_info(LD_CIRC,
2185 "We couldn't find any live%s%s%s routers; falling back "
2186 "to list of all routers.",
2187 need_capacity?", fast":"",
2188 need_uptime?", stable":"",
2189 need_guard?", guard":"");
2190 flags &= ~ (CRN_NEED_UPTIME|CRN_NEED_CAPACITY|CRN_NEED_GUARD);
2191 choice = router_choose_random_node(
2192 excludedsmartlist, excludedset, flags);
2194 smartlist_free(excludednodes);
2195 if (!choice) {
2196 log_warn(LD_CIRC,
2197 "No available nodes when trying to choose node. Failing.");
2199 return choice;
2202 /** Helper: Return true iff the <b>identity_digest</b> and <b>nickname</b>
2203 * combination of a router, encoded in hexadecimal, matches <b>hexdigest</b>
2204 * (which is optionally prefixed with a single dollar sign). Return false if
2205 * <b>hexdigest</b> is malformed, or it doesn't match. */
2206 static INLINE int
2207 hex_digest_matches(const char *hexdigest, const char *identity_digest,
2208 const char *nickname, int is_named)
2210 char digest[DIGEST_LEN];
2211 size_t len;
2212 tor_assert(hexdigest);
2213 if (hexdigest[0] == '$')
2214 ++hexdigest;
2216 len = strlen(hexdigest);
2217 if (len < HEX_DIGEST_LEN)
2218 return 0;
2219 else if (len > HEX_DIGEST_LEN &&
2220 (hexdigest[HEX_DIGEST_LEN] == '=' ||
2221 hexdigest[HEX_DIGEST_LEN] == '~')) {
2222 if (strcasecmp(hexdigest+HEX_DIGEST_LEN+1, nickname))
2223 return 0;
2224 if (hexdigest[HEX_DIGEST_LEN] == '=' && !is_named)
2225 return 0;
2228 if (base16_decode(digest, DIGEST_LEN, hexdigest, HEX_DIGEST_LEN)<0)
2229 return 0;
2230 return (!memcmp(digest, identity_digest, DIGEST_LEN));
2233 /** Return true iff the digest of <b>router</b>'s identity key,
2234 * encoded in hexadecimal, matches <b>hexdigest</b> (which is
2235 * optionally prefixed with a single dollar sign). Return false if
2236 * <b>hexdigest</b> is malformed, or it doesn't match. */
2237 static INLINE int
2238 router_hex_digest_matches(routerinfo_t *router, const char *hexdigest)
2240 return hex_digest_matches(hexdigest, router->cache_info.identity_digest,
2241 router->nickname, router->is_named);
2244 /** Return true if <b>router</b>'s nickname matches <b>nickname</b>
2245 * (case-insensitive), or if <b>router's</b> identity key digest
2246 * matches a hexadecimal value stored in <b>nickname</b>. Return
2247 * false otherwise. */
2248 static int
2249 router_nickname_matches(routerinfo_t *router, const char *nickname)
2251 if (nickname[0]!='$' && !strcasecmp(router->nickname, nickname))
2252 return 1;
2253 return router_hex_digest_matches(router, nickname);
2256 /** Return the router in our routerlist whose (case-insensitive)
2257 * nickname or (case-sensitive) hexadecimal key digest is
2258 * <b>nickname</b>. Return NULL if no such router is known.
2260 routerinfo_t *
2261 router_get_by_nickname(const char *nickname, int warn_if_unnamed)
2263 int maybedigest;
2264 char digest[DIGEST_LEN];
2265 routerinfo_t *best_match=NULL;
2266 int n_matches = 0;
2267 const char *named_digest = NULL;
2269 tor_assert(nickname);
2270 if (!routerlist)
2271 return NULL;
2272 if (nickname[0] == '$')
2273 return router_get_by_hexdigest(nickname);
2274 if (!strcasecmp(nickname, UNNAMED_ROUTER_NICKNAME))
2275 return NULL;
2277 maybedigest = (strlen(nickname) >= HEX_DIGEST_LEN) &&
2278 (base16_decode(digest,DIGEST_LEN,nickname,HEX_DIGEST_LEN) == 0);
2280 if ((named_digest = networkstatus_get_router_digest_by_nickname(nickname))) {
2281 return rimap_get(routerlist->identity_map, named_digest);
2283 if (networkstatus_nickname_is_unnamed(nickname))
2284 return NULL;
2286 /* If we reach this point, there's no canonical value for the nickname. */
2288 SMARTLIST_FOREACH(routerlist->routers, routerinfo_t *, router,
2290 if (!strcasecmp(router->nickname, nickname)) {
2291 ++n_matches;
2292 if (n_matches <= 1 || router->is_running)
2293 best_match = router;
2294 } else if (maybedigest &&
2295 !memcmp(digest, router->cache_info.identity_digest, DIGEST_LEN)
2297 if (router_hex_digest_matches(router, nickname))
2298 return router;
2299 /* If we reach this point, we have a ID=name syntax that matches the
2300 * identity but not the name. That isn't an acceptable match. */
2304 if (best_match) {
2305 if (warn_if_unnamed && n_matches > 1) {
2306 smartlist_t *fps = smartlist_create();
2307 int any_unwarned = 0;
2308 SMARTLIST_FOREACH(routerlist->routers, routerinfo_t *, router,
2310 routerstatus_t *rs;
2311 char *desc;
2312 size_t dlen;
2313 char fp[HEX_DIGEST_LEN+1];
2314 if (strcasecmp(router->nickname, nickname))
2315 continue;
2316 rs = router_get_consensus_status_by_id(
2317 router->cache_info.identity_digest);
2318 if (rs && !rs->name_lookup_warned) {
2319 rs->name_lookup_warned = 1;
2320 any_unwarned = 1;
2322 base16_encode(fp, sizeof(fp),
2323 router->cache_info.identity_digest, DIGEST_LEN);
2324 dlen = 32 + HEX_DIGEST_LEN + strlen(router->address);
2325 desc = tor_malloc(dlen);
2326 tor_snprintf(desc, dlen, "\"$%s\" for the one at %s:%d",
2327 fp, router->address, router->or_port);
2328 smartlist_add(fps, desc);
2330 if (any_unwarned) {
2331 char *alternatives = smartlist_join_strings(fps, "; ",0,NULL);
2332 log_warn(LD_CONFIG,
2333 "There are multiple matches for the nickname \"%s\","
2334 " but none is listed as named by the directory authorities. "
2335 "Choosing one arbitrarily. If you meant one in particular, "
2336 "you should say %s.", nickname, alternatives);
2337 tor_free(alternatives);
2339 SMARTLIST_FOREACH(fps, char *, cp, tor_free(cp));
2340 smartlist_free(fps);
2341 } else if (warn_if_unnamed) {
2342 routerstatus_t *rs = router_get_consensus_status_by_id(
2343 best_match->cache_info.identity_digest);
2344 if (rs && !rs->name_lookup_warned) {
2345 char fp[HEX_DIGEST_LEN+1];
2346 base16_encode(fp, sizeof(fp),
2347 best_match->cache_info.identity_digest, DIGEST_LEN);
2348 log_warn(LD_CONFIG, "You specified a server \"%s\" by name, but this "
2349 "name is not registered, so it could be used by any server, "
2350 "not just the one you meant. "
2351 "To make sure you get the same server in the future, refer to "
2352 "it by key, as \"$%s\".", nickname, fp);
2353 rs->name_lookup_warned = 1;
2356 return best_match;
2359 return NULL;
2362 /** Try to find a routerinfo for <b>digest</b>. If we don't have one,
2363 * return 1. If we do, ask tor_version_as_new_as() for the answer.
2366 router_digest_version_as_new_as(const char *digest, const char *cutoff)
2368 routerinfo_t *router = router_get_by_digest(digest);
2369 if (!router)
2370 return 1;
2371 return tor_version_as_new_as(router->platform, cutoff);
2374 /** Return true iff <b>digest</b> is the digest of the identity key of a
2375 * trusted directory matching at least one bit of <b>type</b>. If <b>type</b>
2376 * is zero, any authority is okay. */
2378 router_digest_is_trusted_dir_type(const char *digest, authority_type_t type)
2380 if (!trusted_dir_servers)
2381 return 0;
2382 if (authdir_mode(get_options()) && router_digest_is_me(digest))
2383 return 1;
2384 SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, ent,
2385 if (!memcmp(digest, ent->digest, DIGEST_LEN)) {
2386 return (!type) || ((type & ent->type) != 0);
2388 return 0;
2391 /** Return true iff <b>addr</b> is the address of one of our trusted
2392 * directory authorities. */
2394 router_addr_is_trusted_dir(uint32_t addr)
2396 if (!trusted_dir_servers)
2397 return 0;
2398 SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, ent,
2399 if (ent->addr == addr)
2400 return 1;
2402 return 0;
2405 /** If hexdigest is correctly formed, base16_decode it into
2406 * digest, which must have DIGEST_LEN space in it.
2407 * Return 0 on success, -1 on failure.
2410 hexdigest_to_digest(const char *hexdigest, char *digest)
2412 if (hexdigest[0]=='$')
2413 ++hexdigest;
2414 if (strlen(hexdigest) < HEX_DIGEST_LEN ||
2415 base16_decode(digest,DIGEST_LEN,hexdigest,HEX_DIGEST_LEN) < 0)
2416 return -1;
2417 return 0;
2420 /** Return the router in our routerlist whose hexadecimal key digest
2421 * is <b>hexdigest</b>. Return NULL if no such router is known. */
2422 routerinfo_t *
2423 router_get_by_hexdigest(const char *hexdigest)
2425 char digest[DIGEST_LEN];
2426 size_t len;
2427 routerinfo_t *ri;
2429 tor_assert(hexdigest);
2430 if (!routerlist)
2431 return NULL;
2432 if (hexdigest[0]=='$')
2433 ++hexdigest;
2434 len = strlen(hexdigest);
2435 if (hexdigest_to_digest(hexdigest, digest) < 0)
2436 return NULL;
2438 ri = router_get_by_digest(digest);
2440 if (ri && len > HEX_DIGEST_LEN) {
2441 if (hexdigest[HEX_DIGEST_LEN] == '=') {
2442 if (strcasecmp(ri->nickname, hexdigest+HEX_DIGEST_LEN+1) ||
2443 !ri->is_named)
2444 return NULL;
2445 } else if (hexdigest[HEX_DIGEST_LEN] == '~') {
2446 if (strcasecmp(ri->nickname, hexdigest+HEX_DIGEST_LEN+1))
2447 return NULL;
2448 } else {
2449 return NULL;
2453 return ri;
2456 /** Return the router in our routerlist whose 20-byte key digest
2457 * is <b>digest</b>. Return NULL if no such router is known. */
2458 routerinfo_t *
2459 router_get_by_digest(const char *digest)
2461 tor_assert(digest);
2463 if (!routerlist) return NULL;
2465 // routerlist_assert_ok(routerlist);
2467 return rimap_get(routerlist->identity_map, digest);
2470 /** Return the router in our routerlist whose 20-byte descriptor
2471 * is <b>digest</b>. Return NULL if no such router is known. */
2472 signed_descriptor_t *
2473 router_get_by_descriptor_digest(const char *digest)
2475 tor_assert(digest);
2477 if (!routerlist) return NULL;
2479 return sdmap_get(routerlist->desc_digest_map, digest);
2482 /** Return the signed descriptor for the router in our routerlist whose
2483 * 20-byte extra-info digest is <b>digest</b>. Return NULL if no such router
2484 * is known. */
2485 signed_descriptor_t *
2486 router_get_by_extrainfo_digest(const char *digest)
2488 tor_assert(digest);
2490 if (!routerlist) return NULL;
2492 return sdmap_get(routerlist->desc_by_eid_map, digest);
2495 /** Return the signed descriptor for the extrainfo_t in our routerlist whose
2496 * extra-info-digest is <b>digest</b>. Return NULL if no such extra-info
2497 * document is known. */
2498 signed_descriptor_t *
2499 extrainfo_get_by_descriptor_digest(const char *digest)
2501 extrainfo_t *ei;
2502 tor_assert(digest);
2503 if (!routerlist) return NULL;
2504 ei = eimap_get(routerlist->extra_info_map, digest);
2505 return ei ? &ei->cache_info : NULL;
2508 /** Return a pointer to the signed textual representation of a descriptor.
2509 * The returned string is not guaranteed to be NUL-terminated: the string's
2510 * length will be in desc-\>signed_descriptor_len.
2512 * If <b>with_annotations</b> is set, the returned string will include
2513 * the annotations
2514 * (if any) preceding the descriptor. This will increase the length of the
2515 * string by desc-\>annotations_len.
2517 * The caller must not free the string returned.
2519 static const char *
2520 signed_descriptor_get_body_impl(signed_descriptor_t *desc,
2521 int with_annotations)
2523 const char *r = NULL;
2524 size_t len = desc->signed_descriptor_len;
2525 off_t offset = desc->saved_offset;
2526 if (with_annotations)
2527 len += desc->annotations_len;
2528 else
2529 offset += desc->annotations_len;
2531 tor_assert(len > 32);
2532 if (desc->saved_location == SAVED_IN_CACHE && routerlist) {
2533 desc_store_t *store = desc_get_store(router_get_routerlist(), desc);
2534 if (store && store->mmap) {
2535 tor_assert(desc->saved_offset + len <= store->mmap->size);
2536 r = store->mmap->data + offset;
2537 } else if (store) {
2538 log_err(LD_DIR, "We couldn't read a descriptor that is supposedly "
2539 "mmaped in our cache. Is another process running in our data "
2540 "directory? Exiting.");
2541 exit(1);
2544 if (!r) /* no mmap, or not in cache. */
2545 r = desc->signed_descriptor_body +
2546 (with_annotations ? 0 : desc->annotations_len);
2548 tor_assert(r);
2549 if (!with_annotations) {
2550 if (memcmp("router ", r, 7) && memcmp("extra-info ", r, 11)) {
2551 char *cp = tor_strndup(r, 64);
2552 log_err(LD_DIR, "descriptor at %p begins with unexpected string %s. "
2553 "Is another process running in our data directory? Exiting.",
2554 desc, escaped(cp));
2555 exit(1);
2559 return r;
2562 /** Return a pointer to the signed textual representation of a descriptor.
2563 * The returned string is not guaranteed to be NUL-terminated: the string's
2564 * length will be in desc-\>signed_descriptor_len.
2566 * The caller must not free the string returned.
2568 const char *
2569 signed_descriptor_get_body(signed_descriptor_t *desc)
2571 return signed_descriptor_get_body_impl(desc, 0);
2574 /** As signed_descriptor_get_body(), but points to the beginning of the
2575 * annotations section rather than the beginning of the descriptor. */
2576 const char *
2577 signed_descriptor_get_annotations(signed_descriptor_t *desc)
2579 return signed_descriptor_get_body_impl(desc, 1);
2582 /** Return the current list of all known routers. */
2583 routerlist_t *
2584 router_get_routerlist(void)
2586 if (PREDICT_UNLIKELY(!routerlist)) {
2587 routerlist = tor_malloc_zero(sizeof(routerlist_t));
2588 routerlist->routers = smartlist_create();
2589 routerlist->old_routers = smartlist_create();
2590 routerlist->identity_map = rimap_new();
2591 routerlist->desc_digest_map = sdmap_new();
2592 routerlist->desc_by_eid_map = sdmap_new();
2593 routerlist->extra_info_map = eimap_new();
2595 routerlist->desc_store.fname_base = "cached-descriptors";
2596 routerlist->desc_store.fname_alt_base = "cached-routers";
2597 routerlist->extrainfo_store.fname_base = "cached-extrainfo";
2599 routerlist->desc_store.type = ROUTER_STORE;
2600 routerlist->extrainfo_store.type = EXTRAINFO_STORE;
2602 routerlist->desc_store.description = "router descriptors";
2603 routerlist->extrainfo_store.description = "extra-info documents";
2605 return routerlist;
2608 /** Free all storage held by <b>router</b>. */
2609 void
2610 routerinfo_free(routerinfo_t *router)
2612 if (!router)
2613 return;
2615 tor_free(router->cache_info.signed_descriptor_body);
2616 tor_free(router->address);
2617 tor_free(router->nickname);
2618 tor_free(router->platform);
2619 tor_free(router->contact_info);
2620 if (router->onion_pkey)
2621 crypto_free_pk_env(router->onion_pkey);
2622 if (router->identity_pkey)
2623 crypto_free_pk_env(router->identity_pkey);
2624 if (router->declared_family) {
2625 SMARTLIST_FOREACH(router->declared_family, char *, s, tor_free(s));
2626 smartlist_free(router->declared_family);
2628 addr_policy_list_free(router->exit_policy);
2630 /* XXXX Remove if this turns out to affect performance. */
2631 memset(router, 77, sizeof(routerinfo_t));
2633 tor_free(router);
2636 /** Release all storage held by <b>extrainfo</b> */
2637 void
2638 extrainfo_free(extrainfo_t *extrainfo)
2640 if (!extrainfo)
2641 return;
2642 tor_free(extrainfo->cache_info.signed_descriptor_body);
2643 tor_free(extrainfo->pending_sig);
2645 /* XXXX remove this if it turns out to slow us down. */
2646 memset(extrainfo, 88, sizeof(extrainfo_t)); /* debug bad memory usage */
2647 tor_free(extrainfo);
2650 /** Release storage held by <b>sd</b>. */
2651 static void
2652 signed_descriptor_free(signed_descriptor_t *sd)
2654 if (!sd)
2655 return;
2657 tor_free(sd->signed_descriptor_body);
2659 /* XXXX remove this once more bugs go away. */
2660 memset(sd, 99, sizeof(signed_descriptor_t)); /* Debug bad mem usage */
2661 tor_free(sd);
2664 /** Extract a signed_descriptor_t from a general routerinfo, and free the
2665 * routerinfo.
2667 static signed_descriptor_t *
2668 signed_descriptor_from_routerinfo(routerinfo_t *ri)
2670 signed_descriptor_t *sd;
2671 tor_assert(ri->purpose == ROUTER_PURPOSE_GENERAL);
2672 sd = tor_malloc_zero(sizeof(signed_descriptor_t));
2673 memcpy(sd, &(ri->cache_info), sizeof(signed_descriptor_t));
2674 sd->routerlist_index = -1;
2675 ri->cache_info.signed_descriptor_body = NULL;
2676 routerinfo_free(ri);
2677 return sd;
2680 /** Helper: free the storage held by the extrainfo_t in <b>e</b>. */
2681 static void
2682 _extrainfo_free(void *e)
2684 extrainfo_free(e);
2687 /** Free all storage held by a routerlist <b>rl</b>. */
2688 void
2689 routerlist_free(routerlist_t *rl)
2691 if (!rl)
2692 return;
2693 rimap_free(rl->identity_map, NULL);
2694 sdmap_free(rl->desc_digest_map, NULL);
2695 sdmap_free(rl->desc_by_eid_map, NULL);
2696 eimap_free(rl->extra_info_map, _extrainfo_free);
2697 SMARTLIST_FOREACH(rl->routers, routerinfo_t *, r,
2698 routerinfo_free(r));
2699 SMARTLIST_FOREACH(rl->old_routers, signed_descriptor_t *, sd,
2700 signed_descriptor_free(sd));
2701 smartlist_free(rl->routers);
2702 smartlist_free(rl->old_routers);
2703 if (routerlist->desc_store.mmap)
2704 tor_munmap_file(routerlist->desc_store.mmap);
2705 if (routerlist->extrainfo_store.mmap)
2706 tor_munmap_file(routerlist->extrainfo_store.mmap);
2707 tor_free(rl);
2709 router_dir_info_changed();
2712 /** Log information about how much memory is being used for routerlist,
2713 * at log level <b>severity</b>. */
2714 void
2715 dump_routerlist_mem_usage(int severity)
2717 uint64_t livedescs = 0;
2718 uint64_t olddescs = 0;
2719 if (!routerlist)
2720 return;
2721 SMARTLIST_FOREACH(routerlist->routers, routerinfo_t *, r,
2722 livedescs += r->cache_info.signed_descriptor_len);
2723 SMARTLIST_FOREACH(routerlist->old_routers, signed_descriptor_t *, sd,
2724 olddescs += sd->signed_descriptor_len);
2726 log(severity, LD_DIR,
2727 "In %d live descriptors: "U64_FORMAT" bytes. "
2728 "In %d old descriptors: "U64_FORMAT" bytes.",
2729 smartlist_len(routerlist->routers), U64_PRINTF_ARG(livedescs),
2730 smartlist_len(routerlist->old_routers), U64_PRINTF_ARG(olddescs));
2733 /** Debugging helper: If <b>idx</b> is nonnegative, assert that <b>ri</b> is
2734 * in <b>sl</b> at position <b>idx</b>. Otherwise, search <b>sl</b> for
2735 * <b>ri</b>. Return the index of <b>ri</b> in <b>sl</b>, or -1 if <b>ri</b>
2736 * is not in <b>sl</b>. */
2737 static INLINE int
2738 _routerlist_find_elt(smartlist_t *sl, void *ri, int idx)
2740 if (idx < 0) {
2741 idx = -1;
2742 SMARTLIST_FOREACH(sl, routerinfo_t *, r,
2743 if (r == ri) {
2744 idx = r_sl_idx;
2745 break;
2747 } else {
2748 tor_assert(idx < smartlist_len(sl));
2749 tor_assert(smartlist_get(sl, idx) == ri);
2751 return idx;
2754 /** Insert an item <b>ri</b> into the routerlist <b>rl</b>, updating indices
2755 * as needed. There must be no previous member of <b>rl</b> with the same
2756 * identity digest as <b>ri</b>: If there is, call routerlist_replace
2757 * instead.
2759 static void
2760 routerlist_insert(routerlist_t *rl, routerinfo_t *ri)
2762 routerinfo_t *ri_old;
2763 signed_descriptor_t *sd_old;
2765 /* XXXX Remove if this slows us down. */
2766 routerinfo_t *ri_generated = router_get_my_routerinfo();
2767 tor_assert(ri_generated != ri);
2769 tor_assert(ri->cache_info.routerlist_index == -1);
2771 ri_old = rimap_set(rl->identity_map, ri->cache_info.identity_digest, ri);
2772 tor_assert(!ri_old);
2774 sd_old = sdmap_set(rl->desc_digest_map,
2775 ri->cache_info.signed_descriptor_digest,
2776 &(ri->cache_info));
2777 if (sd_old) {
2778 rl->desc_store.bytes_dropped += sd_old->signed_descriptor_len;
2779 sdmap_remove(rl->desc_by_eid_map, sd_old->extra_info_digest);
2780 signed_descriptor_free(sd_old);
2783 if (!tor_digest_is_zero(ri->cache_info.extra_info_digest))
2784 sdmap_set(rl->desc_by_eid_map, ri->cache_info.extra_info_digest,
2785 &ri->cache_info);
2786 smartlist_add(rl->routers, ri);
2787 ri->cache_info.routerlist_index = smartlist_len(rl->routers) - 1;
2788 router_dir_info_changed();
2789 #ifdef DEBUG_ROUTERLIST
2790 routerlist_assert_ok(rl);
2791 #endif
2794 /** Adds the extrainfo_t <b>ei</b> to the routerlist <b>rl</b>, if there is a
2795 * corresponding router in rl-\>routers or rl-\>old_routers. Return true iff
2796 * we actually inserted <b>ei</b>. Free <b>ei</b> if it isn't inserted. */
2797 static int
2798 extrainfo_insert(routerlist_t *rl, extrainfo_t *ei)
2800 int r = 0;
2801 routerinfo_t *ri = rimap_get(rl->identity_map,
2802 ei->cache_info.identity_digest);
2803 signed_descriptor_t *sd =
2804 sdmap_get(rl->desc_by_eid_map, ei->cache_info.signed_descriptor_digest);
2805 extrainfo_t *ei_tmp;
2808 /* XXXX remove this code if it slows us down. */
2809 extrainfo_t *ei_generated = router_get_my_extrainfo();
2810 tor_assert(ei_generated != ei);
2813 if (!ri) {
2814 /* This router is unknown; we can't even verify the signature. Give up.*/
2815 goto done;
2817 if (routerinfo_incompatible_with_extrainfo(ri, ei, sd, NULL)) {
2818 goto done;
2821 /* Okay, if we make it here, we definitely have a router corresponding to
2822 * this extrainfo. */
2824 ei_tmp = eimap_set(rl->extra_info_map,
2825 ei->cache_info.signed_descriptor_digest,
2826 ei);
2827 r = 1;
2828 if (ei_tmp) {
2829 rl->extrainfo_store.bytes_dropped +=
2830 ei_tmp->cache_info.signed_descriptor_len;
2831 extrainfo_free(ei_tmp);
2834 done:
2835 if (r == 0)
2836 extrainfo_free(ei);
2838 #ifdef DEBUG_ROUTERLIST
2839 routerlist_assert_ok(rl);
2840 #endif
2841 return r;
2844 #define should_cache_old_descriptors() \
2845 directory_caches_dir_info(get_options())
2847 /** If we're a directory cache and routerlist <b>rl</b> doesn't have
2848 * a copy of router <b>ri</b> yet, add it to the list of old (not
2849 * recommended but still served) descriptors. Else free it. */
2850 static void
2851 routerlist_insert_old(routerlist_t *rl, routerinfo_t *ri)
2854 /* XXXX remove this code if it slows us down. */
2855 routerinfo_t *ri_generated = router_get_my_routerinfo();
2856 tor_assert(ri_generated != ri);
2858 tor_assert(ri->cache_info.routerlist_index == -1);
2860 if (should_cache_old_descriptors() &&
2861 ri->purpose == ROUTER_PURPOSE_GENERAL &&
2862 !sdmap_get(rl->desc_digest_map,
2863 ri->cache_info.signed_descriptor_digest)) {
2864 signed_descriptor_t *sd = signed_descriptor_from_routerinfo(ri);
2865 sdmap_set(rl->desc_digest_map, sd->signed_descriptor_digest, sd);
2866 smartlist_add(rl->old_routers, sd);
2867 sd->routerlist_index = smartlist_len(rl->old_routers)-1;
2868 if (!tor_digest_is_zero(sd->extra_info_digest))
2869 sdmap_set(rl->desc_by_eid_map, sd->extra_info_digest, sd);
2870 } else {
2871 routerinfo_free(ri);
2873 #ifdef DEBUG_ROUTERLIST
2874 routerlist_assert_ok(rl);
2875 #endif
2878 /** Remove an item <b>ri</b> from the routerlist <b>rl</b>, updating indices
2879 * as needed. If <b>idx</b> is nonnegative and smartlist_get(rl-&gt;routers,
2880 * idx) == ri, we don't need to do a linear search over the list to decide
2881 * which to remove. We fill the gap in rl-&gt;routers with a later element in
2882 * the list, if any exists. <b>ri</b> is freed.
2884 * If <b>make_old</b> is true, instead of deleting the router, we try adding
2885 * it to rl-&gt;old_routers. */
2886 void
2887 routerlist_remove(routerlist_t *rl, routerinfo_t *ri, int make_old, time_t now)
2889 routerinfo_t *ri_tmp;
2890 extrainfo_t *ei_tmp;
2891 int idx = ri->cache_info.routerlist_index;
2892 tor_assert(0 <= idx && idx < smartlist_len(rl->routers));
2893 tor_assert(smartlist_get(rl->routers, idx) == ri);
2895 /* make sure the rephist module knows that it's not running */
2896 rep_hist_note_router_unreachable(ri->cache_info.identity_digest, now);
2898 ri->cache_info.routerlist_index = -1;
2899 smartlist_del(rl->routers, idx);
2900 if (idx < smartlist_len(rl->routers)) {
2901 routerinfo_t *r = smartlist_get(rl->routers, idx);
2902 r->cache_info.routerlist_index = idx;
2905 ri_tmp = rimap_remove(rl->identity_map, ri->cache_info.identity_digest);
2906 router_dir_info_changed();
2907 tor_assert(ri_tmp == ri);
2909 if (make_old && should_cache_old_descriptors() &&
2910 ri->purpose == ROUTER_PURPOSE_GENERAL) {
2911 signed_descriptor_t *sd;
2912 sd = signed_descriptor_from_routerinfo(ri);
2913 smartlist_add(rl->old_routers, sd);
2914 sd->routerlist_index = smartlist_len(rl->old_routers)-1;
2915 sdmap_set(rl->desc_digest_map, sd->signed_descriptor_digest, sd);
2916 if (!tor_digest_is_zero(sd->extra_info_digest))
2917 sdmap_set(rl->desc_by_eid_map, sd->extra_info_digest, sd);
2918 } else {
2919 signed_descriptor_t *sd_tmp;
2920 sd_tmp = sdmap_remove(rl->desc_digest_map,
2921 ri->cache_info.signed_descriptor_digest);
2922 tor_assert(sd_tmp == &(ri->cache_info));
2923 rl->desc_store.bytes_dropped += ri->cache_info.signed_descriptor_len;
2924 ei_tmp = eimap_remove(rl->extra_info_map,
2925 ri->cache_info.extra_info_digest);
2926 if (ei_tmp) {
2927 rl->extrainfo_store.bytes_dropped +=
2928 ei_tmp->cache_info.signed_descriptor_len;
2929 extrainfo_free(ei_tmp);
2931 if (!tor_digest_is_zero(ri->cache_info.extra_info_digest))
2932 sdmap_remove(rl->desc_by_eid_map, ri->cache_info.extra_info_digest);
2933 routerinfo_free(ri);
2935 #ifdef DEBUG_ROUTERLIST
2936 routerlist_assert_ok(rl);
2937 #endif
2940 /** Remove a signed_descriptor_t <b>sd</b> from <b>rl</b>-\>old_routers, and
2941 * adjust <b>rl</b> as appropriate. <b>idx</b> is -1, or the index of
2942 * <b>sd</b>. */
2943 static void
2944 routerlist_remove_old(routerlist_t *rl, signed_descriptor_t *sd, int idx)
2946 signed_descriptor_t *sd_tmp;
2947 extrainfo_t *ei_tmp;
2948 desc_store_t *store;
2949 if (idx == -1) {
2950 idx = sd->routerlist_index;
2952 tor_assert(0 <= idx && idx < smartlist_len(rl->old_routers));
2953 /* XXXX edmanm's bridge relay triggered the following assert while
2954 * running 0.2.0.12-alpha. If anybody triggers this again, see if we
2955 * can get a backtrace. */
2956 tor_assert(smartlist_get(rl->old_routers, idx) == sd);
2957 tor_assert(idx == sd->routerlist_index);
2959 sd->routerlist_index = -1;
2960 smartlist_del(rl->old_routers, idx);
2961 if (idx < smartlist_len(rl->old_routers)) {
2962 signed_descriptor_t *d = smartlist_get(rl->old_routers, idx);
2963 d->routerlist_index = idx;
2965 sd_tmp = sdmap_remove(rl->desc_digest_map,
2966 sd->signed_descriptor_digest);
2967 tor_assert(sd_tmp == sd);
2968 store = desc_get_store(rl, sd);
2969 if (store)
2970 store->bytes_dropped += sd->signed_descriptor_len;
2972 ei_tmp = eimap_remove(rl->extra_info_map,
2973 sd->extra_info_digest);
2974 if (ei_tmp) {
2975 rl->extrainfo_store.bytes_dropped +=
2976 ei_tmp->cache_info.signed_descriptor_len;
2977 extrainfo_free(ei_tmp);
2979 if (!tor_digest_is_zero(sd->extra_info_digest))
2980 sdmap_remove(rl->desc_by_eid_map, sd->extra_info_digest);
2982 signed_descriptor_free(sd);
2983 #ifdef DEBUG_ROUTERLIST
2984 routerlist_assert_ok(rl);
2985 #endif
2988 /** Remove <b>ri_old</b> from the routerlist <b>rl</b>, and replace it with
2989 * <b>ri_new</b>, updating all index info. If <b>idx</b> is nonnegative and
2990 * smartlist_get(rl-&gt;routers, idx) == ri, we don't need to do a linear
2991 * search over the list to decide which to remove. We put ri_new in the same
2992 * index as ri_old, if possible. ri is freed as appropriate.
2994 * If should_cache_descriptors() is true, instead of deleting the router,
2995 * we add it to rl-&gt;old_routers. */
2996 static void
2997 routerlist_replace(routerlist_t *rl, routerinfo_t *ri_old,
2998 routerinfo_t *ri_new)
3000 int idx;
3001 int same_descriptors;
3003 routerinfo_t *ri_tmp;
3004 extrainfo_t *ei_tmp;
3006 /* XXXX Remove this if it turns out to slow us down. */
3007 routerinfo_t *ri_generated = router_get_my_routerinfo();
3008 tor_assert(ri_generated != ri_new);
3010 tor_assert(ri_old != ri_new);
3011 tor_assert(ri_new->cache_info.routerlist_index == -1);
3013 idx = ri_old->cache_info.routerlist_index;
3014 tor_assert(0 <= idx && idx < smartlist_len(rl->routers));
3015 tor_assert(smartlist_get(rl->routers, idx) == ri_old);
3017 router_dir_info_changed();
3018 if (idx >= 0) {
3019 smartlist_set(rl->routers, idx, ri_new);
3020 ri_old->cache_info.routerlist_index = -1;
3021 ri_new->cache_info.routerlist_index = idx;
3022 /* Check that ri_old is not in rl->routers anymore: */
3023 tor_assert( _routerlist_find_elt(rl->routers, ri_old, -1) == -1 );
3024 } else {
3025 log_warn(LD_BUG, "Appending entry from routerlist_replace.");
3026 routerlist_insert(rl, ri_new);
3027 return;
3029 if (memcmp(ri_old->cache_info.identity_digest,
3030 ri_new->cache_info.identity_digest, DIGEST_LEN)) {
3031 /* digests don't match; digestmap_set won't replace */
3032 rimap_remove(rl->identity_map, ri_old->cache_info.identity_digest);
3034 ri_tmp = rimap_set(rl->identity_map,
3035 ri_new->cache_info.identity_digest, ri_new);
3036 tor_assert(!ri_tmp || ri_tmp == ri_old);
3037 sdmap_set(rl->desc_digest_map,
3038 ri_new->cache_info.signed_descriptor_digest,
3039 &(ri_new->cache_info));
3041 if (!tor_digest_is_zero(ri_new->cache_info.extra_info_digest)) {
3042 sdmap_set(rl->desc_by_eid_map, ri_new->cache_info.extra_info_digest,
3043 &ri_new->cache_info);
3046 same_descriptors = ! memcmp(ri_old->cache_info.signed_descriptor_digest,
3047 ri_new->cache_info.signed_descriptor_digest,
3048 DIGEST_LEN);
3050 if (should_cache_old_descriptors() &&
3051 ri_old->purpose == ROUTER_PURPOSE_GENERAL &&
3052 !same_descriptors) {
3053 /* ri_old is going to become a signed_descriptor_t and go into
3054 * old_routers */
3055 signed_descriptor_t *sd = signed_descriptor_from_routerinfo(ri_old);
3056 smartlist_add(rl->old_routers, sd);
3057 sd->routerlist_index = smartlist_len(rl->old_routers)-1;
3058 sdmap_set(rl->desc_digest_map, sd->signed_descriptor_digest, sd);
3059 if (!tor_digest_is_zero(sd->extra_info_digest))
3060 sdmap_set(rl->desc_by_eid_map, sd->extra_info_digest, sd);
3061 } else {
3062 /* We're dropping ri_old. */
3063 if (!same_descriptors) {
3064 /* digests don't match; The sdmap_set above didn't replace */
3065 sdmap_remove(rl->desc_digest_map,
3066 ri_old->cache_info.signed_descriptor_digest);
3068 if (memcmp(ri_old->cache_info.extra_info_digest,
3069 ri_new->cache_info.extra_info_digest, DIGEST_LEN)) {
3070 ei_tmp = eimap_remove(rl->extra_info_map,
3071 ri_old->cache_info.extra_info_digest);
3072 if (ei_tmp) {
3073 rl->extrainfo_store.bytes_dropped +=
3074 ei_tmp->cache_info.signed_descriptor_len;
3075 extrainfo_free(ei_tmp);
3079 if (!tor_digest_is_zero(ri_old->cache_info.extra_info_digest)) {
3080 sdmap_remove(rl->desc_by_eid_map,
3081 ri_old->cache_info.extra_info_digest);
3084 rl->desc_store.bytes_dropped += ri_old->cache_info.signed_descriptor_len;
3085 routerinfo_free(ri_old);
3087 #ifdef DEBUG_ROUTERLIST
3088 routerlist_assert_ok(rl);
3089 #endif
3092 /** Extract the descriptor <b>sd</b> from old_routerlist, and re-parse
3093 * it as a fresh routerinfo_t. */
3094 static routerinfo_t *
3095 routerlist_reparse_old(routerlist_t *rl, signed_descriptor_t *sd)
3097 routerinfo_t *ri;
3098 const char *body;
3100 body = signed_descriptor_get_annotations(sd);
3102 ri = router_parse_entry_from_string(body,
3103 body+sd->signed_descriptor_len+sd->annotations_len,
3104 0, 1, NULL);
3105 if (!ri)
3106 return NULL;
3107 memcpy(&ri->cache_info, sd, sizeof(signed_descriptor_t));
3108 sd->signed_descriptor_body = NULL; /* Steal reference. */
3109 ri->cache_info.routerlist_index = -1;
3111 routerlist_remove_old(rl, sd, -1);
3113 return ri;
3116 /** Free all memory held by the routerlist module. */
3117 void
3118 routerlist_free_all(void)
3120 routerlist_free(routerlist);
3121 routerlist = NULL;
3122 if (warned_nicknames) {
3123 SMARTLIST_FOREACH(warned_nicknames, char *, cp, tor_free(cp));
3124 smartlist_free(warned_nicknames);
3125 warned_nicknames = NULL;
3127 if (trusted_dir_servers) {
3128 SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, ds,
3129 trusted_dir_server_free(ds));
3130 smartlist_free(trusted_dir_servers);
3131 trusted_dir_servers = NULL;
3133 if (trusted_dir_certs) {
3134 DIGESTMAP_FOREACH(trusted_dir_certs, key, cert_list_t *, cl) {
3135 SMARTLIST_FOREACH(cl->certs, authority_cert_t *, cert,
3136 authority_cert_free(cert));
3137 smartlist_free(cl->certs);
3138 tor_free(cl);
3139 } DIGESTMAP_FOREACH_END;
3140 digestmap_free(trusted_dir_certs, NULL);
3141 trusted_dir_certs = NULL;
3145 /** Forget that we have issued any router-related warnings, so that we'll
3146 * warn again if we see the same errors. */
3147 void
3148 routerlist_reset_warnings(void)
3150 if (!warned_nicknames)
3151 warned_nicknames = smartlist_create();
3152 SMARTLIST_FOREACH(warned_nicknames, char *, cp, tor_free(cp));
3153 smartlist_clear(warned_nicknames); /* now the list is empty. */
3155 networkstatus_reset_warnings();
3158 /** Mark the router with ID <b>digest</b> as running or non-running
3159 * in our routerlist. */
3160 void
3161 router_set_status(const char *digest, int up)
3163 routerinfo_t *router;
3164 routerstatus_t *status;
3165 tor_assert(digest);
3167 SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, d,
3168 if (!memcmp(d->digest, digest, DIGEST_LEN))
3169 d->is_running = up);
3171 router = router_get_by_digest(digest);
3172 if (router) {
3173 log_debug(LD_DIR,"Marking router '%s/%s' as %s.",
3174 router->nickname, router->address, up ? "up" : "down");
3175 if (!up && router_is_me(router) && !we_are_hibernating())
3176 log_warn(LD_NET, "We just marked ourself as down. Are your external "
3177 "addresses reachable?");
3178 router->is_running = up;
3180 status = router_get_consensus_status_by_id(digest);
3181 if (status && status->is_running != up) {
3182 status->is_running = up;
3183 control_event_networkstatus_changed_single(status);
3185 router_dir_info_changed();
3188 /** Add <b>router</b> to the routerlist, if we don't already have it. Replace
3189 * older entries (if any) with the same key. Note: Callers should not hold
3190 * their pointers to <b>router</b> if this function fails; <b>router</b>
3191 * will either be inserted into the routerlist or freed. Similarly, even
3192 * if this call succeeds, they should not hold their pointers to
3193 * <b>router</b> after subsequent calls with other routerinfo's -- they
3194 * might cause the original routerinfo to get freed.
3196 * Returns the status for the operation. Might set *<b>msg</b> if it wants
3197 * the poster of the router to know something.
3199 * If <b>from_cache</b>, this descriptor came from our disk cache. If
3200 * <b>from_fetch</b>, we received it in response to a request we made.
3201 * (If both are false, that means it was uploaded to us as an auth dir
3202 * server or via the controller.)
3204 * This function should be called *after*
3205 * routers_update_status_from_consensus_networkstatus; subsequently, you
3206 * should call router_rebuild_store and routerlist_descriptors_added.
3208 was_router_added_t
3209 router_add_to_routerlist(routerinfo_t *router, const char **msg,
3210 int from_cache, int from_fetch)
3212 const char *id_digest;
3213 int authdir = authdir_mode_handles_descs(get_options(), router->purpose);
3214 int authdir_believes_valid = 0;
3215 routerinfo_t *old_router;
3216 networkstatus_t *consensus = networkstatus_get_latest_consensus();
3217 const smartlist_t *networkstatus_v2_list = networkstatus_get_v2_list();
3218 int in_consensus = 0;
3220 tor_assert(msg);
3222 if (!routerlist)
3223 router_get_routerlist();
3225 id_digest = router->cache_info.identity_digest;
3227 old_router = router_get_by_digest(id_digest);
3229 /* Make sure that we haven't already got this exact descriptor. */
3230 if (sdmap_get(routerlist->desc_digest_map,
3231 router->cache_info.signed_descriptor_digest)) {
3232 /* If we have this descriptor already and the new descriptor is a bridge
3233 * descriptor, replace it. If we had a bridge descriptor before and the
3234 * new one is not a bridge descriptor, don't replace it. */
3236 /* Only members of routerlist->identity_map can be bridges; we don't
3237 * put bridges in old_routers. */
3238 const int was_bridge = old_router &&
3239 old_router->purpose == ROUTER_PURPOSE_BRIDGE;
3241 if (routerinfo_is_a_configured_bridge(router) &&
3242 router->purpose == ROUTER_PURPOSE_BRIDGE &&
3243 !was_bridge) {
3244 log_info(LD_DIR, "Replacing non-bridge descriptor with bridge "
3245 "descriptor for router '%s'", router->nickname);
3246 } else {
3247 log_info(LD_DIR,
3248 "Dropping descriptor that we already have for router '%s'",
3249 router->nickname);
3250 *msg = "Router descriptor was not new.";
3251 routerinfo_free(router);
3252 return ROUTER_WAS_NOT_NEW;
3256 if (authdir) {
3257 if (authdir_wants_to_reject_router(router, msg,
3258 !from_cache && !from_fetch)) {
3259 tor_assert(*msg);
3260 routerinfo_free(router);
3261 return ROUTER_AUTHDIR_REJECTS;
3263 authdir_believes_valid = router->is_valid;
3264 } else if (from_fetch) {
3265 /* Only check the descriptor digest against the network statuses when
3266 * we are receiving in response to a fetch. */
3268 if (!signed_desc_digest_is_recognized(&router->cache_info) &&
3269 !routerinfo_is_a_configured_bridge(router)) {
3270 /* We asked for it, so some networkstatus must have listed it when we
3271 * did. Save it if we're a cache in case somebody else asks for it. */
3272 log_info(LD_DIR,
3273 "Received a no-longer-recognized descriptor for router '%s'",
3274 router->nickname);
3275 *msg = "Router descriptor is not referenced by any network-status.";
3277 /* Only journal this desc if we'll be serving it. */
3278 if (!from_cache && should_cache_old_descriptors())
3279 signed_desc_append_to_journal(&router->cache_info,
3280 &routerlist->desc_store);
3281 routerlist_insert_old(routerlist, router);
3282 return ROUTER_NOT_IN_CONSENSUS_OR_NETWORKSTATUS;
3286 /* We no longer need a router with this descriptor digest. */
3287 SMARTLIST_FOREACH(networkstatus_v2_list, networkstatus_v2_t *, ns,
3289 routerstatus_t *rs =
3290 networkstatus_v2_find_entry(ns, id_digest);
3291 if (rs && !memcmp(rs->descriptor_digest,
3292 router->cache_info.signed_descriptor_digest,
3293 DIGEST_LEN))
3294 rs->need_to_mirror = 0;
3296 if (consensus) {
3297 routerstatus_t *rs = networkstatus_vote_find_entry(consensus, id_digest);
3298 if (rs && !memcmp(rs->descriptor_digest,
3299 router->cache_info.signed_descriptor_digest,
3300 DIGEST_LEN)) {
3301 in_consensus = 1;
3302 rs->need_to_mirror = 0;
3306 if (router->purpose == ROUTER_PURPOSE_GENERAL &&
3307 consensus && !in_consensus && !authdir) {
3308 /* If it's a general router not listed in the consensus, then don't
3309 * consider replacing the latest router with it. */
3310 if (!from_cache && should_cache_old_descriptors())
3311 signed_desc_append_to_journal(&router->cache_info,
3312 &routerlist->desc_store);
3313 routerlist_insert_old(routerlist, router);
3314 *msg = "Skipping router descriptor: not in consensus.";
3315 return ROUTER_NOT_IN_CONSENSUS;
3318 /* If we have a router with the same identity key, choose the newer one. */
3319 if (old_router) {
3320 if (!in_consensus && (router->cache_info.published_on <=
3321 old_router->cache_info.published_on)) {
3322 /* Same key, but old. This one is not listed in the consensus. */
3323 log_debug(LD_DIR, "Not-new descriptor for router '%s'",
3324 router->nickname);
3325 /* Only journal this desc if we'll be serving it. */
3326 if (!from_cache && should_cache_old_descriptors())
3327 signed_desc_append_to_journal(&router->cache_info,
3328 &routerlist->desc_store);
3329 routerlist_insert_old(routerlist, router);
3330 *msg = "Router descriptor was not new.";
3331 return ROUTER_WAS_NOT_NEW;
3332 } else {
3333 /* Same key, and either new, or listed in the consensus. */
3334 log_debug(LD_DIR, "Replacing entry for router '%s/%s' [%s]",
3335 router->nickname, old_router->nickname,
3336 hex_str(id_digest,DIGEST_LEN));
3337 if (routers_have_same_or_addr(router, old_router)) {
3338 /* these carry over when the address and orport are unchanged. */
3339 router->last_reachable = old_router->last_reachable;
3340 router->testing_since = old_router->testing_since;
3342 routerlist_replace(routerlist, old_router, router);
3343 if (!from_cache) {
3344 signed_desc_append_to_journal(&router->cache_info,
3345 &routerlist->desc_store);
3347 directory_set_dirty();
3348 *msg = authdir_believes_valid ? "Valid server updated" :
3349 ("Invalid server updated. (This dirserver is marking your "
3350 "server as unapproved.)");
3351 return ROUTER_ADDED_SUCCESSFULLY;
3355 if (!in_consensus && from_cache &&
3356 router->cache_info.published_on < time(NULL) - OLD_ROUTER_DESC_MAX_AGE) {
3357 *msg = "Router descriptor was really old.";
3358 routerinfo_free(router);
3359 return ROUTER_WAS_NOT_NEW;
3362 /* We haven't seen a router with this identity before. Add it to the end of
3363 * the list. */
3364 routerlist_insert(routerlist, router);
3365 if (!from_cache) {
3366 signed_desc_append_to_journal(&router->cache_info,
3367 &routerlist->desc_store);
3369 directory_set_dirty();
3370 return ROUTER_ADDED_SUCCESSFULLY;
3373 /** Insert <b>ei</b> into the routerlist, or free it. Other arguments are
3374 * as for router_add_to_routerlist(). Return ROUTER_ADDED_SUCCESSFULLY iff
3375 * we actually inserted it, ROUTER_BAD_EI otherwise.
3377 was_router_added_t
3378 router_add_extrainfo_to_routerlist(extrainfo_t *ei, const char **msg,
3379 int from_cache, int from_fetch)
3381 int inserted;
3382 (void)from_fetch;
3383 if (msg) *msg = NULL;
3384 /*XXXX022 Do something with msg */
3386 inserted = extrainfo_insert(router_get_routerlist(), ei);
3388 if (inserted && !from_cache)
3389 signed_desc_append_to_journal(&ei->cache_info,
3390 &routerlist->extrainfo_store);
3392 if (inserted)
3393 return ROUTER_ADDED_SUCCESSFULLY;
3394 else
3395 return ROUTER_BAD_EI;
3398 /** Sorting helper: return &lt;0, 0, or &gt;0 depending on whether the
3399 * signed_descriptor_t* in *<b>a</b> has an identity digest preceding, equal
3400 * to, or later than that of *<b>b</b>. */
3401 static int
3402 _compare_old_routers_by_identity(const void **_a, const void **_b)
3404 int i;
3405 const signed_descriptor_t *r1 = *_a, *r2 = *_b;
3406 if ((i = memcmp(r1->identity_digest, r2->identity_digest, DIGEST_LEN)))
3407 return i;
3408 return (int)(r1->published_on - r2->published_on);
3411 /** Internal type used to represent how long an old descriptor was valid,
3412 * where it appeared in the list of old descriptors, and whether it's extra
3413 * old. Used only by routerlist_remove_old_cached_routers_with_id(). */
3414 struct duration_idx_t {
3415 int duration;
3416 int idx;
3417 int old;
3420 /** Sorting helper: compare two duration_idx_t by their duration. */
3421 static int
3422 _compare_duration_idx(const void *_d1, const void *_d2)
3424 const struct duration_idx_t *d1 = _d1;
3425 const struct duration_idx_t *d2 = _d2;
3426 return d1->duration - d2->duration;
3429 /** The range <b>lo</b> through <b>hi</b> inclusive of routerlist->old_routers
3430 * must contain routerinfo_t with the same identity and with publication time
3431 * in ascending order. Remove members from this range until there are no more
3432 * than max_descriptors_per_router() remaining. Start by removing the oldest
3433 * members from before <b>cutoff</b>, then remove members which were current
3434 * for the lowest amount of time. The order of members of old_routers at
3435 * indices <b>lo</b> or higher may be changed.
3437 static void
3438 routerlist_remove_old_cached_routers_with_id(time_t now,
3439 time_t cutoff, int lo, int hi,
3440 digestset_t *retain)
3442 int i, n = hi-lo+1;
3443 unsigned n_extra, n_rmv = 0;
3444 struct duration_idx_t *lifespans;
3445 uint8_t *rmv, *must_keep;
3446 smartlist_t *lst = routerlist->old_routers;
3447 #if 1
3448 const char *ident;
3449 tor_assert(hi < smartlist_len(lst));
3450 tor_assert(lo <= hi);
3451 ident = ((signed_descriptor_t*)smartlist_get(lst, lo))->identity_digest;
3452 for (i = lo+1; i <= hi; ++i) {
3453 signed_descriptor_t *r = smartlist_get(lst, i);
3454 tor_assert(!memcmp(ident, r->identity_digest, DIGEST_LEN));
3456 #endif
3457 /* Check whether we need to do anything at all. */
3459 int mdpr = directory_caches_dir_info(get_options()) ? 2 : 1;
3460 if (n <= mdpr)
3461 return;
3462 n_extra = n - mdpr;
3465 lifespans = tor_malloc_zero(sizeof(struct duration_idx_t)*n);
3466 rmv = tor_malloc_zero(sizeof(uint8_t)*n);
3467 must_keep = tor_malloc_zero(sizeof(uint8_t)*n);
3468 /* Set lifespans to contain the lifespan and index of each server. */
3469 /* Set rmv[i-lo]=1 if we're going to remove a server for being too old. */
3470 for (i = lo; i <= hi; ++i) {
3471 signed_descriptor_t *r = smartlist_get(lst, i);
3472 signed_descriptor_t *r_next;
3473 lifespans[i-lo].idx = i;
3474 if (r->last_listed_as_valid_until >= now ||
3475 (retain && digestset_isin(retain, r->signed_descriptor_digest))) {
3476 must_keep[i-lo] = 1;
3478 if (i < hi) {
3479 r_next = smartlist_get(lst, i+1);
3480 tor_assert(r->published_on <= r_next->published_on);
3481 lifespans[i-lo].duration = (int)(r_next->published_on - r->published_on);
3482 } else {
3483 r_next = NULL;
3484 lifespans[i-lo].duration = INT_MAX;
3486 if (!must_keep[i-lo] && r->published_on < cutoff && n_rmv < n_extra) {
3487 ++n_rmv;
3488 lifespans[i-lo].old = 1;
3489 rmv[i-lo] = 1;
3493 if (n_rmv < n_extra) {
3495 * We aren't removing enough servers for being old. Sort lifespans by
3496 * the duration of liveness, and remove the ones we're not already going to
3497 * remove based on how long they were alive.
3499 qsort(lifespans, n, sizeof(struct duration_idx_t), _compare_duration_idx);
3500 for (i = 0; i < n && n_rmv < n_extra; ++i) {
3501 if (!must_keep[lifespans[i].idx-lo] && !lifespans[i].old) {
3502 rmv[lifespans[i].idx-lo] = 1;
3503 ++n_rmv;
3508 i = hi;
3509 do {
3510 if (rmv[i-lo])
3511 routerlist_remove_old(routerlist, smartlist_get(lst, i), i);
3512 } while (--i >= lo);
3513 tor_free(must_keep);
3514 tor_free(rmv);
3515 tor_free(lifespans);
3518 /** Deactivate any routers from the routerlist that are more than
3519 * ROUTER_MAX_AGE seconds old and not recommended by any networkstatuses;
3520 * remove old routers from the list of cached routers if we have too many.
3522 void
3523 routerlist_remove_old_routers(void)
3525 int i, hi=-1;
3526 const char *cur_id = NULL;
3527 time_t now = time(NULL);
3528 time_t cutoff;
3529 routerinfo_t *router;
3530 signed_descriptor_t *sd;
3531 digestset_t *retain;
3532 int caches = directory_caches_dir_info(get_options());
3533 const networkstatus_t *consensus = networkstatus_get_latest_consensus();
3534 const smartlist_t *networkstatus_v2_list = networkstatus_get_v2_list();
3535 int have_enough_v2;
3537 trusted_dirs_remove_old_certs();
3539 if (!routerlist || !consensus)
3540 return;
3542 // routerlist_assert_ok(routerlist);
3544 /* We need to guess how many router descriptors we will wind up wanting to
3545 retain, so that we can be sure to allocate a large enough Bloom filter
3546 to hold the digest set. Overestimating is fine; underestimating is bad.
3549 /* We'll probably retain everything in the consensus. */
3550 int n_max_retain = smartlist_len(consensus->routerstatus_list);
3551 if (caches && networkstatus_v2_list) {
3552 /* If we care about v2 statuses, we'll retain at most as many as are
3553 listed any of the v2 statues. This will be at least the length of
3554 the largest v2 networkstatus, and in the worst case, this set will be
3555 equal to the sum of the lengths of all v2 consensuses. Take the
3556 worst case.
3558 SMARTLIST_FOREACH(networkstatus_v2_list, networkstatus_v2_t *, ns,
3559 n_max_retain += smartlist_len(ns->entries));
3561 retain = digestset_new(n_max_retain);
3564 cutoff = now - OLD_ROUTER_DESC_MAX_AGE;
3565 /* Build a list of all the descriptors that _anybody_ lists. */
3566 if (caches && networkstatus_v2_list) {
3567 SMARTLIST_FOREACH(networkstatus_v2_list, networkstatus_v2_t *, ns,
3569 /* XXXX The inner loop here gets pretty expensive, and actually shows up
3570 * on some profiles. It may be the reason digestmap_set shows up in
3571 * profiles too. If instead we kept a per-descriptor digest count of
3572 * how many networkstatuses recommended each descriptor, and changed
3573 * that only when the networkstatuses changed, that would be a speed
3574 * improvement, possibly 1-4% if it also removes digestmap_set from the
3575 * profile. Not worth it for 0.1.2.x, though. The new directory
3576 * system will obsolete this whole thing in 0.2.0.x. */
3577 SMARTLIST_FOREACH(ns->entries, routerstatus_t *, rs,
3578 if (rs->published_on >= cutoff)
3579 digestset_add(retain, rs->descriptor_digest));
3583 /* Retain anything listed in the consensus. */
3584 if (consensus) {
3585 SMARTLIST_FOREACH(consensus->routerstatus_list, routerstatus_t *, rs,
3586 if (rs->published_on >= cutoff)
3587 digestset_add(retain, rs->descriptor_digest));
3590 /* If we have a consensus, and nearly as many v2 networkstatuses as we want,
3591 * we should consider pruning current routers that are too old and that
3592 * nobody recommends. (If we don't have a consensus or enough v2
3593 * networkstatuses, then we should get more before we decide to kill
3594 * routers.) */
3595 /* we set this to true iff we don't care about v2 info, or we have enough. */
3596 have_enough_v2 = !caches ||
3597 (networkstatus_v2_list &&
3598 smartlist_len(networkstatus_v2_list) > get_n_v2_authorities() / 2);
3600 if (have_enough_v2 && consensus) {
3601 cutoff = now - ROUTER_MAX_AGE;
3602 /* Remove too-old unrecommended members of routerlist->routers. */
3603 for (i = 0; i < smartlist_len(routerlist->routers); ++i) {
3604 router = smartlist_get(routerlist->routers, i);
3605 if (router->cache_info.published_on <= cutoff &&
3606 router->cache_info.last_listed_as_valid_until < now &&
3607 !digestset_isin(retain,
3608 router->cache_info.signed_descriptor_digest)) {
3609 /* Too old: remove it. (If we're a cache, just move it into
3610 * old_routers.) */
3611 log_info(LD_DIR,
3612 "Forgetting obsolete (too old) routerinfo for router '%s'",
3613 router->nickname);
3614 routerlist_remove(routerlist, router, 1, now);
3615 i--;
3620 //routerlist_assert_ok(routerlist);
3622 /* Remove far-too-old members of routerlist->old_routers. */
3623 cutoff = now - OLD_ROUTER_DESC_MAX_AGE;
3624 for (i = 0; i < smartlist_len(routerlist->old_routers); ++i) {
3625 sd = smartlist_get(routerlist->old_routers, i);
3626 if (sd->published_on <= cutoff &&
3627 sd->last_listed_as_valid_until < now &&
3628 !digestset_isin(retain, sd->signed_descriptor_digest)) {
3629 /* Too old. Remove it. */
3630 routerlist_remove_old(routerlist, sd, i--);
3634 //routerlist_assert_ok(routerlist);
3636 log_info(LD_DIR, "We have %d live routers and %d old router descriptors.",
3637 smartlist_len(routerlist->routers),
3638 smartlist_len(routerlist->old_routers));
3640 /* Now we might have to look at routerlist->old_routers for extraneous
3641 * members. (We'd keep all the members if we could, but we need to save
3642 * space.) First, check whether we have too many router descriptors, total.
3643 * We're okay with having too many for some given router, so long as the
3644 * total number doesn't approach max_descriptors_per_router()*len(router).
3646 if (smartlist_len(routerlist->old_routers) <
3647 smartlist_len(routerlist->routers))
3648 goto done;
3650 /* Sort by identity, then fix indices. */
3651 smartlist_sort(routerlist->old_routers, _compare_old_routers_by_identity);
3652 /* Fix indices. */
3653 for (i = 0; i < smartlist_len(routerlist->old_routers); ++i) {
3654 signed_descriptor_t *r = smartlist_get(routerlist->old_routers, i);
3655 r->routerlist_index = i;
3658 /* Iterate through the list from back to front, so when we remove descriptors
3659 * we don't mess up groups we haven't gotten to. */
3660 for (i = smartlist_len(routerlist->old_routers)-1; i >= 0; --i) {
3661 signed_descriptor_t *r = smartlist_get(routerlist->old_routers, i);
3662 if (!cur_id) {
3663 cur_id = r->identity_digest;
3664 hi = i;
3666 if (memcmp(cur_id, r->identity_digest, DIGEST_LEN)) {
3667 routerlist_remove_old_cached_routers_with_id(now,
3668 cutoff, i+1, hi, retain);
3669 cur_id = r->identity_digest;
3670 hi = i;
3673 if (hi>=0)
3674 routerlist_remove_old_cached_routers_with_id(now, cutoff, 0, hi, retain);
3675 //routerlist_assert_ok(routerlist);
3677 done:
3678 digestset_free(retain);
3679 router_rebuild_store(RRS_DONT_REMOVE_OLD, &routerlist->desc_store);
3680 router_rebuild_store(RRS_DONT_REMOVE_OLD,&routerlist->extrainfo_store);
3683 /** We just added a new set of descriptors. Take whatever extra steps
3684 * we need. */
3685 void
3686 routerlist_descriptors_added(smartlist_t *sl, int from_cache)
3688 tor_assert(sl);
3689 control_event_descriptors_changed(sl);
3690 SMARTLIST_FOREACH_BEGIN(sl, routerinfo_t *, ri) {
3691 if (ri->purpose == ROUTER_PURPOSE_BRIDGE)
3692 learned_bridge_descriptor(ri, from_cache);
3693 if (ri->needs_retest_if_added) {
3694 ri->needs_retest_if_added = 0;
3695 dirserv_single_reachability_test(approx_time(), ri);
3697 } SMARTLIST_FOREACH_END(ri);
3701 * Code to parse a single router descriptor and insert it into the
3702 * routerlist. Return -1 if the descriptor was ill-formed; 0 if the
3703 * descriptor was well-formed but could not be added; and 1 if the
3704 * descriptor was added.
3706 * If we don't add it and <b>msg</b> is not NULL, then assign to
3707 * *<b>msg</b> a static string describing the reason for refusing the
3708 * descriptor.
3710 * This is used only by the controller.
3713 router_load_single_router(const char *s, uint8_t purpose, int cache,
3714 const char **msg)
3716 routerinfo_t *ri;
3717 was_router_added_t r;
3718 smartlist_t *lst;
3719 char annotation_buf[ROUTER_ANNOTATION_BUF_LEN];
3720 tor_assert(msg);
3721 *msg = NULL;
3723 tor_snprintf(annotation_buf, sizeof(annotation_buf),
3724 "@source controller\n"
3725 "@purpose %s\n", router_purpose_to_string(purpose));
3727 if (!(ri = router_parse_entry_from_string(s, NULL, 1, 0, annotation_buf))) {
3728 log_warn(LD_DIR, "Error parsing router descriptor; dropping.");
3729 *msg = "Couldn't parse router descriptor.";
3730 return -1;
3732 tor_assert(ri->purpose == purpose);
3733 if (router_is_me(ri)) {
3734 log_warn(LD_DIR, "Router's identity key matches mine; dropping.");
3735 *msg = "Router's identity key matches mine.";
3736 routerinfo_free(ri);
3737 return 0;
3740 if (!cache) /* obey the preference of the controller */
3741 ri->cache_info.do_not_cache = 1;
3743 lst = smartlist_create();
3744 smartlist_add(lst, ri);
3745 routers_update_status_from_consensus_networkstatus(lst, 0);
3747 r = router_add_to_routerlist(ri, msg, 0, 0);
3748 if (!WRA_WAS_ADDED(r)) {
3749 /* we've already assigned to *msg now, and ri is already freed */
3750 tor_assert(*msg);
3751 if (r == ROUTER_AUTHDIR_REJECTS)
3752 log_warn(LD_DIR, "Couldn't add router to list: %s Dropping.", *msg);
3753 smartlist_free(lst);
3754 return 0;
3755 } else {
3756 routerlist_descriptors_added(lst, 0);
3757 smartlist_free(lst);
3758 log_debug(LD_DIR, "Added router to list");
3759 return 1;
3763 /** Given a string <b>s</b> containing some routerdescs, parse it and put the
3764 * routers into our directory. If saved_location is SAVED_NOWHERE, the routers
3765 * are in response to a query to the network: cache them by adding them to
3766 * the journal.
3768 * Return the number of routers actually added.
3770 * If <b>requested_fingerprints</b> is provided, it must contain a list of
3771 * uppercased fingerprints. Do not update any router whose
3772 * fingerprint is not on the list; after updating a router, remove its
3773 * fingerprint from the list.
3775 * If <b>descriptor_digests</b> is non-zero, then the requested_fingerprints
3776 * are descriptor digests. Otherwise they are identity digests.
3779 router_load_routers_from_string(const char *s, const char *eos,
3780 saved_location_t saved_location,
3781 smartlist_t *requested_fingerprints,
3782 int descriptor_digests,
3783 const char *prepend_annotations)
3785 smartlist_t *routers = smartlist_create(), *changed = smartlist_create();
3786 char fp[HEX_DIGEST_LEN+1];
3787 const char *msg;
3788 int from_cache = (saved_location != SAVED_NOWHERE);
3789 int allow_annotations = (saved_location != SAVED_NOWHERE);
3790 int any_changed = 0;
3792 router_parse_list_from_string(&s, eos, routers, saved_location, 0,
3793 allow_annotations, prepend_annotations);
3795 routers_update_status_from_consensus_networkstatus(routers, !from_cache);
3797 log_info(LD_DIR, "%d elements to add", smartlist_len(routers));
3799 SMARTLIST_FOREACH_BEGIN(routers, routerinfo_t *, ri) {
3800 was_router_added_t r;
3801 char d[DIGEST_LEN];
3802 if (requested_fingerprints) {
3803 base16_encode(fp, sizeof(fp), descriptor_digests ?
3804 ri->cache_info.signed_descriptor_digest :
3805 ri->cache_info.identity_digest,
3806 DIGEST_LEN);
3807 if (smartlist_string_isin(requested_fingerprints, fp)) {
3808 smartlist_string_remove(requested_fingerprints, fp);
3809 } else {
3810 char *requested =
3811 smartlist_join_strings(requested_fingerprints," ",0,NULL);
3812 log_warn(LD_DIR,
3813 "We received a router descriptor with a fingerprint (%s) "
3814 "that we never requested. (We asked for: %s.) Dropping.",
3815 fp, requested);
3816 tor_free(requested);
3817 routerinfo_free(ri);
3818 continue;
3822 memcpy(d, ri->cache_info.signed_descriptor_digest, DIGEST_LEN);
3823 r = router_add_to_routerlist(ri, &msg, from_cache, !from_cache);
3824 if (WRA_WAS_ADDED(r)) {
3825 any_changed++;
3826 smartlist_add(changed, ri);
3827 routerlist_descriptors_added(changed, from_cache);
3828 smartlist_clear(changed);
3829 } else if (WRA_WAS_REJECTED(r)) {
3830 download_status_t *dl_status;
3831 dl_status = router_get_dl_status_by_descriptor_digest(d);
3832 if (dl_status) {
3833 log_info(LD_GENERAL, "Marking router %s as never downloadable",
3834 hex_str(d, DIGEST_LEN));
3835 download_status_mark_impossible(dl_status);
3838 } SMARTLIST_FOREACH_END(ri);
3840 routerlist_assert_ok(routerlist);
3842 if (any_changed)
3843 router_rebuild_store(0, &routerlist->desc_store);
3845 smartlist_free(routers);
3846 smartlist_free(changed);
3848 return any_changed;
3851 /** Parse one or more extrainfos from <b>s</b> (ending immediately before
3852 * <b>eos</b> if <b>eos</b> is present). Other arguments are as for
3853 * router_load_routers_from_string(). */
3854 void
3855 router_load_extrainfo_from_string(const char *s, const char *eos,
3856 saved_location_t saved_location,
3857 smartlist_t *requested_fingerprints,
3858 int descriptor_digests)
3860 smartlist_t *extrainfo_list = smartlist_create();
3861 const char *msg;
3862 int from_cache = (saved_location != SAVED_NOWHERE);
3864 router_parse_list_from_string(&s, eos, extrainfo_list, saved_location, 1, 0,
3865 NULL);
3867 log_info(LD_DIR, "%d elements to add", smartlist_len(extrainfo_list));
3869 SMARTLIST_FOREACH(extrainfo_list, extrainfo_t *, ei, {
3870 was_router_added_t added =
3871 router_add_extrainfo_to_routerlist(ei, &msg, from_cache, !from_cache);
3872 if (WRA_WAS_ADDED(added) && requested_fingerprints) {
3873 char fp[HEX_DIGEST_LEN+1];
3874 base16_encode(fp, sizeof(fp), descriptor_digests ?
3875 ei->cache_info.signed_descriptor_digest :
3876 ei->cache_info.identity_digest,
3877 DIGEST_LEN);
3878 smartlist_string_remove(requested_fingerprints, fp);
3879 /* We silently let people stuff us with extrainfos we didn't ask for,
3880 * so long as we would have wanted them anyway. Since we always fetch
3881 * all the extrainfos we want, and we never actually act on them
3882 * inside Tor, this should be harmless. */
3886 routerlist_assert_ok(routerlist);
3887 router_rebuild_store(0, &router_get_routerlist()->extrainfo_store);
3889 smartlist_free(extrainfo_list);
3892 /** Return true iff any networkstatus includes a descriptor whose digest
3893 * is that of <b>desc</b>. */
3894 static int
3895 signed_desc_digest_is_recognized(signed_descriptor_t *desc)
3897 routerstatus_t *rs;
3898 networkstatus_t *consensus = networkstatus_get_latest_consensus();
3899 int caches = directory_caches_dir_info(get_options());
3900 const smartlist_t *networkstatus_v2_list = networkstatus_get_v2_list();
3902 if (consensus) {
3903 rs = networkstatus_vote_find_entry(consensus, desc->identity_digest);
3904 if (rs && !memcmp(rs->descriptor_digest,
3905 desc->signed_descriptor_digest, DIGEST_LEN))
3906 return 1;
3908 if (caches && networkstatus_v2_list) {
3909 SMARTLIST_FOREACH(networkstatus_v2_list, networkstatus_v2_t *, ns,
3911 if (!(rs = networkstatus_v2_find_entry(ns, desc->identity_digest)))
3912 continue;
3913 if (!memcmp(rs->descriptor_digest,
3914 desc->signed_descriptor_digest, DIGEST_LEN))
3915 return 1;
3918 return 0;
3921 /** Clear all our timeouts for fetching v2 and v3 directory stuff, and then
3922 * give it all a try again. */
3923 void
3924 routerlist_retry_directory_downloads(time_t now)
3926 router_reset_status_download_failures();
3927 router_reset_descriptor_download_failures();
3928 update_networkstatus_downloads(now);
3929 update_router_descriptor_downloads(now);
3932 /** Return 1 if all running sufficiently-stable routers will reject
3933 * addr:port, return 0 if any might accept it. */
3935 router_exit_policy_all_routers_reject(uint32_t addr, uint16_t port,
3936 int need_uptime)
3938 addr_policy_result_t r;
3939 if (!routerlist) return 1;
3941 SMARTLIST_FOREACH(routerlist->routers, routerinfo_t *, router,
3943 if (router->is_running &&
3944 !router_is_unreliable(router, need_uptime, 0, 0)) {
3945 r = compare_addr_to_addr_policy(addr, port, router->exit_policy);
3946 if (r != ADDR_POLICY_REJECTED && r != ADDR_POLICY_PROBABLY_REJECTED)
3947 return 0; /* this one could be ok. good enough. */
3950 return 1; /* all will reject. */
3953 /** Return true iff <b>router</b> does not permit exit streams.
3956 router_exit_policy_rejects_all(routerinfo_t *router)
3958 return router->policy_is_reject_star;
3961 /** Add to the list of authoritative directory servers one at
3962 * <b>address</b>:<b>port</b>, with identity key <b>digest</b>. If
3963 * <b>address</b> is NULL, add ourself. Return the new trusted directory
3964 * server entry on success or NULL if we couldn't add it. */
3965 trusted_dir_server_t *
3966 add_trusted_dir_server(const char *nickname, const char *address,
3967 uint16_t dir_port, uint16_t or_port,
3968 const char *digest, const char *v3_auth_digest,
3969 authority_type_t type)
3971 trusted_dir_server_t *ent;
3972 uint32_t a;
3973 char *hostname = NULL;
3974 size_t dlen;
3975 if (!trusted_dir_servers)
3976 trusted_dir_servers = smartlist_create();
3978 if (!address) { /* The address is us; we should guess. */
3979 if (resolve_my_address(LOG_WARN, get_options(), &a, &hostname) < 0) {
3980 log_warn(LD_CONFIG,
3981 "Couldn't find a suitable address when adding ourself as a "
3982 "trusted directory server.");
3983 return NULL;
3985 } else {
3986 if (tor_lookup_hostname(address, &a)) {
3987 log_warn(LD_CONFIG,
3988 "Unable to lookup address for directory server at '%s'",
3989 address);
3990 return NULL;
3992 hostname = tor_strdup(address);
3995 ent = tor_malloc_zero(sizeof(trusted_dir_server_t));
3996 ent->nickname = nickname ? tor_strdup(nickname) : NULL;
3997 ent->address = hostname;
3998 ent->addr = a;
3999 ent->dir_port = dir_port;
4000 ent->or_port = or_port;
4001 ent->is_running = 1;
4002 ent->type = type;
4003 memcpy(ent->digest, digest, DIGEST_LEN);
4004 if (v3_auth_digest && (type & V3_AUTHORITY))
4005 memcpy(ent->v3_identity_digest, v3_auth_digest, DIGEST_LEN);
4007 dlen = 64 + strlen(hostname) + (nickname?strlen(nickname):0);
4008 ent->description = tor_malloc(dlen);
4009 if (nickname)
4010 tor_snprintf(ent->description, dlen, "directory server \"%s\" at %s:%d",
4011 nickname, hostname, (int)dir_port);
4012 else
4013 tor_snprintf(ent->description, dlen, "directory server at %s:%d",
4014 hostname, (int)dir_port);
4016 ent->fake_status.addr = ent->addr;
4017 memcpy(ent->fake_status.identity_digest, digest, DIGEST_LEN);
4018 if (nickname)
4019 strlcpy(ent->fake_status.nickname, nickname,
4020 sizeof(ent->fake_status.nickname));
4021 else
4022 ent->fake_status.nickname[0] = '\0';
4023 ent->fake_status.dir_port = ent->dir_port;
4024 ent->fake_status.or_port = ent->or_port;
4026 if (ent->or_port)
4027 ent->fake_status.version_supports_begindir = 1;
4029 ent->fake_status.version_supports_conditional_consensus = 1;
4031 smartlist_add(trusted_dir_servers, ent);
4032 router_dir_info_changed();
4033 return ent;
4036 /** Free storage held in <b>cert</b>. */
4037 void
4038 authority_cert_free(authority_cert_t *cert)
4040 if (!cert)
4041 return;
4043 tor_free(cert->cache_info.signed_descriptor_body);
4044 crypto_free_pk_env(cert->signing_key);
4045 crypto_free_pk_env(cert->identity_key);
4047 tor_free(cert);
4050 /** Free storage held in <b>ds</b>. */
4051 static void
4052 trusted_dir_server_free(trusted_dir_server_t *ds)
4054 if (!ds)
4055 return;
4057 tor_free(ds->nickname);
4058 tor_free(ds->description);
4059 tor_free(ds->address);
4060 tor_free(ds);
4063 /** Remove all members from the list of trusted dir servers. */
4064 void
4065 clear_trusted_dir_servers(void)
4067 if (trusted_dir_servers) {
4068 SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, ent,
4069 trusted_dir_server_free(ent));
4070 smartlist_clear(trusted_dir_servers);
4071 } else {
4072 trusted_dir_servers = smartlist_create();
4074 router_dir_info_changed();
4077 /** Return 1 if any trusted dir server supports v1 directories,
4078 * else return 0. */
4080 any_trusted_dir_is_v1_authority(void)
4082 if (trusted_dir_servers)
4083 return get_n_authorities(V1_AUTHORITY) > 0;
4085 return 0;
4088 /** For every current directory connection whose purpose is <b>purpose</b>,
4089 * and where the resource being downloaded begins with <b>prefix</b>, split
4090 * rest of the resource into base16 fingerprints, decode them, and set the
4091 * corresponding elements of <b>result</b> to a nonzero value. */
4092 static void
4093 list_pending_downloads(digestmap_t *result,
4094 int purpose, const char *prefix)
4096 const size_t p_len = strlen(prefix);
4097 smartlist_t *tmp = smartlist_create();
4098 smartlist_t *conns = get_connection_array();
4100 tor_assert(result);
4102 SMARTLIST_FOREACH(conns, connection_t *, conn,
4104 if (conn->type == CONN_TYPE_DIR &&
4105 conn->purpose == purpose &&
4106 !conn->marked_for_close) {
4107 const char *resource = TO_DIR_CONN(conn)->requested_resource;
4108 if (!strcmpstart(resource, prefix))
4109 dir_split_resource_into_fingerprints(resource + p_len,
4110 tmp, NULL, DSR_HEX);
4113 SMARTLIST_FOREACH(tmp, char *, d,
4115 digestmap_set(result, d, (void*)1);
4116 tor_free(d);
4118 smartlist_free(tmp);
4121 /** For every router descriptor (or extra-info document if <b>extrainfo</b> is
4122 * true) we are currently downloading by descriptor digest, set result[d] to
4123 * (void*)1. */
4124 static void
4125 list_pending_descriptor_downloads(digestmap_t *result, int extrainfo)
4127 int purpose =
4128 extrainfo ? DIR_PURPOSE_FETCH_EXTRAINFO : DIR_PURPOSE_FETCH_SERVERDESC;
4129 list_pending_downloads(result, purpose, "d/");
4132 /** Launch downloads for all the descriptors whose digests are listed
4133 * as digests[i] for lo <= i < hi. (Lo and hi may be out of range.)
4134 * If <b>source</b> is given, download from <b>source</b>; otherwise,
4135 * download from an appropriate random directory server.
4137 static void
4138 initiate_descriptor_downloads(routerstatus_t *source,
4139 int purpose,
4140 smartlist_t *digests,
4141 int lo, int hi, int pds_flags)
4143 int i, n = hi-lo;
4144 char *resource, *cp;
4145 size_t r_len;
4146 if (n <= 0)
4147 return;
4148 if (lo < 0)
4149 lo = 0;
4150 if (hi > smartlist_len(digests))
4151 hi = smartlist_len(digests);
4153 r_len = 8 + (HEX_DIGEST_LEN+1)*n;
4154 cp = resource = tor_malloc(r_len);
4155 memcpy(cp, "d/", 2);
4156 cp += 2;
4157 for (i = lo; i < hi; ++i) {
4158 base16_encode(cp, r_len-(cp-resource),
4159 smartlist_get(digests,i), DIGEST_LEN);
4160 cp += HEX_DIGEST_LEN;
4161 *cp++ = '+';
4163 memcpy(cp-1, ".z", 3);
4165 if (source) {
4166 /* We know which authority we want. */
4167 directory_initiate_command_routerstatus(source, purpose,
4168 ROUTER_PURPOSE_GENERAL,
4169 0, /* not private */
4170 resource, NULL, 0, 0);
4171 } else {
4172 directory_get_from_dirserver(purpose, ROUTER_PURPOSE_GENERAL, resource,
4173 pds_flags);
4175 tor_free(resource);
4178 /** Return 0 if this routerstatus is obsolete, too new, isn't
4179 * running, or otherwise not a descriptor that we would make any
4180 * use of even if we had it. Else return 1. */
4181 static INLINE int
4182 client_would_use_router(routerstatus_t *rs, time_t now, or_options_t *options)
4184 if (!rs->is_running && !options->FetchUselessDescriptors) {
4185 /* If we had this router descriptor, we wouldn't even bother using it.
4186 * But, if we want to have a complete list, fetch it anyway. */
4187 return 0;
4189 if (rs->published_on + options->TestingEstimatedDescriptorPropagationTime
4190 > now) {
4191 /* Most caches probably don't have this descriptor yet. */
4192 return 0;
4194 if (rs->published_on + OLD_ROUTER_DESC_MAX_AGE < now) {
4195 /* We'd drop it immediately for being too old. */
4196 return 0;
4198 return 1;
4201 /** Max amount of hashes to download per request.
4202 * Since squid does not like URLs >= 4096 bytes we limit it to 96.
4203 * 4096 - strlen(http://255.255.255.255/tor/server/d/.z) == 4058
4204 * 4058/41 (40 for the hash and 1 for the + that separates them) => 98
4205 * So use 96 because it's a nice number.
4207 #define MAX_DL_PER_REQUEST 96
4208 /** Don't split our requests so finely that we are requesting fewer than
4209 * this number per server. */
4210 #define MIN_DL_PER_REQUEST 4
4211 /** To prevent a single screwy cache from confusing us by selective reply,
4212 * try to split our requests into at least this many requests. */
4213 #define MIN_REQUESTS 3
4214 /** If we want fewer than this many descriptors, wait until we
4215 * want more, or until MAX_CLIENT_INTERVAL_WITHOUT_REQUEST has
4216 * passed. */
4217 #define MAX_DL_TO_DELAY 16
4218 /** When directory clients have only a few servers to request, they batch
4219 * them until they have more, or until this amount of time has passed. */
4220 #define MAX_CLIENT_INTERVAL_WITHOUT_REQUEST (10*60)
4222 /** Given a list of router descriptor digests in <b>downloadable</b>, decide
4223 * whether to delay fetching until we have more. If we don't want to delay,
4224 * launch one or more requests to the appropriate directory authorities. */
4225 static void
4226 launch_router_descriptor_downloads(smartlist_t *downloadable,
4227 routerstatus_t *source, time_t now)
4229 int should_delay = 0, n_downloadable;
4230 or_options_t *options = get_options();
4232 n_downloadable = smartlist_len(downloadable);
4233 if (!directory_fetches_dir_info_early(options)) {
4234 if (n_downloadable >= MAX_DL_TO_DELAY) {
4235 log_debug(LD_DIR,
4236 "There are enough downloadable routerdescs to launch requests.");
4237 should_delay = 0;
4238 } else {
4239 should_delay = (last_routerdesc_download_attempted +
4240 MAX_CLIENT_INTERVAL_WITHOUT_REQUEST) > now;
4241 if (!should_delay && n_downloadable) {
4242 if (last_routerdesc_download_attempted) {
4243 log_info(LD_DIR,
4244 "There are not many downloadable routerdescs, but we've "
4245 "been waiting long enough (%d seconds). Downloading.",
4246 (int)(now-last_routerdesc_download_attempted));
4247 } else {
4248 log_info(LD_DIR,
4249 "There are not many downloadable routerdescs, but we haven't "
4250 "tried downloading descriptors recently. Downloading.");
4255 /* XXX should we consider having even the dir mirrors delay
4256 * a little bit, so we don't load the authorities as much? -RD
4257 * I don't think so. If we do, clients that want those descriptors may
4258 * not actually find them if the caches haven't got them yet. -NM
4261 if (! should_delay && n_downloadable) {
4262 int i, n_per_request;
4263 const char *req_plural = "", *rtr_plural = "";
4264 int pds_flags = PDS_RETRY_IF_NO_SERVERS;
4265 if (! authdir_mode_any_nonhidserv(options)) {
4266 /* If we wind up going to the authorities, we want to only open one
4267 * connection to each authority at a time, so that we don't overload
4268 * them. We do this by setting PDS_NO_EXISTING_SERVERDESC_FETCH
4269 * regardless of whether we're a cache or not; it gets ignored if we're
4270 * not calling router_pick_trusteddirserver.
4272 * Setting this flag can make initiate_descriptor_downloads() ignore
4273 * requests. We need to make sure that we do in fact call
4274 * update_router_descriptor_downloads() later on, once the connections
4275 * have succeeded or failed.
4277 pds_flags |= PDS_NO_EXISTING_SERVERDESC_FETCH;
4280 n_per_request = CEIL_DIV(n_downloadable, MIN_REQUESTS);
4281 if (n_per_request > MAX_DL_PER_REQUEST)
4282 n_per_request = MAX_DL_PER_REQUEST;
4283 if (n_per_request < MIN_DL_PER_REQUEST)
4284 n_per_request = MIN_DL_PER_REQUEST;
4286 if (n_downloadable > n_per_request)
4287 req_plural = rtr_plural = "s";
4288 else if (n_downloadable > 1)
4289 rtr_plural = "s";
4291 log_info(LD_DIR,
4292 "Launching %d request%s for %d router%s, %d at a time",
4293 CEIL_DIV(n_downloadable, n_per_request),
4294 req_plural, n_downloadable, rtr_plural, n_per_request);
4295 smartlist_sort_digests(downloadable);
4296 for (i=0; i < n_downloadable; i += n_per_request) {
4297 initiate_descriptor_downloads(source, DIR_PURPOSE_FETCH_SERVERDESC,
4298 downloadable, i, i+n_per_request,
4299 pds_flags);
4301 last_routerdesc_download_attempted = now;
4305 /** Launch downloads for router status as needed, using the strategy used by
4306 * authorities and caches: based on the v2 networkstatuses we have, download
4307 * every descriptor we don't have but would serve, from a random authority
4308 * that lists it. */
4309 static void
4310 update_router_descriptor_cache_downloads_v2(time_t now)
4312 smartlist_t **downloadable; /* For each authority, what can we dl from it? */
4313 smartlist_t **download_from; /* ... and, what will we dl from it? */
4314 digestmap_t *map; /* Which descs are in progress, or assigned? */
4315 int i, j, n;
4316 int n_download;
4317 or_options_t *options = get_options();
4318 const smartlist_t *networkstatus_v2_list = networkstatus_get_v2_list();
4320 if (! directory_fetches_dir_info_early(options)) {
4321 log_warn(LD_BUG, "Called update_router_descriptor_cache_downloads_v2() "
4322 "on a non-dir-mirror?");
4325 if (!networkstatus_v2_list || !smartlist_len(networkstatus_v2_list))
4326 return;
4328 map = digestmap_new();
4329 n = smartlist_len(networkstatus_v2_list);
4331 downloadable = tor_malloc_zero(sizeof(smartlist_t*) * n);
4332 download_from = tor_malloc_zero(sizeof(smartlist_t*) * n);
4334 /* Set map[d]=1 for the digest of every descriptor that we are currently
4335 * downloading. */
4336 list_pending_descriptor_downloads(map, 0);
4338 /* For the digest of every descriptor that we don't have, and that we aren't
4339 * downloading, add d to downloadable[i] if the i'th networkstatus knows
4340 * about that descriptor, and we haven't already failed to get that
4341 * descriptor from the corresponding authority.
4343 n_download = 0;
4344 SMARTLIST_FOREACH(networkstatus_v2_list, networkstatus_v2_t *, ns,
4346 trusted_dir_server_t *ds;
4347 smartlist_t *dl;
4348 dl = downloadable[ns_sl_idx] = smartlist_create();
4349 download_from[ns_sl_idx] = smartlist_create();
4350 if (ns->published_on + MAX_NETWORKSTATUS_AGE+10*60 < now) {
4351 /* Don't download if the networkstatus is almost ancient. */
4352 /* Actually, I suspect what's happening here is that we ask
4353 * for the descriptor when we have a given networkstatus,
4354 * and then we get a newer networkstatus, and then we receive
4355 * the descriptor. Having a networkstatus actually expire is
4356 * probably a rare event, and we'll probably be happiest if
4357 * we take this clause out. -RD */
4358 continue;
4361 /* Don't try dirservers that we think are down -- we might have
4362 * just tried them and just marked them as down. */
4363 ds = router_get_trusteddirserver_by_digest(ns->identity_digest);
4364 if (ds && !ds->is_running)
4365 continue;
4367 SMARTLIST_FOREACH(ns->entries, routerstatus_t * , rs,
4369 if (!rs->need_to_mirror)
4370 continue;
4371 if (router_get_by_descriptor_digest(rs->descriptor_digest)) {
4372 log_warn(LD_BUG,
4373 "We have a router descriptor, but need_to_mirror=1.");
4374 rs->need_to_mirror = 0;
4375 continue;
4377 if (authdir_mode(options) && dirserv_would_reject_router(rs)) {
4378 rs->need_to_mirror = 0;
4379 continue;
4381 if (digestmap_get(map, rs->descriptor_digest)) {
4382 /* We're downloading it already. */
4383 continue;
4384 } else {
4385 /* We could download it from this guy. */
4386 smartlist_add(dl, rs->descriptor_digest);
4387 ++n_download;
4392 /* At random, assign descriptors to authorities such that:
4393 * - if d is a member of some downloadable[x], d is a member of some
4394 * download_from[y]. (Everything we want to download, we try to download
4395 * from somebody.)
4396 * - If d is a member of download_from[y], d is a member of downloadable[y].
4397 * (We only try to download descriptors from authorities who claim to have
4398 * them.)
4399 * - No d is a member of download_from[x] and download_from[y] s.t. x != y.
4400 * (We don't try to download anything from two authorities concurrently.)
4402 while (n_download) {
4403 int which_ns = crypto_rand_int(n);
4404 smartlist_t *dl = downloadable[which_ns];
4405 int idx;
4406 char *d;
4407 if (!smartlist_len(dl))
4408 continue;
4409 idx = crypto_rand_int(smartlist_len(dl));
4410 d = smartlist_get(dl, idx);
4411 if (! digestmap_get(map, d)) {
4412 smartlist_add(download_from[which_ns], d);
4413 digestmap_set(map, d, (void*) 1);
4415 smartlist_del(dl, idx);
4416 --n_download;
4419 /* Now, we can actually launch our requests. */
4420 for (i=0; i<n; ++i) {
4421 networkstatus_v2_t *ns = smartlist_get(networkstatus_v2_list, i);
4422 trusted_dir_server_t *ds =
4423 router_get_trusteddirserver_by_digest(ns->identity_digest);
4424 smartlist_t *dl = download_from[i];
4425 int pds_flags = PDS_RETRY_IF_NO_SERVERS;
4426 if (! authdir_mode_any_nonhidserv(options))
4427 pds_flags |= PDS_NO_EXISTING_SERVERDESC_FETCH; /* XXXX ignored*/
4429 if (!ds) {
4430 log_info(LD_DIR, "Networkstatus with no corresponding authority!");
4431 continue;
4433 if (! smartlist_len(dl))
4434 continue;
4435 log_info(LD_DIR, "Requesting %d descriptors from authority \"%s\"",
4436 smartlist_len(dl), ds->nickname);
4437 for (j=0; j < smartlist_len(dl); j += MAX_DL_PER_REQUEST) {
4438 initiate_descriptor_downloads(&(ds->fake_status),
4439 DIR_PURPOSE_FETCH_SERVERDESC, dl, j,
4440 j+MAX_DL_PER_REQUEST, pds_flags);
4444 for (i=0; i<n; ++i) {
4445 smartlist_free(download_from[i]);
4446 smartlist_free(downloadable[i]);
4448 tor_free(download_from);
4449 tor_free(downloadable);
4450 digestmap_free(map,NULL);
4453 /** For any descriptor that we want that's currently listed in
4454 * <b>consensus</b>, download it as appropriate. */
4455 void
4456 update_consensus_router_descriptor_downloads(time_t now, int is_vote,
4457 networkstatus_t *consensus)
4459 or_options_t *options = get_options();
4460 digestmap_t *map = NULL;
4461 smartlist_t *no_longer_old = smartlist_create();
4462 smartlist_t *downloadable = smartlist_create();
4463 routerstatus_t *source = NULL;
4464 int authdir = authdir_mode(options);
4465 int n_delayed=0, n_have=0, n_would_reject=0, n_wouldnt_use=0,
4466 n_inprogress=0, n_in_oldrouters=0;
4468 if (directory_too_idle_to_fetch_descriptors(options, now))
4469 goto done;
4470 if (!consensus)
4471 goto done;
4473 if (is_vote) {
4474 /* where's it from, so we know whom to ask for descriptors */
4475 trusted_dir_server_t *ds;
4476 networkstatus_voter_info_t *voter = smartlist_get(consensus->voters, 0);
4477 tor_assert(voter);
4478 ds = trusteddirserver_get_by_v3_auth_digest(voter->identity_digest);
4479 if (ds)
4480 source = &(ds->fake_status);
4481 else
4482 log_warn(LD_DIR, "couldn't lookup source from vote?");
4485 map = digestmap_new();
4486 list_pending_descriptor_downloads(map, 0);
4487 SMARTLIST_FOREACH(consensus->routerstatus_list, void *, rsp,
4489 routerstatus_t *rs =
4490 is_vote ? &(((vote_routerstatus_t *)rsp)->status) : rsp;
4491 signed_descriptor_t *sd;
4492 if ((sd = router_get_by_descriptor_digest(rs->descriptor_digest))) {
4493 routerinfo_t *ri;
4494 ++n_have;
4495 if (!(ri = router_get_by_digest(rs->identity_digest)) ||
4496 memcmp(ri->cache_info.signed_descriptor_digest,
4497 sd->signed_descriptor_digest, DIGEST_LEN)) {
4498 /* We have a descriptor with this digest, but either there is no
4499 * entry in routerlist with the same ID (!ri), or there is one,
4500 * but the identity digest differs (memcmp).
4502 smartlist_add(no_longer_old, sd);
4503 ++n_in_oldrouters; /* We have it in old_routers. */
4505 continue; /* We have it already. */
4507 if (digestmap_get(map, rs->descriptor_digest)) {
4508 ++n_inprogress;
4509 continue; /* We have an in-progress download. */
4511 if (!download_status_is_ready(&rs->dl_status, now,
4512 MAX_ROUTERDESC_DOWNLOAD_FAILURES)) {
4513 ++n_delayed; /* Not ready for retry. */
4514 continue;
4516 if (authdir && dirserv_would_reject_router(rs)) {
4517 ++n_would_reject;
4518 continue; /* We would throw it out immediately. */
4520 if (!directory_caches_dir_info(options) &&
4521 !client_would_use_router(rs, now, options)) {
4522 ++n_wouldnt_use;
4523 continue; /* We would never use it ourself. */
4525 if (is_vote && source) {
4526 char time_bufnew[ISO_TIME_LEN+1];
4527 char time_bufold[ISO_TIME_LEN+1];
4528 routerinfo_t *oldrouter = router_get_by_digest(rs->identity_digest);
4529 format_iso_time(time_bufnew, rs->published_on);
4530 if (oldrouter)
4531 format_iso_time(time_bufold, oldrouter->cache_info.published_on);
4532 log_info(LD_DIR, "Learned about %s (%s vs %s) from %s's vote (%s)",
4533 rs->nickname, time_bufnew,
4534 oldrouter ? time_bufold : "none",
4535 source->nickname, oldrouter ? "known" : "unknown");
4537 smartlist_add(downloadable, rs->descriptor_digest);
4540 if (!authdir_mode_handles_descs(options, ROUTER_PURPOSE_GENERAL)
4541 && smartlist_len(no_longer_old)) {
4542 routerlist_t *rl = router_get_routerlist();
4543 log_info(LD_DIR, "%d router descriptors listed in consensus are "
4544 "currently in old_routers; making them current.",
4545 smartlist_len(no_longer_old));
4546 SMARTLIST_FOREACH(no_longer_old, signed_descriptor_t *, sd, {
4547 const char *msg;
4548 was_router_added_t r;
4549 routerinfo_t *ri = routerlist_reparse_old(rl, sd);
4550 if (!ri) {
4551 log_warn(LD_BUG, "Failed to re-parse a router.");
4552 continue;
4554 r = router_add_to_routerlist(ri, &msg, 1, 0);
4555 if (WRA_WAS_OUTDATED(r)) {
4556 log_warn(LD_DIR, "Couldn't add re-parsed router: %s",
4557 msg?msg:"???");
4560 routerlist_assert_ok(rl);
4563 log_info(LD_DIR,
4564 "%d router descriptors downloadable. %d delayed; %d present "
4565 "(%d of those were in old_routers); %d would_reject; "
4566 "%d wouldnt_use; %d in progress.",
4567 smartlist_len(downloadable), n_delayed, n_have, n_in_oldrouters,
4568 n_would_reject, n_wouldnt_use, n_inprogress);
4570 launch_router_descriptor_downloads(downloadable, source, now);
4572 digestmap_free(map, NULL);
4573 done:
4574 smartlist_free(downloadable);
4575 smartlist_free(no_longer_old);
4578 /** How often should we launch a server/authority request to be sure of getting
4579 * a guess for our IP? */
4580 /*XXXX021 this info should come from netinfo cells or something, or we should
4581 * do this only when we aren't seeing incoming data. see bug 652. */
4582 #define DUMMY_DOWNLOAD_INTERVAL (20*60)
4584 /** Launch downloads for router status as needed. */
4585 void
4586 update_router_descriptor_downloads(time_t now)
4588 or_options_t *options = get_options();
4589 static time_t last_dummy_download = 0;
4590 if (should_delay_dir_fetches(options))
4591 return;
4592 if (directory_fetches_dir_info_early(options)) {
4593 update_router_descriptor_cache_downloads_v2(now);
4595 update_consensus_router_descriptor_downloads(now, 0,
4596 networkstatus_get_reasonably_live_consensus(now));
4598 /* XXXX021 we could be smarter here; see notes on bug 652. */
4599 /* If we're a server that doesn't have a configured address, we rely on
4600 * directory fetches to learn when our address changes. So if we haven't
4601 * tried to get any routerdescs in a long time, try a dummy fetch now. */
4602 if (!options->Address &&
4603 server_mode(options) &&
4604 last_routerdesc_download_attempted + DUMMY_DOWNLOAD_INTERVAL < now &&
4605 last_dummy_download + DUMMY_DOWNLOAD_INTERVAL < now) {
4606 last_dummy_download = now;
4607 directory_get_from_dirserver(DIR_PURPOSE_FETCH_SERVERDESC,
4608 ROUTER_PURPOSE_GENERAL, "authority.z",
4609 PDS_RETRY_IF_NO_SERVERS);
4613 /** Launch extrainfo downloads as needed. */
4614 void
4615 update_extrainfo_downloads(time_t now)
4617 or_options_t *options = get_options();
4618 routerlist_t *rl;
4619 smartlist_t *wanted;
4620 digestmap_t *pending;
4621 int old_routers, i;
4622 int n_no_ei = 0, n_pending = 0, n_have = 0, n_delay = 0;
4623 if (! options->DownloadExtraInfo)
4624 return;
4625 if (should_delay_dir_fetches(options))
4626 return;
4627 if (!router_have_minimum_dir_info())
4628 return;
4630 pending = digestmap_new();
4631 list_pending_descriptor_downloads(pending, 1);
4632 rl = router_get_routerlist();
4633 wanted = smartlist_create();
4634 for (old_routers = 0; old_routers < 2; ++old_routers) {
4635 smartlist_t *lst = old_routers ? rl->old_routers : rl->routers;
4636 for (i = 0; i < smartlist_len(lst); ++i) {
4637 signed_descriptor_t *sd;
4638 char *d;
4639 if (old_routers)
4640 sd = smartlist_get(lst, i);
4641 else
4642 sd = &((routerinfo_t*)smartlist_get(lst, i))->cache_info;
4643 if (sd->is_extrainfo)
4644 continue; /* This should never happen. */
4645 if (old_routers && !router_get_by_digest(sd->identity_digest))
4646 continue; /* Couldn't check the signature if we got it. */
4647 if (sd->extrainfo_is_bogus)
4648 continue;
4649 d = sd->extra_info_digest;
4650 if (tor_digest_is_zero(d)) {
4651 ++n_no_ei;
4652 continue;
4654 if (eimap_get(rl->extra_info_map, d)) {
4655 ++n_have;
4656 continue;
4658 if (!download_status_is_ready(&sd->ei_dl_status, now,
4659 MAX_ROUTERDESC_DOWNLOAD_FAILURES)) {
4660 ++n_delay;
4661 continue;
4663 if (digestmap_get(pending, d)) {
4664 ++n_pending;
4665 continue;
4667 smartlist_add(wanted, d);
4670 digestmap_free(pending, NULL);
4672 log_info(LD_DIR, "Extrainfo download status: %d router with no ei, %d "
4673 "with present ei, %d delaying, %d pending, %d downloadable.",
4674 n_no_ei, n_have, n_delay, n_pending, smartlist_len(wanted));
4676 smartlist_shuffle(wanted);
4677 for (i = 0; i < smartlist_len(wanted); i += MAX_DL_PER_REQUEST) {
4678 initiate_descriptor_downloads(NULL, DIR_PURPOSE_FETCH_EXTRAINFO,
4679 wanted, i, i + MAX_DL_PER_REQUEST,
4680 PDS_RETRY_IF_NO_SERVERS|PDS_NO_EXISTING_SERVERDESC_FETCH);
4683 smartlist_free(wanted);
4686 /** True iff, the last time we checked whether we had enough directory info
4687 * to build circuits, the answer was "yes". */
4688 static int have_min_dir_info = 0;
4689 /** True iff enough has changed since the last time we checked whether we had
4690 * enough directory info to build circuits that our old answer can no longer
4691 * be trusted. */
4692 static int need_to_update_have_min_dir_info = 1;
4693 /** String describing what we're missing before we have enough directory
4694 * info. */
4695 static char dir_info_status[128] = "";
4697 /** Return true iff we have enough networkstatus and router information to
4698 * start building circuits. Right now, this means "more than half the
4699 * networkstatus documents, and at least 1/4 of expected routers." */
4700 //XXX should consider whether we have enough exiting nodes here.
4702 router_have_minimum_dir_info(void)
4704 if (PREDICT_UNLIKELY(need_to_update_have_min_dir_info)) {
4705 update_router_have_minimum_dir_info();
4706 need_to_update_have_min_dir_info = 0;
4708 return have_min_dir_info;
4711 /** Called when our internal view of the directory has changed. This can be
4712 * when the authorities change, networkstatuses change, the list of routerdescs
4713 * changes, or number of running routers changes.
4715 void
4716 router_dir_info_changed(void)
4718 need_to_update_have_min_dir_info = 1;
4719 rend_hsdir_routers_changed();
4722 /** Return a string describing what we're missing before we have enough
4723 * directory info. */
4724 const char *
4725 get_dir_info_status_string(void)
4727 return dir_info_status;
4730 /** Iterate over the servers listed in <b>consensus</b>, and count how many of
4731 * them seem like ones we'd use, and how many of <em>those</em> we have
4732 * descriptors for. Store the former in *<b>num_usable</b> and the latter in
4733 * *<b>num_present</b>. If <b>in_set</b> is non-NULL, only consider those
4734 * routers in <b>in_set</b>.
4736 static void
4737 count_usable_descriptors(int *num_present, int *num_usable,
4738 const networkstatus_t *consensus,
4739 or_options_t *options, time_t now,
4740 routerset_t *in_set)
4742 *num_present = 0, *num_usable=0;
4744 SMARTLIST_FOREACH(consensus->routerstatus_list, routerstatus_t *, rs,
4746 if (in_set && ! routerset_contains_routerstatus(in_set, rs))
4747 continue;
4748 if (client_would_use_router(rs, now, options)) {
4749 ++*num_usable; /* the consensus says we want it. */
4750 if (router_get_by_descriptor_digest(rs->descriptor_digest)) {
4751 /* we have the descriptor listed in the consensus. */
4752 ++*num_present;
4757 log_debug(LD_DIR, "%d usable, %d present.", *num_usable, *num_present);
4760 /** We just fetched a new set of descriptors. Compute how far through
4761 * the "loading descriptors" bootstrapping phase we are, so we can inform
4762 * the controller of our progress. */
4764 count_loading_descriptors_progress(void)
4766 int num_present = 0, num_usable=0;
4767 time_t now = time(NULL);
4768 const networkstatus_t *consensus =
4769 networkstatus_get_reasonably_live_consensus(now);
4770 double fraction;
4772 if (!consensus)
4773 return 0; /* can't count descriptors if we have no list of them */
4775 count_usable_descriptors(&num_present, &num_usable,
4776 consensus, get_options(), now, NULL);
4778 if (num_usable == 0)
4779 return 0; /* don't div by 0 */
4780 fraction = num_present / (num_usable/4.);
4781 if (fraction > 1.0)
4782 return 0; /* it's not the number of descriptors holding us back */
4783 return BOOTSTRAP_STATUS_LOADING_DESCRIPTORS + (int)
4784 (fraction*(BOOTSTRAP_STATUS_CONN_OR-1 -
4785 BOOTSTRAP_STATUS_LOADING_DESCRIPTORS));
4788 /** Change the value of have_min_dir_info, setting it true iff we have enough
4789 * network and router information to build circuits. Clear the value of
4790 * need_to_update_have_min_dir_info. */
4791 static void
4792 update_router_have_minimum_dir_info(void)
4794 int num_present = 0, num_usable=0;
4795 time_t now = time(NULL);
4796 int res;
4797 or_options_t *options = get_options();
4798 const networkstatus_t *consensus =
4799 networkstatus_get_reasonably_live_consensus(now);
4801 if (!consensus) {
4802 if (!networkstatus_get_latest_consensus())
4803 strlcpy(dir_info_status, "We have no network-status consensus.",
4804 sizeof(dir_info_status));
4805 else
4806 strlcpy(dir_info_status, "We have no recent network-status consensus.",
4807 sizeof(dir_info_status));
4808 res = 0;
4809 goto done;
4812 if (should_delay_dir_fetches(get_options())) {
4813 log_notice(LD_DIR, "no known bridge descriptors running yet; stalling");
4814 strlcpy(dir_info_status, "No live bridge descriptors.",
4815 sizeof(dir_info_status));
4816 res = 0;
4817 goto done;
4820 count_usable_descriptors(&num_present, &num_usable, consensus, options, now,
4821 NULL);
4823 if (num_present < num_usable/4) {
4824 tor_snprintf(dir_info_status, sizeof(dir_info_status),
4825 "We have only %d/%d usable descriptors.", num_present, num_usable);
4826 res = 0;
4827 control_event_bootstrap(BOOTSTRAP_STATUS_REQUESTING_DESCRIPTORS, 0);
4828 goto done;
4829 } else if (num_present < 2) {
4830 tor_snprintf(dir_info_status, sizeof(dir_info_status),
4831 "Only %d descriptor%s here and believed reachable!",
4832 num_present, num_present ? "" : "s");
4833 res = 0;
4834 goto done;
4837 /* Check for entry nodes. */
4838 if (options->EntryNodes) {
4839 count_usable_descriptors(&num_present, &num_usable, consensus, options,
4840 now, options->EntryNodes);
4842 if (!num_usable || !num_present) {
4843 tor_snprintf(dir_info_status, sizeof(dir_info_status),
4844 "We have only %d/%d usable entry node descriptors.",
4845 num_present, num_usable);
4846 res = 0;
4847 goto done;
4851 res = 1;
4853 done:
4854 if (res && !have_min_dir_info) {
4855 log(LOG_NOTICE, LD_DIR,
4856 "We now have enough directory information to build circuits.");
4857 control_event_client_status(LOG_NOTICE, "ENOUGH_DIR_INFO");
4858 control_event_bootstrap(BOOTSTRAP_STATUS_CONN_OR, 0);
4860 if (!res && have_min_dir_info) {
4861 int quiet = directory_too_idle_to_fetch_descriptors(options, now);
4862 log(quiet ? LOG_INFO : LOG_NOTICE, LD_DIR,
4863 "Our directory information is no longer up-to-date "
4864 "enough to build circuits: %s", dir_info_status);
4866 /* a) make us log when we next complete a circuit, so we know when Tor
4867 * is back up and usable, and b) disable some activities that Tor
4868 * should only do while circuits are working, like reachability tests
4869 * and fetching bridge descriptors only over circuits. */
4870 can_complete_circuit = 0;
4872 control_event_client_status(LOG_NOTICE, "NOT_ENOUGH_DIR_INFO");
4874 have_min_dir_info = res;
4875 need_to_update_have_min_dir_info = 0;
4878 /** Reset the descriptor download failure count on all routers, so that we
4879 * can retry any long-failed routers immediately.
4881 void
4882 router_reset_descriptor_download_failures(void)
4884 networkstatus_reset_download_failures();
4885 last_routerdesc_download_attempted = 0;
4886 if (!routerlist)
4887 return;
4888 SMARTLIST_FOREACH(routerlist->routers, routerinfo_t *, ri,
4890 download_status_reset(&ri->cache_info.ei_dl_status);
4892 SMARTLIST_FOREACH(routerlist->old_routers, signed_descriptor_t *, sd,
4894 download_status_reset(&sd->ei_dl_status);
4898 /** Any changes in a router descriptor's publication time larger than this are
4899 * automatically non-cosmetic. */
4900 #define ROUTER_MAX_COSMETIC_TIME_DIFFERENCE (12*60*60)
4902 /** We allow uptime to vary from how much it ought to be by this much. */
4903 #define ROUTER_ALLOW_UPTIME_DRIFT (6*60*60)
4905 /** Return true iff the only differences between r1 and r2 are such that
4906 * would not cause a recent (post 0.1.1.6) dirserver to republish.
4909 router_differences_are_cosmetic(routerinfo_t *r1, routerinfo_t *r2)
4911 time_t r1pub, r2pub;
4912 long time_difference;
4913 tor_assert(r1 && r2);
4915 /* r1 should be the one that was published first. */
4916 if (r1->cache_info.published_on > r2->cache_info.published_on) {
4917 routerinfo_t *ri_tmp = r2;
4918 r2 = r1;
4919 r1 = ri_tmp;
4922 /* If any key fields differ, they're different. */
4923 if (strcasecmp(r1->address, r2->address) ||
4924 strcasecmp(r1->nickname, r2->nickname) ||
4925 r1->or_port != r2->or_port ||
4926 r1->dir_port != r2->dir_port ||
4927 r1->purpose != r2->purpose ||
4928 crypto_pk_cmp_keys(r1->onion_pkey, r2->onion_pkey) ||
4929 crypto_pk_cmp_keys(r1->identity_pkey, r2->identity_pkey) ||
4930 strcasecmp(r1->platform, r2->platform) ||
4931 (r1->contact_info && !r2->contact_info) || /* contact_info is optional */
4932 (!r1->contact_info && r2->contact_info) ||
4933 (r1->contact_info && r2->contact_info &&
4934 strcasecmp(r1->contact_info, r2->contact_info)) ||
4935 r1->is_hibernating != r2->is_hibernating ||
4936 r1->has_old_dnsworkers != r2->has_old_dnsworkers ||
4937 cmp_addr_policies(r1->exit_policy, r2->exit_policy))
4938 return 0;
4939 if ((r1->declared_family == NULL) != (r2->declared_family == NULL))
4940 return 0;
4941 if (r1->declared_family && r2->declared_family) {
4942 int i, n;
4943 if (smartlist_len(r1->declared_family)!=smartlist_len(r2->declared_family))
4944 return 0;
4945 n = smartlist_len(r1->declared_family);
4946 for (i=0; i < n; ++i) {
4947 if (strcasecmp(smartlist_get(r1->declared_family, i),
4948 smartlist_get(r2->declared_family, i)))
4949 return 0;
4953 /* Did bandwidth change a lot? */
4954 if ((r1->bandwidthcapacity < r2->bandwidthcapacity/2) ||
4955 (r2->bandwidthcapacity < r1->bandwidthcapacity/2))
4956 return 0;
4958 /* Did the bandwidthrate or bandwidthburst change? */
4959 if ((r1->bandwidthrate != r2->bandwidthrate) ||
4960 (r1->bandwidthburst != r2->bandwidthburst))
4961 return 0;
4963 /* Did more than 12 hours pass? */
4964 if (r1->cache_info.published_on + ROUTER_MAX_COSMETIC_TIME_DIFFERENCE
4965 < r2->cache_info.published_on)
4966 return 0;
4968 /* Did uptime fail to increase by approximately the amount we would think,
4969 * give or take some slop? */
4970 r1pub = r1->cache_info.published_on;
4971 r2pub = r2->cache_info.published_on;
4972 time_difference = labs(r2->uptime - (r1->uptime + (r2pub - r1pub)));
4973 if (time_difference > ROUTER_ALLOW_UPTIME_DRIFT &&
4974 time_difference > r1->uptime * .05 &&
4975 time_difference > r2->uptime * .05)
4976 return 0;
4978 /* Otherwise, the difference is cosmetic. */
4979 return 1;
4982 /** Check whether <b>ri</b> (a.k.a. sd) is a router compatible with the
4983 * extrainfo document
4984 * <b>ei</b>. If no router is compatible with <b>ei</b>, <b>ei</b> should be
4985 * dropped. Return 0 for "compatible", return 1 for "reject, and inform
4986 * whoever uploaded <b>ei</b>, and return -1 for "reject silently.". If
4987 * <b>msg</b> is present, set *<b>msg</b> to a description of the
4988 * incompatibility (if any).
4991 routerinfo_incompatible_with_extrainfo(routerinfo_t *ri, extrainfo_t *ei,
4992 signed_descriptor_t *sd,
4993 const char **msg)
4995 int digest_matches, r=1;
4996 tor_assert(ri);
4997 tor_assert(ei);
4998 if (!sd)
4999 sd = &ri->cache_info;
5001 if (ei->bad_sig) {
5002 if (msg) *msg = "Extrainfo signature was bad, or signed with wrong key.";
5003 return 1;
5006 digest_matches = !memcmp(ei->cache_info.signed_descriptor_digest,
5007 sd->extra_info_digest, DIGEST_LEN);
5009 /* The identity must match exactly to have been generated at the same time
5010 * by the same router. */
5011 if (memcmp(ri->cache_info.identity_digest, ei->cache_info.identity_digest,
5012 DIGEST_LEN)) {
5013 if (msg) *msg = "Extrainfo nickname or identity did not match routerinfo";
5014 goto err; /* different servers */
5017 if (ei->pending_sig) {
5018 char signed_digest[128];
5019 if (crypto_pk_public_checksig(ri->identity_pkey, signed_digest,
5020 ei->pending_sig, ei->pending_sig_len) != DIGEST_LEN ||
5021 memcmp(signed_digest, ei->cache_info.signed_descriptor_digest,
5022 DIGEST_LEN)) {
5023 ei->bad_sig = 1;
5024 tor_free(ei->pending_sig);
5025 if (msg) *msg = "Extrainfo signature bad, or signed with wrong key";
5026 goto err; /* Bad signature, or no match. */
5029 ei->cache_info.send_unencrypted = ri->cache_info.send_unencrypted;
5030 tor_free(ei->pending_sig);
5033 if (ei->cache_info.published_on < sd->published_on) {
5034 if (msg) *msg = "Extrainfo published time did not match routerdesc";
5035 goto err;
5036 } else if (ei->cache_info.published_on > sd->published_on) {
5037 if (msg) *msg = "Extrainfo published time did not match routerdesc";
5038 r = -1;
5039 goto err;
5042 if (!digest_matches) {
5043 if (msg) *msg = "Extrainfo digest did not match value from routerdesc";
5044 goto err; /* Digest doesn't match declared value. */
5047 return 0;
5048 err:
5049 if (digest_matches) {
5050 /* This signature was okay, and the digest was right: This is indeed the
5051 * corresponding extrainfo. But insanely, it doesn't match the routerinfo
5052 * that lists it. Don't try to fetch this one again. */
5053 sd->extrainfo_is_bogus = 1;
5056 return r;
5059 /** Assert that the internal representation of <b>rl</b> is
5060 * self-consistent. */
5061 void
5062 routerlist_assert_ok(routerlist_t *rl)
5064 routerinfo_t *r2;
5065 signed_descriptor_t *sd2;
5066 if (!rl)
5067 return;
5068 SMARTLIST_FOREACH(rl->routers, routerinfo_t *, r,
5070 r2 = rimap_get(rl->identity_map, r->cache_info.identity_digest);
5071 tor_assert(r == r2);
5072 sd2 = sdmap_get(rl->desc_digest_map,
5073 r->cache_info.signed_descriptor_digest);
5074 tor_assert(&(r->cache_info) == sd2);
5075 tor_assert(r->cache_info.routerlist_index == r_sl_idx);
5076 /* XXXX
5078 * Hoo boy. We need to fix this one, and the fix is a bit tricky, so
5079 * commenting this out is just a band-aid.
5081 * The problem is that, although well-behaved router descriptors
5082 * should never have the same value for their extra_info_digest, it's
5083 * possible for ill-behaved routers to claim whatever they like there.
5085 * The real answer is to trash desc_by_eid_map and instead have
5086 * something that indicates for a given extra-info digest we want,
5087 * what its download status is. We'll do that as a part of routerlist
5088 * refactoring once consensus directories are in. For now,
5089 * this rep violation is probably harmless: an adversary can make us
5090 * reset our retry count for an extrainfo, but that's not the end
5091 * of the world. Changing the representation in 0.2.0.x would just
5092 * destabilize the codebase.
5093 if (!tor_digest_is_zero(r->cache_info.extra_info_digest)) {
5094 signed_descriptor_t *sd3 =
5095 sdmap_get(rl->desc_by_eid_map, r->cache_info.extra_info_digest);
5096 tor_assert(sd3 == &(r->cache_info));
5100 SMARTLIST_FOREACH(rl->old_routers, signed_descriptor_t *, sd,
5102 r2 = rimap_get(rl->identity_map, sd->identity_digest);
5103 tor_assert(sd != &(r2->cache_info));
5104 sd2 = sdmap_get(rl->desc_digest_map, sd->signed_descriptor_digest);
5105 tor_assert(sd == sd2);
5106 tor_assert(sd->routerlist_index == sd_sl_idx);
5107 /* XXXX see above.
5108 if (!tor_digest_is_zero(sd->extra_info_digest)) {
5109 signed_descriptor_t *sd3 =
5110 sdmap_get(rl->desc_by_eid_map, sd->extra_info_digest);
5111 tor_assert(sd3 == sd);
5116 RIMAP_FOREACH(rl->identity_map, d, r) {
5117 tor_assert(!memcmp(r->cache_info.identity_digest, d, DIGEST_LEN));
5118 } DIGESTMAP_FOREACH_END;
5119 SDMAP_FOREACH(rl->desc_digest_map, d, sd) {
5120 tor_assert(!memcmp(sd->signed_descriptor_digest, d, DIGEST_LEN));
5121 } DIGESTMAP_FOREACH_END;
5122 SDMAP_FOREACH(rl->desc_by_eid_map, d, sd) {
5123 tor_assert(!tor_digest_is_zero(d));
5124 tor_assert(sd);
5125 tor_assert(!memcmp(sd->extra_info_digest, d, DIGEST_LEN));
5126 } DIGESTMAP_FOREACH_END;
5127 EIMAP_FOREACH(rl->extra_info_map, d, ei) {
5128 signed_descriptor_t *sd;
5129 tor_assert(!memcmp(ei->cache_info.signed_descriptor_digest,
5130 d, DIGEST_LEN));
5131 sd = sdmap_get(rl->desc_by_eid_map,
5132 ei->cache_info.signed_descriptor_digest);
5133 // tor_assert(sd); // XXXX see above
5134 if (sd) {
5135 tor_assert(!memcmp(ei->cache_info.signed_descriptor_digest,
5136 sd->extra_info_digest, DIGEST_LEN));
5138 } DIGESTMAP_FOREACH_END;
5141 /** Allocate and return a new string representing the contact info
5142 * and platform string for <b>router</b>,
5143 * surrounded by quotes and using standard C escapes.
5145 * THIS FUNCTION IS NOT REENTRANT. Don't call it from outside the main
5146 * thread. Also, each call invalidates the last-returned value, so don't
5147 * try log_warn(LD_GENERAL, "%s %s", esc_router_info(a), esc_router_info(b));
5149 * If <b>router</b> is NULL, it just frees its internal memory and returns.
5151 const char *
5152 esc_router_info(routerinfo_t *router)
5154 static char *info=NULL;
5155 char *esc_contact, *esc_platform;
5156 size_t len;
5157 tor_free(info);
5159 if (!router)
5160 return NULL; /* we're exiting; just free the memory we use */
5162 esc_contact = esc_for_log(router->contact_info);
5163 esc_platform = esc_for_log(router->platform);
5165 len = strlen(esc_contact)+strlen(esc_platform)+32;
5166 info = tor_malloc(len);
5167 tor_snprintf(info, len, "Contact %s, Platform %s", esc_contact,
5168 esc_platform);
5169 tor_free(esc_contact);
5170 tor_free(esc_platform);
5172 return info;
5175 /** Helper for sorting: compare two routerinfos by their identity
5176 * digest. */
5177 static int
5178 _compare_routerinfo_by_id_digest(const void **a, const void **b)
5180 routerinfo_t *first = *(routerinfo_t **)a, *second = *(routerinfo_t **)b;
5181 return memcmp(first->cache_info.identity_digest,
5182 second->cache_info.identity_digest,
5183 DIGEST_LEN);
5186 /** Sort a list of routerinfo_t in ascending order of identity digest. */
5187 void
5188 routers_sort_by_identity(smartlist_t *routers)
5190 smartlist_sort(routers, _compare_routerinfo_by_id_digest);
5193 /** A routerset specifies constraints on a set of possible routerinfos, based
5194 * on their names, identities, or addresses. It is optimized for determining
5195 * whether a router is a member or not, in O(1+P) time, where P is the number
5196 * of address policy constraints. */
5197 struct routerset_t {
5198 /** A list of strings for the elements of the policy. Each string is either
5199 * a nickname, a hexadecimal identity fingerprint, or an address policy. A
5200 * router belongs to the set if its nickname OR its identity OR its address
5201 * matches an entry here. */
5202 smartlist_t *list;
5203 /** A map from lowercase nicknames of routers in the set to (void*)1 */
5204 strmap_t *names;
5205 /** A map from identity digests routers in the set to (void*)1 */
5206 digestmap_t *digests;
5207 /** An address policy for routers in the set. For implementation reasons,
5208 * a router belongs to the set if it is _rejected_ by this policy. */
5209 smartlist_t *policies;
5211 /** A human-readable description of what this routerset is for. Used in
5212 * log messages. */
5213 char *description;
5215 /** A list of the country codes in this set. */
5216 smartlist_t *country_names;
5217 /** Total number of countries we knew about when we built <b>countries</b>.*/
5218 int n_countries;
5219 /** Bit array mapping the return value of geoip_get_country() to 1 iff the
5220 * country is a member of this routerset. Note that we MUST call
5221 * routerset_refresh_countries() whenever the geoip country list is
5222 * reloaded. */
5223 bitarray_t *countries;
5226 /** Return a new empty routerset. */
5227 routerset_t *
5228 routerset_new(void)
5230 routerset_t *result = tor_malloc_zero(sizeof(routerset_t));
5231 result->list = smartlist_create();
5232 result->names = strmap_new();
5233 result->digests = digestmap_new();
5234 result->policies = smartlist_create();
5235 result->country_names = smartlist_create();
5236 return result;
5239 /** If <b>c</b> is a country code in the form {cc}, return a newly allocated
5240 * string holding the "cc" part. Else, return NULL. */
5241 static char *
5242 routerset_get_countryname(const char *c)
5244 char *country;
5246 if (strlen(c) < 4 || c[0] !='{' || c[3] !='}')
5247 return NULL;
5249 country = tor_strndup(c+1, 2);
5250 tor_strlower(country);
5251 return country;
5254 #if 0
5255 /** Add the GeoIP database's integer index (+1) of a valid two-character
5256 * country code to the routerset's <b>countries</b> bitarray. Return the
5257 * integer index if the country code is valid, -1 otherwise.*/
5258 static int
5259 routerset_add_country(const char *c)
5261 char country[3];
5262 country_t cc;
5264 /* XXXX: Country codes must be of the form \{[a-z\?]{2}\} but this accepts
5265 \{[.]{2}\}. Do we need to be strict? -RH */
5266 /* Nope; if the country code is bad, we'll get 0 when we look it up. */
5268 if (!geoip_is_loaded()) {
5269 log(LOG_WARN, LD_CONFIG, "GeoIP database not loaded: Cannot add country"
5270 "entry %s, ignoring.", c);
5271 return -1;
5274 memcpy(country, c+1, 2);
5275 country[2] = '\0';
5276 tor_strlower(country);
5278 if ((cc=geoip_get_country(country))==-1) {
5279 log(LOG_WARN, LD_CONFIG, "Country code '%s' is not valid, ignoring.",
5280 country);
5282 return cc;
5284 #endif
5286 /** Update the routerset's <b>countries</b> bitarray_t. Called whenever
5287 * the GeoIP database is reloaded.
5289 void
5290 routerset_refresh_countries(routerset_t *target)
5292 int cc;
5293 bitarray_free(target->countries);
5295 if (!geoip_is_loaded()) {
5296 target->countries = NULL;
5297 target->n_countries = 0;
5298 return;
5300 target->n_countries = geoip_get_n_countries();
5301 target->countries = bitarray_init_zero(target->n_countries);
5302 SMARTLIST_FOREACH_BEGIN(target->country_names, const char *, country) {
5303 cc = geoip_get_country(country);
5304 if (cc >= 0) {
5305 tor_assert(cc < target->n_countries);
5306 bitarray_set(target->countries, cc);
5307 } else {
5308 log(LOG_WARN, LD_CONFIG, "Country code '%s' is not recognized.",
5309 country);
5311 } SMARTLIST_FOREACH_END(country);
5314 /** Parse the string <b>s</b> to create a set of routerset entries, and add
5315 * them to <b>target</b>. In log messages, refer to the string as
5316 * <b>description</b>. Return 0 on success, -1 on failure.
5318 * Three kinds of elements are allowed in routersets: nicknames, IP address
5319 * patterns, and fingerprints. They may be surrounded by optional space, and
5320 * must be separated by commas.
5323 routerset_parse(routerset_t *target, const char *s, const char *description)
5325 int r = 0;
5326 int added_countries = 0;
5327 char *countryname;
5328 smartlist_t *list = smartlist_create();
5329 smartlist_split_string(list, s, ",",
5330 SPLIT_SKIP_SPACE | SPLIT_IGNORE_BLANK, 0);
5331 SMARTLIST_FOREACH_BEGIN(list, char *, nick) {
5332 addr_policy_t *p;
5333 if (is_legal_hexdigest(nick)) {
5334 char d[DIGEST_LEN];
5335 if (*nick == '$')
5336 ++nick;
5337 log_debug(LD_CONFIG, "Adding identity %s to %s", nick, description);
5338 base16_decode(d, sizeof(d), nick, HEX_DIGEST_LEN);
5339 digestmap_set(target->digests, d, (void*)1);
5340 } else if (is_legal_nickname(nick)) {
5341 log_debug(LD_CONFIG, "Adding nickname %s to %s", nick, description);
5342 strmap_set_lc(target->names, nick, (void*)1);
5343 } else if ((countryname = routerset_get_countryname(nick)) != NULL) {
5344 log_debug(LD_CONFIG, "Adding country %s to %s", nick,
5345 description);
5346 smartlist_add(target->country_names, countryname);
5347 added_countries = 1;
5348 } else if ((strchr(nick,'.') || strchr(nick, '*')) &&
5349 (p = router_parse_addr_policy_item_from_string(
5350 nick, ADDR_POLICY_REJECT))) {
5351 log_debug(LD_CONFIG, "Adding address %s to %s", nick, description);
5352 smartlist_add(target->policies, p);
5353 } else {
5354 log_warn(LD_CONFIG, "Entry '%s' in %s is misformed.", nick,
5355 description);
5356 r = -1;
5357 tor_free(nick);
5358 SMARTLIST_DEL_CURRENT(list, nick);
5360 } SMARTLIST_FOREACH_END(nick);
5361 smartlist_add_all(target->list, list);
5362 smartlist_free(list);
5363 if (added_countries)
5364 routerset_refresh_countries(target);
5365 return r;
5368 /** Called when we change a node set, or when we reload the geoip list:
5369 * recompute all country info in all configuration node sets and in the
5370 * routerlist. */
5371 void
5372 refresh_all_country_info(void)
5374 or_options_t *options = get_options();
5376 if (options->EntryNodes)
5377 routerset_refresh_countries(options->EntryNodes);
5378 if (options->ExitNodes)
5379 routerset_refresh_countries(options->ExitNodes);
5380 if (options->ExcludeNodes)
5381 routerset_refresh_countries(options->ExcludeNodes);
5382 if (options->ExcludeExitNodes)
5383 routerset_refresh_countries(options->ExcludeExitNodes);
5384 if (options->_ExcludeExitNodesUnion)
5385 routerset_refresh_countries(options->_ExcludeExitNodesUnion);
5387 routerlist_refresh_countries();
5390 /** Add all members of the set <b>source</b> to <b>target</b>. */
5391 void
5392 routerset_union(routerset_t *target, const routerset_t *source)
5394 char *s;
5395 tor_assert(target);
5396 if (!source || !source->list)
5397 return;
5398 s = routerset_to_string(source);
5399 routerset_parse(target, s, "other routerset");
5400 tor_free(s);
5403 /** Return true iff <b>set</b> lists only nicknames and digests, and includes
5404 * no IP ranges or countries. */
5406 routerset_is_list(const routerset_t *set)
5408 return smartlist_len(set->country_names) == 0 &&
5409 smartlist_len(set->policies) == 0;
5412 /** Return true iff we need a GeoIP IP-to-country database to make sense of
5413 * <b>set</b>. */
5415 routerset_needs_geoip(const routerset_t *set)
5417 return set && smartlist_len(set->country_names);
5420 /** Return true iff there are no entries in <b>set</b>. */
5421 static int
5422 routerset_is_empty(const routerset_t *set)
5424 return !set || smartlist_len(set->list) == 0;
5427 /** Helper. Return true iff <b>set</b> contains a router based on the other
5428 * provided fields. Return higher values for more specific subentries: a
5429 * single router is more specific than an address range of routers, which is
5430 * more specific in turn than a country code.
5432 * (If country is -1, then we take the country
5433 * from addr.) */
5434 static int
5435 routerset_contains(const routerset_t *set, const tor_addr_t *addr,
5436 uint16_t orport,
5437 const char *nickname, const char *id_digest, int is_named,
5438 country_t country)
5440 if (!set || !set->list) return 0;
5441 (void) is_named; /* not supported */
5442 if (nickname && strmap_get_lc(set->names, nickname))
5443 return 4;
5444 if (id_digest && digestmap_get(set->digests, id_digest))
5445 return 4;
5446 if (addr && compare_tor_addr_to_addr_policy(addr, orport, set->policies)
5447 == ADDR_POLICY_REJECTED)
5448 return 3;
5449 if (set->countries) {
5450 if (country < 0 && addr)
5451 country = geoip_get_country_by_ip(tor_addr_to_ipv4h(addr));
5453 if (country >= 0 && country < set->n_countries &&
5454 bitarray_is_set(set->countries, country))
5455 return 2;
5457 return 0;
5460 /** Return true iff we can tell that <b>ei</b> is a member of <b>set</b>. */
5462 routerset_contains_extendinfo(const routerset_t *set, const extend_info_t *ei)
5464 return routerset_contains(set,
5465 &ei->addr,
5466 ei->port,
5467 ei->nickname,
5468 ei->identity_digest,
5469 -1, /*is_named*/
5470 -1 /*country*/);
5473 /** Return true iff <b>ri</b> is in <b>set</b>. */
5475 routerset_contains_router(const routerset_t *set, routerinfo_t *ri)
5477 tor_addr_t addr;
5478 tor_addr_from_ipv4h(&addr, ri->addr);
5479 return routerset_contains(set,
5480 &addr,
5481 ri->or_port,
5482 ri->nickname,
5483 ri->cache_info.identity_digest,
5484 ri->is_named,
5485 ri->country);
5488 /** Return true iff <b>rs</b> is in <b>set</b>. */
5490 routerset_contains_routerstatus(const routerset_t *set, routerstatus_t *rs)
5492 tor_addr_t addr;
5493 tor_addr_from_ipv4h(&addr, rs->addr);
5494 return routerset_contains(set,
5495 &addr,
5496 rs->or_port,
5497 rs->nickname,
5498 rs->identity_digest,
5499 rs->is_named,
5500 -1);
5503 /** Add every known routerinfo_t that is a member of <b>routerset</b> to
5504 * <b>out</b>. If <b>running_only</b>, only add the running ones. */
5505 void
5506 routerset_get_all_routers(smartlist_t *out, const routerset_t *routerset,
5507 int running_only)
5509 tor_assert(out);
5510 if (!routerset || !routerset->list)
5511 return;
5512 if (!warned_nicknames)
5513 warned_nicknames = smartlist_create();
5514 if (routerset_is_list(routerset)) {
5516 /* No routers are specified by type; all are given by name or digest.
5517 * we can do a lookup in O(len(list)). */
5518 SMARTLIST_FOREACH(routerset->list, const char *, name, {
5519 routerinfo_t *router = router_get_by_nickname(name, 1);
5520 if (router) {
5521 if (!running_only || router->is_running)
5522 smartlist_add(out, router);
5525 } else {
5526 /* We need to iterate over the routerlist to get all the ones of the
5527 * right kind. */
5528 routerlist_t *rl = router_get_routerlist();
5529 SMARTLIST_FOREACH(rl->routers, routerinfo_t *, router, {
5530 if (running_only && !router->is_running)
5531 continue;
5532 if (routerset_contains_router(routerset, router))
5533 smartlist_add(out, router);
5538 /** Add to <b>target</b> every routerinfo_t from <b>source</b> except:
5540 * 1) Don't add it if <b>include</b> is non-empty and the relay isn't in
5541 * <b>include</b>; and
5542 * 2) Don't add it if <b>exclude</b> is non-empty and the relay is
5543 * excluded in a more specific fashion by <b>exclude</b>.
5544 * 3) If <b>running_only</b>, don't add non-running routers.
5546 void
5547 routersets_get_disjunction(smartlist_t *target,
5548 const smartlist_t *source,
5549 const routerset_t *include,
5550 const routerset_t *exclude, int running_only)
5552 SMARTLIST_FOREACH(source, routerinfo_t *, router, {
5553 int include_result;
5554 if (running_only && !router->is_running)
5555 continue;
5556 if (!routerset_is_empty(include))
5557 include_result = routerset_contains_router(include, router);
5558 else
5559 include_result = 1;
5561 if (include_result) {
5562 int exclude_result = routerset_contains_router(exclude, router);
5563 if (include_result >= exclude_result)
5564 smartlist_add(target, router);
5569 /** Remove every routerinfo_t from <b>lst</b> that is in <b>routerset</b>. */
5570 void
5571 routerset_subtract_routers(smartlist_t *lst, const routerset_t *routerset)
5573 tor_assert(lst);
5574 if (!routerset)
5575 return;
5576 SMARTLIST_FOREACH(lst, routerinfo_t *, r, {
5577 if (routerset_contains_router(routerset, r)) {
5578 //log_debug(LD_DIR, "Subtracting %s",r->nickname);
5579 SMARTLIST_DEL_CURRENT(lst, r);
5584 /** Return a new string that when parsed by routerset_parse_string() will
5585 * yield <b>set</b>. */
5586 char *
5587 routerset_to_string(const routerset_t *set)
5589 if (!set || !set->list)
5590 return tor_strdup("");
5591 return smartlist_join_strings(set->list, ",", 0, NULL);
5594 /** Helper: return true iff old and new are both NULL, or both non-NULL
5595 * equal routersets. */
5597 routerset_equal(const routerset_t *old, const routerset_t *new)
5599 if (old == NULL && new == NULL)
5600 return 1;
5601 else if (old == NULL || new == NULL)
5602 return 0;
5604 if (smartlist_len(old->list) != smartlist_len(new->list))
5605 return 0;
5607 SMARTLIST_FOREACH(old->list, const char *, cp1, {
5608 const char *cp2 = smartlist_get(new->list, cp1_sl_idx);
5609 if (strcmp(cp1, cp2))
5610 return 0;
5613 return 1;
5616 /** Free all storage held in <b>routerset</b>. */
5617 void
5618 routerset_free(routerset_t *routerset)
5620 if (!routerset)
5621 return;
5623 SMARTLIST_FOREACH(routerset->list, char *, cp, tor_free(cp));
5624 smartlist_free(routerset->list);
5625 SMARTLIST_FOREACH(routerset->policies, addr_policy_t *, p,
5626 addr_policy_free(p));
5627 smartlist_free(routerset->policies);
5628 SMARTLIST_FOREACH(routerset->country_names, char *, cp, tor_free(cp));
5629 smartlist_free(routerset->country_names);
5631 strmap_free(routerset->names, NULL);
5632 digestmap_free(routerset->digests, NULL);
5633 bitarray_free(routerset->countries);
5634 tor_free(routerset);
5637 /** Refresh the country code of <b>ri</b>. This function MUST be called on
5638 * each router when the GeoIP database is reloaded, and on all new routers. */
5639 void
5640 routerinfo_set_country(routerinfo_t *ri)
5642 ri->country = geoip_get_country_by_ip(ri->addr);
5645 /** Set the country code of all routers in the routerlist. */
5646 void
5647 routerlist_refresh_countries(void)
5649 routerlist_t *rl = router_get_routerlist();
5650 SMARTLIST_FOREACH(rl->routers, routerinfo_t *, ri,
5651 routerinfo_set_country(ri));
5654 /** Determine the routers that are responsible for <b>id</b> (binary) and
5655 * add pointers to those routers' routerstatus_t to <b>responsible_dirs</b>.
5656 * Return -1 if we're returning an empty smartlist, else return 0.
5659 hid_serv_get_responsible_directories(smartlist_t *responsible_dirs,
5660 const char *id)
5662 int start, found, n_added = 0, i;
5663 networkstatus_t *c = networkstatus_get_latest_consensus();
5664 int use_begindir = get_options()->TunnelDirConns;
5665 if (!c || !smartlist_len(c->routerstatus_list)) {
5666 log_warn(LD_REND, "We don't have a consensus, so we can't perform v2 "
5667 "rendezvous operations.");
5668 return -1;
5670 tor_assert(id);
5671 start = networkstatus_vote_find_entry_idx(c, id, &found);
5672 if (start == smartlist_len(c->routerstatus_list)) start = 0;
5673 i = start;
5674 do {
5675 routerstatus_t *r = smartlist_get(c->routerstatus_list, i);
5676 if (r->is_hs_dir) {
5677 if (r->dir_port || use_begindir)
5678 smartlist_add(responsible_dirs, r);
5679 else
5680 log_info(LD_REND, "Not adding router '%s' to list of responsible "
5681 "hidden service directories, because we have no way of "
5682 "reaching it.", r->nickname);
5683 if (++n_added == REND_NUMBER_OF_CONSECUTIVE_REPLICAS)
5684 break;
5686 if (++i == smartlist_len(c->routerstatus_list))
5687 i = 0;
5688 } while (i != start);
5690 /* Even though we don't have the desired number of hidden service
5691 * directories, be happy if we got any. */
5692 return smartlist_len(responsible_dirs) ? 0 : -1;
5695 /** Return true if this node is currently acting as hidden service
5696 * directory, false otherwise. */
5698 hid_serv_acting_as_directory(void)
5700 routerinfo_t *me = router_get_my_routerinfo();
5701 networkstatus_t *c;
5702 routerstatus_t *rs;
5703 if (!me)
5704 return 0;
5705 if (!get_options()->HidServDirectoryV2) {
5706 log_info(LD_REND, "We are not acting as hidden service directory, "
5707 "because we have not been configured as such.");
5708 return 0;
5710 if (!(c = networkstatus_get_latest_consensus())) {
5711 log_info(LD_REND, "There's no consensus, so I can't tell if I'm a hidden "
5712 "service directory");
5713 return 0;
5715 rs = networkstatus_vote_find_entry(c, me->cache_info.identity_digest);
5716 if (!rs) {
5717 log_info(LD_REND, "We're not listed in the consensus, so we're not "
5718 "being a hidden service directory.");
5719 return 0;
5721 if (!rs->is_hs_dir) {
5722 log_info(LD_REND, "We're not listed as a hidden service directory in "
5723 "the consensus, so we won't be one.");
5724 return 0;
5726 return 1;
5729 /** Return true if this node is responsible for storing the descriptor ID
5730 * in <b>query</b> and false otherwise. */
5732 hid_serv_responsible_for_desc_id(const char *query)
5734 routerinfo_t *me;
5735 routerstatus_t *last_rs;
5736 const char *my_id, *last_id;
5737 int result;
5738 smartlist_t *responsible;
5739 if (!hid_serv_acting_as_directory())
5740 return 0;
5741 if (!(me = router_get_my_routerinfo()))
5742 return 0; /* This is redundant, but let's be paranoid. */
5743 my_id = me->cache_info.identity_digest;
5744 responsible = smartlist_create();
5745 if (hid_serv_get_responsible_directories(responsible, query) < 0) {
5746 smartlist_free(responsible);
5747 return 0;
5749 last_rs = smartlist_get(responsible, smartlist_len(responsible)-1);
5750 last_id = last_rs->identity_digest;
5751 result = rend_id_is_in_interval(my_id, query, last_id);
5752 smartlist_free(responsible);
5753 return result;