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