Rename has_completed_circuit to can_complete_circuit
[tor/rransom.git] / src / or / routerlist.c
blob5fb4fe13c291abc69883e92b655ea07e67284e44
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-2010, 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 /** Return bw*1000, unless bw*1000 would overflow, in which case return
1576 * INT32_MAX. */
1577 static INLINE int32_t
1578 kb_to_bytes(uint32_t bw)
1580 return (bw > (INT32_MAX/1000)) ? INT32_MAX : bw*1000;
1583 /** Helper function:
1584 * choose a random element of smartlist <b>sl</b>, weighted by
1585 * the advertised bandwidth of each element using the consensus
1586 * bandwidth weights.
1588 * If <b>statuses</b> is zero, then <b>sl</b> is a list of
1589 * routerinfo_t's. Otherwise it's a list of routerstatus_t's.
1591 * If <b>rule</b>==WEIGHT_FOR_EXIT. we're picking an exit node: consider all
1592 * nodes' bandwidth equally regardless of their Exit status, since there may
1593 * be some in the list because they exit to obscure ports. If
1594 * <b>rule</b>==NO_WEIGHTING, we're picking a non-exit node: weight
1595 * exit-node's bandwidth less depending on the smallness of the fraction of
1596 * Exit-to-total bandwidth. If <b>rule</b>==WEIGHT_FOR_GUARD, we're picking a
1597 * guard node: consider all guard's bandwidth equally. Otherwise, weight
1598 * guards proportionally less.
1600 static void *
1601 smartlist_choose_by_bandwidth_weights(smartlist_t *sl,
1602 bandwidth_weight_rule_t rule,
1603 int statuses)
1605 int64_t weight_scale;
1606 int64_t rand_bw;
1607 double Wg = -1, Wm = -1, We = -1, Wd = -1;
1608 double Wgb = -1, Wmb = -1, Web = -1, Wdb = -1;
1609 double weighted_bw = 0;
1610 double *bandwidths;
1611 double tmp = 0;
1612 unsigned int i;
1614 /* Can't choose exit and guard at same time */
1615 tor_assert(rule == NO_WEIGHTING ||
1616 rule == WEIGHT_FOR_EXIT ||
1617 rule == WEIGHT_FOR_GUARD ||
1618 rule == WEIGHT_FOR_MID ||
1619 rule == WEIGHT_FOR_DIR);
1621 if (smartlist_len(sl) == 0) {
1622 log_info(LD_CIRC,
1623 "Empty routerlist passed in to consensus weight node "
1624 "selection for rule %s",
1625 bandwidth_weight_rule_to_string(rule));
1626 return NULL;
1629 weight_scale = networkstatus_get_param(NULL, "bwweightscale",
1630 BW_WEIGHT_SCALE);
1632 if (rule == WEIGHT_FOR_GUARD) {
1633 Wg = networkstatus_get_bw_weight(NULL, "Wgg", -1);
1634 Wm = networkstatus_get_bw_weight(NULL, "Wgm", -1); /* Bridges */
1635 We = 0;
1636 Wd = networkstatus_get_bw_weight(NULL, "Wgd", -1);
1638 Wgb = networkstatus_get_bw_weight(NULL, "Wgb", -1);
1639 Wmb = networkstatus_get_bw_weight(NULL, "Wmb", -1);
1640 Web = networkstatus_get_bw_weight(NULL, "Web", -1);
1641 Wdb = networkstatus_get_bw_weight(NULL, "Wdb", -1);
1642 } else if (rule == WEIGHT_FOR_MID) {
1643 Wg = networkstatus_get_bw_weight(NULL, "Wmg", -1);
1644 Wm = networkstatus_get_bw_weight(NULL, "Wmm", -1);
1645 We = networkstatus_get_bw_weight(NULL, "Wme", -1);
1646 Wd = networkstatus_get_bw_weight(NULL, "Wmd", -1);
1648 Wgb = networkstatus_get_bw_weight(NULL, "Wgb", -1);
1649 Wmb = networkstatus_get_bw_weight(NULL, "Wmb", -1);
1650 Web = networkstatus_get_bw_weight(NULL, "Web", -1);
1651 Wdb = networkstatus_get_bw_weight(NULL, "Wdb", -1);
1652 } else if (rule == WEIGHT_FOR_EXIT) {
1653 // Guards CAN be exits if they have weird exit policies
1654 // They are d then I guess...
1655 We = networkstatus_get_bw_weight(NULL, "Wee", -1);
1656 Wm = networkstatus_get_bw_weight(NULL, "Wem", -1); /* Odd exit policies */
1657 Wd = networkstatus_get_bw_weight(NULL, "Wed", -1);
1658 Wg = networkstatus_get_bw_weight(NULL, "Weg", -1); /* Odd exit policies */
1660 Wgb = networkstatus_get_bw_weight(NULL, "Wgb", -1);
1661 Wmb = networkstatus_get_bw_weight(NULL, "Wmb", -1);
1662 Web = networkstatus_get_bw_weight(NULL, "Web", -1);
1663 Wdb = networkstatus_get_bw_weight(NULL, "Wdb", -1);
1664 } else if (rule == WEIGHT_FOR_DIR) {
1665 We = networkstatus_get_bw_weight(NULL, "Wbe", -1);
1666 Wm = networkstatus_get_bw_weight(NULL, "Wbm", -1);
1667 Wd = networkstatus_get_bw_weight(NULL, "Wbd", -1);
1668 Wg = networkstatus_get_bw_weight(NULL, "Wbg", -1);
1670 Wgb = Wmb = Web = Wdb = weight_scale;
1671 } else if (rule == NO_WEIGHTING) {
1672 Wg = Wm = We = Wd = weight_scale;
1673 Wgb = Wmb = Web = Wdb = weight_scale;
1676 if (Wg < 0 || Wm < 0 || We < 0 || Wd < 0 || Wgb < 0 || Wmb < 0 || Wdb < 0
1677 || Web < 0) {
1678 log_debug(LD_CIRC,
1679 "Got negative bandwidth weights. Defaulting to old selection"
1680 " algorithm.");
1681 return NULL; // Use old algorithm.
1684 Wg /= weight_scale;
1685 Wm /= weight_scale;
1686 We /= weight_scale;
1687 Wd /= weight_scale;
1689 Wgb /= weight_scale;
1690 Wmb /= weight_scale;
1691 Web /= weight_scale;
1692 Wdb /= weight_scale;
1694 bandwidths = tor_malloc_zero(sizeof(double)*smartlist_len(sl));
1696 // Cycle through smartlist and total the bandwidth.
1697 for (i = 0; i < (unsigned)smartlist_len(sl); ++i) {
1698 int is_exit = 0, is_guard = 0, is_dir = 0, this_bw = 0, is_me = 0;
1699 double weight = 1;
1700 if (statuses) {
1701 routerstatus_t *status = smartlist_get(sl, i);
1702 is_exit = status->is_exit;
1703 is_guard = status->is_possible_guard;
1704 is_dir = (status->dir_port != 0);
1705 if (!status->has_bandwidth) {
1706 tor_free(bandwidths);
1707 /* This should never happen, unless all the authorites downgrade
1708 * to 0.2.0 or rogue routerstatuses get inserted into our consensus. */
1709 log_warn(LD_BUG,
1710 "Consensus is not listing bandwidths. Defaulting back to "
1711 "old router selection algorithm.");
1712 return NULL;
1714 this_bw = kb_to_bytes(status->bandwidth);
1715 if (router_digest_is_me(status->identity_digest))
1716 is_me = 1;
1717 } else {
1718 routerstatus_t *rs;
1719 routerinfo_t *router = smartlist_get(sl, i);
1720 rs = router_get_consensus_status_by_id(
1721 router->cache_info.identity_digest);
1722 is_exit = router->is_exit;
1723 is_guard = router->is_possible_guard;
1724 is_dir = (router->dir_port != 0);
1725 if (rs && rs->has_bandwidth) {
1726 this_bw = kb_to_bytes(rs->bandwidth);
1727 } else { /* bridge or other descriptor not in our consensus */
1728 this_bw = router_get_advertised_bandwidth_capped(router);
1730 if (router_digest_is_me(router->cache_info.identity_digest))
1731 is_me = 1;
1733 if (is_guard && is_exit) {
1734 weight = (is_dir ? Wdb*Wd : Wd);
1735 } else if (is_guard) {
1736 weight = (is_dir ? Wgb*Wg : Wg);
1737 } else if (is_exit) {
1738 weight = (is_dir ? Web*We : We);
1739 } else { // middle
1740 weight = (is_dir ? Wmb*Wm : Wm);
1743 bandwidths[i] = weight*this_bw;
1744 weighted_bw += weight*this_bw;
1745 if (is_me)
1746 sl_last_weighted_bw_of_me = weight*this_bw;
1749 /* XXXX022 this is a kludge to expose these values. */
1750 sl_last_total_weighted_bw = weighted_bw;
1752 log_debug(LD_CIRC, "Choosing node for rule %s based on weights "
1753 "Wg=%lf Wm=%lf We=%lf Wd=%lf with total bw %lf",
1754 bandwidth_weight_rule_to_string(rule),
1755 Wg, Wm, We, Wd, weighted_bw);
1757 /* If there is no bandwidth, choose at random */
1758 if (DBL_TO_U64(weighted_bw) == 0) {
1759 log_warn(LD_CIRC,
1760 "Weighted bandwidth is %lf in node selection for rule %s",
1761 weighted_bw, bandwidth_weight_rule_to_string(rule));
1762 tor_free(bandwidths);
1763 return smartlist_choose(sl);
1766 rand_bw = crypto_rand_uint64(DBL_TO_U64(weighted_bw));
1767 rand_bw++; /* crypto_rand_uint64() counts from 0, and we need to count
1768 * from 1 below. See bug 1203 for details. */
1770 /* Last, count through sl until we get to the element we picked */
1771 tmp = 0.0;
1772 for (i=0; i < (unsigned)smartlist_len(sl); i++) {
1773 tmp += bandwidths[i];
1774 if (tmp >= rand_bw)
1775 break;
1778 if (i == (unsigned)smartlist_len(sl)) {
1779 /* This was once possible due to round-off error, but shouldn't be able
1780 * to occur any longer. */
1781 tor_fragile_assert();
1782 --i;
1783 log_warn(LD_BUG, "Round-off error in computing bandwidth had an effect on "
1784 " which router we chose. Please tell the developers. "
1785 "%lf " U64_FORMAT " %lf", tmp, U64_PRINTF_ARG(rand_bw),
1786 weighted_bw);
1788 tor_free(bandwidths);
1789 return smartlist_get(sl, i);
1792 /** Helper function:
1793 * choose a random element of smartlist <b>sl</b>, weighted by
1794 * the advertised bandwidth of each element.
1796 * If <b>statuses</b> is zero, then <b>sl</b> is a list of
1797 * routerinfo_t's. Otherwise it's a list of routerstatus_t's.
1799 * If <b>rule</b>==WEIGHT_FOR_EXIT. we're picking an exit node: consider all
1800 * nodes' bandwidth equally regardless of their Exit status, since there may
1801 * be some in the list because they exit to obscure ports. If
1802 * <b>rule</b>==NO_WEIGHTING, we're picking a non-exit node: weight
1803 * exit-node's bandwidth less depending on the smallness of the fraction of
1804 * Exit-to-total bandwidth. If <b>rule</b>==WEIGHT_FOR_GUARD, we're picking a
1805 * guard node: consider all guard's bandwidth equally. Otherwise, weight
1806 * guards proportionally less.
1808 static void *
1809 smartlist_choose_by_bandwidth(smartlist_t *sl, bandwidth_weight_rule_t rule,
1810 int statuses)
1812 unsigned int i;
1813 routerinfo_t *router;
1814 routerstatus_t *status=NULL;
1815 int32_t *bandwidths;
1816 int is_exit;
1817 int is_guard;
1818 uint64_t total_nonexit_bw = 0, total_exit_bw = 0, total_bw = 0;
1819 uint64_t total_nonguard_bw = 0, total_guard_bw = 0;
1820 uint64_t rand_bw, tmp;
1821 double exit_weight;
1822 double guard_weight;
1823 int n_unknown = 0;
1824 bitarray_t *exit_bits;
1825 bitarray_t *guard_bits;
1826 int me_idx = -1;
1828 // This function does not support WEIGHT_FOR_DIR
1829 // or WEIGHT_FOR_MID
1830 if (rule == WEIGHT_FOR_DIR || rule == WEIGHT_FOR_MID) {
1831 rule = NO_WEIGHTING;
1834 /* Can't choose exit and guard at same time */
1835 tor_assert(rule == NO_WEIGHTING ||
1836 rule == WEIGHT_FOR_EXIT ||
1837 rule == WEIGHT_FOR_GUARD);
1839 if (smartlist_len(sl) == 0) {
1840 log_info(LD_CIRC,
1841 "Empty routerlist passed in to old node selection for rule %s",
1842 bandwidth_weight_rule_to_string(rule));
1843 return NULL;
1846 /* First count the total bandwidth weight, and make a list
1847 * of each value. <0 means "unknown; no routerinfo." We use the
1848 * bits of negative values to remember whether the router was fast (-x)&1
1849 * and whether it was an exit (-x)&2 or guard (-x)&4. Yes, it's a hack. */
1850 bandwidths = tor_malloc(sizeof(int32_t)*smartlist_len(sl));
1851 exit_bits = bitarray_init_zero(smartlist_len(sl));
1852 guard_bits = bitarray_init_zero(smartlist_len(sl));
1854 /* Iterate over all the routerinfo_t or routerstatus_t, and */
1855 for (i = 0; i < (unsigned)smartlist_len(sl); ++i) {
1856 /* first, learn what bandwidth we think i has */
1857 int is_known = 1;
1858 int32_t flags = 0;
1859 uint32_t this_bw = 0;
1860 if (statuses) {
1861 status = smartlist_get(sl, i);
1862 if (router_digest_is_me(status->identity_digest))
1863 me_idx = i;
1864 router = router_get_by_digest(status->identity_digest);
1865 is_exit = status->is_exit;
1866 is_guard = status->is_possible_guard;
1867 if (status->has_bandwidth) {
1868 this_bw = kb_to_bytes(status->bandwidth);
1869 } else { /* guess */
1870 /* XXX022 once consensuses always list bandwidths, we can take
1871 * this guessing business out. -RD */
1872 is_known = 0;
1873 flags = status->is_fast ? 1 : 0;
1874 flags |= is_exit ? 2 : 0;
1875 flags |= is_guard ? 4 : 0;
1877 } else {
1878 routerstatus_t *rs;
1879 router = smartlist_get(sl, i);
1880 rs = router_get_consensus_status_by_id(
1881 router->cache_info.identity_digest);
1882 if (router_digest_is_me(router->cache_info.identity_digest))
1883 me_idx = i;
1884 is_exit = router->is_exit;
1885 is_guard = router->is_possible_guard;
1886 if (rs && rs->has_bandwidth) {
1887 this_bw = kb_to_bytes(rs->bandwidth);
1888 } else if (rs) { /* guess; don't trust the descriptor */
1889 /* XXX022 once consensuses always list bandwidths, we can take
1890 * this guessing business out. -RD */
1891 is_known = 0;
1892 flags = router->is_fast ? 1 : 0;
1893 flags |= is_exit ? 2 : 0;
1894 flags |= is_guard ? 4 : 0;
1895 } else /* bridge or other descriptor not in our consensus */
1896 this_bw = router_get_advertised_bandwidth_capped(router);
1898 if (is_exit)
1899 bitarray_set(exit_bits, i);
1900 if (is_guard)
1901 bitarray_set(guard_bits, i);
1902 if (is_known) {
1903 bandwidths[i] = (int32_t) this_bw; // safe since MAX_BELIEVABLE<INT32_MAX
1904 tor_assert(bandwidths[i] >= 0);
1905 if (is_guard)
1906 total_guard_bw += this_bw;
1907 else
1908 total_nonguard_bw += this_bw;
1909 if (is_exit)
1910 total_exit_bw += this_bw;
1911 else
1912 total_nonexit_bw += this_bw;
1913 } else {
1914 ++n_unknown;
1915 bandwidths[i] = -flags;
1919 /* Now, fill in the unknown values. */
1920 if (n_unknown) {
1921 int32_t avg_fast, avg_slow;
1922 if (total_exit_bw+total_nonexit_bw) {
1923 /* if there's some bandwidth, there's at least one known router,
1924 * so no worries about div by 0 here */
1925 int n_known = smartlist_len(sl)-n_unknown;
1926 avg_fast = avg_slow = (int32_t)
1927 ((total_exit_bw+total_nonexit_bw)/((uint64_t) n_known));
1928 } else {
1929 avg_fast = 40000;
1930 avg_slow = 20000;
1932 for (i=0; i<(unsigned)smartlist_len(sl); ++i) {
1933 int32_t bw = bandwidths[i];
1934 if (bw>=0)
1935 continue;
1936 is_exit = ((-bw)&2);
1937 is_guard = ((-bw)&4);
1938 bandwidths[i] = ((-bw)&1) ? avg_fast : avg_slow;
1939 if (is_exit)
1940 total_exit_bw += bandwidths[i];
1941 else
1942 total_nonexit_bw += bandwidths[i];
1943 if (is_guard)
1944 total_guard_bw += bandwidths[i];
1945 else
1946 total_nonguard_bw += bandwidths[i];
1950 /* If there's no bandwidth at all, pick at random. */
1951 if (!(total_exit_bw+total_nonexit_bw)) {
1952 tor_free(bandwidths);
1953 tor_free(exit_bits);
1954 tor_free(guard_bits);
1955 return smartlist_choose(sl);
1958 /* Figure out how to weight exits and guards */
1960 double all_bw = U64_TO_DBL(total_exit_bw+total_nonexit_bw);
1961 double exit_bw = U64_TO_DBL(total_exit_bw);
1962 double guard_bw = U64_TO_DBL(total_guard_bw);
1964 * For detailed derivation of this formula, see
1965 * http://archives.seul.org/or/dev/Jul-2007/msg00056.html
1967 if (rule == WEIGHT_FOR_EXIT || !total_exit_bw)
1968 exit_weight = 1.0;
1969 else
1970 exit_weight = 1.0 - all_bw/(3.0*exit_bw);
1972 if (rule == WEIGHT_FOR_GUARD || !total_guard_bw)
1973 guard_weight = 1.0;
1974 else
1975 guard_weight = 1.0 - all_bw/(3.0*guard_bw);
1977 if (exit_weight <= 0.0)
1978 exit_weight = 0.0;
1980 if (guard_weight <= 0.0)
1981 guard_weight = 0.0;
1983 total_bw = 0;
1984 sl_last_weighted_bw_of_me = 0;
1985 for (i=0; i < (unsigned)smartlist_len(sl); i++) {
1986 uint64_t bw;
1987 is_exit = bitarray_is_set(exit_bits, i);
1988 is_guard = bitarray_is_set(guard_bits, i);
1989 if (is_exit && is_guard)
1990 bw = ((uint64_t)(bandwidths[i] * exit_weight * guard_weight));
1991 else if (is_guard)
1992 bw = ((uint64_t)(bandwidths[i] * guard_weight));
1993 else if (is_exit)
1994 bw = ((uint64_t)(bandwidths[i] * exit_weight));
1995 else
1996 bw = bandwidths[i];
1997 total_bw += bw;
1998 if (i == (unsigned) me_idx)
1999 sl_last_weighted_bw_of_me = bw;
2003 /* XXXX022 this is a kludge to expose these values. */
2004 sl_last_total_weighted_bw = total_bw;
2006 log_debug(LD_CIRC, "Total weighted bw = "U64_FORMAT
2007 ", exit bw = "U64_FORMAT
2008 ", nonexit bw = "U64_FORMAT", exit weight = %lf "
2009 "(for exit == %d)"
2010 ", guard bw = "U64_FORMAT
2011 ", nonguard bw = "U64_FORMAT", guard weight = %lf "
2012 "(for guard == %d)",
2013 U64_PRINTF_ARG(total_bw),
2014 U64_PRINTF_ARG(total_exit_bw), U64_PRINTF_ARG(total_nonexit_bw),
2015 exit_weight, (int)(rule == WEIGHT_FOR_EXIT),
2016 U64_PRINTF_ARG(total_guard_bw), U64_PRINTF_ARG(total_nonguard_bw),
2017 guard_weight, (int)(rule == WEIGHT_FOR_GUARD));
2019 /* Almost done: choose a random value from the bandwidth weights. */
2020 rand_bw = crypto_rand_uint64(total_bw);
2021 rand_bw++; /* crypto_rand_uint64() counts from 0, and we need to count
2022 * from 1 below. See bug 1203 for details. */
2024 /* Last, count through sl until we get to the element we picked */
2025 tmp = 0;
2026 for (i=0; i < (unsigned)smartlist_len(sl); i++) {
2027 is_exit = bitarray_is_set(exit_bits, i);
2028 is_guard = bitarray_is_set(guard_bits, i);
2030 /* Weights can be 0 if not counting guards/exits */
2031 if (is_exit && is_guard)
2032 tmp += ((uint64_t)(bandwidths[i] * exit_weight * guard_weight));
2033 else if (is_guard)
2034 tmp += ((uint64_t)(bandwidths[i] * guard_weight));
2035 else if (is_exit)
2036 tmp += ((uint64_t)(bandwidths[i] * exit_weight));
2037 else
2038 tmp += bandwidths[i];
2040 if (tmp >= rand_bw)
2041 break;
2043 if (i == (unsigned)smartlist_len(sl)) {
2044 /* This was once possible due to round-off error, but shouldn't be able
2045 * to occur any longer. */
2046 tor_fragile_assert();
2047 --i;
2048 log_warn(LD_BUG, "Round-off error in computing bandwidth had an effect on "
2049 " which router we chose. Please tell the developers. "
2050 U64_FORMAT " " U64_FORMAT " " U64_FORMAT, U64_PRINTF_ARG(tmp),
2051 U64_PRINTF_ARG(rand_bw), U64_PRINTF_ARG(total_bw));
2053 tor_free(bandwidths);
2054 tor_free(exit_bits);
2055 tor_free(guard_bits);
2056 return smartlist_get(sl, i);
2059 /** Choose a random element of router list <b>sl</b>, weighted by
2060 * the advertised bandwidth of each router.
2062 routerinfo_t *
2063 routerlist_sl_choose_by_bandwidth(smartlist_t *sl,
2064 bandwidth_weight_rule_t rule)
2066 routerinfo_t *ret;
2067 if ((ret = smartlist_choose_by_bandwidth_weights(sl, rule, 0))) {
2068 return ret;
2069 } else {
2070 return smartlist_choose_by_bandwidth(sl, rule, 0);
2074 /** Choose a random element of status list <b>sl</b>, weighted by
2075 * the advertised bandwidth of each status.
2077 routerstatus_t *
2078 routerstatus_sl_choose_by_bandwidth(smartlist_t *sl,
2079 bandwidth_weight_rule_t rule)
2081 /* We are choosing neither exit nor guard here. Weight accordingly. */
2082 routerstatus_t *ret;
2083 if ((ret = smartlist_choose_by_bandwidth_weights(sl, rule, 1))) {
2084 return ret;
2085 } else {
2086 return smartlist_choose_by_bandwidth(sl, rule, 1);
2090 /** Return a random running router from the routerlist. Never
2091 * pick a node whose routerinfo is in
2092 * <b>excludedsmartlist</b>, or whose routerinfo matches <b>excludedset</b>,
2093 * even if they are the only nodes available.
2094 * If <b>CRN_NEED_UPTIME</b> is set in flags and any router has more than
2095 * a minimum uptime, return one of those.
2096 * If <b>CRN_NEED_CAPACITY</b> is set in flags, weight your choice by the
2097 * advertised capacity of each router.
2098 * If <b>CRN_ALLOW_INVALID</b> is not set in flags, consider only Valid
2099 * routers.
2100 * If <b>CRN_NEED_GUARD</b> is set in flags, consider only Guard routers.
2101 * If <b>CRN_WEIGHT_AS_EXIT</b> is set in flags, we weight bandwidths as if
2102 * picking an exit node, otherwise we weight bandwidths for picking a relay
2103 * node (that is, possibly discounting exit nodes).
2105 routerinfo_t *
2106 router_choose_random_node(smartlist_t *excludedsmartlist,
2107 routerset_t *excludedset,
2108 router_crn_flags_t flags)
2110 const int need_uptime = (flags & CRN_NEED_UPTIME) != 0;
2111 const int need_capacity = (flags & CRN_NEED_CAPACITY) != 0;
2112 const int need_guard = (flags & CRN_NEED_GUARD) != 0;
2113 const int allow_invalid = (flags & CRN_ALLOW_INVALID) != 0;
2114 const int weight_for_exit = (flags & CRN_WEIGHT_AS_EXIT) != 0;
2116 smartlist_t *sl=smartlist_create(),
2117 *excludednodes=smartlist_create();
2118 routerinfo_t *choice = NULL, *r;
2119 bandwidth_weight_rule_t rule;
2121 tor_assert(!(weight_for_exit && need_guard));
2122 rule = weight_for_exit ? WEIGHT_FOR_EXIT :
2123 (need_guard ? WEIGHT_FOR_GUARD : WEIGHT_FOR_MID);
2125 /* Exclude relays that allow single hop exit circuits, if the user
2126 * wants to (such relays might be risky) */
2127 if (get_options()->ExcludeSingleHopRelays) {
2128 routerlist_t *rl = router_get_routerlist();
2129 SMARTLIST_FOREACH(rl->routers, routerinfo_t *, r,
2130 if (r->allow_single_hop_exits) {
2131 smartlist_add(excludednodes, r);
2135 if ((r = routerlist_find_my_routerinfo())) {
2136 smartlist_add(excludednodes, r);
2137 routerlist_add_family(excludednodes, r);
2140 router_add_running_routers_to_smartlist(sl, allow_invalid,
2141 need_uptime, need_capacity,
2142 need_guard);
2143 smartlist_subtract(sl,excludednodes);
2144 if (excludedsmartlist)
2145 smartlist_subtract(sl,excludedsmartlist);
2146 if (excludedset)
2147 routerset_subtract_routers(sl,excludedset);
2149 // Always weight by bandwidth
2150 choice = routerlist_sl_choose_by_bandwidth(sl, rule);
2152 smartlist_free(sl);
2153 if (!choice && (need_uptime || need_capacity || need_guard)) {
2154 /* try once more -- recurse but with fewer restrictions. */
2155 log_info(LD_CIRC,
2156 "We couldn't find any live%s%s%s routers; falling back "
2157 "to list of all routers.",
2158 need_capacity?", fast":"",
2159 need_uptime?", stable":"",
2160 need_guard?", guard":"");
2161 flags &= ~ (CRN_NEED_UPTIME|CRN_NEED_CAPACITY|CRN_NEED_GUARD);
2162 choice = router_choose_random_node(
2163 excludedsmartlist, excludedset, flags);
2165 smartlist_free(excludednodes);
2166 if (!choice) {
2167 log_warn(LD_CIRC,
2168 "No available nodes when trying to choose node. Failing.");
2170 return choice;
2173 /** Helper: Return true iff the <b>identity_digest</b> and <b>nickname</b>
2174 * combination of a router, encoded in hexadecimal, matches <b>hexdigest</b>
2175 * (which is optionally prefixed with a single dollar sign). Return false if
2176 * <b>hexdigest</b> is malformed, or it doesn't match. */
2177 static INLINE int
2178 hex_digest_matches(const char *hexdigest, const char *identity_digest,
2179 const char *nickname, int is_named)
2181 char digest[DIGEST_LEN];
2182 size_t len;
2183 tor_assert(hexdigest);
2184 if (hexdigest[0] == '$')
2185 ++hexdigest;
2187 len = strlen(hexdigest);
2188 if (len < HEX_DIGEST_LEN)
2189 return 0;
2190 else if (len > HEX_DIGEST_LEN &&
2191 (hexdigest[HEX_DIGEST_LEN] == '=' ||
2192 hexdigest[HEX_DIGEST_LEN] == '~')) {
2193 if (strcasecmp(hexdigest+HEX_DIGEST_LEN+1, nickname))
2194 return 0;
2195 if (hexdigest[HEX_DIGEST_LEN] == '=' && !is_named)
2196 return 0;
2199 if (base16_decode(digest, DIGEST_LEN, hexdigest, HEX_DIGEST_LEN)<0)
2200 return 0;
2201 return (!memcmp(digest, identity_digest, DIGEST_LEN));
2204 /** Return true iff the digest of <b>router</b>'s identity key,
2205 * encoded in hexadecimal, matches <b>hexdigest</b> (which is
2206 * optionally prefixed with a single dollar sign). Return false if
2207 * <b>hexdigest</b> is malformed, or it doesn't match. */
2208 static INLINE int
2209 router_hex_digest_matches(routerinfo_t *router, const char *hexdigest)
2211 return hex_digest_matches(hexdigest, router->cache_info.identity_digest,
2212 router->nickname, router->is_named);
2215 /** Return true if <b>router</b>'s nickname matches <b>nickname</b>
2216 * (case-insensitive), or if <b>router's</b> identity key digest
2217 * matches a hexadecimal value stored in <b>nickname</b>. Return
2218 * false otherwise. */
2219 static int
2220 router_nickname_matches(routerinfo_t *router, const char *nickname)
2222 if (nickname[0]!='$' && !strcasecmp(router->nickname, nickname))
2223 return 1;
2224 return router_hex_digest_matches(router, nickname);
2227 /** Return the router in our routerlist whose (case-insensitive)
2228 * nickname or (case-sensitive) hexadecimal key digest is
2229 * <b>nickname</b>. Return NULL if no such router is known.
2231 routerinfo_t *
2232 router_get_by_nickname(const char *nickname, int warn_if_unnamed)
2234 int maybedigest;
2235 char digest[DIGEST_LEN];
2236 routerinfo_t *best_match=NULL;
2237 int n_matches = 0;
2238 const char *named_digest = NULL;
2240 tor_assert(nickname);
2241 if (!routerlist)
2242 return NULL;
2243 if (nickname[0] == '$')
2244 return router_get_by_hexdigest(nickname);
2245 if (!strcasecmp(nickname, UNNAMED_ROUTER_NICKNAME))
2246 return NULL;
2247 if (server_mode(get_options()) &&
2248 !strcasecmp(nickname, get_options()->Nickname))
2249 return router_get_my_routerinfo();
2251 maybedigest = (strlen(nickname) >= HEX_DIGEST_LEN) &&
2252 (base16_decode(digest,DIGEST_LEN,nickname,HEX_DIGEST_LEN) == 0);
2254 if ((named_digest = networkstatus_get_router_digest_by_nickname(nickname))) {
2255 return rimap_get(routerlist->identity_map, named_digest);
2257 if (networkstatus_nickname_is_unnamed(nickname))
2258 return NULL;
2260 /* If we reach this point, there's no canonical value for the nickname. */
2262 SMARTLIST_FOREACH(routerlist->routers, routerinfo_t *, router,
2264 if (!strcasecmp(router->nickname, nickname)) {
2265 ++n_matches;
2266 if (n_matches <= 1 || router->is_running)
2267 best_match = router;
2268 } else if (maybedigest &&
2269 !memcmp(digest, router->cache_info.identity_digest, DIGEST_LEN)
2271 if (router_hex_digest_matches(router, nickname))
2272 return router;
2273 /* If we reach this point, we have a ID=name syntax that matches the
2274 * identity but not the name. That isn't an acceptable match. */
2278 if (best_match) {
2279 if (warn_if_unnamed && n_matches > 1) {
2280 smartlist_t *fps = smartlist_create();
2281 int any_unwarned = 0;
2282 SMARTLIST_FOREACH(routerlist->routers, routerinfo_t *, router,
2284 routerstatus_t *rs;
2285 char *desc;
2286 size_t dlen;
2287 char fp[HEX_DIGEST_LEN+1];
2288 if (strcasecmp(router->nickname, nickname))
2289 continue;
2290 rs = router_get_consensus_status_by_id(
2291 router->cache_info.identity_digest);
2292 if (rs && !rs->name_lookup_warned) {
2293 rs->name_lookup_warned = 1;
2294 any_unwarned = 1;
2296 base16_encode(fp, sizeof(fp),
2297 router->cache_info.identity_digest, DIGEST_LEN);
2298 dlen = 32 + HEX_DIGEST_LEN + strlen(router->address);
2299 desc = tor_malloc(dlen);
2300 tor_snprintf(desc, dlen, "\"$%s\" for the one at %s:%d",
2301 fp, router->address, router->or_port);
2302 smartlist_add(fps, desc);
2304 if (any_unwarned) {
2305 char *alternatives = smartlist_join_strings(fps, "; ",0,NULL);
2306 log_warn(LD_CONFIG,
2307 "There are multiple matches for the nickname \"%s\","
2308 " but none is listed as named by the directory authorities. "
2309 "Choosing one arbitrarily. If you meant one in particular, "
2310 "you should say %s.", nickname, alternatives);
2311 tor_free(alternatives);
2313 SMARTLIST_FOREACH(fps, char *, cp, tor_free(cp));
2314 smartlist_free(fps);
2315 } else if (warn_if_unnamed) {
2316 routerstatus_t *rs = router_get_consensus_status_by_id(
2317 best_match->cache_info.identity_digest);
2318 if (rs && !rs->name_lookup_warned) {
2319 char fp[HEX_DIGEST_LEN+1];
2320 base16_encode(fp, sizeof(fp),
2321 best_match->cache_info.identity_digest, DIGEST_LEN);
2322 log_warn(LD_CONFIG, "You specified a server \"%s\" by name, but this "
2323 "name is not registered, so it could be used by any server, "
2324 "not just the one you meant. "
2325 "To make sure you get the same server in the future, refer to "
2326 "it by key, as \"$%s\".", nickname, fp);
2327 rs->name_lookup_warned = 1;
2330 return best_match;
2333 return NULL;
2336 /** Try to find a routerinfo for <b>digest</b>. If we don't have one,
2337 * return 1. If we do, ask tor_version_as_new_as() for the answer.
2340 router_digest_version_as_new_as(const char *digest, const char *cutoff)
2342 routerinfo_t *router = router_get_by_digest(digest);
2343 if (!router)
2344 return 1;
2345 return tor_version_as_new_as(router->platform, cutoff);
2348 /** Return true iff <b>digest</b> is the digest of the identity key of a
2349 * trusted directory matching at least one bit of <b>type</b>. If <b>type</b>
2350 * is zero, any authority is okay. */
2352 router_digest_is_trusted_dir_type(const char *digest, authority_type_t type)
2354 if (!trusted_dir_servers)
2355 return 0;
2356 if (authdir_mode(get_options()) && router_digest_is_me(digest))
2357 return 1;
2358 SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, ent,
2359 if (!memcmp(digest, ent->digest, DIGEST_LEN)) {
2360 return (!type) || ((type & ent->type) != 0);
2362 return 0;
2365 /** Return true iff <b>addr</b> is the address of one of our trusted
2366 * directory authorities. */
2368 router_addr_is_trusted_dir(uint32_t addr)
2370 if (!trusted_dir_servers)
2371 return 0;
2372 SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, ent,
2373 if (ent->addr == addr)
2374 return 1;
2376 return 0;
2379 /** If hexdigest is correctly formed, base16_decode it into
2380 * digest, which must have DIGEST_LEN space in it.
2381 * Return 0 on success, -1 on failure.
2384 hexdigest_to_digest(const char *hexdigest, char *digest)
2386 if (hexdigest[0]=='$')
2387 ++hexdigest;
2388 if (strlen(hexdigest) < HEX_DIGEST_LEN ||
2389 base16_decode(digest,DIGEST_LEN,hexdigest,HEX_DIGEST_LEN) < 0)
2390 return -1;
2391 return 0;
2394 /** Return the router in our routerlist whose hexadecimal key digest
2395 * is <b>hexdigest</b>. Return NULL if no such router is known. */
2396 routerinfo_t *
2397 router_get_by_hexdigest(const char *hexdigest)
2399 char digest[DIGEST_LEN];
2400 size_t len;
2401 routerinfo_t *ri;
2403 tor_assert(hexdigest);
2404 if (!routerlist)
2405 return NULL;
2406 if (hexdigest[0]=='$')
2407 ++hexdigest;
2408 len = strlen(hexdigest);
2409 if (hexdigest_to_digest(hexdigest, digest) < 0)
2410 return NULL;
2412 ri = router_get_by_digest(digest);
2414 if (ri && len > HEX_DIGEST_LEN) {
2415 if (hexdigest[HEX_DIGEST_LEN] == '=') {
2416 if (strcasecmp(ri->nickname, hexdigest+HEX_DIGEST_LEN+1) ||
2417 !ri->is_named)
2418 return NULL;
2419 } else if (hexdigest[HEX_DIGEST_LEN] == '~') {
2420 if (strcasecmp(ri->nickname, hexdigest+HEX_DIGEST_LEN+1))
2421 return NULL;
2422 } else {
2423 return NULL;
2427 return ri;
2430 /** Return the router in our routerlist whose 20-byte key digest
2431 * is <b>digest</b>. Return NULL if no such router is known. */
2432 routerinfo_t *
2433 router_get_by_digest(const char *digest)
2435 tor_assert(digest);
2437 if (!routerlist) return NULL;
2439 // routerlist_assert_ok(routerlist);
2441 return rimap_get(routerlist->identity_map, digest);
2444 /** Return the router in our routerlist whose 20-byte descriptor
2445 * is <b>digest</b>. Return NULL if no such router is known. */
2446 signed_descriptor_t *
2447 router_get_by_descriptor_digest(const char *digest)
2449 tor_assert(digest);
2451 if (!routerlist) return NULL;
2453 return sdmap_get(routerlist->desc_digest_map, digest);
2456 /** Return the signed descriptor for the router in our routerlist whose
2457 * 20-byte extra-info digest is <b>digest</b>. Return NULL if no such router
2458 * is known. */
2459 signed_descriptor_t *
2460 router_get_by_extrainfo_digest(const char *digest)
2462 tor_assert(digest);
2464 if (!routerlist) return NULL;
2466 return sdmap_get(routerlist->desc_by_eid_map, digest);
2469 /** Return the signed descriptor for the extrainfo_t in our routerlist whose
2470 * extra-info-digest is <b>digest</b>. Return NULL if no such extra-info
2471 * document is known. */
2472 signed_descriptor_t *
2473 extrainfo_get_by_descriptor_digest(const char *digest)
2475 extrainfo_t *ei;
2476 tor_assert(digest);
2477 if (!routerlist) return NULL;
2478 ei = eimap_get(routerlist->extra_info_map, digest);
2479 return ei ? &ei->cache_info : NULL;
2482 /** Return a pointer to the signed textual representation of a descriptor.
2483 * The returned string is not guaranteed to be NUL-terminated: the string's
2484 * length will be in desc-\>signed_descriptor_len.
2486 * If <b>with_annotations</b> is set, the returned string will include
2487 * the annotations
2488 * (if any) preceding the descriptor. This will increase the length of the
2489 * string by desc-\>annotations_len.
2491 * The caller must not free the string returned.
2493 static const char *
2494 signed_descriptor_get_body_impl(signed_descriptor_t *desc,
2495 int with_annotations)
2497 const char *r = NULL;
2498 size_t len = desc->signed_descriptor_len;
2499 off_t offset = desc->saved_offset;
2500 if (with_annotations)
2501 len += desc->annotations_len;
2502 else
2503 offset += desc->annotations_len;
2505 tor_assert(len > 32);
2506 if (desc->saved_location == SAVED_IN_CACHE && routerlist) {
2507 desc_store_t *store = desc_get_store(router_get_routerlist(), desc);
2508 if (store && store->mmap) {
2509 tor_assert(desc->saved_offset + len <= store->mmap->size);
2510 r = store->mmap->data + offset;
2511 } else if (store) {
2512 log_err(LD_DIR, "We couldn't read a descriptor that is supposedly "
2513 "mmaped in our cache. Is another process running in our data "
2514 "directory? Exiting.");
2515 exit(1);
2518 if (!r) /* no mmap, or not in cache. */
2519 r = desc->signed_descriptor_body +
2520 (with_annotations ? 0 : desc->annotations_len);
2522 tor_assert(r);
2523 if (!with_annotations) {
2524 if (memcmp("router ", r, 7) && memcmp("extra-info ", r, 11)) {
2525 char *cp = tor_strndup(r, 64);
2526 log_err(LD_DIR, "descriptor at %p begins with unexpected string %s. "
2527 "Is another process running in our data directory? Exiting.",
2528 desc, escaped(cp));
2529 exit(1);
2533 return r;
2536 /** Return a pointer to the signed textual representation of a descriptor.
2537 * The returned string is not guaranteed to be NUL-terminated: the string's
2538 * length will be in desc-\>signed_descriptor_len.
2540 * The caller must not free the string returned.
2542 const char *
2543 signed_descriptor_get_body(signed_descriptor_t *desc)
2545 return signed_descriptor_get_body_impl(desc, 0);
2548 /** As signed_descriptor_get_body(), but points to the beginning of the
2549 * annotations section rather than the beginning of the descriptor. */
2550 const char *
2551 signed_descriptor_get_annotations(signed_descriptor_t *desc)
2553 return signed_descriptor_get_body_impl(desc, 1);
2556 /** Return the current list of all known routers. */
2557 routerlist_t *
2558 router_get_routerlist(void)
2560 if (PREDICT_UNLIKELY(!routerlist)) {
2561 routerlist = tor_malloc_zero(sizeof(routerlist_t));
2562 routerlist->routers = smartlist_create();
2563 routerlist->old_routers = smartlist_create();
2564 routerlist->identity_map = rimap_new();
2565 routerlist->desc_digest_map = sdmap_new();
2566 routerlist->desc_by_eid_map = sdmap_new();
2567 routerlist->extra_info_map = eimap_new();
2569 routerlist->desc_store.fname_base = "cached-descriptors";
2570 routerlist->desc_store.fname_alt_base = "cached-routers";
2571 routerlist->extrainfo_store.fname_base = "cached-extrainfo";
2573 routerlist->desc_store.type = ROUTER_STORE;
2574 routerlist->extrainfo_store.type = EXTRAINFO_STORE;
2576 routerlist->desc_store.description = "router descriptors";
2577 routerlist->extrainfo_store.description = "extra-info documents";
2579 return routerlist;
2582 /** Free all storage held by <b>router</b>. */
2583 void
2584 routerinfo_free(routerinfo_t *router)
2586 if (!router)
2587 return;
2589 tor_free(router->cache_info.signed_descriptor_body);
2590 tor_free(router->address);
2591 tor_free(router->nickname);
2592 tor_free(router->platform);
2593 tor_free(router->contact_info);
2594 if (router->onion_pkey)
2595 crypto_free_pk_env(router->onion_pkey);
2596 if (router->identity_pkey)
2597 crypto_free_pk_env(router->identity_pkey);
2598 if (router->declared_family) {
2599 SMARTLIST_FOREACH(router->declared_family, char *, s, tor_free(s));
2600 smartlist_free(router->declared_family);
2602 addr_policy_list_free(router->exit_policy);
2604 /* XXXX Remove if this turns out to affect performance. */
2605 memset(router, 77, sizeof(routerinfo_t));
2607 tor_free(router);
2610 /** Release all storage held by <b>extrainfo</b> */
2611 void
2612 extrainfo_free(extrainfo_t *extrainfo)
2614 if (!extrainfo)
2615 return;
2616 tor_free(extrainfo->cache_info.signed_descriptor_body);
2617 tor_free(extrainfo->pending_sig);
2619 /* XXXX remove this if it turns out to slow us down. */
2620 memset(extrainfo, 88, sizeof(extrainfo_t)); /* debug bad memory usage */
2621 tor_free(extrainfo);
2624 /** Release storage held by <b>sd</b>. */
2625 static void
2626 signed_descriptor_free(signed_descriptor_t *sd)
2628 if (!sd)
2629 return;
2631 tor_free(sd->signed_descriptor_body);
2633 /* XXXX remove this once more bugs go away. */
2634 memset(sd, 99, sizeof(signed_descriptor_t)); /* Debug bad mem usage */
2635 tor_free(sd);
2638 /** Extract a signed_descriptor_t from a routerinfo, and free the routerinfo.
2640 static signed_descriptor_t *
2641 signed_descriptor_from_routerinfo(routerinfo_t *ri)
2643 signed_descriptor_t *sd = tor_malloc_zero(sizeof(signed_descriptor_t));
2644 memcpy(sd, &(ri->cache_info), sizeof(signed_descriptor_t));
2645 sd->routerlist_index = -1;
2646 ri->cache_info.signed_descriptor_body = NULL;
2647 routerinfo_free(ri);
2648 return sd;
2651 /** Helper: free the storage held by the extrainfo_t in <b>e</b>. */
2652 static void
2653 _extrainfo_free(void *e)
2655 extrainfo_free(e);
2658 /** Free all storage held by a routerlist <b>rl</b>. */
2659 void
2660 routerlist_free(routerlist_t *rl)
2662 if (!rl)
2663 return;
2664 rimap_free(rl->identity_map, NULL);
2665 sdmap_free(rl->desc_digest_map, NULL);
2666 sdmap_free(rl->desc_by_eid_map, NULL);
2667 eimap_free(rl->extra_info_map, _extrainfo_free);
2668 SMARTLIST_FOREACH(rl->routers, routerinfo_t *, r,
2669 routerinfo_free(r));
2670 SMARTLIST_FOREACH(rl->old_routers, signed_descriptor_t *, sd,
2671 signed_descriptor_free(sd));
2672 smartlist_free(rl->routers);
2673 smartlist_free(rl->old_routers);
2674 if (routerlist->desc_store.mmap)
2675 tor_munmap_file(routerlist->desc_store.mmap);
2676 if (routerlist->extrainfo_store.mmap)
2677 tor_munmap_file(routerlist->extrainfo_store.mmap);
2678 tor_free(rl);
2680 router_dir_info_changed();
2683 /** Log information about how much memory is being used for routerlist,
2684 * at log level <b>severity</b>. */
2685 void
2686 dump_routerlist_mem_usage(int severity)
2688 uint64_t livedescs = 0;
2689 uint64_t olddescs = 0;
2690 if (!routerlist)
2691 return;
2692 SMARTLIST_FOREACH(routerlist->routers, routerinfo_t *, r,
2693 livedescs += r->cache_info.signed_descriptor_len);
2694 SMARTLIST_FOREACH(routerlist->old_routers, signed_descriptor_t *, sd,
2695 olddescs += sd->signed_descriptor_len);
2697 log(severity, LD_DIR,
2698 "In %d live descriptors: "U64_FORMAT" bytes. "
2699 "In %d old descriptors: "U64_FORMAT" bytes.",
2700 smartlist_len(routerlist->routers), U64_PRINTF_ARG(livedescs),
2701 smartlist_len(routerlist->old_routers), U64_PRINTF_ARG(olddescs));
2704 /** Debugging helper: If <b>idx</b> is nonnegative, assert that <b>ri</b> is
2705 * in <b>sl</b> at position <b>idx</b>. Otherwise, search <b>sl</b> for
2706 * <b>ri</b>. Return the index of <b>ri</b> in <b>sl</b>, or -1 if <b>ri</b>
2707 * is not in <b>sl</b>. */
2708 static INLINE int
2709 _routerlist_find_elt(smartlist_t *sl, void *ri, int idx)
2711 if (idx < 0) {
2712 idx = -1;
2713 SMARTLIST_FOREACH(sl, routerinfo_t *, r,
2714 if (r == ri) {
2715 idx = r_sl_idx;
2716 break;
2718 } else {
2719 tor_assert(idx < smartlist_len(sl));
2720 tor_assert(smartlist_get(sl, idx) == ri);
2722 return idx;
2725 /** Insert an item <b>ri</b> into the routerlist <b>rl</b>, updating indices
2726 * as needed. There must be no previous member of <b>rl</b> with the same
2727 * identity digest as <b>ri</b>: If there is, call routerlist_replace
2728 * instead.
2730 static void
2731 routerlist_insert(routerlist_t *rl, routerinfo_t *ri)
2733 routerinfo_t *ri_old;
2735 /* XXXX Remove if this slows us down. */
2736 routerinfo_t *ri_generated = router_get_my_routerinfo();
2737 tor_assert(ri_generated != ri);
2739 tor_assert(ri->cache_info.routerlist_index == -1);
2741 ri_old = rimap_set(rl->identity_map, ri->cache_info.identity_digest, ri);
2742 tor_assert(!ri_old);
2743 sdmap_set(rl->desc_digest_map, ri->cache_info.signed_descriptor_digest,
2744 &(ri->cache_info));
2745 if (!tor_digest_is_zero(ri->cache_info.extra_info_digest))
2746 sdmap_set(rl->desc_by_eid_map, ri->cache_info.extra_info_digest,
2747 &ri->cache_info);
2748 smartlist_add(rl->routers, ri);
2749 ri->cache_info.routerlist_index = smartlist_len(rl->routers) - 1;
2750 router_dir_info_changed();
2751 #ifdef DEBUG_ROUTERLIST
2752 routerlist_assert_ok(rl);
2753 #endif
2756 /** Adds the extrainfo_t <b>ei</b> to the routerlist <b>rl</b>, if there is a
2757 * corresponding router in rl-\>routers or rl-\>old_routers. Return true iff
2758 * we actually inserted <b>ei</b>. Free <b>ei</b> if it isn't inserted. */
2759 static int
2760 extrainfo_insert(routerlist_t *rl, extrainfo_t *ei)
2762 int r = 0;
2763 routerinfo_t *ri = rimap_get(rl->identity_map,
2764 ei->cache_info.identity_digest);
2765 signed_descriptor_t *sd =
2766 sdmap_get(rl->desc_by_eid_map, ei->cache_info.signed_descriptor_digest);
2767 extrainfo_t *ei_tmp;
2770 /* XXXX remove this code if it slows us down. */
2771 extrainfo_t *ei_generated = router_get_my_extrainfo();
2772 tor_assert(ei_generated != ei);
2775 if (!ri) {
2776 /* This router is unknown; we can't even verify the signature. Give up.*/
2777 goto done;
2779 if (routerinfo_incompatible_with_extrainfo(ri, ei, sd, NULL)) {
2780 goto done;
2783 /* Okay, if we make it here, we definitely have a router corresponding to
2784 * this extrainfo. */
2786 ei_tmp = eimap_set(rl->extra_info_map,
2787 ei->cache_info.signed_descriptor_digest,
2788 ei);
2789 r = 1;
2790 if (ei_tmp) {
2791 rl->extrainfo_store.bytes_dropped +=
2792 ei_tmp->cache_info.signed_descriptor_len;
2793 extrainfo_free(ei_tmp);
2796 done:
2797 if (r == 0)
2798 extrainfo_free(ei);
2800 #ifdef DEBUG_ROUTERLIST
2801 routerlist_assert_ok(rl);
2802 #endif
2803 return r;
2806 #define should_cache_old_descriptors() \
2807 directory_caches_dir_info(get_options())
2809 /** If we're a directory cache and routerlist <b>rl</b> doesn't have
2810 * a copy of router <b>ri</b> yet, add it to the list of old (not
2811 * recommended but still served) descriptors. Else free it. */
2812 static void
2813 routerlist_insert_old(routerlist_t *rl, routerinfo_t *ri)
2816 /* XXXX remove this code if it slows us down. */
2817 routerinfo_t *ri_generated = router_get_my_routerinfo();
2818 tor_assert(ri_generated != ri);
2820 tor_assert(ri->cache_info.routerlist_index == -1);
2822 if (should_cache_old_descriptors() &&
2823 ri->purpose == ROUTER_PURPOSE_GENERAL &&
2824 !sdmap_get(rl->desc_digest_map,
2825 ri->cache_info.signed_descriptor_digest)) {
2826 signed_descriptor_t *sd = signed_descriptor_from_routerinfo(ri);
2827 sdmap_set(rl->desc_digest_map, sd->signed_descriptor_digest, sd);
2828 smartlist_add(rl->old_routers, sd);
2829 sd->routerlist_index = smartlist_len(rl->old_routers)-1;
2830 if (!tor_digest_is_zero(sd->extra_info_digest))
2831 sdmap_set(rl->desc_by_eid_map, sd->extra_info_digest, sd);
2832 } else {
2833 routerinfo_free(ri);
2835 #ifdef DEBUG_ROUTERLIST
2836 routerlist_assert_ok(rl);
2837 #endif
2840 /** Remove an item <b>ri</b> from the routerlist <b>rl</b>, updating indices
2841 * as needed. If <b>idx</b> is nonnegative and smartlist_get(rl-&gt;routers,
2842 * idx) == ri, we don't need to do a linear search over the list to decide
2843 * which to remove. We fill the gap in rl-&gt;routers with a later element in
2844 * the list, if any exists. <b>ri</b> is freed.
2846 * If <b>make_old</b> is true, instead of deleting the router, we try adding
2847 * it to rl-&gt;old_routers. */
2848 void
2849 routerlist_remove(routerlist_t *rl, routerinfo_t *ri, int make_old, time_t now)
2851 routerinfo_t *ri_tmp;
2852 extrainfo_t *ei_tmp;
2853 int idx = ri->cache_info.routerlist_index;
2854 tor_assert(0 <= idx && idx < smartlist_len(rl->routers));
2855 tor_assert(smartlist_get(rl->routers, idx) == ri);
2857 /* make sure the rephist module knows that it's not running */
2858 rep_hist_note_router_unreachable(ri->cache_info.identity_digest, now);
2860 ri->cache_info.routerlist_index = -1;
2861 smartlist_del(rl->routers, idx);
2862 if (idx < smartlist_len(rl->routers)) {
2863 routerinfo_t *r = smartlist_get(rl->routers, idx);
2864 r->cache_info.routerlist_index = idx;
2867 ri_tmp = rimap_remove(rl->identity_map, ri->cache_info.identity_digest);
2868 router_dir_info_changed();
2869 tor_assert(ri_tmp == ri);
2871 if (make_old && should_cache_old_descriptors() &&
2872 ri->purpose == ROUTER_PURPOSE_GENERAL) {
2873 signed_descriptor_t *sd;
2874 sd = signed_descriptor_from_routerinfo(ri);
2875 smartlist_add(rl->old_routers, sd);
2876 sd->routerlist_index = smartlist_len(rl->old_routers)-1;
2877 sdmap_set(rl->desc_digest_map, sd->signed_descriptor_digest, sd);
2878 if (!tor_digest_is_zero(sd->extra_info_digest))
2879 sdmap_set(rl->desc_by_eid_map, sd->extra_info_digest, sd);
2880 } else {
2881 signed_descriptor_t *sd_tmp;
2882 sd_tmp = sdmap_remove(rl->desc_digest_map,
2883 ri->cache_info.signed_descriptor_digest);
2884 tor_assert(sd_tmp == &(ri->cache_info));
2885 rl->desc_store.bytes_dropped += ri->cache_info.signed_descriptor_len;
2886 ei_tmp = eimap_remove(rl->extra_info_map,
2887 ri->cache_info.extra_info_digest);
2888 if (ei_tmp) {
2889 rl->extrainfo_store.bytes_dropped +=
2890 ei_tmp->cache_info.signed_descriptor_len;
2891 extrainfo_free(ei_tmp);
2893 if (!tor_digest_is_zero(ri->cache_info.extra_info_digest))
2894 sdmap_remove(rl->desc_by_eid_map, ri->cache_info.extra_info_digest);
2895 routerinfo_free(ri);
2897 #ifdef DEBUG_ROUTERLIST
2898 routerlist_assert_ok(rl);
2899 #endif
2902 /** Remove a signed_descriptor_t <b>sd</b> from <b>rl</b>-\>old_routers, and
2903 * adjust <b>rl</b> as appropriate. <b>idx</b> is -1, or the index of
2904 * <b>sd</b>. */
2905 static void
2906 routerlist_remove_old(routerlist_t *rl, signed_descriptor_t *sd, int idx)
2908 signed_descriptor_t *sd_tmp;
2909 extrainfo_t *ei_tmp;
2910 desc_store_t *store;
2911 if (idx == -1) {
2912 idx = sd->routerlist_index;
2914 tor_assert(0 <= idx && idx < smartlist_len(rl->old_routers));
2915 /* XXXX edmanm's bridge relay triggered the following assert while
2916 * running 0.2.0.12-alpha. If anybody triggers this again, see if we
2917 * can get a backtrace. */
2918 tor_assert(smartlist_get(rl->old_routers, idx) == sd);
2919 tor_assert(idx == sd->routerlist_index);
2921 sd->routerlist_index = -1;
2922 smartlist_del(rl->old_routers, idx);
2923 if (idx < smartlist_len(rl->old_routers)) {
2924 signed_descriptor_t *d = smartlist_get(rl->old_routers, idx);
2925 d->routerlist_index = idx;
2927 sd_tmp = sdmap_remove(rl->desc_digest_map,
2928 sd->signed_descriptor_digest);
2929 tor_assert(sd_tmp == sd);
2930 store = desc_get_store(rl, sd);
2931 if (store)
2932 store->bytes_dropped += sd->signed_descriptor_len;
2934 ei_tmp = eimap_remove(rl->extra_info_map,
2935 sd->extra_info_digest);
2936 if (ei_tmp) {
2937 rl->extrainfo_store.bytes_dropped +=
2938 ei_tmp->cache_info.signed_descriptor_len;
2939 extrainfo_free(ei_tmp);
2941 if (!tor_digest_is_zero(sd->extra_info_digest))
2942 sdmap_remove(rl->desc_by_eid_map, sd->extra_info_digest);
2944 signed_descriptor_free(sd);
2945 #ifdef DEBUG_ROUTERLIST
2946 routerlist_assert_ok(rl);
2947 #endif
2950 /** Remove <b>ri_old</b> from the routerlist <b>rl</b>, and replace it with
2951 * <b>ri_new</b>, updating all index info. If <b>idx</b> is nonnegative and
2952 * smartlist_get(rl-&gt;routers, idx) == ri, we don't need to do a linear
2953 * search over the list to decide which to remove. We put ri_new in the same
2954 * index as ri_old, if possible. ri is freed as appropriate.
2956 * If should_cache_descriptors() is true, instead of deleting the router,
2957 * we add it to rl-&gt;old_routers. */
2958 static void
2959 routerlist_replace(routerlist_t *rl, routerinfo_t *ri_old,
2960 routerinfo_t *ri_new)
2962 int idx;
2964 routerinfo_t *ri_tmp;
2965 extrainfo_t *ei_tmp;
2967 /* XXXX Remove this if it turns out to slow us down. */
2968 routerinfo_t *ri_generated = router_get_my_routerinfo();
2969 tor_assert(ri_generated != ri_new);
2971 tor_assert(ri_old != ri_new);
2972 tor_assert(ri_new->cache_info.routerlist_index == -1);
2974 idx = ri_old->cache_info.routerlist_index;
2975 tor_assert(0 <= idx && idx < smartlist_len(rl->routers));
2976 tor_assert(smartlist_get(rl->routers, idx) == ri_old);
2978 router_dir_info_changed();
2979 if (idx >= 0) {
2980 smartlist_set(rl->routers, idx, ri_new);
2981 ri_old->cache_info.routerlist_index = -1;
2982 ri_new->cache_info.routerlist_index = idx;
2983 /* Check that ri_old is not in rl->routers anymore: */
2984 tor_assert( _routerlist_find_elt(rl->routers, ri_old, -1) == -1 );
2985 } else {
2986 log_warn(LD_BUG, "Appending entry from routerlist_replace.");
2987 routerlist_insert(rl, ri_new);
2988 return;
2990 if (memcmp(ri_old->cache_info.identity_digest,
2991 ri_new->cache_info.identity_digest, DIGEST_LEN)) {
2992 /* digests don't match; digestmap_set won't replace */
2993 rimap_remove(rl->identity_map, ri_old->cache_info.identity_digest);
2995 ri_tmp = rimap_set(rl->identity_map,
2996 ri_new->cache_info.identity_digest, ri_new);
2997 tor_assert(!ri_tmp || ri_tmp == ri_old);
2998 sdmap_set(rl->desc_digest_map,
2999 ri_new->cache_info.signed_descriptor_digest,
3000 &(ri_new->cache_info));
3002 if (!tor_digest_is_zero(ri_new->cache_info.extra_info_digest)) {
3003 sdmap_set(rl->desc_by_eid_map, ri_new->cache_info.extra_info_digest,
3004 &ri_new->cache_info);
3007 if (should_cache_old_descriptors() &&
3008 ri_old->purpose == ROUTER_PURPOSE_GENERAL) {
3009 signed_descriptor_t *sd = signed_descriptor_from_routerinfo(ri_old);
3010 smartlist_add(rl->old_routers, sd);
3011 sd->routerlist_index = smartlist_len(rl->old_routers)-1;
3012 sdmap_set(rl->desc_digest_map, sd->signed_descriptor_digest, sd);
3013 if (!tor_digest_is_zero(sd->extra_info_digest))
3014 sdmap_set(rl->desc_by_eid_map, sd->extra_info_digest, sd);
3015 } else {
3016 if (memcmp(ri_old->cache_info.signed_descriptor_digest,
3017 ri_new->cache_info.signed_descriptor_digest,
3018 DIGEST_LEN)) {
3019 /* digests don't match; digestmap_set didn't replace */
3020 sdmap_remove(rl->desc_digest_map,
3021 ri_old->cache_info.signed_descriptor_digest);
3024 ei_tmp = eimap_remove(rl->extra_info_map,
3025 ri_old->cache_info.extra_info_digest);
3026 if (ei_tmp) {
3027 rl->extrainfo_store.bytes_dropped +=
3028 ei_tmp->cache_info.signed_descriptor_len;
3029 extrainfo_free(ei_tmp);
3031 if (!tor_digest_is_zero(ri_old->cache_info.extra_info_digest)) {
3032 sdmap_remove(rl->desc_by_eid_map,
3033 ri_old->cache_info.extra_info_digest);
3035 rl->desc_store.bytes_dropped += ri_old->cache_info.signed_descriptor_len;
3036 routerinfo_free(ri_old);
3038 #ifdef DEBUG_ROUTERLIST
3039 routerlist_assert_ok(rl);
3040 #endif
3043 /** Extract the descriptor <b>sd</b> from old_routerlist, and re-parse
3044 * it as a fresh routerinfo_t. */
3045 static routerinfo_t *
3046 routerlist_reparse_old(routerlist_t *rl, signed_descriptor_t *sd)
3048 routerinfo_t *ri;
3049 const char *body;
3051 body = signed_descriptor_get_annotations(sd);
3053 ri = router_parse_entry_from_string(body,
3054 body+sd->signed_descriptor_len+sd->annotations_len,
3055 0, 1, NULL);
3056 if (!ri)
3057 return NULL;
3058 memcpy(&ri->cache_info, sd, sizeof(signed_descriptor_t));
3059 sd->signed_descriptor_body = NULL; /* Steal reference. */
3060 ri->cache_info.routerlist_index = -1;
3062 routerlist_remove_old(rl, sd, -1);
3064 return ri;
3067 /** Free all memory held by the routerlist module. */
3068 void
3069 routerlist_free_all(void)
3071 routerlist_free(routerlist);
3072 routerlist = NULL;
3073 if (warned_nicknames) {
3074 SMARTLIST_FOREACH(warned_nicknames, char *, cp, tor_free(cp));
3075 smartlist_free(warned_nicknames);
3076 warned_nicknames = NULL;
3078 if (trusted_dir_servers) {
3079 SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, ds,
3080 trusted_dir_server_free(ds));
3081 smartlist_free(trusted_dir_servers);
3082 trusted_dir_servers = NULL;
3084 if (trusted_dir_certs) {
3085 DIGESTMAP_FOREACH(trusted_dir_certs, key, cert_list_t *, cl) {
3086 SMARTLIST_FOREACH(cl->certs, authority_cert_t *, cert,
3087 authority_cert_free(cert));
3088 smartlist_free(cl->certs);
3089 tor_free(cl);
3090 } DIGESTMAP_FOREACH_END;
3091 digestmap_free(trusted_dir_certs, NULL);
3092 trusted_dir_certs = NULL;
3096 /** Forget that we have issued any router-related warnings, so that we'll
3097 * warn again if we see the same errors. */
3098 void
3099 routerlist_reset_warnings(void)
3101 if (!warned_nicknames)
3102 warned_nicknames = smartlist_create();
3103 SMARTLIST_FOREACH(warned_nicknames, char *, cp, tor_free(cp));
3104 smartlist_clear(warned_nicknames); /* now the list is empty. */
3106 networkstatus_reset_warnings();
3109 /** Mark the router with ID <b>digest</b> as running or non-running
3110 * in our routerlist. */
3111 void
3112 router_set_status(const char *digest, int up)
3114 routerinfo_t *router;
3115 routerstatus_t *status;
3116 tor_assert(digest);
3118 SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, d,
3119 if (!memcmp(d->digest, digest, DIGEST_LEN))
3120 d->is_running = up);
3122 router = router_get_by_digest(digest);
3123 if (router) {
3124 log_debug(LD_DIR,"Marking router '%s/%s' as %s.",
3125 router->nickname, router->address, up ? "up" : "down");
3126 if (!up && router_is_me(router) && !we_are_hibernating())
3127 log_warn(LD_NET, "We just marked ourself as down. Are your external "
3128 "addresses reachable?");
3129 router->is_running = up;
3131 status = router_get_consensus_status_by_id(digest);
3132 if (status && status->is_running != up) {
3133 status->is_running = up;
3134 control_event_networkstatus_changed_single(status);
3136 router_dir_info_changed();
3139 /** Add <b>router</b> to the routerlist, if we don't already have it. Replace
3140 * older entries (if any) with the same key. Note: Callers should not hold
3141 * their pointers to <b>router</b> if this function fails; <b>router</b>
3142 * will either be inserted into the routerlist or freed. Similarly, even
3143 * if this call succeeds, they should not hold their pointers to
3144 * <b>router</b> after subsequent calls with other routerinfo's -- they
3145 * might cause the original routerinfo to get freed.
3147 * Returns the status for the operation. Might set *<b>msg</b> if it wants
3148 * the poster of the router to know something.
3150 * If <b>from_cache</b>, this descriptor came from our disk cache. If
3151 * <b>from_fetch</b>, we received it in response to a request we made.
3152 * (If both are false, that means it was uploaded to us as an auth dir
3153 * server or via the controller.)
3155 * This function should be called *after*
3156 * routers_update_status_from_consensus_networkstatus; subsequently, you
3157 * should call router_rebuild_store and routerlist_descriptors_added.
3159 was_router_added_t
3160 router_add_to_routerlist(routerinfo_t *router, const char **msg,
3161 int from_cache, int from_fetch)
3163 const char *id_digest;
3164 int authdir = authdir_mode_handles_descs(get_options(), router->purpose);
3165 int authdir_believes_valid = 0;
3166 routerinfo_t *old_router;
3167 networkstatus_t *consensus = networkstatus_get_latest_consensus();
3168 const smartlist_t *networkstatus_v2_list = networkstatus_get_v2_list();
3169 int in_consensus = 0;
3171 tor_assert(msg);
3173 if (!routerlist)
3174 router_get_routerlist();
3176 id_digest = router->cache_info.identity_digest;
3178 old_router = router_get_by_digest(id_digest);
3180 /* Make sure that we haven't already got this exact descriptor. */
3181 if (sdmap_get(routerlist->desc_digest_map,
3182 router->cache_info.signed_descriptor_digest)) {
3183 /* If we have this descriptor already and the new descriptor is a bridge
3184 * descriptor, replace it. If we had a bridge descriptor before and the
3185 * new one is not a bridge descriptor, don't replace it. */
3186 tor_assert(old_router);
3187 if (! (routerinfo_is_a_configured_bridge(router) &&
3188 (router->purpose == ROUTER_PURPOSE_BRIDGE ||
3189 old_router->purpose != ROUTER_PURPOSE_BRIDGE))) {
3190 log_info(LD_DIR,
3191 "Dropping descriptor that we already have for router '%s'",
3192 router->nickname);
3193 *msg = "Router descriptor was not new.";
3194 routerinfo_free(router);
3195 return ROUTER_WAS_NOT_NEW;
3199 if (authdir) {
3200 if (authdir_wants_to_reject_router(router, msg,
3201 !from_cache && !from_fetch)) {
3202 tor_assert(*msg);
3203 routerinfo_free(router);
3204 return ROUTER_AUTHDIR_REJECTS;
3206 authdir_believes_valid = router->is_valid;
3207 } else if (from_fetch) {
3208 /* Only check the descriptor digest against the network statuses when
3209 * we are receiving in response to a fetch. */
3211 if (!signed_desc_digest_is_recognized(&router->cache_info) &&
3212 !routerinfo_is_a_configured_bridge(router)) {
3213 /* We asked for it, so some networkstatus must have listed it when we
3214 * did. Save it if we're a cache in case somebody else asks for it. */
3215 log_info(LD_DIR,
3216 "Received a no-longer-recognized descriptor for router '%s'",
3217 router->nickname);
3218 *msg = "Router descriptor is not referenced by any network-status.";
3220 /* Only journal this desc if we'll be serving it. */
3221 if (!from_cache && should_cache_old_descriptors())
3222 signed_desc_append_to_journal(&router->cache_info,
3223 &routerlist->desc_store);
3224 routerlist_insert_old(routerlist, router);
3225 return ROUTER_NOT_IN_CONSENSUS_OR_NETWORKSTATUS;
3229 /* We no longer need a router with this descriptor digest. */
3230 SMARTLIST_FOREACH(networkstatus_v2_list, networkstatus_v2_t *, ns,
3232 routerstatus_t *rs =
3233 networkstatus_v2_find_entry(ns, id_digest);
3234 if (rs && !memcmp(rs->descriptor_digest,
3235 router->cache_info.signed_descriptor_digest,
3236 DIGEST_LEN))
3237 rs->need_to_mirror = 0;
3239 if (consensus) {
3240 routerstatus_t *rs = networkstatus_vote_find_entry(consensus, id_digest);
3241 if (rs && !memcmp(rs->descriptor_digest,
3242 router->cache_info.signed_descriptor_digest,
3243 DIGEST_LEN)) {
3244 in_consensus = 1;
3245 rs->need_to_mirror = 0;
3249 if (router->purpose == ROUTER_PURPOSE_GENERAL &&
3250 consensus && !in_consensus && !authdir) {
3251 /* If it's a general router not listed in the consensus, then don't
3252 * consider replacing the latest router with it. */
3253 if (!from_cache && should_cache_old_descriptors())
3254 signed_desc_append_to_journal(&router->cache_info,
3255 &routerlist->desc_store);
3256 routerlist_insert_old(routerlist, router);
3257 *msg = "Skipping router descriptor: not in consensus.";
3258 return ROUTER_NOT_IN_CONSENSUS;
3261 /* If we have a router with the same identity key, choose the newer one. */
3262 if (old_router) {
3263 if (!in_consensus && (router->cache_info.published_on <=
3264 old_router->cache_info.published_on)) {
3265 /* Same key, but old. This one is not listed in the consensus. */
3266 log_debug(LD_DIR, "Not-new descriptor for router '%s'",
3267 router->nickname);
3268 /* Only journal this desc if we'll be serving it. */
3269 if (!from_cache && should_cache_old_descriptors())
3270 signed_desc_append_to_journal(&router->cache_info,
3271 &routerlist->desc_store);
3272 routerlist_insert_old(routerlist, router);
3273 *msg = "Router descriptor was not new.";
3274 return ROUTER_WAS_NOT_NEW;
3275 } else {
3276 /* Same key, and either new, or listed in the consensus. */
3277 log_debug(LD_DIR, "Replacing entry for router '%s/%s' [%s]",
3278 router->nickname, old_router->nickname,
3279 hex_str(id_digest,DIGEST_LEN));
3280 if (routers_have_same_or_addr(router, old_router)) {
3281 /* these carry over when the address and orport are unchanged. */
3282 router->last_reachable = old_router->last_reachable;
3283 router->testing_since = old_router->testing_since;
3285 routerlist_replace(routerlist, old_router, router);
3286 if (!from_cache) {
3287 signed_desc_append_to_journal(&router->cache_info,
3288 &routerlist->desc_store);
3290 directory_set_dirty();
3291 *msg = authdir_believes_valid ? "Valid server updated" :
3292 ("Invalid server updated. (This dirserver is marking your "
3293 "server as unapproved.)");
3294 return ROUTER_ADDED_SUCCESSFULLY;
3298 if (!in_consensus && from_cache &&
3299 router->cache_info.published_on < time(NULL) - OLD_ROUTER_DESC_MAX_AGE) {
3300 *msg = "Router descriptor was really old.";
3301 routerinfo_free(router);
3302 return ROUTER_WAS_NOT_NEW;
3305 /* We haven't seen a router with this identity before. Add it to the end of
3306 * the list. */
3307 routerlist_insert(routerlist, router);
3308 if (!from_cache) {
3309 signed_desc_append_to_journal(&router->cache_info,
3310 &routerlist->desc_store);
3312 directory_set_dirty();
3313 return ROUTER_ADDED_SUCCESSFULLY;
3316 /** Insert <b>ei</b> into the routerlist, or free it. Other arguments are
3317 * as for router_add_to_routerlist(). Return ROUTER_ADDED_SUCCESSFULLY iff
3318 * we actually inserted it, ROUTER_BAD_EI otherwise.
3320 was_router_added_t
3321 router_add_extrainfo_to_routerlist(extrainfo_t *ei, const char **msg,
3322 int from_cache, int from_fetch)
3324 int inserted;
3325 (void)from_fetch;
3326 if (msg) *msg = NULL;
3327 /*XXXX022 Do something with msg */
3329 inserted = extrainfo_insert(router_get_routerlist(), ei);
3331 if (inserted && !from_cache)
3332 signed_desc_append_to_journal(&ei->cache_info,
3333 &routerlist->extrainfo_store);
3335 if (inserted)
3336 return ROUTER_ADDED_SUCCESSFULLY;
3337 else
3338 return ROUTER_BAD_EI;
3341 /** Sorting helper: return &lt;0, 0, or &gt;0 depending on whether the
3342 * signed_descriptor_t* in *<b>a</b> has an identity digest preceding, equal
3343 * to, or later than that of *<b>b</b>. */
3344 static int
3345 _compare_old_routers_by_identity(const void **_a, const void **_b)
3347 int i;
3348 const signed_descriptor_t *r1 = *_a, *r2 = *_b;
3349 if ((i = memcmp(r1->identity_digest, r2->identity_digest, DIGEST_LEN)))
3350 return i;
3351 return (int)(r1->published_on - r2->published_on);
3354 /** Internal type used to represent how long an old descriptor was valid,
3355 * where it appeared in the list of old descriptors, and whether it's extra
3356 * old. Used only by routerlist_remove_old_cached_routers_with_id(). */
3357 struct duration_idx_t {
3358 int duration;
3359 int idx;
3360 int old;
3363 /** Sorting helper: compare two duration_idx_t by their duration. */
3364 static int
3365 _compare_duration_idx(const void *_d1, const void *_d2)
3367 const struct duration_idx_t *d1 = _d1;
3368 const struct duration_idx_t *d2 = _d2;
3369 return d1->duration - d2->duration;
3372 /** The range <b>lo</b> through <b>hi</b> inclusive of routerlist->old_routers
3373 * must contain routerinfo_t with the same identity and with publication time
3374 * in ascending order. Remove members from this range until there are no more
3375 * than max_descriptors_per_router() remaining. Start by removing the oldest
3376 * members from before <b>cutoff</b>, then remove members which were current
3377 * for the lowest amount of time. The order of members of old_routers at
3378 * indices <b>lo</b> or higher may be changed.
3380 static void
3381 routerlist_remove_old_cached_routers_with_id(time_t now,
3382 time_t cutoff, int lo, int hi,
3383 digestset_t *retain)
3385 int i, n = hi-lo+1;
3386 unsigned n_extra, n_rmv = 0;
3387 struct duration_idx_t *lifespans;
3388 uint8_t *rmv, *must_keep;
3389 smartlist_t *lst = routerlist->old_routers;
3390 #if 1
3391 const char *ident;
3392 tor_assert(hi < smartlist_len(lst));
3393 tor_assert(lo <= hi);
3394 ident = ((signed_descriptor_t*)smartlist_get(lst, lo))->identity_digest;
3395 for (i = lo+1; i <= hi; ++i) {
3396 signed_descriptor_t *r = smartlist_get(lst, i);
3397 tor_assert(!memcmp(ident, r->identity_digest, DIGEST_LEN));
3399 #endif
3400 /* Check whether we need to do anything at all. */
3402 int mdpr = directory_caches_dir_info(get_options()) ? 2 : 1;
3403 if (n <= mdpr)
3404 return;
3405 n_extra = n - mdpr;
3408 lifespans = tor_malloc_zero(sizeof(struct duration_idx_t)*n);
3409 rmv = tor_malloc_zero(sizeof(uint8_t)*n);
3410 must_keep = tor_malloc_zero(sizeof(uint8_t)*n);
3411 /* Set lifespans to contain the lifespan and index of each server. */
3412 /* Set rmv[i-lo]=1 if we're going to remove a server for being too old. */
3413 for (i = lo; i <= hi; ++i) {
3414 signed_descriptor_t *r = smartlist_get(lst, i);
3415 signed_descriptor_t *r_next;
3416 lifespans[i-lo].idx = i;
3417 if (r->last_listed_as_valid_until >= now ||
3418 (retain && digestset_isin(retain, r->signed_descriptor_digest))) {
3419 must_keep[i-lo] = 1;
3421 if (i < hi) {
3422 r_next = smartlist_get(lst, i+1);
3423 tor_assert(r->published_on <= r_next->published_on);
3424 lifespans[i-lo].duration = (int)(r_next->published_on - r->published_on);
3425 } else {
3426 r_next = NULL;
3427 lifespans[i-lo].duration = INT_MAX;
3429 if (!must_keep[i-lo] && r->published_on < cutoff && n_rmv < n_extra) {
3430 ++n_rmv;
3431 lifespans[i-lo].old = 1;
3432 rmv[i-lo] = 1;
3436 if (n_rmv < n_extra) {
3438 * We aren't removing enough servers for being old. Sort lifespans by
3439 * the duration of liveness, and remove the ones we're not already going to
3440 * remove based on how long they were alive.
3442 qsort(lifespans, n, sizeof(struct duration_idx_t), _compare_duration_idx);
3443 for (i = 0; i < n && n_rmv < n_extra; ++i) {
3444 if (!must_keep[lifespans[i].idx-lo] && !lifespans[i].old) {
3445 rmv[lifespans[i].idx-lo] = 1;
3446 ++n_rmv;
3451 i = hi;
3452 do {
3453 if (rmv[i-lo])
3454 routerlist_remove_old(routerlist, smartlist_get(lst, i), i);
3455 } while (--i >= lo);
3456 tor_free(must_keep);
3457 tor_free(rmv);
3458 tor_free(lifespans);
3461 /** Deactivate any routers from the routerlist that are more than
3462 * ROUTER_MAX_AGE seconds old and not recommended by any networkstatuses;
3463 * remove old routers from the list of cached routers if we have too many.
3465 void
3466 routerlist_remove_old_routers(void)
3468 int i, hi=-1;
3469 const char *cur_id = NULL;
3470 time_t now = time(NULL);
3471 time_t cutoff;
3472 routerinfo_t *router;
3473 signed_descriptor_t *sd;
3474 digestset_t *retain;
3475 int caches = directory_caches_dir_info(get_options());
3476 const networkstatus_t *consensus = networkstatus_get_latest_consensus();
3477 const smartlist_t *networkstatus_v2_list = networkstatus_get_v2_list();
3478 int have_enough_v2;
3480 trusted_dirs_remove_old_certs();
3482 if (!routerlist || !consensus)
3483 return;
3485 // routerlist_assert_ok(routerlist);
3487 /* We need to guess how many router descriptors we will wind up wanting to
3488 retain, so that we can be sure to allocate a large enough Bloom filter
3489 to hold the digest set. Overestimating is fine; underestimating is bad.
3492 /* We'll probably retain everything in the consensus. */
3493 int n_max_retain = smartlist_len(consensus->routerstatus_list);
3494 if (caches && networkstatus_v2_list) {
3495 /* If we care about v2 statuses, we'll retain at most as many as are
3496 listed any of the v2 statues. This will be at least the length of
3497 the largest v2 networkstatus, and in the worst case, this set will be
3498 equal to the sum of the lengths of all v2 consensuses. Take the
3499 worst case.
3501 SMARTLIST_FOREACH(networkstatus_v2_list, networkstatus_v2_t *, ns,
3502 n_max_retain += smartlist_len(ns->entries));
3504 retain = digestset_new(n_max_retain);
3507 cutoff = now - OLD_ROUTER_DESC_MAX_AGE;
3508 /* Build a list of all the descriptors that _anybody_ lists. */
3509 if (caches && networkstatus_v2_list) {
3510 SMARTLIST_FOREACH(networkstatus_v2_list, networkstatus_v2_t *, ns,
3512 /* XXXX The inner loop here gets pretty expensive, and actually shows up
3513 * on some profiles. It may be the reason digestmap_set shows up in
3514 * profiles too. If instead we kept a per-descriptor digest count of
3515 * how many networkstatuses recommended each descriptor, and changed
3516 * that only when the networkstatuses changed, that would be a speed
3517 * improvement, possibly 1-4% if it also removes digestmap_set from the
3518 * profile. Not worth it for 0.1.2.x, though. The new directory
3519 * system will obsolete this whole thing in 0.2.0.x. */
3520 SMARTLIST_FOREACH(ns->entries, routerstatus_t *, rs,
3521 if (rs->published_on >= cutoff)
3522 digestset_add(retain, rs->descriptor_digest));
3526 /* Retain anything listed in the consensus. */
3527 if (consensus) {
3528 SMARTLIST_FOREACH(consensus->routerstatus_list, routerstatus_t *, rs,
3529 if (rs->published_on >= cutoff)
3530 digestset_add(retain, rs->descriptor_digest));
3533 /* If we have a consensus, and nearly as many v2 networkstatuses as we want,
3534 * we should consider pruning current routers that are too old and that
3535 * nobody recommends. (If we don't have a consensus or enough v2
3536 * networkstatuses, then we should get more before we decide to kill
3537 * routers.) */
3538 /* we set this to true iff we don't care about v2 info, or we have enough. */
3539 have_enough_v2 = !caches ||
3540 (networkstatus_v2_list &&
3541 smartlist_len(networkstatus_v2_list) > get_n_v2_authorities() / 2);
3543 if (have_enough_v2 && consensus) {
3544 cutoff = now - ROUTER_MAX_AGE;
3545 /* Remove too-old unrecommended members of routerlist->routers. */
3546 for (i = 0; i < smartlist_len(routerlist->routers); ++i) {
3547 router = smartlist_get(routerlist->routers, i);
3548 if (router->cache_info.published_on <= cutoff &&
3549 router->cache_info.last_listed_as_valid_until < now &&
3550 !digestset_isin(retain,
3551 router->cache_info.signed_descriptor_digest)) {
3552 /* Too old: remove it. (If we're a cache, just move it into
3553 * old_routers.) */
3554 log_info(LD_DIR,
3555 "Forgetting obsolete (too old) routerinfo for router '%s'",
3556 router->nickname);
3557 routerlist_remove(routerlist, router, 1, now);
3558 i--;
3563 //routerlist_assert_ok(routerlist);
3565 /* Remove far-too-old members of routerlist->old_routers. */
3566 cutoff = now - OLD_ROUTER_DESC_MAX_AGE;
3567 for (i = 0; i < smartlist_len(routerlist->old_routers); ++i) {
3568 sd = smartlist_get(routerlist->old_routers, i);
3569 if (sd->published_on <= cutoff &&
3570 sd->last_listed_as_valid_until < now &&
3571 !digestset_isin(retain, sd->signed_descriptor_digest)) {
3572 /* Too old. Remove it. */
3573 routerlist_remove_old(routerlist, sd, i--);
3577 //routerlist_assert_ok(routerlist);
3579 log_info(LD_DIR, "We have %d live routers and %d old router descriptors.",
3580 smartlist_len(routerlist->routers),
3581 smartlist_len(routerlist->old_routers));
3583 /* Now we might have to look at routerlist->old_routers for extraneous
3584 * members. (We'd keep all the members if we could, but we need to save
3585 * space.) First, check whether we have too many router descriptors, total.
3586 * We're okay with having too many for some given router, so long as the
3587 * total number doesn't approach max_descriptors_per_router()*len(router).
3589 if (smartlist_len(routerlist->old_routers) <
3590 smartlist_len(routerlist->routers))
3591 goto done;
3593 /* Sort by identity, then fix indices. */
3594 smartlist_sort(routerlist->old_routers, _compare_old_routers_by_identity);
3595 /* Fix indices. */
3596 for (i = 0; i < smartlist_len(routerlist->old_routers); ++i) {
3597 signed_descriptor_t *r = smartlist_get(routerlist->old_routers, i);
3598 r->routerlist_index = i;
3601 /* Iterate through the list from back to front, so when we remove descriptors
3602 * we don't mess up groups we haven't gotten to. */
3603 for (i = smartlist_len(routerlist->old_routers)-1; i >= 0; --i) {
3604 signed_descriptor_t *r = smartlist_get(routerlist->old_routers, i);
3605 if (!cur_id) {
3606 cur_id = r->identity_digest;
3607 hi = i;
3609 if (memcmp(cur_id, r->identity_digest, DIGEST_LEN)) {
3610 routerlist_remove_old_cached_routers_with_id(now,
3611 cutoff, i+1, hi, retain);
3612 cur_id = r->identity_digest;
3613 hi = i;
3616 if (hi>=0)
3617 routerlist_remove_old_cached_routers_with_id(now, cutoff, 0, hi, retain);
3618 //routerlist_assert_ok(routerlist);
3620 done:
3621 digestset_free(retain);
3622 router_rebuild_store(RRS_DONT_REMOVE_OLD, &routerlist->desc_store);
3623 router_rebuild_store(RRS_DONT_REMOVE_OLD,&routerlist->extrainfo_store);
3626 /** We just added a new set of descriptors. Take whatever extra steps
3627 * we need. */
3628 void
3629 routerlist_descriptors_added(smartlist_t *sl, int from_cache)
3631 tor_assert(sl);
3632 control_event_descriptors_changed(sl);
3633 SMARTLIST_FOREACH_BEGIN(sl, routerinfo_t *, ri) {
3634 if (ri->purpose == ROUTER_PURPOSE_BRIDGE)
3635 learned_bridge_descriptor(ri, from_cache);
3636 if (ri->needs_retest_if_added) {
3637 ri->needs_retest_if_added = 0;
3638 dirserv_single_reachability_test(approx_time(), ri);
3640 } SMARTLIST_FOREACH_END(ri);
3644 * Code to parse a single router descriptor and insert it into the
3645 * routerlist. Return -1 if the descriptor was ill-formed; 0 if the
3646 * descriptor was well-formed but could not be added; and 1 if the
3647 * descriptor was added.
3649 * If we don't add it and <b>msg</b> is not NULL, then assign to
3650 * *<b>msg</b> a static string describing the reason for refusing the
3651 * descriptor.
3653 * This is used only by the controller.
3656 router_load_single_router(const char *s, uint8_t purpose, int cache,
3657 const char **msg)
3659 routerinfo_t *ri;
3660 was_router_added_t r;
3661 smartlist_t *lst;
3662 char annotation_buf[ROUTER_ANNOTATION_BUF_LEN];
3663 tor_assert(msg);
3664 *msg = NULL;
3666 tor_snprintf(annotation_buf, sizeof(annotation_buf),
3667 "@source controller\n"
3668 "@purpose %s\n", router_purpose_to_string(purpose));
3670 if (!(ri = router_parse_entry_from_string(s, NULL, 1, 0, annotation_buf))) {
3671 log_warn(LD_DIR, "Error parsing router descriptor; dropping.");
3672 *msg = "Couldn't parse router descriptor.";
3673 return -1;
3675 tor_assert(ri->purpose == purpose);
3676 if (router_is_me(ri)) {
3677 log_warn(LD_DIR, "Router's identity key matches mine; dropping.");
3678 *msg = "Router's identity key matches mine.";
3679 routerinfo_free(ri);
3680 return 0;
3683 if (!cache) /* obey the preference of the controller */
3684 ri->cache_info.do_not_cache = 1;
3686 lst = smartlist_create();
3687 smartlist_add(lst, ri);
3688 routers_update_status_from_consensus_networkstatus(lst, 0);
3690 r = router_add_to_routerlist(ri, msg, 0, 0);
3691 if (!WRA_WAS_ADDED(r)) {
3692 /* we've already assigned to *msg now, and ri is already freed */
3693 tor_assert(*msg);
3694 if (r == ROUTER_AUTHDIR_REJECTS)
3695 log_warn(LD_DIR, "Couldn't add router to list: %s Dropping.", *msg);
3696 smartlist_free(lst);
3697 return 0;
3698 } else {
3699 routerlist_descriptors_added(lst, 0);
3700 smartlist_free(lst);
3701 log_debug(LD_DIR, "Added router to list");
3702 return 1;
3706 /** Given a string <b>s</b> containing some routerdescs, parse it and put the
3707 * routers into our directory. If saved_location is SAVED_NOWHERE, the routers
3708 * are in response to a query to the network: cache them by adding them to
3709 * the journal.
3711 * Return the number of routers actually added.
3713 * If <b>requested_fingerprints</b> is provided, it must contain a list of
3714 * uppercased fingerprints. Do not update any router whose
3715 * fingerprint is not on the list; after updating a router, remove its
3716 * fingerprint from the list.
3718 * If <b>descriptor_digests</b> is non-zero, then the requested_fingerprints
3719 * are descriptor digests. Otherwise they are identity digests.
3722 router_load_routers_from_string(const char *s, const char *eos,
3723 saved_location_t saved_location,
3724 smartlist_t *requested_fingerprints,
3725 int descriptor_digests,
3726 const char *prepend_annotations)
3728 smartlist_t *routers = smartlist_create(), *changed = smartlist_create();
3729 char fp[HEX_DIGEST_LEN+1];
3730 const char *msg;
3731 int from_cache = (saved_location != SAVED_NOWHERE);
3732 int allow_annotations = (saved_location != SAVED_NOWHERE);
3733 int any_changed = 0;
3735 router_parse_list_from_string(&s, eos, routers, saved_location, 0,
3736 allow_annotations, prepend_annotations);
3738 routers_update_status_from_consensus_networkstatus(routers, !from_cache);
3740 log_info(LD_DIR, "%d elements to add", smartlist_len(routers));
3742 SMARTLIST_FOREACH_BEGIN(routers, routerinfo_t *, ri) {
3743 was_router_added_t r;
3744 char d[DIGEST_LEN];
3745 if (requested_fingerprints) {
3746 base16_encode(fp, sizeof(fp), descriptor_digests ?
3747 ri->cache_info.signed_descriptor_digest :
3748 ri->cache_info.identity_digest,
3749 DIGEST_LEN);
3750 if (smartlist_string_isin(requested_fingerprints, fp)) {
3751 smartlist_string_remove(requested_fingerprints, fp);
3752 } else {
3753 char *requested =
3754 smartlist_join_strings(requested_fingerprints," ",0,NULL);
3755 log_warn(LD_DIR,
3756 "We received a router descriptor with a fingerprint (%s) "
3757 "that we never requested. (We asked for: %s.) Dropping.",
3758 fp, requested);
3759 tor_free(requested);
3760 routerinfo_free(ri);
3761 continue;
3765 memcpy(d, ri->cache_info.signed_descriptor_digest, DIGEST_LEN);
3766 r = router_add_to_routerlist(ri, &msg, from_cache, !from_cache);
3767 if (WRA_WAS_ADDED(r)) {
3768 any_changed++;
3769 smartlist_add(changed, ri);
3770 routerlist_descriptors_added(changed, from_cache);
3771 smartlist_clear(changed);
3772 } else if (WRA_WAS_REJECTED(r)) {
3773 download_status_t *dl_status;
3774 dl_status = router_get_dl_status_by_descriptor_digest(d);
3775 if (dl_status) {
3776 log_info(LD_GENERAL, "Marking router %s as never downloadable",
3777 hex_str(d, DIGEST_LEN));
3778 download_status_mark_impossible(dl_status);
3781 } SMARTLIST_FOREACH_END(ri);
3783 routerlist_assert_ok(routerlist);
3785 if (any_changed)
3786 router_rebuild_store(0, &routerlist->desc_store);
3788 smartlist_free(routers);
3789 smartlist_free(changed);
3791 return any_changed;
3794 /** Parse one or more extrainfos from <b>s</b> (ending immediately before
3795 * <b>eos</b> if <b>eos</b> is present). Other arguments are as for
3796 * router_load_routers_from_string(). */
3797 void
3798 router_load_extrainfo_from_string(const char *s, const char *eos,
3799 saved_location_t saved_location,
3800 smartlist_t *requested_fingerprints,
3801 int descriptor_digests)
3803 smartlist_t *extrainfo_list = smartlist_create();
3804 const char *msg;
3805 int from_cache = (saved_location != SAVED_NOWHERE);
3807 router_parse_list_from_string(&s, eos, extrainfo_list, saved_location, 1, 0,
3808 NULL);
3810 log_info(LD_DIR, "%d elements to add", smartlist_len(extrainfo_list));
3812 SMARTLIST_FOREACH(extrainfo_list, extrainfo_t *, ei, {
3813 was_router_added_t added =
3814 router_add_extrainfo_to_routerlist(ei, &msg, from_cache, !from_cache);
3815 if (WRA_WAS_ADDED(added) && requested_fingerprints) {
3816 char fp[HEX_DIGEST_LEN+1];
3817 base16_encode(fp, sizeof(fp), descriptor_digests ?
3818 ei->cache_info.signed_descriptor_digest :
3819 ei->cache_info.identity_digest,
3820 DIGEST_LEN);
3821 smartlist_string_remove(requested_fingerprints, fp);
3822 /* We silently let people stuff us with extrainfos we didn't ask for,
3823 * so long as we would have wanted them anyway. Since we always fetch
3824 * all the extrainfos we want, and we never actually act on them
3825 * inside Tor, this should be harmless. */
3829 routerlist_assert_ok(routerlist);
3830 router_rebuild_store(0, &router_get_routerlist()->extrainfo_store);
3832 smartlist_free(extrainfo_list);
3835 /** Return true iff any networkstatus includes a descriptor whose digest
3836 * is that of <b>desc</b>. */
3837 static int
3838 signed_desc_digest_is_recognized(signed_descriptor_t *desc)
3840 routerstatus_t *rs;
3841 networkstatus_t *consensus = networkstatus_get_latest_consensus();
3842 int caches = directory_caches_dir_info(get_options());
3843 const smartlist_t *networkstatus_v2_list = networkstatus_get_v2_list();
3845 if (consensus) {
3846 rs = networkstatus_vote_find_entry(consensus, desc->identity_digest);
3847 if (rs && !memcmp(rs->descriptor_digest,
3848 desc->signed_descriptor_digest, DIGEST_LEN))
3849 return 1;
3851 if (caches && networkstatus_v2_list) {
3852 SMARTLIST_FOREACH(networkstatus_v2_list, networkstatus_v2_t *, ns,
3854 if (!(rs = networkstatus_v2_find_entry(ns, desc->identity_digest)))
3855 continue;
3856 if (!memcmp(rs->descriptor_digest,
3857 desc->signed_descriptor_digest, DIGEST_LEN))
3858 return 1;
3861 return 0;
3864 /** Clear all our timeouts for fetching v2 and v3 directory stuff, and then
3865 * give it all a try again. */
3866 void
3867 routerlist_retry_directory_downloads(time_t now)
3869 router_reset_status_download_failures();
3870 router_reset_descriptor_download_failures();
3871 update_networkstatus_downloads(now);
3872 update_router_descriptor_downloads(now);
3875 /** Return 1 if all running sufficiently-stable routers will reject
3876 * addr:port, return 0 if any might accept it. */
3878 router_exit_policy_all_routers_reject(uint32_t addr, uint16_t port,
3879 int need_uptime)
3881 addr_policy_result_t r;
3882 if (!routerlist) return 1;
3884 SMARTLIST_FOREACH(routerlist->routers, routerinfo_t *, router,
3886 if (router->is_running &&
3887 !router_is_unreliable(router, need_uptime, 0, 0)) {
3888 r = compare_addr_to_addr_policy(addr, port, router->exit_policy);
3889 if (r != ADDR_POLICY_REJECTED && r != ADDR_POLICY_PROBABLY_REJECTED)
3890 return 0; /* this one could be ok. good enough. */
3893 return 1; /* all will reject. */
3896 /** Return true iff <b>router</b> does not permit exit streams.
3899 router_exit_policy_rejects_all(routerinfo_t *router)
3901 return router->policy_is_reject_star;
3904 /** Add to the list of authoritative directory servers one at
3905 * <b>address</b>:<b>port</b>, with identity key <b>digest</b>. If
3906 * <b>address</b> is NULL, add ourself. Return the new trusted directory
3907 * server entry on success or NULL if we couldn't add it. */
3908 trusted_dir_server_t *
3909 add_trusted_dir_server(const char *nickname, const char *address,
3910 uint16_t dir_port, uint16_t or_port,
3911 const char *digest, const char *v3_auth_digest,
3912 authority_type_t type)
3914 trusted_dir_server_t *ent;
3915 uint32_t a;
3916 char *hostname = NULL;
3917 size_t dlen;
3918 if (!trusted_dir_servers)
3919 trusted_dir_servers = smartlist_create();
3921 if (!address) { /* The address is us; we should guess. */
3922 if (resolve_my_address(LOG_WARN, get_options(), &a, &hostname) < 0) {
3923 log_warn(LD_CONFIG,
3924 "Couldn't find a suitable address when adding ourself as a "
3925 "trusted directory server.");
3926 return NULL;
3928 } else {
3929 if (tor_lookup_hostname(address, &a)) {
3930 log_warn(LD_CONFIG,
3931 "Unable to lookup address for directory server at '%s'",
3932 address);
3933 return NULL;
3935 hostname = tor_strdup(address);
3938 ent = tor_malloc_zero(sizeof(trusted_dir_server_t));
3939 ent->nickname = nickname ? tor_strdup(nickname) : NULL;
3940 ent->address = hostname;
3941 ent->addr = a;
3942 ent->dir_port = dir_port;
3943 ent->or_port = or_port;
3944 ent->is_running = 1;
3945 ent->type = type;
3946 memcpy(ent->digest, digest, DIGEST_LEN);
3947 if (v3_auth_digest && (type & V3_AUTHORITY))
3948 memcpy(ent->v3_identity_digest, v3_auth_digest, DIGEST_LEN);
3950 dlen = 64 + strlen(hostname) + (nickname?strlen(nickname):0);
3951 ent->description = tor_malloc(dlen);
3952 if (nickname)
3953 tor_snprintf(ent->description, dlen, "directory server \"%s\" at %s:%d",
3954 nickname, hostname, (int)dir_port);
3955 else
3956 tor_snprintf(ent->description, dlen, "directory server at %s:%d",
3957 hostname, (int)dir_port);
3959 ent->fake_status.addr = ent->addr;
3960 memcpy(ent->fake_status.identity_digest, digest, DIGEST_LEN);
3961 if (nickname)
3962 strlcpy(ent->fake_status.nickname, nickname,
3963 sizeof(ent->fake_status.nickname));
3964 else
3965 ent->fake_status.nickname[0] = '\0';
3966 ent->fake_status.dir_port = ent->dir_port;
3967 ent->fake_status.or_port = ent->or_port;
3969 if (ent->or_port)
3970 ent->fake_status.version_supports_begindir = 1;
3972 ent->fake_status.version_supports_conditional_consensus = 1;
3974 smartlist_add(trusted_dir_servers, ent);
3975 router_dir_info_changed();
3976 return ent;
3979 /** Free storage held in <b>cert</b>. */
3980 void
3981 authority_cert_free(authority_cert_t *cert)
3983 if (!cert)
3984 return;
3986 tor_free(cert->cache_info.signed_descriptor_body);
3987 crypto_free_pk_env(cert->signing_key);
3988 crypto_free_pk_env(cert->identity_key);
3990 tor_free(cert);
3993 /** Free storage held in <b>ds</b>. */
3994 static void
3995 trusted_dir_server_free(trusted_dir_server_t *ds)
3997 if (!ds)
3998 return;
4000 tor_free(ds->nickname);
4001 tor_free(ds->description);
4002 tor_free(ds->address);
4003 tor_free(ds);
4006 /** Remove all members from the list of trusted dir servers. */
4007 void
4008 clear_trusted_dir_servers(void)
4010 if (trusted_dir_servers) {
4011 SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, ent,
4012 trusted_dir_server_free(ent));
4013 smartlist_clear(trusted_dir_servers);
4014 } else {
4015 trusted_dir_servers = smartlist_create();
4017 router_dir_info_changed();
4020 /** Return 1 if any trusted dir server supports v1 directories,
4021 * else return 0. */
4023 any_trusted_dir_is_v1_authority(void)
4025 if (trusted_dir_servers)
4026 return get_n_authorities(V1_AUTHORITY) > 0;
4028 return 0;
4031 /** For every current directory connection whose purpose is <b>purpose</b>,
4032 * and where the resource being downloaded begins with <b>prefix</b>, split
4033 * rest of the resource into base16 fingerprints, decode them, and set the
4034 * corresponding elements of <b>result</b> to a nonzero value. */
4035 static void
4036 list_pending_downloads(digestmap_t *result,
4037 int purpose, const char *prefix)
4039 const size_t p_len = strlen(prefix);
4040 smartlist_t *tmp = smartlist_create();
4041 smartlist_t *conns = get_connection_array();
4043 tor_assert(result);
4045 SMARTLIST_FOREACH(conns, connection_t *, conn,
4047 if (conn->type == CONN_TYPE_DIR &&
4048 conn->purpose == purpose &&
4049 !conn->marked_for_close) {
4050 const char *resource = TO_DIR_CONN(conn)->requested_resource;
4051 if (!strcmpstart(resource, prefix))
4052 dir_split_resource_into_fingerprints(resource + p_len,
4053 tmp, NULL, DSR_HEX);
4056 SMARTLIST_FOREACH(tmp, char *, d,
4058 digestmap_set(result, d, (void*)1);
4059 tor_free(d);
4061 smartlist_free(tmp);
4064 /** For every router descriptor (or extra-info document if <b>extrainfo</b> is
4065 * true) we are currently downloading by descriptor digest, set result[d] to
4066 * (void*)1. */
4067 static void
4068 list_pending_descriptor_downloads(digestmap_t *result, int extrainfo)
4070 int purpose =
4071 extrainfo ? DIR_PURPOSE_FETCH_EXTRAINFO : DIR_PURPOSE_FETCH_SERVERDESC;
4072 list_pending_downloads(result, purpose, "d/");
4075 /** Launch downloads for all the descriptors whose digests are listed
4076 * as digests[i] for lo <= i < hi. (Lo and hi may be out of range.)
4077 * If <b>source</b> is given, download from <b>source</b>; otherwise,
4078 * download from an appropriate random directory server.
4080 static void
4081 initiate_descriptor_downloads(routerstatus_t *source,
4082 int purpose,
4083 smartlist_t *digests,
4084 int lo, int hi, int pds_flags)
4086 int i, n = hi-lo;
4087 char *resource, *cp;
4088 size_t r_len;
4089 if (n <= 0)
4090 return;
4091 if (lo < 0)
4092 lo = 0;
4093 if (hi > smartlist_len(digests))
4094 hi = smartlist_len(digests);
4096 r_len = 8 + (HEX_DIGEST_LEN+1)*n;
4097 cp = resource = tor_malloc(r_len);
4098 memcpy(cp, "d/", 2);
4099 cp += 2;
4100 for (i = lo; i < hi; ++i) {
4101 base16_encode(cp, r_len-(cp-resource),
4102 smartlist_get(digests,i), DIGEST_LEN);
4103 cp += HEX_DIGEST_LEN;
4104 *cp++ = '+';
4106 memcpy(cp-1, ".z", 3);
4108 if (source) {
4109 /* We know which authority we want. */
4110 directory_initiate_command_routerstatus(source, purpose,
4111 ROUTER_PURPOSE_GENERAL,
4112 0, /* not private */
4113 resource, NULL, 0, 0);
4114 } else {
4115 directory_get_from_dirserver(purpose, ROUTER_PURPOSE_GENERAL, resource,
4116 pds_flags);
4118 tor_free(resource);
4121 /** Return 0 if this routerstatus is obsolete, too new, isn't
4122 * running, or otherwise not a descriptor that we would make any
4123 * use of even if we had it. Else return 1. */
4124 static INLINE int
4125 client_would_use_router(routerstatus_t *rs, time_t now, or_options_t *options)
4127 if (!rs->is_running && !options->FetchUselessDescriptors) {
4128 /* If we had this router descriptor, we wouldn't even bother using it.
4129 * But, if we want to have a complete list, fetch it anyway. */
4130 return 0;
4132 if (rs->published_on + options->TestingEstimatedDescriptorPropagationTime
4133 > now) {
4134 /* Most caches probably don't have this descriptor yet. */
4135 return 0;
4137 if (rs->published_on + OLD_ROUTER_DESC_MAX_AGE < now) {
4138 /* We'd drop it immediately for being too old. */
4139 return 0;
4141 return 1;
4144 /** Max amount of hashes to download per request.
4145 * Since squid does not like URLs >= 4096 bytes we limit it to 96.
4146 * 4096 - strlen(http://255.255.255.255/tor/server/d/.z) == 4058
4147 * 4058/41 (40 for the hash and 1 for the + that separates them) => 98
4148 * So use 96 because it's a nice number.
4150 #define MAX_DL_PER_REQUEST 96
4151 /** Don't split our requests so finely that we are requesting fewer than
4152 * this number per server. */
4153 #define MIN_DL_PER_REQUEST 4
4154 /** To prevent a single screwy cache from confusing us by selective reply,
4155 * try to split our requests into at least this many requests. */
4156 #define MIN_REQUESTS 3
4157 /** If we want fewer than this many descriptors, wait until we
4158 * want more, or until MAX_CLIENT_INTERVAL_WITHOUT_REQUEST has
4159 * passed. */
4160 #define MAX_DL_TO_DELAY 16
4161 /** When directory clients have only a few servers to request, they batch
4162 * them until they have more, or until this amount of time has passed. */
4163 #define MAX_CLIENT_INTERVAL_WITHOUT_REQUEST (10*60)
4165 /** Given a list of router descriptor digests in <b>downloadable</b>, decide
4166 * whether to delay fetching until we have more. If we don't want to delay,
4167 * launch one or more requests to the appropriate directory authorities. */
4168 static void
4169 launch_router_descriptor_downloads(smartlist_t *downloadable,
4170 routerstatus_t *source, time_t now)
4172 int should_delay = 0, n_downloadable;
4173 or_options_t *options = get_options();
4175 n_downloadable = smartlist_len(downloadable);
4176 if (!directory_fetches_dir_info_early(options)) {
4177 if (n_downloadable >= MAX_DL_TO_DELAY) {
4178 log_debug(LD_DIR,
4179 "There are enough downloadable routerdescs to launch requests.");
4180 should_delay = 0;
4181 } else {
4182 should_delay = (last_routerdesc_download_attempted +
4183 MAX_CLIENT_INTERVAL_WITHOUT_REQUEST) > now;
4184 if (!should_delay && n_downloadable) {
4185 if (last_routerdesc_download_attempted) {
4186 log_info(LD_DIR,
4187 "There are not many downloadable routerdescs, but we've "
4188 "been waiting long enough (%d seconds). Downloading.",
4189 (int)(now-last_routerdesc_download_attempted));
4190 } else {
4191 log_info(LD_DIR,
4192 "There are not many downloadable routerdescs, but we haven't "
4193 "tried downloading descriptors recently. Downloading.");
4198 /* XXX should we consider having even the dir mirrors delay
4199 * a little bit, so we don't load the authorities as much? -RD
4200 * I don't think so. If we do, clients that want those descriptors may
4201 * not actually find them if the caches haven't got them yet. -NM
4204 if (! should_delay && n_downloadable) {
4205 int i, n_per_request;
4206 const char *req_plural = "", *rtr_plural = "";
4207 int pds_flags = PDS_RETRY_IF_NO_SERVERS;
4208 if (! authdir_mode_any_nonhidserv(options)) {
4209 /* If we wind up going to the authorities, we want to only open one
4210 * connection to each authority at a time, so that we don't overload
4211 * them. We do this by setting PDS_NO_EXISTING_SERVERDESC_FETCH
4212 * regardless of whether we're a cache or not; it gets ignored if we're
4213 * not calling router_pick_trusteddirserver.
4215 * Setting this flag can make initiate_descriptor_downloads() ignore
4216 * requests. We need to make sure that we do in fact call
4217 * update_router_descriptor_downloads() later on, once the connections
4218 * have succeeded or failed.
4220 pds_flags |= PDS_NO_EXISTING_SERVERDESC_FETCH;
4223 n_per_request = CEIL_DIV(n_downloadable, MIN_REQUESTS);
4224 if (n_per_request > MAX_DL_PER_REQUEST)
4225 n_per_request = MAX_DL_PER_REQUEST;
4226 if (n_per_request < MIN_DL_PER_REQUEST)
4227 n_per_request = MIN_DL_PER_REQUEST;
4229 if (n_downloadable > n_per_request)
4230 req_plural = rtr_plural = "s";
4231 else if (n_downloadable > 1)
4232 rtr_plural = "s";
4234 log_info(LD_DIR,
4235 "Launching %d request%s for %d router%s, %d at a time",
4236 CEIL_DIV(n_downloadable, n_per_request),
4237 req_plural, n_downloadable, rtr_plural, n_per_request);
4238 smartlist_sort_digests(downloadable);
4239 for (i=0; i < n_downloadable; i += n_per_request) {
4240 initiate_descriptor_downloads(source, DIR_PURPOSE_FETCH_SERVERDESC,
4241 downloadable, i, i+n_per_request,
4242 pds_flags);
4244 last_routerdesc_download_attempted = now;
4248 /** Launch downloads for router status as needed, using the strategy used by
4249 * authorities and caches: based on the v2 networkstatuses we have, download
4250 * every descriptor we don't have but would serve, from a random authority
4251 * that lists it. */
4252 static void
4253 update_router_descriptor_cache_downloads_v2(time_t now)
4255 smartlist_t **downloadable; /* For each authority, what can we dl from it? */
4256 smartlist_t **download_from; /* ... and, what will we dl from it? */
4257 digestmap_t *map; /* Which descs are in progress, or assigned? */
4258 int i, j, n;
4259 int n_download;
4260 or_options_t *options = get_options();
4261 const smartlist_t *networkstatus_v2_list = networkstatus_get_v2_list();
4263 if (! directory_fetches_dir_info_early(options)) {
4264 log_warn(LD_BUG, "Called update_router_descriptor_cache_downloads_v2() "
4265 "on a non-dir-mirror?");
4268 if (!networkstatus_v2_list || !smartlist_len(networkstatus_v2_list))
4269 return;
4271 map = digestmap_new();
4272 n = smartlist_len(networkstatus_v2_list);
4274 downloadable = tor_malloc_zero(sizeof(smartlist_t*) * n);
4275 download_from = tor_malloc_zero(sizeof(smartlist_t*) * n);
4277 /* Set map[d]=1 for the digest of every descriptor that we are currently
4278 * downloading. */
4279 list_pending_descriptor_downloads(map, 0);
4281 /* For the digest of every descriptor that we don't have, and that we aren't
4282 * downloading, add d to downloadable[i] if the i'th networkstatus knows
4283 * about that descriptor, and we haven't already failed to get that
4284 * descriptor from the corresponding authority.
4286 n_download = 0;
4287 SMARTLIST_FOREACH(networkstatus_v2_list, networkstatus_v2_t *, ns,
4289 trusted_dir_server_t *ds;
4290 smartlist_t *dl;
4291 dl = downloadable[ns_sl_idx] = smartlist_create();
4292 download_from[ns_sl_idx] = smartlist_create();
4293 if (ns->published_on + MAX_NETWORKSTATUS_AGE+10*60 < now) {
4294 /* Don't download if the networkstatus is almost ancient. */
4295 /* Actually, I suspect what's happening here is that we ask
4296 * for the descriptor when we have a given networkstatus,
4297 * and then we get a newer networkstatus, and then we receive
4298 * the descriptor. Having a networkstatus actually expire is
4299 * probably a rare event, and we'll probably be happiest if
4300 * we take this clause out. -RD */
4301 continue;
4304 /* Don't try dirservers that we think are down -- we might have
4305 * just tried them and just marked them as down. */
4306 ds = router_get_trusteddirserver_by_digest(ns->identity_digest);
4307 if (ds && !ds->is_running)
4308 continue;
4310 SMARTLIST_FOREACH(ns->entries, routerstatus_t * , rs,
4312 if (!rs->need_to_mirror)
4313 continue;
4314 if (router_get_by_descriptor_digest(rs->descriptor_digest)) {
4315 log_warn(LD_BUG,
4316 "We have a router descriptor, but need_to_mirror=1.");
4317 rs->need_to_mirror = 0;
4318 continue;
4320 if (authdir_mode(options) && dirserv_would_reject_router(rs)) {
4321 rs->need_to_mirror = 0;
4322 continue;
4324 if (digestmap_get(map, rs->descriptor_digest)) {
4325 /* We're downloading it already. */
4326 continue;
4327 } else {
4328 /* We could download it from this guy. */
4329 smartlist_add(dl, rs->descriptor_digest);
4330 ++n_download;
4335 /* At random, assign descriptors to authorities such that:
4336 * - if d is a member of some downloadable[x], d is a member of some
4337 * download_from[y]. (Everything we want to download, we try to download
4338 * from somebody.)
4339 * - If d is a member of download_from[y], d is a member of downloadable[y].
4340 * (We only try to download descriptors from authorities who claim to have
4341 * them.)
4342 * - No d is a member of download_from[x] and download_from[y] s.t. x != y.
4343 * (We don't try to download anything from two authorities concurrently.)
4345 while (n_download) {
4346 int which_ns = crypto_rand_int(n);
4347 smartlist_t *dl = downloadable[which_ns];
4348 int idx;
4349 char *d;
4350 if (!smartlist_len(dl))
4351 continue;
4352 idx = crypto_rand_int(smartlist_len(dl));
4353 d = smartlist_get(dl, idx);
4354 if (! digestmap_get(map, d)) {
4355 smartlist_add(download_from[which_ns], d);
4356 digestmap_set(map, d, (void*) 1);
4358 smartlist_del(dl, idx);
4359 --n_download;
4362 /* Now, we can actually launch our requests. */
4363 for (i=0; i<n; ++i) {
4364 networkstatus_v2_t *ns = smartlist_get(networkstatus_v2_list, i);
4365 trusted_dir_server_t *ds =
4366 router_get_trusteddirserver_by_digest(ns->identity_digest);
4367 smartlist_t *dl = download_from[i];
4368 int pds_flags = PDS_RETRY_IF_NO_SERVERS;
4369 if (! authdir_mode_any_nonhidserv(options))
4370 pds_flags |= PDS_NO_EXISTING_SERVERDESC_FETCH; /* XXXX ignored*/
4372 if (!ds) {
4373 log_info(LD_DIR, "Networkstatus with no corresponding authority!");
4374 continue;
4376 if (! smartlist_len(dl))
4377 continue;
4378 log_info(LD_DIR, "Requesting %d descriptors from authority \"%s\"",
4379 smartlist_len(dl), ds->nickname);
4380 for (j=0; j < smartlist_len(dl); j += MAX_DL_PER_REQUEST) {
4381 initiate_descriptor_downloads(&(ds->fake_status),
4382 DIR_PURPOSE_FETCH_SERVERDESC, dl, j,
4383 j+MAX_DL_PER_REQUEST, pds_flags);
4387 for (i=0; i<n; ++i) {
4388 smartlist_free(download_from[i]);
4389 smartlist_free(downloadable[i]);
4391 tor_free(download_from);
4392 tor_free(downloadable);
4393 digestmap_free(map,NULL);
4396 /** For any descriptor that we want that's currently listed in
4397 * <b>consensus</b>, download it as appropriate. */
4398 void
4399 update_consensus_router_descriptor_downloads(time_t now, int is_vote,
4400 networkstatus_t *consensus)
4402 or_options_t *options = get_options();
4403 digestmap_t *map = NULL;
4404 smartlist_t *no_longer_old = smartlist_create();
4405 smartlist_t *downloadable = smartlist_create();
4406 routerstatus_t *source = NULL;
4407 int authdir = authdir_mode(options);
4408 int n_delayed=0, n_have=0, n_would_reject=0, n_wouldnt_use=0,
4409 n_inprogress=0, n_in_oldrouters=0;
4411 if (directory_too_idle_to_fetch_descriptors(options, now))
4412 goto done;
4413 if (!consensus)
4414 goto done;
4416 if (is_vote) {
4417 /* where's it from, so we know whom to ask for descriptors */
4418 trusted_dir_server_t *ds;
4419 networkstatus_voter_info_t *voter = smartlist_get(consensus->voters, 0);
4420 tor_assert(voter);
4421 ds = trusteddirserver_get_by_v3_auth_digest(voter->identity_digest);
4422 if (ds)
4423 source = &(ds->fake_status);
4424 else
4425 log_warn(LD_DIR, "couldn't lookup source from vote?");
4428 map = digestmap_new();
4429 list_pending_descriptor_downloads(map, 0);
4430 SMARTLIST_FOREACH(consensus->routerstatus_list, void *, rsp,
4432 routerstatus_t *rs =
4433 is_vote ? &(((vote_routerstatus_t *)rsp)->status) : rsp;
4434 signed_descriptor_t *sd;
4435 if ((sd = router_get_by_descriptor_digest(rs->descriptor_digest))) {
4436 routerinfo_t *ri;
4437 ++n_have;
4438 if (!(ri = router_get_by_digest(rs->identity_digest)) ||
4439 memcmp(ri->cache_info.signed_descriptor_digest,
4440 sd->signed_descriptor_digest, DIGEST_LEN)) {
4441 /* We have a descriptor with this digest, but either there is no
4442 * entry in routerlist with the same ID (!ri), or there is one,
4443 * but the identity digest differs (memcmp).
4445 smartlist_add(no_longer_old, sd);
4446 ++n_in_oldrouters; /* We have it in old_routers. */
4448 continue; /* We have it already. */
4450 if (digestmap_get(map, rs->descriptor_digest)) {
4451 ++n_inprogress;
4452 continue; /* We have an in-progress download. */
4454 if (!download_status_is_ready(&rs->dl_status, now,
4455 MAX_ROUTERDESC_DOWNLOAD_FAILURES)) {
4456 ++n_delayed; /* Not ready for retry. */
4457 continue;
4459 if (authdir && dirserv_would_reject_router(rs)) {
4460 ++n_would_reject;
4461 continue; /* We would throw it out immediately. */
4463 if (!directory_caches_dir_info(options) &&
4464 !client_would_use_router(rs, now, options)) {
4465 ++n_wouldnt_use;
4466 continue; /* We would never use it ourself. */
4468 if (is_vote && source) {
4469 char time_bufnew[ISO_TIME_LEN+1];
4470 char time_bufold[ISO_TIME_LEN+1];
4471 routerinfo_t *oldrouter = router_get_by_digest(rs->identity_digest);
4472 format_iso_time(time_bufnew, rs->published_on);
4473 if (oldrouter)
4474 format_iso_time(time_bufold, oldrouter->cache_info.published_on);
4475 log_info(LD_DIR, "Learned about %s (%s vs %s) from %s's vote (%s)",
4476 rs->nickname, time_bufnew,
4477 oldrouter ? time_bufold : "none",
4478 source->nickname, oldrouter ? "known" : "unknown");
4480 smartlist_add(downloadable, rs->descriptor_digest);
4483 if (!authdir_mode_handles_descs(options, ROUTER_PURPOSE_GENERAL)
4484 && smartlist_len(no_longer_old)) {
4485 routerlist_t *rl = router_get_routerlist();
4486 log_info(LD_DIR, "%d router descriptors listed in consensus are "
4487 "currently in old_routers; making them current.",
4488 smartlist_len(no_longer_old));
4489 SMARTLIST_FOREACH(no_longer_old, signed_descriptor_t *, sd, {
4490 const char *msg;
4491 was_router_added_t r;
4492 routerinfo_t *ri = routerlist_reparse_old(rl, sd);
4493 if (!ri) {
4494 log_warn(LD_BUG, "Failed to re-parse a router.");
4495 continue;
4497 r = router_add_to_routerlist(ri, &msg, 1, 0);
4498 if (WRA_WAS_OUTDATED(r)) {
4499 log_warn(LD_DIR, "Couldn't add re-parsed router: %s",
4500 msg?msg:"???");
4503 routerlist_assert_ok(rl);
4506 log_info(LD_DIR,
4507 "%d router descriptors downloadable. %d delayed; %d present "
4508 "(%d of those were in old_routers); %d would_reject; "
4509 "%d wouldnt_use; %d in progress.",
4510 smartlist_len(downloadable), n_delayed, n_have, n_in_oldrouters,
4511 n_would_reject, n_wouldnt_use, n_inprogress);
4513 launch_router_descriptor_downloads(downloadable, source, now);
4515 digestmap_free(map, NULL);
4516 done:
4517 smartlist_free(downloadable);
4518 smartlist_free(no_longer_old);
4521 /** How often should we launch a server/authority request to be sure of getting
4522 * a guess for our IP? */
4523 /*XXXX021 this info should come from netinfo cells or something, or we should
4524 * do this only when we aren't seeing incoming data. see bug 652. */
4525 #define DUMMY_DOWNLOAD_INTERVAL (20*60)
4527 /** Launch downloads for router status as needed. */
4528 void
4529 update_router_descriptor_downloads(time_t now)
4531 or_options_t *options = get_options();
4532 static time_t last_dummy_download = 0;
4533 if (should_delay_dir_fetches(options))
4534 return;
4535 if (directory_fetches_dir_info_early(options)) {
4536 update_router_descriptor_cache_downloads_v2(now);
4538 update_consensus_router_descriptor_downloads(now, 0,
4539 networkstatus_get_reasonably_live_consensus(now));
4541 /* XXXX021 we could be smarter here; see notes on bug 652. */
4542 /* If we're a server that doesn't have a configured address, we rely on
4543 * directory fetches to learn when our address changes. So if we haven't
4544 * tried to get any routerdescs in a long time, try a dummy fetch now. */
4545 if (!options->Address &&
4546 server_mode(options) &&
4547 last_routerdesc_download_attempted + DUMMY_DOWNLOAD_INTERVAL < now &&
4548 last_dummy_download + DUMMY_DOWNLOAD_INTERVAL < now) {
4549 last_dummy_download = now;
4550 directory_get_from_dirserver(DIR_PURPOSE_FETCH_SERVERDESC,
4551 ROUTER_PURPOSE_GENERAL, "authority.z",
4552 PDS_RETRY_IF_NO_SERVERS);
4556 /** Launch extrainfo downloads as needed. */
4557 void
4558 update_extrainfo_downloads(time_t now)
4560 or_options_t *options = get_options();
4561 routerlist_t *rl;
4562 smartlist_t *wanted;
4563 digestmap_t *pending;
4564 int old_routers, i;
4565 int n_no_ei = 0, n_pending = 0, n_have = 0, n_delay = 0;
4566 if (! options->DownloadExtraInfo)
4567 return;
4568 if (should_delay_dir_fetches(options))
4569 return;
4570 if (!router_have_minimum_dir_info())
4571 return;
4573 pending = digestmap_new();
4574 list_pending_descriptor_downloads(pending, 1);
4575 rl = router_get_routerlist();
4576 wanted = smartlist_create();
4577 for (old_routers = 0; old_routers < 2; ++old_routers) {
4578 smartlist_t *lst = old_routers ? rl->old_routers : rl->routers;
4579 for (i = 0; i < smartlist_len(lst); ++i) {
4580 signed_descriptor_t *sd;
4581 char *d;
4582 if (old_routers)
4583 sd = smartlist_get(lst, i);
4584 else
4585 sd = &((routerinfo_t*)smartlist_get(lst, i))->cache_info;
4586 if (sd->is_extrainfo)
4587 continue; /* This should never happen. */
4588 if (old_routers && !router_get_by_digest(sd->identity_digest))
4589 continue; /* Couldn't check the signature if we got it. */
4590 if (sd->extrainfo_is_bogus)
4591 continue;
4592 d = sd->extra_info_digest;
4593 if (tor_digest_is_zero(d)) {
4594 ++n_no_ei;
4595 continue;
4597 if (eimap_get(rl->extra_info_map, d)) {
4598 ++n_have;
4599 continue;
4601 if (!download_status_is_ready(&sd->ei_dl_status, now,
4602 MAX_ROUTERDESC_DOWNLOAD_FAILURES)) {
4603 ++n_delay;
4604 continue;
4606 if (digestmap_get(pending, d)) {
4607 ++n_pending;
4608 continue;
4610 smartlist_add(wanted, d);
4613 digestmap_free(pending, NULL);
4615 log_info(LD_DIR, "Extrainfo download status: %d router with no ei, %d "
4616 "with present ei, %d delaying, %d pending, %d downloadable.",
4617 n_no_ei, n_have, n_delay, n_pending, smartlist_len(wanted));
4619 smartlist_shuffle(wanted);
4620 for (i = 0; i < smartlist_len(wanted); i += MAX_DL_PER_REQUEST) {
4621 initiate_descriptor_downloads(NULL, DIR_PURPOSE_FETCH_EXTRAINFO,
4622 wanted, i, i + MAX_DL_PER_REQUEST,
4623 PDS_RETRY_IF_NO_SERVERS|PDS_NO_EXISTING_SERVERDESC_FETCH);
4626 smartlist_free(wanted);
4629 /** True iff, the last time we checked whether we had enough directory info
4630 * to build circuits, the answer was "yes". */
4631 static int have_min_dir_info = 0;
4632 /** True iff enough has changed since the last time we checked whether we had
4633 * enough directory info to build circuits that our old answer can no longer
4634 * be trusted. */
4635 static int need_to_update_have_min_dir_info = 1;
4636 /** String describing what we're missing before we have enough directory
4637 * info. */
4638 static char dir_info_status[128] = "";
4640 /** Return true iff we have enough networkstatus and router information to
4641 * start building circuits. Right now, this means "more than half the
4642 * networkstatus documents, and at least 1/4 of expected routers." */
4643 //XXX should consider whether we have enough exiting nodes here.
4645 router_have_minimum_dir_info(void)
4647 if (PREDICT_UNLIKELY(need_to_update_have_min_dir_info)) {
4648 update_router_have_minimum_dir_info();
4649 need_to_update_have_min_dir_info = 0;
4651 return have_min_dir_info;
4654 /** Called when our internal view of the directory has changed. This can be
4655 * when the authorities change, networkstatuses change, the list of routerdescs
4656 * changes, or number of running routers changes.
4658 void
4659 router_dir_info_changed(void)
4661 need_to_update_have_min_dir_info = 1;
4662 rend_hsdir_routers_changed();
4665 /** Return a string describing what we're missing before we have enough
4666 * directory info. */
4667 const char *
4668 get_dir_info_status_string(void)
4670 return dir_info_status;
4673 /** Iterate over the servers listed in <b>consensus</b>, and count how many of
4674 * them seem like ones we'd use, and how many of <em>those</em> we have
4675 * descriptors for. Store the former in *<b>num_usable</b> and the latter in
4676 * *<b>num_present</b>. If <b>in_set</b> is non-NULL, only consider those
4677 * routers in <b>in_set</b>.
4679 static void
4680 count_usable_descriptors(int *num_present, int *num_usable,
4681 const networkstatus_t *consensus,
4682 or_options_t *options, time_t now,
4683 routerset_t *in_set)
4685 *num_present = 0, *num_usable=0;
4687 SMARTLIST_FOREACH(consensus->routerstatus_list, routerstatus_t *, rs,
4689 if (in_set && ! routerset_contains_routerstatus(in_set, rs))
4690 continue;
4691 if (client_would_use_router(rs, now, options)) {
4692 ++*num_usable; /* the consensus says we want it. */
4693 if (router_get_by_descriptor_digest(rs->descriptor_digest)) {
4694 /* we have the descriptor listed in the consensus. */
4695 ++*num_present;
4700 log_debug(LD_DIR, "%d usable, %d present.", *num_usable, *num_present);
4703 /** We just fetched a new set of descriptors. Compute how far through
4704 * the "loading descriptors" bootstrapping phase we are, so we can inform
4705 * the controller of our progress. */
4707 count_loading_descriptors_progress(void)
4709 int num_present = 0, num_usable=0;
4710 time_t now = time(NULL);
4711 const networkstatus_t *consensus =
4712 networkstatus_get_reasonably_live_consensus(now);
4713 double fraction;
4715 if (!consensus)
4716 return 0; /* can't count descriptors if we have no list of them */
4718 count_usable_descriptors(&num_present, &num_usable,
4719 consensus, get_options(), now, NULL);
4721 if (num_usable == 0)
4722 return 0; /* don't div by 0 */
4723 fraction = num_present / (num_usable/4.);
4724 if (fraction > 1.0)
4725 return 0; /* it's not the number of descriptors holding us back */
4726 return BOOTSTRAP_STATUS_LOADING_DESCRIPTORS + (int)
4727 (fraction*(BOOTSTRAP_STATUS_CONN_OR-1 -
4728 BOOTSTRAP_STATUS_LOADING_DESCRIPTORS));
4731 /** Change the value of have_min_dir_info, setting it true iff we have enough
4732 * network and router information to build circuits. Clear the value of
4733 * need_to_update_have_min_dir_info. */
4734 static void
4735 update_router_have_minimum_dir_info(void)
4737 int num_present = 0, num_usable=0;
4738 time_t now = time(NULL);
4739 int res;
4740 or_options_t *options = get_options();
4741 const networkstatus_t *consensus =
4742 networkstatus_get_reasonably_live_consensus(now);
4744 if (!consensus) {
4745 if (!networkstatus_get_latest_consensus())
4746 strlcpy(dir_info_status, "We have no network-status consensus.",
4747 sizeof(dir_info_status));
4748 else
4749 strlcpy(dir_info_status, "We have no recent network-status consensus.",
4750 sizeof(dir_info_status));
4751 res = 0;
4752 goto done;
4755 if (should_delay_dir_fetches(get_options())) {
4756 log_notice(LD_DIR, "no known bridge descriptors running yet; stalling");
4757 strlcpy(dir_info_status, "No live bridge descriptors.",
4758 sizeof(dir_info_status));
4759 res = 0;
4760 goto done;
4763 count_usable_descriptors(&num_present, &num_usable, consensus, options, now,
4764 NULL);
4766 if (num_present < num_usable/4) {
4767 tor_snprintf(dir_info_status, sizeof(dir_info_status),
4768 "We have only %d/%d usable descriptors.", num_present, num_usable);
4769 res = 0;
4770 control_event_bootstrap(BOOTSTRAP_STATUS_REQUESTING_DESCRIPTORS, 0);
4771 goto done;
4772 } else if (num_present < 2) {
4773 tor_snprintf(dir_info_status, sizeof(dir_info_status),
4774 "Only %d descriptor%s here and believed reachable!",
4775 num_present, num_present ? "" : "s");
4776 res = 0;
4777 goto done;
4780 /* Check for entry nodes. */
4781 if (options->EntryNodes) {
4782 count_usable_descriptors(&num_present, &num_usable, consensus, options,
4783 now, options->EntryNodes);
4785 if (num_usable && (num_present == 0)) {
4786 tor_snprintf(dir_info_status, sizeof(dir_info_status),
4787 "We have only %d/%d usable entry node descriptors.",
4788 num_present, num_usable);
4789 res = 0;
4790 goto done;
4794 res = 1;
4796 done:
4797 if (res && !have_min_dir_info) {
4798 log(LOG_NOTICE, LD_DIR,
4799 "We now have enough directory information to build circuits.");
4800 control_event_client_status(LOG_NOTICE, "ENOUGH_DIR_INFO");
4801 control_event_bootstrap(BOOTSTRAP_STATUS_CONN_OR, 0);
4803 if (!res && have_min_dir_info) {
4804 int quiet = directory_too_idle_to_fetch_descriptors(options, now);
4805 log(quiet ? LOG_INFO : LOG_NOTICE, LD_DIR,
4806 "Our directory information is no longer up-to-date "
4807 "enough to build circuits: %s", dir_info_status);
4809 /* a) make us log when we next complete a circuit, so we know when Tor
4810 * is back up and usable, and b) disable some activities that Tor
4811 * should only do while circuits are working, like reachability tests
4812 * and fetching bridge descriptors only over circuits. */
4813 can_complete_circuit = 0;
4815 control_event_client_status(LOG_NOTICE, "NOT_ENOUGH_DIR_INFO");
4817 have_min_dir_info = res;
4818 need_to_update_have_min_dir_info = 0;
4821 /** Reset the descriptor download failure count on all routers, so that we
4822 * can retry any long-failed routers immediately.
4824 void
4825 router_reset_descriptor_download_failures(void)
4827 networkstatus_reset_download_failures();
4828 last_routerdesc_download_attempted = 0;
4829 if (!routerlist)
4830 return;
4831 SMARTLIST_FOREACH(routerlist->routers, routerinfo_t *, ri,
4833 download_status_reset(&ri->cache_info.ei_dl_status);
4835 SMARTLIST_FOREACH(routerlist->old_routers, signed_descriptor_t *, sd,
4837 download_status_reset(&sd->ei_dl_status);
4841 /** Any changes in a router descriptor's publication time larger than this are
4842 * automatically non-cosmetic. */
4843 #define ROUTER_MAX_COSMETIC_TIME_DIFFERENCE (12*60*60)
4845 /** We allow uptime to vary from how much it ought to be by this much. */
4846 #define ROUTER_ALLOW_UPTIME_DRIFT (6*60*60)
4848 /** Return true iff the only differences between r1 and r2 are such that
4849 * would not cause a recent (post 0.1.1.6) dirserver to republish.
4852 router_differences_are_cosmetic(routerinfo_t *r1, routerinfo_t *r2)
4854 time_t r1pub, r2pub;
4855 long time_difference;
4856 tor_assert(r1 && r2);
4858 /* r1 should be the one that was published first. */
4859 if (r1->cache_info.published_on > r2->cache_info.published_on) {
4860 routerinfo_t *ri_tmp = r2;
4861 r2 = r1;
4862 r1 = ri_tmp;
4865 /* If any key fields differ, they're different. */
4866 if (strcasecmp(r1->address, r2->address) ||
4867 strcasecmp(r1->nickname, r2->nickname) ||
4868 r1->or_port != r2->or_port ||
4869 r1->dir_port != r2->dir_port ||
4870 r1->purpose != r2->purpose ||
4871 crypto_pk_cmp_keys(r1->onion_pkey, r2->onion_pkey) ||
4872 crypto_pk_cmp_keys(r1->identity_pkey, r2->identity_pkey) ||
4873 strcasecmp(r1->platform, r2->platform) ||
4874 (r1->contact_info && !r2->contact_info) || /* contact_info is optional */
4875 (!r1->contact_info && r2->contact_info) ||
4876 (r1->contact_info && r2->contact_info &&
4877 strcasecmp(r1->contact_info, r2->contact_info)) ||
4878 r1->is_hibernating != r2->is_hibernating ||
4879 r1->has_old_dnsworkers != r2->has_old_dnsworkers ||
4880 cmp_addr_policies(r1->exit_policy, r2->exit_policy))
4881 return 0;
4882 if ((r1->declared_family == NULL) != (r2->declared_family == NULL))
4883 return 0;
4884 if (r1->declared_family && r2->declared_family) {
4885 int i, n;
4886 if (smartlist_len(r1->declared_family)!=smartlist_len(r2->declared_family))
4887 return 0;
4888 n = smartlist_len(r1->declared_family);
4889 for (i=0; i < n; ++i) {
4890 if (strcasecmp(smartlist_get(r1->declared_family, i),
4891 smartlist_get(r2->declared_family, i)))
4892 return 0;
4896 /* Did bandwidth change a lot? */
4897 if ((r1->bandwidthcapacity < r2->bandwidthcapacity/2) ||
4898 (r2->bandwidthcapacity < r1->bandwidthcapacity/2))
4899 return 0;
4901 /* Did the bandwidthrate or bandwidthburst change? */
4902 if ((r1->bandwidthrate != r2->bandwidthrate) ||
4903 (r1->bandwidthburst != r2->bandwidthburst))
4904 return 0;
4906 /* Did more than 12 hours pass? */
4907 if (r1->cache_info.published_on + ROUTER_MAX_COSMETIC_TIME_DIFFERENCE
4908 < r2->cache_info.published_on)
4909 return 0;
4911 /* Did uptime fail to increase by approximately the amount we would think,
4912 * give or take some slop? */
4913 r1pub = r1->cache_info.published_on;
4914 r2pub = r2->cache_info.published_on;
4915 time_difference = labs(r2->uptime - (r1->uptime + (r2pub - r1pub)));
4916 if (time_difference > ROUTER_ALLOW_UPTIME_DRIFT &&
4917 time_difference > r1->uptime * .05 &&
4918 time_difference > r2->uptime * .05)
4919 return 0;
4921 /* Otherwise, the difference is cosmetic. */
4922 return 1;
4925 /** Check whether <b>ri</b> (a.k.a. sd) is a router compatible with the
4926 * extrainfo document
4927 * <b>ei</b>. If no router is compatible with <b>ei</b>, <b>ei</b> should be
4928 * dropped. Return 0 for "compatible", return 1 for "reject, and inform
4929 * whoever uploaded <b>ei</b>, and return -1 for "reject silently.". If
4930 * <b>msg</b> is present, set *<b>msg</b> to a description of the
4931 * incompatibility (if any).
4934 routerinfo_incompatible_with_extrainfo(routerinfo_t *ri, extrainfo_t *ei,
4935 signed_descriptor_t *sd,
4936 const char **msg)
4938 int digest_matches, r=1;
4939 tor_assert(ri);
4940 tor_assert(ei);
4941 if (!sd)
4942 sd = &ri->cache_info;
4944 if (ei->bad_sig) {
4945 if (msg) *msg = "Extrainfo signature was bad, or signed with wrong key.";
4946 return 1;
4949 digest_matches = !memcmp(ei->cache_info.signed_descriptor_digest,
4950 sd->extra_info_digest, DIGEST_LEN);
4952 /* The identity must match exactly to have been generated at the same time
4953 * by the same router. */
4954 if (memcmp(ri->cache_info.identity_digest, ei->cache_info.identity_digest,
4955 DIGEST_LEN)) {
4956 if (msg) *msg = "Extrainfo nickname or identity did not match routerinfo";
4957 goto err; /* different servers */
4960 if (ei->pending_sig) {
4961 char signed_digest[128];
4962 if (crypto_pk_public_checksig(ri->identity_pkey, signed_digest,
4963 ei->pending_sig, ei->pending_sig_len) != DIGEST_LEN ||
4964 memcmp(signed_digest, ei->cache_info.signed_descriptor_digest,
4965 DIGEST_LEN)) {
4966 ei->bad_sig = 1;
4967 tor_free(ei->pending_sig);
4968 if (msg) *msg = "Extrainfo signature bad, or signed with wrong key";
4969 goto err; /* Bad signature, or no match. */
4972 ei->cache_info.send_unencrypted = ri->cache_info.send_unencrypted;
4973 tor_free(ei->pending_sig);
4976 if (ei->cache_info.published_on < sd->published_on) {
4977 if (msg) *msg = "Extrainfo published time did not match routerdesc";
4978 goto err;
4979 } else if (ei->cache_info.published_on > sd->published_on) {
4980 if (msg) *msg = "Extrainfo published time did not match routerdesc";
4981 r = -1;
4982 goto err;
4985 if (!digest_matches) {
4986 if (msg) *msg = "Extrainfo digest did not match value from routerdesc";
4987 goto err; /* Digest doesn't match declared value. */
4990 return 0;
4991 err:
4992 if (digest_matches) {
4993 /* This signature was okay, and the digest was right: This is indeed the
4994 * corresponding extrainfo. But insanely, it doesn't match the routerinfo
4995 * that lists it. Don't try to fetch this one again. */
4996 sd->extrainfo_is_bogus = 1;
4999 return r;
5002 /** Assert that the internal representation of <b>rl</b> is
5003 * self-consistent. */
5004 void
5005 routerlist_assert_ok(routerlist_t *rl)
5007 routerinfo_t *r2;
5008 signed_descriptor_t *sd2;
5009 if (!rl)
5010 return;
5011 SMARTLIST_FOREACH(rl->routers, routerinfo_t *, r,
5013 r2 = rimap_get(rl->identity_map, r->cache_info.identity_digest);
5014 tor_assert(r == r2);
5015 sd2 = sdmap_get(rl->desc_digest_map,
5016 r->cache_info.signed_descriptor_digest);
5017 tor_assert(&(r->cache_info) == sd2);
5018 tor_assert(r->cache_info.routerlist_index == r_sl_idx);
5019 /* XXXX
5021 * Hoo boy. We need to fix this one, and the fix is a bit tricky, so
5022 * commenting this out is just a band-aid.
5024 * The problem is that, although well-behaved router descriptors
5025 * should never have the same value for their extra_info_digest, it's
5026 * possible for ill-behaved routers to claim whatever they like there.
5028 * The real answer is to trash desc_by_eid_map and instead have
5029 * something that indicates for a given extra-info digest we want,
5030 * what its download status is. We'll do that as a part of routerlist
5031 * refactoring once consensus directories are in. For now,
5032 * this rep violation is probably harmless: an adversary can make us
5033 * reset our retry count for an extrainfo, but that's not the end
5034 * of the world. Changing the representation in 0.2.0.x would just
5035 * destabilize the codebase.
5036 if (!tor_digest_is_zero(r->cache_info.extra_info_digest)) {
5037 signed_descriptor_t *sd3 =
5038 sdmap_get(rl->desc_by_eid_map, r->cache_info.extra_info_digest);
5039 tor_assert(sd3 == &(r->cache_info));
5043 SMARTLIST_FOREACH(rl->old_routers, signed_descriptor_t *, sd,
5045 r2 = rimap_get(rl->identity_map, sd->identity_digest);
5046 tor_assert(sd != &(r2->cache_info));
5047 sd2 = sdmap_get(rl->desc_digest_map, sd->signed_descriptor_digest);
5048 tor_assert(sd == sd2);
5049 tor_assert(sd->routerlist_index == sd_sl_idx);
5050 /* XXXX see above.
5051 if (!tor_digest_is_zero(sd->extra_info_digest)) {
5052 signed_descriptor_t *sd3 =
5053 sdmap_get(rl->desc_by_eid_map, sd->extra_info_digest);
5054 tor_assert(sd3 == sd);
5059 RIMAP_FOREACH(rl->identity_map, d, r) {
5060 tor_assert(!memcmp(r->cache_info.identity_digest, d, DIGEST_LEN));
5061 } DIGESTMAP_FOREACH_END;
5062 SDMAP_FOREACH(rl->desc_digest_map, d, sd) {
5063 tor_assert(!memcmp(sd->signed_descriptor_digest, d, DIGEST_LEN));
5064 } DIGESTMAP_FOREACH_END;
5065 SDMAP_FOREACH(rl->desc_by_eid_map, d, sd) {
5066 tor_assert(!tor_digest_is_zero(d));
5067 tor_assert(sd);
5068 tor_assert(!memcmp(sd->extra_info_digest, d, DIGEST_LEN));
5069 } DIGESTMAP_FOREACH_END;
5070 EIMAP_FOREACH(rl->extra_info_map, d, ei) {
5071 signed_descriptor_t *sd;
5072 tor_assert(!memcmp(ei->cache_info.signed_descriptor_digest,
5073 d, DIGEST_LEN));
5074 sd = sdmap_get(rl->desc_by_eid_map,
5075 ei->cache_info.signed_descriptor_digest);
5076 // tor_assert(sd); // XXXX see above
5077 if (sd) {
5078 tor_assert(!memcmp(ei->cache_info.signed_descriptor_digest,
5079 sd->extra_info_digest, DIGEST_LEN));
5081 } DIGESTMAP_FOREACH_END;
5084 /** Allocate and return a new string representing the contact info
5085 * and platform string for <b>router</b>,
5086 * surrounded by quotes and using standard C escapes.
5088 * THIS FUNCTION IS NOT REENTRANT. Don't call it from outside the main
5089 * thread. Also, each call invalidates the last-returned value, so don't
5090 * try log_warn(LD_GENERAL, "%s %s", esc_router_info(a), esc_router_info(b));
5092 * If <b>router</b> is NULL, it just frees its internal memory and returns.
5094 const char *
5095 esc_router_info(routerinfo_t *router)
5097 static char *info=NULL;
5098 char *esc_contact, *esc_platform;
5099 size_t len;
5100 tor_free(info);
5102 if (!router)
5103 return NULL; /* we're exiting; just free the memory we use */
5105 esc_contact = esc_for_log(router->contact_info);
5106 esc_platform = esc_for_log(router->platform);
5108 len = strlen(esc_contact)+strlen(esc_platform)+32;
5109 info = tor_malloc(len);
5110 tor_snprintf(info, len, "Contact %s, Platform %s", esc_contact,
5111 esc_platform);
5112 tor_free(esc_contact);
5113 tor_free(esc_platform);
5115 return info;
5118 /** Helper for sorting: compare two routerinfos by their identity
5119 * digest. */
5120 static int
5121 _compare_routerinfo_by_id_digest(const void **a, const void **b)
5123 routerinfo_t *first = *(routerinfo_t **)a, *second = *(routerinfo_t **)b;
5124 return memcmp(first->cache_info.identity_digest,
5125 second->cache_info.identity_digest,
5126 DIGEST_LEN);
5129 /** Sort a list of routerinfo_t in ascending order of identity digest. */
5130 void
5131 routers_sort_by_identity(smartlist_t *routers)
5133 smartlist_sort(routers, _compare_routerinfo_by_id_digest);
5136 /** A routerset specifies constraints on a set of possible routerinfos, based
5137 * on their names, identities, or addresses. It is optimized for determining
5138 * whether a router is a member or not, in O(1+P) time, where P is the number
5139 * of address policy constraints. */
5140 struct routerset_t {
5141 /** A list of strings for the elements of the policy. Each string is either
5142 * a nickname, a hexadecimal identity fingerprint, or an address policy. A
5143 * router belongs to the set if its nickname OR its identity OR its address
5144 * matches an entry here. */
5145 smartlist_t *list;
5146 /** A map from lowercase nicknames of routers in the set to (void*)1 */
5147 strmap_t *names;
5148 /** A map from identity digests routers in the set to (void*)1 */
5149 digestmap_t *digests;
5150 /** An address policy for routers in the set. For implementation reasons,
5151 * a router belongs to the set if it is _rejected_ by this policy. */
5152 smartlist_t *policies;
5154 /** A human-readable description of what this routerset is for. Used in
5155 * log messages. */
5156 char *description;
5158 /** A list of the country codes in this set. */
5159 smartlist_t *country_names;
5160 /** Total number of countries we knew about when we built <b>countries</b>.*/
5161 int n_countries;
5162 /** Bit array mapping the return value of geoip_get_country() to 1 iff the
5163 * country is a member of this routerset. Note that we MUST call
5164 * routerset_refresh_countries() whenever the geoip country list is
5165 * reloaded. */
5166 bitarray_t *countries;
5169 /** Return a new empty routerset. */
5170 routerset_t *
5171 routerset_new(void)
5173 routerset_t *result = tor_malloc_zero(sizeof(routerset_t));
5174 result->list = smartlist_create();
5175 result->names = strmap_new();
5176 result->digests = digestmap_new();
5177 result->policies = smartlist_create();
5178 result->country_names = smartlist_create();
5179 return result;
5182 /** If <b>c</b> is a country code in the form {cc}, return a newly allocated
5183 * string holding the "cc" part. Else, return NULL. */
5184 static char *
5185 routerset_get_countryname(const char *c)
5187 char *country;
5189 if (strlen(c) < 4 || c[0] !='{' || c[3] !='}')
5190 return NULL;
5192 country = tor_strndup(c+1, 2);
5193 tor_strlower(country);
5194 return country;
5197 #if 0
5198 /** Add the GeoIP database's integer index (+1) of a valid two-character
5199 * country code to the routerset's <b>countries</b> bitarray. Return the
5200 * integer index if the country code is valid, -1 otherwise.*/
5201 static int
5202 routerset_add_country(const char *c)
5204 char country[3];
5205 country_t cc;
5207 /* XXXX: Country codes must be of the form \{[a-z\?]{2}\} but this accepts
5208 \{[.]{2}\}. Do we need to be strict? -RH */
5209 /* Nope; if the country code is bad, we'll get 0 when we look it up. */
5211 if (!geoip_is_loaded()) {
5212 log(LOG_WARN, LD_CONFIG, "GeoIP database not loaded: Cannot add country"
5213 "entry %s, ignoring.", c);
5214 return -1;
5217 memcpy(country, c+1, 2);
5218 country[2] = '\0';
5219 tor_strlower(country);
5221 if ((cc=geoip_get_country(country))==-1) {
5222 log(LOG_WARN, LD_CONFIG, "Country code '%s' is not valid, ignoring.",
5223 country);
5225 return cc;
5227 #endif
5229 /** Update the routerset's <b>countries</b> bitarray_t. Called whenever
5230 * the GeoIP database is reloaded.
5232 void
5233 routerset_refresh_countries(routerset_t *target)
5235 int cc;
5236 bitarray_free(target->countries);
5238 if (!geoip_is_loaded()) {
5239 target->countries = NULL;
5240 target->n_countries = 0;
5241 return;
5243 target->n_countries = geoip_get_n_countries();
5244 target->countries = bitarray_init_zero(target->n_countries);
5245 SMARTLIST_FOREACH_BEGIN(target->country_names, const char *, country) {
5246 cc = geoip_get_country(country);
5247 if (cc >= 0) {
5248 tor_assert(cc < target->n_countries);
5249 bitarray_set(target->countries, cc);
5250 } else {
5251 log(LOG_WARN, LD_CONFIG, "Country code '%s' is not recognized.",
5252 country);
5254 } SMARTLIST_FOREACH_END(country);
5257 /** Parse the string <b>s</b> to create a set of routerset entries, and add
5258 * them to <b>target</b>. In log messages, refer to the string as
5259 * <b>description</b>. Return 0 on success, -1 on failure.
5261 * Three kinds of elements are allowed in routersets: nicknames, IP address
5262 * patterns, and fingerprints. They may be surrounded by optional space, and
5263 * must be separated by commas.
5266 routerset_parse(routerset_t *target, const char *s, const char *description)
5268 int r = 0;
5269 int added_countries = 0;
5270 char *countryname;
5271 smartlist_t *list = smartlist_create();
5272 smartlist_split_string(list, s, ",",
5273 SPLIT_SKIP_SPACE | SPLIT_IGNORE_BLANK, 0);
5274 SMARTLIST_FOREACH_BEGIN(list, char *, nick) {
5275 addr_policy_t *p;
5276 if (is_legal_hexdigest(nick)) {
5277 char d[DIGEST_LEN];
5278 if (*nick == '$')
5279 ++nick;
5280 log_debug(LD_CONFIG, "Adding identity %s to %s", nick, description);
5281 base16_decode(d, sizeof(d), nick, HEX_DIGEST_LEN);
5282 digestmap_set(target->digests, d, (void*)1);
5283 } else if (is_legal_nickname(nick)) {
5284 log_debug(LD_CONFIG, "Adding nickname %s to %s", nick, description);
5285 strmap_set_lc(target->names, nick, (void*)1);
5286 } else if ((countryname = routerset_get_countryname(nick)) != NULL) {
5287 log_debug(LD_CONFIG, "Adding country %s to %s", nick,
5288 description);
5289 smartlist_add(target->country_names, countryname);
5290 added_countries = 1;
5291 } else if ((strchr(nick,'.') || strchr(nick, '*')) &&
5292 (p = router_parse_addr_policy_item_from_string(
5293 nick, ADDR_POLICY_REJECT))) {
5294 log_debug(LD_CONFIG, "Adding address %s to %s", nick, description);
5295 smartlist_add(target->policies, p);
5296 } else {
5297 log_warn(LD_CONFIG, "Entry '%s' in %s is misformed.", nick,
5298 description);
5299 r = -1;
5300 tor_free(nick);
5301 SMARTLIST_DEL_CURRENT(list, nick);
5303 } SMARTLIST_FOREACH_END(nick);
5304 smartlist_add_all(target->list, list);
5305 smartlist_free(list);
5306 if (added_countries)
5307 routerset_refresh_countries(target);
5308 return r;
5311 /** Called when we change a node set, or when we reload the geoip list:
5312 * recompute all country info in all configuration node sets and in the
5313 * routerlist. */
5314 void
5315 refresh_all_country_info(void)
5317 or_options_t *options = get_options();
5319 if (options->EntryNodes)
5320 routerset_refresh_countries(options->EntryNodes);
5321 if (options->ExitNodes)
5322 routerset_refresh_countries(options->ExitNodes);
5323 if (options->ExcludeNodes)
5324 routerset_refresh_countries(options->ExcludeNodes);
5325 if (options->ExcludeExitNodes)
5326 routerset_refresh_countries(options->ExcludeExitNodes);
5327 if (options->_ExcludeExitNodesUnion)
5328 routerset_refresh_countries(options->_ExcludeExitNodesUnion);
5330 routerlist_refresh_countries();
5333 /** Add all members of the set <b>source</b> to <b>target</b>. */
5334 void
5335 routerset_union(routerset_t *target, const routerset_t *source)
5337 char *s;
5338 tor_assert(target);
5339 if (!source || !source->list)
5340 return;
5341 s = routerset_to_string(source);
5342 routerset_parse(target, s, "other routerset");
5343 tor_free(s);
5346 /** Return true iff <b>set</b> lists only nicknames and digests, and includes
5347 * no IP ranges or countries. */
5349 routerset_is_list(const routerset_t *set)
5351 return smartlist_len(set->country_names) == 0 &&
5352 smartlist_len(set->policies) == 0;
5355 /** Return true iff we need a GeoIP IP-to-country database to make sense of
5356 * <b>set</b>. */
5358 routerset_needs_geoip(const routerset_t *set)
5360 return set && smartlist_len(set->country_names);
5363 /** Return true iff there are no entries in <b>set</b>. */
5364 static int
5365 routerset_is_empty(const routerset_t *set)
5367 return !set || smartlist_len(set->list) == 0;
5370 /** Helper. Return true iff <b>set</b> contains a router based on the other
5371 * provided fields. Return higher values for more specific subentries: a
5372 * single router is more specific than an address range of routers, which is
5373 * more specific in turn than a country code.
5375 * (If country is -1, then we take the country
5376 * from addr.) */
5377 static int
5378 routerset_contains(const routerset_t *set, const tor_addr_t *addr,
5379 uint16_t orport,
5380 const char *nickname, const char *id_digest, int is_named,
5381 country_t country)
5383 if (!set || !set->list) return 0;
5384 (void) is_named; /* not supported */
5385 if (nickname && strmap_get_lc(set->names, nickname))
5386 return 4;
5387 if (id_digest && digestmap_get(set->digests, id_digest))
5388 return 4;
5389 if (addr && compare_tor_addr_to_addr_policy(addr, orport, set->policies)
5390 == ADDR_POLICY_REJECTED)
5391 return 3;
5392 if (set->countries) {
5393 if (country < 0 && addr)
5394 country = geoip_get_country_by_ip(tor_addr_to_ipv4h(addr));
5396 if (country >= 0 && country < set->n_countries &&
5397 bitarray_is_set(set->countries, country))
5398 return 2;
5400 return 0;
5403 /** Return true iff we can tell that <b>ei</b> is a member of <b>set</b>. */
5405 routerset_contains_extendinfo(const routerset_t *set, const extend_info_t *ei)
5407 return routerset_contains(set,
5408 &ei->addr,
5409 ei->port,
5410 ei->nickname,
5411 ei->identity_digest,
5412 -1, /*is_named*/
5413 -1 /*country*/);
5416 /** Return true iff <b>ri</b> is in <b>set</b>. */
5418 routerset_contains_router(const routerset_t *set, routerinfo_t *ri)
5420 tor_addr_t addr;
5421 tor_addr_from_ipv4h(&addr, ri->addr);
5422 return routerset_contains(set,
5423 &addr,
5424 ri->or_port,
5425 ri->nickname,
5426 ri->cache_info.identity_digest,
5427 ri->is_named,
5428 ri->country);
5431 /** Return true iff <b>rs</b> is in <b>set</b>. */
5433 routerset_contains_routerstatus(const routerset_t *set, routerstatus_t *rs)
5435 tor_addr_t addr;
5436 tor_addr_from_ipv4h(&addr, rs->addr);
5437 return routerset_contains(set,
5438 &addr,
5439 rs->or_port,
5440 rs->nickname,
5441 rs->identity_digest,
5442 rs->is_named,
5443 -1);
5446 /** Add every known routerinfo_t that is a member of <b>routerset</b> to
5447 * <b>out</b>. If <b>running_only</b>, only add the running ones. */
5448 void
5449 routerset_get_all_routers(smartlist_t *out, const routerset_t *routerset,
5450 int running_only)
5452 tor_assert(out);
5453 if (!routerset || !routerset->list)
5454 return;
5455 if (!warned_nicknames)
5456 warned_nicknames = smartlist_create();
5457 if (routerset_is_list(routerset)) {
5459 /* No routers are specified by type; all are given by name or digest.
5460 * we can do a lookup in O(len(list)). */
5461 SMARTLIST_FOREACH(routerset->list, const char *, name, {
5462 routerinfo_t *router = router_get_by_nickname(name, 1);
5463 if (router) {
5464 if (!running_only || router->is_running)
5465 smartlist_add(out, router);
5468 } else {
5469 /* We need to iterate over the routerlist to get all the ones of the
5470 * right kind. */
5471 routerlist_t *rl = router_get_routerlist();
5472 SMARTLIST_FOREACH(rl->routers, routerinfo_t *, router, {
5473 if (running_only && !router->is_running)
5474 continue;
5475 if (routerset_contains_router(routerset, router))
5476 smartlist_add(out, router);
5481 /** Add to <b>target</b> every routerinfo_t from <b>source</b> except:
5483 * 1) Don't add it if <b>include</b> is non-empty and the relay isn't in
5484 * <b>include</b>; and
5485 * 2) Don't add it if <b>exclude</b> is non-empty and the relay is
5486 * excluded in a more specific fashion by <b>exclude</b>.
5487 * 3) If <b>running_only</b>, don't add non-running routers.
5489 void
5490 routersets_get_disjunction(smartlist_t *target,
5491 const smartlist_t *source,
5492 const routerset_t *include,
5493 const routerset_t *exclude, int running_only)
5495 SMARTLIST_FOREACH(source, routerinfo_t *, router, {
5496 int include_result;
5497 if (running_only && !router->is_running)
5498 continue;
5499 if (!routerset_is_empty(include))
5500 include_result = routerset_contains_router(include, router);
5501 else
5502 include_result = 1;
5504 if (include_result) {
5505 int exclude_result = routerset_contains_router(exclude, router);
5506 if (include_result >= exclude_result)
5507 smartlist_add(target, router);
5512 /** Remove every routerinfo_t from <b>lst</b> that is in <b>routerset</b>. */
5513 void
5514 routerset_subtract_routers(smartlist_t *lst, const routerset_t *routerset)
5516 tor_assert(lst);
5517 if (!routerset)
5518 return;
5519 SMARTLIST_FOREACH(lst, routerinfo_t *, r, {
5520 if (routerset_contains_router(routerset, r)) {
5521 //log_debug(LD_DIR, "Subtracting %s",r->nickname);
5522 SMARTLIST_DEL_CURRENT(lst, r);
5527 /** Return a new string that when parsed by routerset_parse_string() will
5528 * yield <b>set</b>. */
5529 char *
5530 routerset_to_string(const routerset_t *set)
5532 if (!set || !set->list)
5533 return tor_strdup("");
5534 return smartlist_join_strings(set->list, ",", 0, NULL);
5537 /** Helper: return true iff old and new are both NULL, or both non-NULL
5538 * equal routersets. */
5540 routerset_equal(const routerset_t *old, const routerset_t *new)
5542 if (old == NULL && new == NULL)
5543 return 1;
5544 else if (old == NULL || new == NULL)
5545 return 0;
5547 if (smartlist_len(old->list) != smartlist_len(new->list))
5548 return 0;
5550 SMARTLIST_FOREACH(old->list, const char *, cp1, {
5551 const char *cp2 = smartlist_get(new->list, cp1_sl_idx);
5552 if (strcmp(cp1, cp2))
5553 return 0;
5556 return 1;
5559 /** Free all storage held in <b>routerset</b>. */
5560 void
5561 routerset_free(routerset_t *routerset)
5563 if (!routerset)
5564 return;
5566 SMARTLIST_FOREACH(routerset->list, char *, cp, tor_free(cp));
5567 smartlist_free(routerset->list);
5568 SMARTLIST_FOREACH(routerset->policies, addr_policy_t *, p,
5569 addr_policy_free(p));
5570 smartlist_free(routerset->policies);
5571 SMARTLIST_FOREACH(routerset->country_names, char *, cp, tor_free(cp));
5572 smartlist_free(routerset->country_names);
5574 strmap_free(routerset->names, NULL);
5575 digestmap_free(routerset->digests, NULL);
5576 bitarray_free(routerset->countries);
5577 tor_free(routerset);
5580 /** Refresh the country code of <b>ri</b>. This function MUST be called on
5581 * each router when the GeoIP database is reloaded, and on all new routers. */
5582 void
5583 routerinfo_set_country(routerinfo_t *ri)
5585 ri->country = geoip_get_country_by_ip(ri->addr);
5588 /** Set the country code of all routers in the routerlist. */
5589 void
5590 routerlist_refresh_countries(void)
5592 routerlist_t *rl = router_get_routerlist();
5593 SMARTLIST_FOREACH(rl->routers, routerinfo_t *, ri,
5594 routerinfo_set_country(ri));
5597 /** Determine the routers that are responsible for <b>id</b> (binary) and
5598 * add pointers to those routers' routerstatus_t to <b>responsible_dirs</b>.
5599 * Return -1 if we're returning an empty smartlist, else return 0.
5602 hid_serv_get_responsible_directories(smartlist_t *responsible_dirs,
5603 const char *id)
5605 int start, found, n_added = 0, i;
5606 networkstatus_t *c = networkstatus_get_latest_consensus();
5607 int use_begindir = get_options()->TunnelDirConns;
5608 if (!c || !smartlist_len(c->routerstatus_list)) {
5609 log_warn(LD_REND, "We don't have a consensus, so we can't perform v2 "
5610 "rendezvous operations.");
5611 return -1;
5613 tor_assert(id);
5614 start = networkstatus_vote_find_entry_idx(c, id, &found);
5615 if (start == smartlist_len(c->routerstatus_list)) start = 0;
5616 i = start;
5617 do {
5618 routerstatus_t *r = smartlist_get(c->routerstatus_list, i);
5619 if (r->is_hs_dir) {
5620 if (r->dir_port || use_begindir)
5621 smartlist_add(responsible_dirs, r);
5622 else
5623 log_info(LD_REND, "Not adding router '%s' to list of responsible "
5624 "hidden service directories, because we have no way of "
5625 "reaching it.", r->nickname);
5626 if (++n_added == REND_NUMBER_OF_CONSECUTIVE_REPLICAS)
5627 break;
5629 if (++i == smartlist_len(c->routerstatus_list))
5630 i = 0;
5631 } while (i != start);
5633 /* Even though we don't have the desired number of hidden service
5634 * directories, be happy if we got any. */
5635 return smartlist_len(responsible_dirs) ? 0 : -1;
5638 /** Return true if this node is currently acting as hidden service
5639 * directory, false otherwise. */
5641 hid_serv_acting_as_directory(void)
5643 routerinfo_t *me = router_get_my_routerinfo();
5644 networkstatus_t *c;
5645 routerstatus_t *rs;
5646 if (!me)
5647 return 0;
5648 if (!get_options()->HidServDirectoryV2) {
5649 log_info(LD_REND, "We are not acting as hidden service directory, "
5650 "because we have not been configured as such.");
5651 return 0;
5653 if (!(c = networkstatus_get_latest_consensus())) {
5654 log_info(LD_REND, "There's no consensus, so I can't tell if I'm a hidden "
5655 "service directory");
5656 return 0;
5658 rs = networkstatus_vote_find_entry(c, me->cache_info.identity_digest);
5659 if (!rs) {
5660 log_info(LD_REND, "We're not listed in the consensus, so we're not "
5661 "being a hidden service directory.");
5662 return 0;
5664 if (!rs->is_hs_dir) {
5665 log_info(LD_REND, "We're not listed as a hidden service directory in "
5666 "the consensus, so we won't be one.");
5667 return 0;
5669 return 1;
5672 /** Return true if this node is responsible for storing the descriptor ID
5673 * in <b>query</b> and false otherwise. */
5675 hid_serv_responsible_for_desc_id(const char *query)
5677 routerinfo_t *me;
5678 routerstatus_t *last_rs;
5679 const char *my_id, *last_id;
5680 int result;
5681 smartlist_t *responsible;
5682 if (!hid_serv_acting_as_directory())
5683 return 0;
5684 if (!(me = router_get_my_routerinfo()))
5685 return 0; /* This is redundant, but let's be paranoid. */
5686 my_id = me->cache_info.identity_digest;
5687 responsible = smartlist_create();
5688 if (hid_serv_get_responsible_directories(responsible, query) < 0) {
5689 smartlist_free(responsible);
5690 return 0;
5692 last_rs = smartlist_get(responsible, smartlist_len(responsible)-1);
5693 last_id = last_rs->identity_digest;
5694 result = rend_id_is_in_interval(my_id, query, last_id);
5695 smartlist_free(responsible);
5696 return result;