Fix compile warnings on Snow Leopard
[tor/rransom.git] / src / or / routerlist.c
blob42b385b101163ddfab072ccab000a0f9dd319fae
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-2009, 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"
16 // #define DEBUG_ROUTERLIST
18 /****************************************************************************/
20 /* static function prototypes */
21 static routerstatus_t *router_pick_directory_server_impl(
22 authority_type_t auth, int flags);
23 static routerstatus_t *router_pick_trusteddirserver_impl(
24 authority_type_t auth, int flags, int *n_busy_out);
25 static void mark_all_trusteddirservers_up(void);
26 static int router_nickname_matches(routerinfo_t *router, const char *nickname);
27 static void trusted_dir_server_free(trusted_dir_server_t *ds);
28 static void launch_router_descriptor_downloads(smartlist_t *downloadable,
29 time_t now);
30 static void update_consensus_router_descriptor_downloads(time_t now);
31 static int signed_desc_digest_is_recognized(signed_descriptor_t *desc);
32 static void update_router_have_minimum_dir_info(void);
33 static const char *signed_descriptor_get_body_impl(signed_descriptor_t *desc,
34 int with_annotations);
35 static void list_pending_downloads(digestmap_t *result,
36 int purpose, const char *prefix);
38 DECLARE_TYPED_DIGESTMAP_FNS(sdmap_, digest_sd_map_t, signed_descriptor_t)
39 DECLARE_TYPED_DIGESTMAP_FNS(rimap_, digest_ri_map_t, routerinfo_t)
40 DECLARE_TYPED_DIGESTMAP_FNS(eimap_, digest_ei_map_t, extrainfo_t)
41 #define SDMAP_FOREACH(map, keyvar, valvar) \
42 DIGESTMAP_FOREACH(sdmap_to_digestmap(map), keyvar, signed_descriptor_t *, \
43 valvar)
44 #define RIMAP_FOREACH(map, keyvar, valvar) \
45 DIGESTMAP_FOREACH(rimap_to_digestmap(map), keyvar, routerinfo_t *, valvar)
46 #define EIMAP_FOREACH(map, keyvar, valvar) \
47 DIGESTMAP_FOREACH(eimap_to_digestmap(map), keyvar, extrainfo_t *, valvar)
49 /****************************************************************************/
51 /** Global list of a trusted_dir_server_t object for each trusted directory
52 * server. */
53 static smartlist_t *trusted_dir_servers = NULL;
55 /** List of for a given authority, and download status for latest certificate.
57 typedef struct cert_list_t {
58 download_status_t dl_status;
59 smartlist_t *certs;
60 } cert_list_t;
61 /** Map from v3 identity key digest to cert_list_t. */
62 static digestmap_t *trusted_dir_certs = NULL;
63 /** True iff any key certificate in at least one member of
64 * <b>trusted_dir_certs</b> has changed since we last flushed the
65 * certificates to disk. */
66 static int trusted_dir_servers_certs_changed = 0;
68 /** Global list of all of the routers that we know about. */
69 static routerlist_t *routerlist = NULL;
71 /** List of strings for nicknames we've already warned about and that are
72 * still unknown / unavailable. */
73 static smartlist_t *warned_nicknames = NULL;
75 /** The last time we tried to download any routerdesc, or 0 for "never". We
76 * use this to rate-limit download attempts when the number of routerdescs to
77 * download is low. */
78 static time_t last_routerdesc_download_attempted = 0;
80 /** When we last computed the weights to use for bandwidths on directory
81 * requests, what were the total weighted bandwidth, and our share of that
82 * bandwidth? Used to determine what fraction of directory requests we should
83 * expect to see. */
84 static uint64_t sl_last_total_weighted_bw = 0,
85 sl_last_weighted_bw_of_me = 0;
87 /** Return the number of directory authorities whose type matches some bit set
88 * in <b>type</b> */
89 int
90 get_n_authorities(authority_type_t type)
92 int n = 0;
93 if (!trusted_dir_servers)
94 return 0;
95 SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, ds,
96 if (ds->type & type)
97 ++n);
98 return n;
101 #define get_n_v2_authorities() get_n_authorities(V2_AUTHORITY)
103 /** Helper: Return the cert_list_t for an authority whose authority ID is
104 * <b>id_digest</b>, allocating a new list if necessary. */
105 static cert_list_t *
106 get_cert_list(const char *id_digest)
108 cert_list_t *cl;
109 if (!trusted_dir_certs)
110 trusted_dir_certs = digestmap_new();
111 cl = digestmap_get(trusted_dir_certs, id_digest);
112 if (!cl) {
113 cl = tor_malloc_zero(sizeof(cert_list_t));
114 cl->dl_status.schedule = DL_SCHED_CONSENSUS;
115 cl->certs = smartlist_create();
116 digestmap_set(trusted_dir_certs, id_digest, cl);
118 return cl;
121 /** Reload the cached v3 key certificates from the cached-certs file in
122 * the data directory. Return 0 on success, -1 on failure. */
124 trusted_dirs_reload_certs(void)
126 char *filename;
127 char *contents;
128 int r;
130 filename = get_datadir_fname("cached-certs");
131 contents = read_file_to_str(filename, RFTS_IGNORE_MISSING, NULL);
132 tor_free(filename);
133 if (!contents)
134 return 0;
135 r = trusted_dirs_load_certs_from_string(contents, 1, 1);
136 tor_free(contents);
137 return r;
140 /** Helper: return true iff we already have loaded the exact cert
141 * <b>cert</b>. */
142 static INLINE int
143 already_have_cert(authority_cert_t *cert)
145 cert_list_t *cl = get_cert_list(cert->cache_info.identity_digest);
147 SMARTLIST_FOREACH(cl->certs, authority_cert_t *, c,
149 if (!memcmp(c->cache_info.signed_descriptor_digest,
150 cert->cache_info.signed_descriptor_digest,
151 DIGEST_LEN))
152 return 1;
154 return 0;
157 /** Load a bunch of new key certificates from the string <b>contents</b>. If
158 * <b>from_store</b> is true, the certificates are from the cache, and we
159 * don't need to flush them to disk. If <b>from_store</b> is false, we need
160 * to flush any changed certificates to disk. Return 0 on success, -1 on
161 * failure. */
163 trusted_dirs_load_certs_from_string(const char *contents, int from_store,
164 int flush)
166 trusted_dir_server_t *ds;
167 const char *s, *eos;
169 for (s = contents; *s; s = eos) {
170 authority_cert_t *cert = authority_cert_parse_from_string(s, &eos);
171 cert_list_t *cl;
172 if (!cert)
173 break;
174 ds = trusteddirserver_get_by_v3_auth_digest(
175 cert->cache_info.identity_digest);
176 log_debug(LD_DIR, "Parsed certificate for %s",
177 ds ? ds->nickname : "unknown authority");
179 if (already_have_cert(cert)) {
180 /* we already have this one. continue. */
181 log_info(LD_DIR, "Skipping %s certificate for %s that we "
182 "already have.",
183 from_store ? "cached" : "downloaded",
184 ds ? ds->nickname : "??");
186 /* a duplicate on a download should be treated as a failure, since it
187 * probably means we wanted a different secret key or we are trying to
188 * replace an expired cert that has not in fact been updated. */
189 if (!from_store) {
190 log_warn(LD_DIR, "Got a certificate for %s that we already have. "
191 "Maybe they haven't updated it. Waiting for a while.",
192 ds ? ds->nickname : "??");
193 authority_cert_dl_failed(cert->cache_info.identity_digest, 404);
196 authority_cert_free(cert);
197 continue;
200 if (ds) {
201 log_info(LD_DIR, "Adding %s certificate for directory authority %s with "
202 "signing key %s", from_store ? "cached" : "downloaded",
203 ds->nickname, hex_str(cert->signing_key_digest,DIGEST_LEN));
204 } else {
205 int adding = directory_caches_dir_info(get_options());
206 log_info(LD_DIR, "%s %s certificate for unrecognized directory "
207 "authority with signing key %s",
208 adding ? "Adding" : "Not adding",
209 from_store ? "cached" : "downloaded",
210 hex_str(cert->signing_key_digest,DIGEST_LEN));
211 if (!adding) {
212 authority_cert_free(cert);
213 continue;
217 cl = get_cert_list(cert->cache_info.identity_digest);
218 smartlist_add(cl->certs, cert);
219 if (ds && cert->cache_info.published_on > ds->addr_current_at) {
220 /* Check to see whether we should update our view of the authority's
221 * address. */
222 if (cert->addr && cert->dir_port &&
223 (ds->addr != cert->addr ||
224 ds->dir_port != cert->dir_port)) {
225 char *a = tor_dup_ip(cert->addr);
226 log_notice(LD_DIR, "Updating address for directory authority %s "
227 "from %s:%d to %s:%d based on in certificate.",
228 ds->nickname, ds->address, (int)ds->dir_port,
229 a, cert->dir_port);
230 tor_free(a);
231 ds->addr = cert->addr;
232 ds->dir_port = cert->dir_port;
234 ds->addr_current_at = cert->cache_info.published_on;
237 if (!from_store)
238 trusted_dir_servers_certs_changed = 1;
241 if (flush)
242 trusted_dirs_flush_certs_to_disk();
244 networkstatus_note_certs_arrived();
245 return 0;
248 /** Save all v3 key certificates to the cached-certs file. */
249 void
250 trusted_dirs_flush_certs_to_disk(void)
252 char *filename;
253 smartlist_t *chunks;
255 if (!trusted_dir_servers_certs_changed || !trusted_dir_certs)
256 return;
258 chunks = smartlist_create();
259 DIGESTMAP_FOREACH(trusted_dir_certs, key, cert_list_t *, cl) {
260 SMARTLIST_FOREACH(cl->certs, authority_cert_t *, cert,
262 sized_chunk_t *c = tor_malloc(sizeof(sized_chunk_t));
263 c->bytes = cert->cache_info.signed_descriptor_body;
264 c->len = cert->cache_info.signed_descriptor_len;
265 smartlist_add(chunks, c);
267 } DIGESTMAP_FOREACH_END;
269 filename = get_datadir_fname("cached-certs");
270 if (write_chunks_to_file(filename, chunks, 0)) {
271 log_warn(LD_FS, "Error writing certificates to disk.");
273 tor_free(filename);
274 SMARTLIST_FOREACH(chunks, sized_chunk_t *, c, tor_free(c));
275 smartlist_free(chunks);
277 trusted_dir_servers_certs_changed = 0;
280 /** Remove all v3 authority certificates that have been superseded for more
281 * than 48 hours. (If the most recent cert was published more than 48 hours
282 * ago, then we aren't going to get any consensuses signed with older
283 * keys.) */
284 static void
285 trusted_dirs_remove_old_certs(void)
287 time_t now = time(NULL);
288 #define DEAD_CERT_LIFETIME (2*24*60*60)
289 #define OLD_CERT_LIFETIME (7*24*60*60)
290 if (!trusted_dir_certs)
291 return;
293 DIGESTMAP_FOREACH(trusted_dir_certs, key, cert_list_t *, cl) {
294 authority_cert_t *newest = NULL;
295 SMARTLIST_FOREACH(cl->certs, authority_cert_t *, cert,
296 if (!newest || (cert->cache_info.published_on >
297 newest->cache_info.published_on))
298 newest = cert);
299 if (newest) {
300 const time_t newest_published = newest->cache_info.published_on;
301 SMARTLIST_FOREACH_BEGIN(cl->certs, authority_cert_t *, cert) {
302 int expired;
303 time_t cert_published;
304 if (newest == cert)
305 continue;
306 expired = ftime_definitely_after(now, cert->expires);
307 cert_published = cert->cache_info.published_on;
308 /* Store expired certs for 48 hours after a newer arrives;
310 if (expired ?
311 (newest_published + DEAD_CERT_LIFETIME < now) :
312 (cert_published + OLD_CERT_LIFETIME < newest_published)) {
313 SMARTLIST_DEL_CURRENT(cl->certs, cert);
314 authority_cert_free(cert);
315 trusted_dir_servers_certs_changed = 1;
317 } SMARTLIST_FOREACH_END(cert);
319 } DIGESTMAP_FOREACH_END;
320 #undef OLD_CERT_LIFETIME
322 trusted_dirs_flush_certs_to_disk();
325 /** Return the newest v3 authority certificate whose v3 authority identity key
326 * has digest <b>id_digest</b>. Return NULL if no such authority is known,
327 * or it has no certificate. */
328 authority_cert_t *
329 authority_cert_get_newest_by_id(const char *id_digest)
331 cert_list_t *cl;
332 authority_cert_t *best = NULL;
333 if (!trusted_dir_certs ||
334 !(cl = digestmap_get(trusted_dir_certs, id_digest)))
335 return NULL;
337 SMARTLIST_FOREACH(cl->certs, authority_cert_t *, cert,
339 if (!best || cert->cache_info.published_on > best->cache_info.published_on)
340 best = cert;
342 return best;
345 /** Return the newest v3 authority certificate whose directory signing key has
346 * digest <b>sk_digest</b>. Return NULL if no such certificate is known.
348 authority_cert_t *
349 authority_cert_get_by_sk_digest(const char *sk_digest)
351 authority_cert_t *c;
352 if (!trusted_dir_certs)
353 return NULL;
355 if ((c = get_my_v3_authority_cert()) &&
356 !memcmp(c->signing_key_digest, sk_digest, DIGEST_LEN))
357 return c;
358 if ((c = get_my_v3_legacy_cert()) &&
359 !memcmp(c->signing_key_digest, sk_digest, DIGEST_LEN))
360 return c;
362 DIGESTMAP_FOREACH(trusted_dir_certs, key, cert_list_t *, cl) {
363 SMARTLIST_FOREACH(cl->certs, authority_cert_t *, cert,
365 if (!memcmp(cert->signing_key_digest, sk_digest, DIGEST_LEN))
366 return cert;
368 } DIGESTMAP_FOREACH_END;
369 return NULL;
372 /** Return the v3 authority certificate with signing key matching
373 * <b>sk_digest</b>, for the authority with identity digest <b>id_digest</b>.
374 * Return NULL if no such authority is known. */
375 authority_cert_t *
376 authority_cert_get_by_digests(const char *id_digest,
377 const char *sk_digest)
379 cert_list_t *cl;
380 if (!trusted_dir_certs ||
381 !(cl = digestmap_get(trusted_dir_certs, id_digest)))
382 return NULL;
383 SMARTLIST_FOREACH(cl->certs, authority_cert_t *, cert,
384 if (!memcmp(cert->signing_key_digest, sk_digest, DIGEST_LEN))
385 return cert; );
387 return NULL;
390 /** Add every known authority_cert_t to <b>certs_out</b>. */
391 void
392 authority_cert_get_all(smartlist_t *certs_out)
394 tor_assert(certs_out);
395 if (!trusted_dir_certs)
396 return;
398 DIGESTMAP_FOREACH(trusted_dir_certs, key, cert_list_t *, cl) {
399 SMARTLIST_FOREACH(cl->certs, authority_cert_t *, c,
400 smartlist_add(certs_out, c));
401 } DIGESTMAP_FOREACH_END;
404 /** Called when an attempt to download a certificate with the authority with
405 * ID <b>id_digest</b> fails with HTTP response code <b>status</b>: remember
406 * the failure, so we don't try again immediately. */
407 void
408 authority_cert_dl_failed(const char *id_digest, int status)
410 cert_list_t *cl;
411 if (!trusted_dir_certs ||
412 !(cl = digestmap_get(trusted_dir_certs, id_digest)))
413 return;
415 download_status_failed(&cl->dl_status, status);
418 /** How many times will we try to fetch a certificate before giving up? */
419 #define MAX_CERT_DL_FAILURES 8
421 /** Try to download any v3 authority certificates that we may be missing. If
422 * <b>status</b> is provided, try to get all the ones that were used to sign
423 * <b>status</b>. Additionally, try to have a non-expired certificate for
424 * every V3 authority in trusted_dir_servers. Don't fetch certificates we
425 * already have.
427 void
428 authority_certs_fetch_missing(networkstatus_t *status, time_t now)
430 digestmap_t *pending;
431 authority_cert_t *cert;
432 smartlist_t *missing_digests;
433 char *resource = NULL;
434 cert_list_t *cl;
435 const int cache = directory_caches_dir_info(get_options());
437 if (should_delay_dir_fetches(get_options()))
438 return;
440 pending = digestmap_new();
441 missing_digests = smartlist_create();
443 list_pending_downloads(pending, DIR_PURPOSE_FETCH_CERTIFICATE, "fp/");
444 if (status) {
445 SMARTLIST_FOREACH(status->voters, networkstatus_voter_info_t *, voter,
447 if (tor_digest_is_zero(voter->signing_key_digest))
448 continue; /* This authority never signed this consensus, so don't
449 * go looking for a cert with key digest 0000000000. */
450 if (!cache &&
451 !trusteddirserver_get_by_v3_auth_digest(voter->identity_digest))
452 continue; /* We are not a cache, and we don't know this authority.*/
453 cl = get_cert_list(voter->identity_digest);
454 cert = authority_cert_get_by_digests(voter->identity_digest,
455 voter->signing_key_digest);
456 if (cert) {
457 if (now < cert->expires)
458 download_status_reset(&cl->dl_status);
459 continue;
461 if (download_status_is_ready(&cl->dl_status, now,
462 MAX_CERT_DL_FAILURES) &&
463 !digestmap_get(pending, voter->identity_digest)) {
464 log_notice(LD_DIR, "We're missing a certificate from authority "
465 "with signing key %s: launching request.",
466 hex_str(voter->signing_key_digest, DIGEST_LEN));
467 smartlist_add(missing_digests, voter->identity_digest);
471 SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, ds,
473 int found = 0;
474 if (!(ds->type & V3_AUTHORITY))
475 continue;
476 if (smartlist_digest_isin(missing_digests, ds->v3_identity_digest))
477 continue;
478 cl = get_cert_list(ds->v3_identity_digest);
479 SMARTLIST_FOREACH(cl->certs, authority_cert_t *, cert,
481 if (!ftime_definitely_after(now, cert->expires)) {
482 /* It's not expired, and we weren't looking for something to
483 * verify a consensus with. Call it done. */
484 download_status_reset(&cl->dl_status);
485 found = 1;
486 break;
489 if (!found &&
490 download_status_is_ready(&cl->dl_status, now,MAX_CERT_DL_FAILURES) &&
491 !digestmap_get(pending, ds->v3_identity_digest)) {
492 log_notice(LD_DIR, "No current certificate known for authority %s; "
493 "launching request.", ds->nickname);
494 smartlist_add(missing_digests, ds->v3_identity_digest);
498 if (!smartlist_len(missing_digests)) {
499 goto done;
500 } else {
501 smartlist_t *fps = smartlist_create();
502 smartlist_add(fps, tor_strdup("fp/"));
503 SMARTLIST_FOREACH(missing_digests, const char *, d, {
504 char *fp;
505 if (digestmap_get(pending, d))
506 continue;
507 fp = tor_malloc(HEX_DIGEST_LEN+2);
508 base16_encode(fp, HEX_DIGEST_LEN+1, d, DIGEST_LEN);
509 fp[HEX_DIGEST_LEN] = '+';
510 fp[HEX_DIGEST_LEN+1] = '\0';
511 smartlist_add(fps, fp);
513 if (smartlist_len(fps) == 1) {
514 /* we didn't add any: they were all pending */
515 SMARTLIST_FOREACH(fps, char *, cp, tor_free(cp));
516 smartlist_free(fps);
517 goto done;
519 resource = smartlist_join_strings(fps, "", 0, NULL);
520 resource[strlen(resource)-1] = '\0';
521 SMARTLIST_FOREACH(fps, char *, cp, tor_free(cp));
522 smartlist_free(fps);
524 directory_get_from_dirserver(DIR_PURPOSE_FETCH_CERTIFICATE, 0,
525 resource, PDS_RETRY_IF_NO_SERVERS);
527 done:
528 tor_free(resource);
529 smartlist_free(missing_digests);
530 digestmap_free(pending, NULL);
533 /* Router descriptor storage.
535 * Routerdescs are stored in a big file, named "cached-descriptors". As new
536 * routerdescs arrive, we append them to a journal file named
537 * "cached-descriptors.new".
539 * From time to time, we replace "cached-descriptors" with a new file
540 * containing only the live, non-superseded descriptors, and clear
541 * cached-routers.new.
543 * On startup, we read both files.
546 /** Helper: return 1 iff the router log is so big we want to rebuild the
547 * store. */
548 static int
549 router_should_rebuild_store(desc_store_t *store)
551 if (store->store_len > (1<<16))
552 return (store->journal_len > store->store_len / 2 ||
553 store->bytes_dropped > store->store_len / 2);
554 else
555 return store->journal_len > (1<<15);
558 /** Return the desc_store_t in <b>rl</b> that should be used to store
559 * <b>sd</b>. */
560 static INLINE desc_store_t *
561 desc_get_store(routerlist_t *rl, signed_descriptor_t *sd)
563 if (sd->is_extrainfo)
564 return &rl->extrainfo_store;
565 else
566 return &rl->desc_store;
569 /** Add the signed_descriptor_t in <b>desc</b> to the router
570 * journal; change its saved_location to SAVED_IN_JOURNAL and set its
571 * offset appropriately. */
572 static int
573 signed_desc_append_to_journal(signed_descriptor_t *desc,
574 desc_store_t *store)
576 char *fname = get_datadir_fname_suffix(store->fname_base, ".new");
577 const char *body = signed_descriptor_get_body_impl(desc,1);
578 size_t len = desc->signed_descriptor_len + desc->annotations_len;
580 tor_assert(len == strlen(body));
582 if (append_bytes_to_file(fname, body, len, 1)) {
583 log_warn(LD_FS, "Unable to store router descriptor");
584 tor_free(fname);
585 return -1;
587 desc->saved_location = SAVED_IN_JOURNAL;
588 tor_free(fname);
590 desc->saved_offset = store->journal_len;
591 store->journal_len += len;
593 return 0;
596 /** Sorting helper: return &lt;0, 0, or &gt;0 depending on whether the
597 * signed_descriptor_t* in *<b>a</b> is older, the same age as, or newer than
598 * the signed_descriptor_t* in *<b>b</b>. */
599 static int
600 _compare_signed_descriptors_by_age(const void **_a, const void **_b)
602 const signed_descriptor_t *r1 = *_a, *r2 = *_b;
603 return (int)(r1->published_on - r2->published_on);
606 #define RRS_FORCE 1
607 #define RRS_DONT_REMOVE_OLD 2
609 /** If the journal of <b>store</b> is too long, or if RRS_FORCE is set in
610 * <b>flags</b>, then atomically replace the saved router store with the
611 * routers currently in our routerlist, and clear the journal. Unless
612 * RRS_DONT_REMOVE_OLD is set in <b>flags</b>, delete expired routers before
613 * rebuilding the store. Return 0 on success, -1 on failure.
615 static int
616 router_rebuild_store(int flags, desc_store_t *store)
618 smartlist_t *chunk_list = NULL;
619 char *fname = NULL, *fname_tmp = NULL;
620 int r = -1;
621 off_t offset = 0;
622 smartlist_t *signed_descriptors = NULL;
623 int nocache=0;
624 size_t total_expected_len = 0;
625 int had_any;
626 int force = flags & RRS_FORCE;
628 if (!force && !router_should_rebuild_store(store)) {
629 r = 0;
630 goto done;
632 if (!routerlist) {
633 r = 0;
634 goto done;
637 if (store->type == EXTRAINFO_STORE)
638 had_any = !eimap_isempty(routerlist->extra_info_map);
639 else
640 had_any = (smartlist_len(routerlist->routers)+
641 smartlist_len(routerlist->old_routers))>0;
643 /* Don't save deadweight. */
644 if (!(flags & RRS_DONT_REMOVE_OLD))
645 routerlist_remove_old_routers();
647 log_info(LD_DIR, "Rebuilding %s cache", store->description);
649 fname = get_datadir_fname(store->fname_base);
650 fname_tmp = get_datadir_fname_suffix(store->fname_base, ".tmp");
652 chunk_list = smartlist_create();
654 /* We sort the routers by age to enhance locality on disk. */
655 signed_descriptors = smartlist_create();
656 if (store->type == EXTRAINFO_STORE) {
657 eimap_iter_t *iter;
658 for (iter = eimap_iter_init(routerlist->extra_info_map);
659 !eimap_iter_done(iter);
660 iter = eimap_iter_next(routerlist->extra_info_map, iter)) {
661 const char *key;
662 extrainfo_t *ei;
663 eimap_iter_get(iter, &key, &ei);
664 smartlist_add(signed_descriptors, &ei->cache_info);
666 } else {
667 SMARTLIST_FOREACH(routerlist->old_routers, signed_descriptor_t *, sd,
668 smartlist_add(signed_descriptors, sd));
669 SMARTLIST_FOREACH(routerlist->routers, routerinfo_t *, ri,
670 smartlist_add(signed_descriptors, &ri->cache_info));
673 smartlist_sort(signed_descriptors, _compare_signed_descriptors_by_age);
675 /* Now, add the appropriate members to chunk_list */
676 SMARTLIST_FOREACH(signed_descriptors, signed_descriptor_t *, sd,
678 sized_chunk_t *c;
679 const char *body = signed_descriptor_get_body_impl(sd, 1);
680 if (!body) {
681 log_warn(LD_BUG, "No descriptor available for router.");
682 goto done;
684 if (sd->do_not_cache) {
685 ++nocache;
686 continue;
688 c = tor_malloc(sizeof(sized_chunk_t));
689 c->bytes = body;
690 c->len = sd->signed_descriptor_len + sd->annotations_len;
691 total_expected_len += c->len;
692 smartlist_add(chunk_list, c);
695 if (write_chunks_to_file(fname_tmp, chunk_list, 1)<0) {
696 log_warn(LD_FS, "Error writing router store to disk.");
697 goto done;
700 /* Our mmap is now invalid. */
701 if (store->mmap) {
702 tor_munmap_file(store->mmap);
703 store->mmap = NULL;
706 if (replace_file(fname_tmp, fname)<0) {
707 log_warn(LD_FS, "Error replacing old router store: %s", strerror(errno));
708 goto done;
711 errno = 0;
712 store->mmap = tor_mmap_file(fname);
713 if (! store->mmap) {
714 if (errno == ERANGE) {
715 /* empty store.*/
716 if (total_expected_len) {
717 log_warn(LD_FS, "We wrote some bytes to a new descriptor file at '%s',"
718 " but when we went to mmap it, it was empty!", fname);
719 } else if (had_any) {
720 log_info(LD_FS, "We just removed every descriptor in '%s'. This is "
721 "okay if we're just starting up after a long time. "
722 "Otherwise, it's a bug.", fname);
724 } else {
725 log_warn(LD_FS, "Unable to mmap new descriptor file at '%s'.",fname);
729 log_info(LD_DIR, "Reconstructing pointers into cache");
731 offset = 0;
732 SMARTLIST_FOREACH(signed_descriptors, signed_descriptor_t *, sd,
734 if (sd->do_not_cache)
735 continue;
736 sd->saved_location = SAVED_IN_CACHE;
737 if (store->mmap) {
738 tor_free(sd->signed_descriptor_body); // sets it to null
739 sd->saved_offset = offset;
741 offset += sd->signed_descriptor_len + sd->annotations_len;
742 signed_descriptor_get_body(sd); /* reconstruct and assert */
745 tor_free(fname);
746 fname = get_datadir_fname_suffix(store->fname_base, ".new");
747 write_str_to_file(fname, "", 1);
749 r = 0;
750 store->store_len = (size_t) offset;
751 store->journal_len = 0;
752 store->bytes_dropped = 0;
753 done:
754 if (signed_descriptors)
755 smartlist_free(signed_descriptors);
756 tor_free(fname);
757 tor_free(fname_tmp);
758 if (chunk_list) {
759 SMARTLIST_FOREACH(chunk_list, sized_chunk_t *, c, tor_free(c));
760 smartlist_free(chunk_list);
763 return r;
766 /** Helper: Reload a cache file and its associated journal, setting metadata
767 * appropriately. If <b>extrainfo</b> is true, reload the extrainfo store;
768 * else reload the router descriptor store. */
769 static int
770 router_reload_router_list_impl(desc_store_t *store)
772 char *fname = NULL, *altname = NULL, *contents = NULL;
773 struct stat st;
774 int read_from_old_location = 0;
775 int extrainfo = (store->type == EXTRAINFO_STORE);
776 time_t now = time(NULL);
777 store->journal_len = store->store_len = 0;
779 fname = get_datadir_fname(store->fname_base);
780 if (store->fname_alt_base)
781 altname = get_datadir_fname(store->fname_alt_base);
783 if (store->mmap) /* get rid of it first */
784 tor_munmap_file(store->mmap);
785 store->mmap = NULL;
787 store->mmap = tor_mmap_file(fname);
788 if (!store->mmap && altname && file_status(altname) == FN_FILE) {
789 read_from_old_location = 1;
790 log_notice(LD_DIR, "Couldn't read %s; trying to load routers from old "
791 "location %s.", fname, altname);
792 if ((store->mmap = tor_mmap_file(altname)))
793 read_from_old_location = 1;
795 if (altname && !read_from_old_location) {
796 remove_file_if_very_old(altname, now);
798 if (store->mmap) {
799 store->store_len = store->mmap->size;
800 if (extrainfo)
801 router_load_extrainfo_from_string(store->mmap->data,
802 store->mmap->data+store->mmap->size,
803 SAVED_IN_CACHE, NULL, 0);
804 else
805 router_load_routers_from_string(store->mmap->data,
806 store->mmap->data+store->mmap->size,
807 SAVED_IN_CACHE, NULL, 0, NULL);
810 tor_free(fname);
811 fname = get_datadir_fname_suffix(store->fname_base, ".new");
812 if (file_status(fname) == FN_FILE)
813 contents = read_file_to_str(fname, RFTS_BIN|RFTS_IGNORE_MISSING, &st);
814 if (read_from_old_location) {
815 tor_free(altname);
816 altname = get_datadir_fname_suffix(store->fname_alt_base, ".new");
817 if (!contents)
818 contents = read_file_to_str(altname, RFTS_BIN|RFTS_IGNORE_MISSING, &st);
819 else
820 remove_file_if_very_old(altname, now);
822 if (contents) {
823 if (extrainfo)
824 router_load_extrainfo_from_string(contents, NULL,SAVED_IN_JOURNAL,
825 NULL, 0);
826 else
827 router_load_routers_from_string(contents, NULL, SAVED_IN_JOURNAL,
828 NULL, 0, NULL);
829 store->journal_len = (size_t) st.st_size;
830 tor_free(contents);
833 tor_free(fname);
834 tor_free(altname);
836 if (store->journal_len || read_from_old_location) {
837 /* Always clear the journal on startup.*/
838 router_rebuild_store(RRS_FORCE, store);
839 } else if (!extrainfo) {
840 /* Don't cache expired routers. (This is in an else because
841 * router_rebuild_store() also calls remove_old_routers().) */
842 routerlist_remove_old_routers();
845 return 0;
848 /** Load all cached router descriptors and extra-info documents from the
849 * store. Return 0 on success and -1 on failure.
852 router_reload_router_list(void)
854 routerlist_t *rl = router_get_routerlist();
855 if (router_reload_router_list_impl(&rl->desc_store))
856 return -1;
857 if (router_reload_router_list_impl(&rl->extrainfo_store))
858 return -1;
859 return 0;
862 /** Return a smartlist containing a list of trusted_dir_server_t * for all
863 * known trusted dirservers. Callers must not modify the list or its
864 * contents.
866 smartlist_t *
867 router_get_trusted_dir_servers(void)
869 if (!trusted_dir_servers)
870 trusted_dir_servers = smartlist_create();
872 return trusted_dir_servers;
875 /** Try to find a running dirserver that supports operations of <b>type</b>.
877 * If there are no running dirservers in our routerlist and the
878 * <b>PDS_RETRY_IF_NO_SERVERS</b> flag is set, set all the authoritative ones
879 * as running again, and pick one.
881 * If the <b>PDS_IGNORE_FASCISTFIREWALL</b> flag is set, then include
882 * dirservers that we can't reach.
884 * If the <b>PDS_ALLOW_SELF</b> flag is not set, then don't include ourself
885 * (if we're a dirserver).
887 * Don't pick an authority if any non-authority is viable; try to avoid using
888 * servers that have returned 503 recently.
890 routerstatus_t *
891 router_pick_directory_server(authority_type_t type, int flags)
893 routerstatus_t *choice;
894 if (get_options()->PreferTunneledDirConns)
895 flags |= _PDS_PREFER_TUNNELED_DIR_CONNS;
897 if (!routerlist)
898 return NULL;
900 choice = router_pick_directory_server_impl(type, flags);
901 if (choice || !(flags & PDS_RETRY_IF_NO_SERVERS))
902 return choice;
904 log_info(LD_DIR,
905 "No reachable router entries for dirservers. "
906 "Trying them all again.");
907 /* mark all authdirservers as up again */
908 mark_all_trusteddirservers_up();
909 /* try again */
910 choice = router_pick_directory_server_impl(type, flags);
911 return choice;
914 /** Try to determine which fraction of v2 and v3 directory requests aimed at
915 * caches will be sent to us. Set *<b>v2_share_out</b> and
916 * *<b>v3_share_out</b> to the fractions of v2 and v3 protocol shares we
917 * expect to see, respectively. Return 0 on success, negative on failure. */
919 router_get_my_share_of_directory_requests(double *v2_share_out,
920 double *v3_share_out)
922 routerinfo_t *me = router_get_my_routerinfo();
923 routerstatus_t *rs;
924 const int pds_flags = PDS_ALLOW_SELF|PDS_IGNORE_FASCISTFIREWALL;
925 *v2_share_out = *v3_share_out = 0.0;
926 if (!me)
927 return -1;
928 rs = router_get_consensus_status_by_id(me->cache_info.identity_digest);
929 if (!rs)
930 return -1;
932 /* Calling for side effect */
933 /* XXXX This is a bit of a kludge */
934 if (rs->is_v2_dir) {
935 sl_last_total_weighted_bw = 0;
936 router_pick_directory_server(V2_AUTHORITY, pds_flags);
937 if (sl_last_total_weighted_bw != 0) {
938 *v2_share_out = U64_TO_DBL(sl_last_weighted_bw_of_me) /
939 U64_TO_DBL(sl_last_total_weighted_bw);
943 if (rs->version_supports_v3_dir) {
944 sl_last_total_weighted_bw = 0;
945 router_pick_directory_server(V3_AUTHORITY, pds_flags);
946 if (sl_last_total_weighted_bw != 0) {
947 *v3_share_out = U64_TO_DBL(sl_last_weighted_bw_of_me) /
948 U64_TO_DBL(sl_last_total_weighted_bw);
952 return 0;
955 /** Return the trusted_dir_server_t for the directory authority whose identity
956 * key hashes to <b>digest</b>, or NULL if no such authority is known.
958 trusted_dir_server_t *
959 router_get_trusteddirserver_by_digest(const char *digest)
961 if (!trusted_dir_servers)
962 return NULL;
964 SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, ds,
966 if (!memcmp(ds->digest, digest, DIGEST_LEN))
967 return ds;
970 return NULL;
973 /** Return the trusted_dir_server_t for the directory authority whose identity
974 * key hashes to <b>digest</b>, or NULL if no such authority is known.
976 trusted_dir_server_t *
977 trusteddirserver_get_by_v3_auth_digest(const char *digest)
979 if (!trusted_dir_servers)
980 return NULL;
982 SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, ds,
984 if (!memcmp(ds->v3_identity_digest, digest, DIGEST_LEN) &&
985 (ds->type & V3_AUTHORITY))
986 return ds;
989 return NULL;
992 /** Try to find a running trusted dirserver. Flags are as for
993 * router_pick_directory_server.
995 routerstatus_t *
996 router_pick_trusteddirserver(authority_type_t type, int flags)
998 routerstatus_t *choice;
999 int busy = 0;
1000 if (get_options()->PreferTunneledDirConns)
1001 flags |= _PDS_PREFER_TUNNELED_DIR_CONNS;
1003 choice = router_pick_trusteddirserver_impl(type, flags, &busy);
1004 if (choice || !(flags & PDS_RETRY_IF_NO_SERVERS))
1005 return choice;
1006 if (busy) {
1007 /* If the reason that we got no server is that servers are "busy",
1008 * we must be excluding good servers because we already have serverdesc
1009 * fetches with them. Do not mark down servers up because of this. */
1010 tor_assert((flags & PDS_NO_EXISTING_SERVERDESC_FETCH));
1011 return NULL;
1014 log_info(LD_DIR,
1015 "No trusted dirservers are reachable. Trying them all again.");
1016 mark_all_trusteddirservers_up();
1017 return router_pick_trusteddirserver_impl(type, flags, NULL);
1020 /** How long do we avoid using a directory server after it's given us a 503? */
1021 #define DIR_503_TIMEOUT (60*60)
1023 /** Pick a random running valid directory server/mirror from our
1024 * routerlist. Arguments are as for router_pick_directory_server(), except
1025 * that RETRY_IF_NO_SERVERS is ignored, and:
1027 * If the _PDS_PREFER_TUNNELED_DIR_CONNS flag is set, prefer directory servers
1028 * that we can use with BEGINDIR.
1030 static routerstatus_t *
1031 router_pick_directory_server_impl(authority_type_t type, int flags)
1033 routerstatus_t *result;
1034 smartlist_t *direct, *tunnel;
1035 smartlist_t *trusted_direct, *trusted_tunnel;
1036 smartlist_t *overloaded_direct, *overloaded_tunnel;
1037 time_t now = time(NULL);
1038 const networkstatus_t *consensus = networkstatus_get_latest_consensus();
1039 int requireother = ! (flags & PDS_ALLOW_SELF);
1040 int fascistfirewall = ! (flags & PDS_IGNORE_FASCISTFIREWALL);
1041 int prefer_tunnel = (flags & _PDS_PREFER_TUNNELED_DIR_CONNS);
1043 if (!consensus)
1044 return NULL;
1046 direct = smartlist_create();
1047 tunnel = smartlist_create();
1048 trusted_direct = smartlist_create();
1049 trusted_tunnel = smartlist_create();
1050 overloaded_direct = smartlist_create();
1051 overloaded_tunnel = smartlist_create();
1053 /* Find all the running dirservers we know about. */
1054 SMARTLIST_FOREACH_BEGIN(consensus->routerstatus_list, routerstatus_t *,
1055 status) {
1056 int is_trusted;
1057 int is_overloaded = status->last_dir_503_at + DIR_503_TIMEOUT > now;
1058 tor_addr_t addr;
1059 if (!status->is_running || !status->dir_port || !status->is_valid)
1060 continue;
1061 if (status->is_bad_directory)
1062 continue;
1063 if (requireother && router_digest_is_me(status->identity_digest))
1064 continue;
1065 if (type & V3_AUTHORITY) {
1066 if (!(status->version_supports_v3_dir ||
1067 router_digest_is_trusted_dir_type(status->identity_digest,
1068 V3_AUTHORITY)))
1069 continue;
1071 is_trusted = router_digest_is_trusted_dir(status->identity_digest);
1072 if ((type & V2_AUTHORITY) && !(status->is_v2_dir || is_trusted))
1073 continue;
1074 if ((type & EXTRAINFO_CACHE) &&
1075 !router_supports_extrainfo(status->identity_digest, 0))
1076 continue;
1078 /* XXXX IP6 proposal 118 */
1079 tor_addr_from_ipv4h(&addr, status->addr);
1081 if (prefer_tunnel &&
1082 status->version_supports_begindir &&
1083 (!fascistfirewall ||
1084 fascist_firewall_allows_address_or(&addr, status->or_port)))
1085 smartlist_add(is_trusted ? trusted_tunnel :
1086 is_overloaded ? overloaded_tunnel : tunnel, status);
1087 else if (!fascistfirewall ||
1088 fascist_firewall_allows_address_dir(&addr, status->dir_port))
1089 smartlist_add(is_trusted ? trusted_direct :
1090 is_overloaded ? overloaded_direct : direct, status);
1091 } SMARTLIST_FOREACH_END(status);
1093 if (smartlist_len(tunnel)) {
1094 result = routerstatus_sl_choose_by_bandwidth(tunnel);
1095 } else if (smartlist_len(overloaded_tunnel)) {
1096 result = routerstatus_sl_choose_by_bandwidth(overloaded_tunnel);
1097 } else if (smartlist_len(trusted_tunnel)) {
1098 /* FFFF We don't distinguish between trusteds and overloaded trusteds
1099 * yet. Maybe one day we should. */
1100 /* FFFF We also don't load balance over authorities yet. I think this
1101 * is a feature, but it could easily be a bug. -RD */
1102 result = smartlist_choose(trusted_tunnel);
1103 } else if (smartlist_len(direct)) {
1104 result = routerstatus_sl_choose_by_bandwidth(direct);
1105 } else if (smartlist_len(overloaded_direct)) {
1106 result = routerstatus_sl_choose_by_bandwidth(overloaded_direct);
1107 } else {
1108 result = smartlist_choose(trusted_direct);
1110 smartlist_free(direct);
1111 smartlist_free(tunnel);
1112 smartlist_free(trusted_direct);
1113 smartlist_free(trusted_tunnel);
1114 smartlist_free(overloaded_direct);
1115 smartlist_free(overloaded_tunnel);
1116 return result;
1119 /** Choose randomly from among the trusted dirservers that are up. Flags
1120 * are as for router_pick_directory_server_impl().
1122 static routerstatus_t *
1123 router_pick_trusteddirserver_impl(authority_type_t type, int flags,
1124 int *n_busy_out)
1126 smartlist_t *direct, *tunnel;
1127 smartlist_t *overloaded_direct, *overloaded_tunnel;
1128 routerinfo_t *me = router_get_my_routerinfo();
1129 routerstatus_t *result;
1130 time_t now = time(NULL);
1131 const int requireother = ! (flags & PDS_ALLOW_SELF);
1132 const int fascistfirewall = ! (flags & PDS_IGNORE_FASCISTFIREWALL);
1133 const int prefer_tunnel = (flags & _PDS_PREFER_TUNNELED_DIR_CONNS);
1134 const int no_serverdesc_fetching =(flags & PDS_NO_EXISTING_SERVERDESC_FETCH);
1135 int n_busy = 0;
1137 if (!trusted_dir_servers)
1138 return NULL;
1140 direct = smartlist_create();
1141 tunnel = smartlist_create();
1142 overloaded_direct = smartlist_create();
1143 overloaded_tunnel = smartlist_create();
1145 SMARTLIST_FOREACH_BEGIN(trusted_dir_servers, trusted_dir_server_t *, d)
1147 int is_overloaded =
1148 d->fake_status.last_dir_503_at + DIR_503_TIMEOUT > now;
1149 tor_addr_t addr;
1150 if (!d->is_running) continue;
1151 if ((type & d->type) == 0)
1152 continue;
1153 if ((type & EXTRAINFO_CACHE) &&
1154 !router_supports_extrainfo(d->digest, 1))
1155 continue;
1156 if (requireother && me && router_digest_is_me(d->digest))
1157 continue;
1159 /* XXXX IP6 proposal 118 */
1160 tor_addr_from_ipv4h(&addr, d->addr);
1162 if (no_serverdesc_fetching) {
1163 if (connection_get_by_type_addr_port_purpose(
1164 CONN_TYPE_DIR, &addr, d->dir_port, DIR_PURPOSE_FETCH_SERVERDESC)
1165 || connection_get_by_type_addr_port_purpose(
1166 CONN_TYPE_DIR, &addr, d->dir_port, DIR_PURPOSE_FETCH_EXTRAINFO)) {
1167 //log_debug(LD_DIR, "We have an existing connection to fetch "
1168 // "descriptor from %s; delaying",d->description);
1169 ++n_busy;
1170 continue;
1174 if (prefer_tunnel &&
1175 d->or_port &&
1176 (!fascistfirewall ||
1177 fascist_firewall_allows_address_or(&addr, d->or_port)))
1178 smartlist_add(is_overloaded ? overloaded_tunnel : tunnel,
1179 &d->fake_status);
1180 else if (!fascistfirewall ||
1181 fascist_firewall_allows_address_dir(&addr, d->dir_port))
1182 smartlist_add(is_overloaded ? overloaded_direct : direct,
1183 &d->fake_status);
1185 SMARTLIST_FOREACH_END(d);
1187 if (smartlist_len(tunnel)) {
1188 result = smartlist_choose(tunnel);
1189 } else if (smartlist_len(overloaded_tunnel)) {
1190 result = smartlist_choose(overloaded_tunnel);
1191 } else if (smartlist_len(direct)) {
1192 result = smartlist_choose(direct);
1193 } else {
1194 result = smartlist_choose(overloaded_direct);
1197 if (n_busy_out)
1198 *n_busy_out = n_busy;
1200 smartlist_free(direct);
1201 smartlist_free(tunnel);
1202 smartlist_free(overloaded_direct);
1203 smartlist_free(overloaded_tunnel);
1204 return result;
1207 /** Go through and mark the authoritative dirservers as up. */
1208 static void
1209 mark_all_trusteddirservers_up(void)
1211 if (routerlist) {
1212 SMARTLIST_FOREACH(routerlist->routers, routerinfo_t *, router,
1213 if (router_digest_is_trusted_dir(router->cache_info.identity_digest) &&
1214 router->dir_port > 0) {
1215 router->is_running = 1;
1218 if (trusted_dir_servers) {
1219 SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, dir,
1221 routerstatus_t *rs;
1222 dir->is_running = 1;
1223 download_status_reset(&dir->v2_ns_dl_status);
1224 rs = router_get_consensus_status_by_id(dir->digest);
1225 if (rs && !rs->is_running) {
1226 rs->is_running = 1;
1227 rs->last_dir_503_at = 0;
1228 control_event_networkstatus_changed_single(rs);
1232 router_dir_info_changed();
1235 /** Reset all internal variables used to count failed downloads of network
1236 * status objects. */
1237 void
1238 router_reset_status_download_failures(void)
1240 mark_all_trusteddirservers_up();
1243 /** Return true iff router1 and router2 have the same /16 network. */
1244 static INLINE int
1245 routers_in_same_network_family(routerinfo_t *r1, routerinfo_t *r2)
1247 return (r1->addr & 0xffff0000) == (r2->addr & 0xffff0000);
1250 /** Look through the routerlist and identify routers that
1251 * advertise the same /16 network address as <b>router</b>.
1252 * Add each of them to <b>sl</b>.
1254 static void
1255 routerlist_add_network_family(smartlist_t *sl, routerinfo_t *router)
1257 SMARTLIST_FOREACH(routerlist->routers, routerinfo_t *, r,
1259 if (router != r && routers_in_same_network_family(router, r))
1260 smartlist_add(sl, r);
1264 /** Add all the family of <b>router</b> to the smartlist <b>sl</b>.
1265 * This is used to make sure we don't pick siblings in a single path,
1266 * or pick more than one relay from a family for our entry guard list.
1268 void
1269 routerlist_add_family(smartlist_t *sl, routerinfo_t *router)
1271 routerinfo_t *r;
1272 config_line_t *cl;
1273 or_options_t *options = get_options();
1275 /* First, add any routers with similar network addresses. */
1276 if (options->EnforceDistinctSubnets)
1277 routerlist_add_network_family(sl, router);
1279 if (router->declared_family) {
1280 /* Add every r such that router declares familyness with r, and r
1281 * declares familyhood with router. */
1282 SMARTLIST_FOREACH(router->declared_family, const char *, n,
1284 if (!(r = router_get_by_nickname(n, 0)))
1285 continue;
1286 if (!r->declared_family)
1287 continue;
1288 SMARTLIST_FOREACH(r->declared_family, const char *, n2,
1290 if (router_nickname_matches(router, n2))
1291 smartlist_add(sl, r);
1296 /* If the user declared any families locally, honor those too. */
1297 for (cl = options->NodeFamilies; cl; cl = cl->next) {
1298 if (router_nickname_is_in_list(router, cl->value)) {
1299 add_nickname_list_to_smartlist(sl, cl->value, 0);
1304 /** Return true iff r is named by some nickname in <b>lst</b>. */
1305 static INLINE int
1306 router_in_nickname_smartlist(smartlist_t *lst, routerinfo_t *r)
1308 if (!lst) return 0;
1309 SMARTLIST_FOREACH(lst, const char *, name,
1310 if (router_nickname_matches(r, name))
1311 return 1;);
1312 return 0;
1315 /** Return true iff r1 and r2 are in the same family, but not the same
1316 * router. */
1318 routers_in_same_family(routerinfo_t *r1, routerinfo_t *r2)
1320 or_options_t *options = get_options();
1321 config_line_t *cl;
1323 if (options->EnforceDistinctSubnets && routers_in_same_network_family(r1,r2))
1324 return 1;
1326 if (router_in_nickname_smartlist(r1->declared_family, r2) &&
1327 router_in_nickname_smartlist(r2->declared_family, r1))
1328 return 1;
1330 for (cl = options->NodeFamilies; cl; cl = cl->next) {
1331 if (router_nickname_is_in_list(r1, cl->value) &&
1332 router_nickname_is_in_list(r2, cl->value))
1333 return 1;
1335 return 0;
1338 /** Given a (possibly NULL) comma-and-whitespace separated list of nicknames,
1339 * see which nicknames in <b>list</b> name routers in our routerlist, and add
1340 * the routerinfos for those routers to <b>sl</b>. If <b>must_be_running</b>,
1341 * only include routers that we think are running.
1342 * Warn if any non-Named routers are specified by nickname.
1344 void
1345 add_nickname_list_to_smartlist(smartlist_t *sl, const char *list,
1346 int must_be_running)
1348 routerinfo_t *router;
1349 smartlist_t *nickname_list;
1350 int have_dir_info = router_have_minimum_dir_info();
1352 if (!list)
1353 return; /* nothing to do */
1354 tor_assert(sl);
1356 nickname_list = smartlist_create();
1357 if (!warned_nicknames)
1358 warned_nicknames = smartlist_create();
1360 smartlist_split_string(nickname_list, list, ",",
1361 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
1363 SMARTLIST_FOREACH(nickname_list, const char *, nick, {
1364 int warned;
1365 if (!is_legal_nickname_or_hexdigest(nick)) {
1366 log_warn(LD_CONFIG, "Nickname '%s' is misformed; skipping", nick);
1367 continue;
1369 router = router_get_by_nickname(nick, 1);
1370 warned = smartlist_string_isin(warned_nicknames, nick);
1371 if (router) {
1372 if (!must_be_running || router->is_running) {
1373 smartlist_add(sl,router);
1375 } else if (!router_get_consensus_status_by_nickname(nick,1)) {
1376 if (!warned) {
1377 log_fn(have_dir_info ? LOG_WARN : LOG_INFO, LD_CONFIG,
1378 "Nickname list includes '%s' which isn't a known router.",nick);
1379 smartlist_add(warned_nicknames, tor_strdup(nick));
1383 SMARTLIST_FOREACH(nickname_list, char *, nick, tor_free(nick));
1384 smartlist_free(nickname_list);
1387 /** Return 1 iff any member of the (possibly NULL) comma-separated list
1388 * <b>list</b> is an acceptable nickname or hexdigest for <b>router</b>. Else
1389 * return 0.
1392 router_nickname_is_in_list(routerinfo_t *router, const char *list)
1394 smartlist_t *nickname_list;
1395 int v = 0;
1397 if (!list)
1398 return 0; /* definitely not */
1399 tor_assert(router);
1401 nickname_list = smartlist_create();
1402 smartlist_split_string(nickname_list, list, ",",
1403 SPLIT_SKIP_SPACE|SPLIT_STRIP_SPACE|SPLIT_IGNORE_BLANK, 0);
1404 SMARTLIST_FOREACH(nickname_list, const char *, cp,
1405 if (router_nickname_matches(router, cp)) {v=1;break;});
1406 SMARTLIST_FOREACH(nickname_list, char *, cp, tor_free(cp));
1407 smartlist_free(nickname_list);
1408 return v;
1411 /** Add every suitable router from our routerlist to <b>sl</b>, so that
1412 * we can pick a node for a circuit.
1414 static void
1415 router_add_running_routers_to_smartlist(smartlist_t *sl, int allow_invalid,
1416 int need_uptime, int need_capacity,
1417 int need_guard)
1419 if (!routerlist)
1420 return;
1422 SMARTLIST_FOREACH(routerlist->routers, routerinfo_t *, router,
1424 if (router->is_running &&
1425 router->purpose == ROUTER_PURPOSE_GENERAL &&
1426 (router->is_valid || allow_invalid) &&
1427 !router_is_unreliable(router, need_uptime,
1428 need_capacity, need_guard)) {
1429 /* If it's running, and it's suitable according to the
1430 * other flags we had in mind */
1431 smartlist_add(sl, router);
1436 /** Look through the routerlist until we find a router that has my key.
1437 Return it. */
1438 routerinfo_t *
1439 routerlist_find_my_routerinfo(void)
1441 if (!routerlist)
1442 return NULL;
1444 SMARTLIST_FOREACH(routerlist->routers, routerinfo_t *, router,
1446 if (router_is_me(router))
1447 return router;
1449 return NULL;
1452 /** Find a router that's up, that has this IP address, and
1453 * that allows exit to this address:port, or return NULL if there
1454 * isn't a good one.
1456 routerinfo_t *
1457 router_find_exact_exit_enclave(const char *address, uint16_t port)
1459 uint32_t addr;
1460 struct in_addr in;
1461 tor_addr_t a;
1463 if (!tor_inet_aton(address, &in))
1464 return NULL; /* it's not an IP already */
1465 addr = ntohl(in.s_addr);
1467 tor_addr_from_ipv4h(&a, addr);
1469 SMARTLIST_FOREACH(routerlist->routers, routerinfo_t *, router,
1471 if (router->addr == addr &&
1472 router->is_running &&
1473 compare_tor_addr_to_addr_policy(&a, port, router->exit_policy) ==
1474 ADDR_POLICY_ACCEPTED)
1475 return router;
1477 return NULL;
1480 /** Return 1 if <b>router</b> is not suitable for these parameters, else 0.
1481 * If <b>need_uptime</b> is non-zero, we require a minimum uptime.
1482 * If <b>need_capacity</b> is non-zero, we require a minimum advertised
1483 * bandwidth.
1484 * If <b>need_guard</b>, we require that the router is a possible entry guard.
1487 router_is_unreliable(routerinfo_t *router, int need_uptime,
1488 int need_capacity, int need_guard)
1490 if (need_uptime && !router->is_stable)
1491 return 1;
1492 if (need_capacity && !router->is_fast)
1493 return 1;
1494 if (need_guard && !router->is_possible_guard)
1495 return 1;
1496 return 0;
1499 /** Return the smaller of the router's configured BandwidthRate
1500 * and its advertised capacity. */
1501 uint32_t
1502 router_get_advertised_bandwidth(routerinfo_t *router)
1504 if (router->bandwidthcapacity < router->bandwidthrate)
1505 return router->bandwidthcapacity;
1506 return router->bandwidthrate;
1509 /** Do not weight any declared bandwidth more than this much when picking
1510 * routers by bandwidth. */
1511 #define DEFAULT_MAX_BELIEVABLE_BANDWIDTH 10000000 /* 10 MB/sec */
1513 /** Return the smaller of the router's configured BandwidthRate
1514 * and its advertised capacity, capped by max-believe-bw. */
1515 uint32_t
1516 router_get_advertised_bandwidth_capped(routerinfo_t *router)
1518 uint32_t result = router->bandwidthcapacity;
1519 if (result > router->bandwidthrate)
1520 result = router->bandwidthrate;
1521 if (result > DEFAULT_MAX_BELIEVABLE_BANDWIDTH)
1522 result = DEFAULT_MAX_BELIEVABLE_BANDWIDTH;
1523 return result;
1526 /** Return bw*1000, unless bw*1000 would overflow, in which case return
1527 * INT32_MAX. */
1528 static INLINE int32_t
1529 kb_to_bytes(uint32_t bw)
1531 return (bw > (INT32_MAX/1000)) ? INT32_MAX : bw*1000;
1534 /** Helper function:
1535 * choose a random element of smartlist <b>sl</b>, weighted by
1536 * the advertised bandwidth of each element.
1538 * If <b>statuses</b> is zero, then <b>sl</b> is a list of
1539 * routerinfo_t's. Otherwise it's a list of routerstatus_t's.
1541 * If <b>rule</b>==WEIGHT_FOR_EXIT. we're picking an exit node: consider all
1542 * nodes' bandwidth equally regardless of their Exit status, since there may
1543 * be some in the list because they exit to obscure ports. If
1544 * <b>rule</b>==NO_WEIGHTING, we're picking a non-exit node: weight
1545 * exit-node's bandwidth less depending on the smallness of the fraction of
1546 * Exit-to-total bandwidth. If <b>rule</b>==WEIGHT_FOR_GUARD, we're picking a
1547 * guard node: consider all guard's bandwidth equally. Otherwise, weight
1548 * guards proportionally less.
1550 static void *
1551 smartlist_choose_by_bandwidth(smartlist_t *sl, bandwidth_weight_rule_t rule,
1552 int statuses)
1554 unsigned int i;
1555 routerinfo_t *router;
1556 routerstatus_t *status=NULL;
1557 int32_t *bandwidths;
1558 int is_exit;
1559 int is_guard;
1560 uint64_t total_nonexit_bw = 0, total_exit_bw = 0, total_bw = 0;
1561 uint64_t total_nonguard_bw = 0, total_guard_bw = 0;
1562 uint64_t rand_bw, tmp;
1563 double exit_weight;
1564 double guard_weight;
1565 int n_unknown = 0;
1566 bitarray_t *exit_bits;
1567 bitarray_t *guard_bits;
1568 int me_idx = -1;
1570 /* Can't choose exit and guard at same time */
1571 tor_assert(rule == NO_WEIGHTING ||
1572 rule == WEIGHT_FOR_EXIT ||
1573 rule == WEIGHT_FOR_GUARD);
1575 /* First count the total bandwidth weight, and make a list
1576 * of each value. <0 means "unknown; no routerinfo." We use the
1577 * bits of negative values to remember whether the router was fast (-x)&1
1578 * and whether it was an exit (-x)&2 or guard (-x)&4. Yes, it's a hack. */
1579 bandwidths = tor_malloc(sizeof(int32_t)*smartlist_len(sl));
1580 exit_bits = bitarray_init_zero(smartlist_len(sl));
1581 guard_bits = bitarray_init_zero(smartlist_len(sl));
1583 /* Iterate over all the routerinfo_t or routerstatus_t, and */
1584 for (i = 0; i < (unsigned)smartlist_len(sl); ++i) {
1585 /* first, learn what bandwidth we think i has */
1586 int is_known = 1;
1587 int32_t flags = 0;
1588 uint32_t this_bw = 0;
1589 if (statuses) {
1590 status = smartlist_get(sl, i);
1591 if (router_digest_is_me(status->identity_digest))
1592 me_idx = i;
1593 router = router_get_by_digest(status->identity_digest);
1594 is_exit = status->is_exit;
1595 is_guard = status->is_possible_guard;
1596 if (status->has_bandwidth) {
1597 this_bw = kb_to_bytes(status->bandwidth);
1598 } else { /* guess */
1599 /* XXX022 once consensuses always list bandwidths, we can take
1600 * this guessing business out. -RD */
1601 is_known = 0;
1602 flags = status->is_fast ? 1 : 0;
1603 flags |= is_exit ? 2 : 0;
1604 flags |= is_guard ? 4 : 0;
1606 } else {
1607 routerstatus_t *rs;
1608 router = smartlist_get(sl, i);
1609 rs = router_get_consensus_status_by_id(
1610 router->cache_info.identity_digest);
1611 if (router_digest_is_me(router->cache_info.identity_digest))
1612 me_idx = i;
1613 is_exit = router->is_exit;
1614 is_guard = router->is_possible_guard;
1615 if (rs && rs->has_bandwidth) {
1616 this_bw = kb_to_bytes(rs->bandwidth);
1617 } else if (rs) { /* guess; don't trust the descriptor */
1618 /* XXX022 once consensuses always list bandwidths, we can take
1619 * this guessing business out. -RD */
1620 is_known = 0;
1621 flags = router->is_fast ? 1 : 0;
1622 flags |= is_exit ? 2 : 0;
1623 flags |= is_guard ? 4 : 0;
1624 } else /* bridge or other descriptor not in our consensus */
1625 this_bw = router_get_advertised_bandwidth_capped(router);
1627 if (is_exit)
1628 bitarray_set(exit_bits, i);
1629 if (is_guard)
1630 bitarray_set(guard_bits, i);
1631 if (is_known) {
1632 bandwidths[i] = (int32_t) this_bw; // safe since MAX_BELIEVABLE<INT32_MAX
1633 tor_assert(bandwidths[i] >= 0);
1634 if (is_guard)
1635 total_guard_bw += this_bw;
1636 else
1637 total_nonguard_bw += this_bw;
1638 if (is_exit)
1639 total_exit_bw += this_bw;
1640 else
1641 total_nonexit_bw += this_bw;
1642 } else {
1643 ++n_unknown;
1644 bandwidths[i] = -flags;
1648 /* Now, fill in the unknown values. */
1649 if (n_unknown) {
1650 int32_t avg_fast, avg_slow;
1651 if (total_exit_bw+total_nonexit_bw) {
1652 /* if there's some bandwidth, there's at least one known router,
1653 * so no worries about div by 0 here */
1654 int n_known = smartlist_len(sl)-n_unknown;
1655 avg_fast = avg_slow = (int32_t)
1656 ((total_exit_bw+total_nonexit_bw)/((uint64_t) n_known));
1657 } else {
1658 avg_fast = 40000;
1659 avg_slow = 20000;
1661 for (i=0; i<(unsigned)smartlist_len(sl); ++i) {
1662 int32_t bw = bandwidths[i];
1663 if (bw>=0)
1664 continue;
1665 is_exit = ((-bw)&2);
1666 is_guard = ((-bw)&4);
1667 bandwidths[i] = ((-bw)&1) ? avg_fast : avg_slow;
1668 if (is_exit)
1669 total_exit_bw += bandwidths[i];
1670 else
1671 total_nonexit_bw += bandwidths[i];
1672 if (is_guard)
1673 total_guard_bw += bandwidths[i];
1674 else
1675 total_nonguard_bw += bandwidths[i];
1679 /* If there's no bandwidth at all, pick at random. */
1680 if (!(total_exit_bw+total_nonexit_bw)) {
1681 tor_free(bandwidths);
1682 tor_free(exit_bits);
1683 tor_free(guard_bits);
1684 return smartlist_choose(sl);
1687 /* Figure out how to weight exits and guards */
1689 double all_bw = U64_TO_DBL(total_exit_bw+total_nonexit_bw);
1690 double exit_bw = U64_TO_DBL(total_exit_bw);
1691 double guard_bw = U64_TO_DBL(total_guard_bw);
1693 * For detailed derivation of this formula, see
1694 * http://archives.seul.org/or/dev/Jul-2007/msg00056.html
1696 if (rule == WEIGHT_FOR_EXIT)
1697 exit_weight = 1.0;
1698 else
1699 exit_weight = 1.0 - all_bw/(3.0*exit_bw);
1701 if (rule == WEIGHT_FOR_GUARD)
1702 guard_weight = 1.0;
1703 else
1704 guard_weight = 1.0 - all_bw/(3.0*guard_bw);
1706 if (exit_weight <= 0.0)
1707 exit_weight = 0.0;
1709 if (guard_weight <= 0.0)
1710 guard_weight = 0.0;
1712 total_bw = 0;
1713 sl_last_weighted_bw_of_me = 0;
1714 for (i=0; i < (unsigned)smartlist_len(sl); i++) {
1715 uint64_t bw;
1716 is_exit = bitarray_is_set(exit_bits, i);
1717 is_guard = bitarray_is_set(guard_bits, i);
1718 if (is_exit && is_guard)
1719 bw = ((uint64_t)(bandwidths[i] * exit_weight * guard_weight));
1720 else if (is_guard)
1721 bw = ((uint64_t)(bandwidths[i] * guard_weight));
1722 else if (is_exit)
1723 bw = ((uint64_t)(bandwidths[i] * exit_weight));
1724 else
1725 bw = bandwidths[i];
1726 total_bw += bw;
1727 if (i == (unsigned) me_idx)
1728 sl_last_weighted_bw_of_me = bw;
1732 /* XXXX022 this is a kludge to expose these values. */
1733 sl_last_total_weighted_bw = total_bw;
1735 log_debug(LD_CIRC, "Total weighted bw = "U64_FORMAT
1736 ", exit bw = "U64_FORMAT
1737 ", nonexit bw = "U64_FORMAT", exit weight = %lf "
1738 "(for exit == %d)"
1739 ", guard bw = "U64_FORMAT
1740 ", nonguard bw = "U64_FORMAT", guard weight = %lf "
1741 "(for guard == %d)",
1742 U64_PRINTF_ARG(total_bw),
1743 U64_PRINTF_ARG(total_exit_bw), U64_PRINTF_ARG(total_nonexit_bw),
1744 exit_weight, (int)(rule == WEIGHT_FOR_EXIT),
1745 U64_PRINTF_ARG(total_guard_bw), U64_PRINTF_ARG(total_nonguard_bw),
1746 guard_weight, (int)(rule == WEIGHT_FOR_GUARD));
1748 /* Almost done: choose a random value from the bandwidth weights. */
1749 rand_bw = crypto_rand_uint64(total_bw);
1751 /* Last, count through sl until we get to the element we picked */
1752 tmp = 0;
1753 for (i=0; i < (unsigned)smartlist_len(sl); i++) {
1754 is_exit = bitarray_is_set(exit_bits, i);
1755 is_guard = bitarray_is_set(guard_bits, i);
1757 /* Weights can be 0 if not counting guards/exits */
1758 if (is_exit && is_guard)
1759 tmp += ((uint64_t)(bandwidths[i] * exit_weight * guard_weight));
1760 else if (is_guard)
1761 tmp += ((uint64_t)(bandwidths[i] * guard_weight));
1762 else if (is_exit)
1763 tmp += ((uint64_t)(bandwidths[i] * exit_weight));
1764 else
1765 tmp += bandwidths[i];
1767 if (tmp >= rand_bw)
1768 break;
1770 if (i == (unsigned)smartlist_len(sl)) {
1771 /* This was once possible due to round-off error, but shouldn't be able
1772 * to occur any longer. */
1773 tor_fragile_assert();
1774 --i;
1775 log_warn(LD_BUG, "Round-off error in computing bandwidth had an effect on "
1776 " which router we chose. Please tell the developers. "
1777 U64_FORMAT " " U64_FORMAT " " U64_FORMAT, U64_PRINTF_ARG(tmp),
1778 U64_PRINTF_ARG(rand_bw), U64_PRINTF_ARG(total_bw));
1780 tor_free(bandwidths);
1781 tor_free(exit_bits);
1782 tor_free(guard_bits);
1783 return smartlist_get(sl, i);
1786 /** Choose a random element of router list <b>sl</b>, weighted by
1787 * the advertised bandwidth of each router.
1789 routerinfo_t *
1790 routerlist_sl_choose_by_bandwidth(smartlist_t *sl,
1791 bandwidth_weight_rule_t rule)
1793 return smartlist_choose_by_bandwidth(sl, rule, 0);
1796 /** Choose a random element of status list <b>sl</b>, weighted by
1797 * the advertised bandwidth of each status.
1799 routerstatus_t *
1800 routerstatus_sl_choose_by_bandwidth(smartlist_t *sl)
1802 /* We are choosing neither exit nor guard here. Weight accordingly. */
1803 return smartlist_choose_by_bandwidth(sl, NO_WEIGHTING, 1);
1806 /** Return a random running router from the routerlist. If any node
1807 * named in <b>preferred</b> is available, pick one of those. Never
1808 * pick a node whose routerinfo is in
1809 * <b>excludedsmartlist</b>, or whose routerinfo matches <b>excludedset</b>,
1810 * even if they are the only nodes
1811 * available. If <b>CRN_STRICT_PREFERRED</b> is set in flags, never pick
1812 * any node besides those in <b>preferred</b>.
1813 * If <b>CRN_NEED_UPTIME</b> is set in flags and any router has more than
1814 * a minimum uptime, return one of those.
1815 * If <b>CRN_NEED_CAPACITY</b> is set in flags, weight your choice by the
1816 * advertised capacity of each router.
1817 * If <b>CRN_ALLOW_INVALID</b> is not set in flags, consider only Valid
1818 * routers.
1819 * If <b>CRN_NEED_GUARD</b> is set in flags, consider only Guard routers.
1820 * If <b>CRN_WEIGHT_AS_EXIT</b> is set in flags, we weight bandwidths as if
1821 * picking an exit node, otherwise we weight bandwidths for picking a relay
1822 * node (that is, possibly discounting exit nodes).
1824 routerinfo_t *
1825 router_choose_random_node(const char *preferred,
1826 smartlist_t *excludedsmartlist,
1827 routerset_t *excludedset,
1828 router_crn_flags_t flags)
1830 const int need_uptime = (flags & CRN_NEED_UPTIME) != 0;
1831 const int need_capacity = (flags & CRN_NEED_CAPACITY) != 0;
1832 const int need_guard = (flags & CRN_NEED_GUARD) != 0;
1833 const int allow_invalid = (flags & CRN_ALLOW_INVALID) != 0;
1834 const int strict = (flags & CRN_STRICT_PREFERRED) != 0;
1835 const int weight_for_exit = (flags & CRN_WEIGHT_AS_EXIT) != 0;
1837 smartlist_t *sl, *excludednodes;
1838 routerinfo_t *choice = NULL, *r;
1839 bandwidth_weight_rule_t rule;
1841 tor_assert(!(weight_for_exit && need_guard));
1842 rule = weight_for_exit ? WEIGHT_FOR_EXIT :
1843 (need_guard ? WEIGHT_FOR_GUARD : NO_WEIGHTING);
1845 excludednodes = smartlist_create();
1847 /* Exclude relays that allow single hop exit circuits, if the user
1848 * wants to (such relays might be risky) */
1849 if (get_options()->ExcludeSingleHopRelays) {
1850 routerlist_t *rl = router_get_routerlist();
1851 SMARTLIST_FOREACH(rl->routers, routerinfo_t *, r,
1852 if (r->allow_single_hop_exits) {
1853 smartlist_add(excludednodes, r);
1857 if ((r = routerlist_find_my_routerinfo())) {
1858 smartlist_add(excludednodes, r);
1859 routerlist_add_family(excludednodes, r);
1862 /* Try the preferred nodes first. Ignore need_uptime and need_capacity
1863 * and need_guard, since the user explicitly asked for these nodes. */
1864 if (preferred) {
1865 sl = smartlist_create();
1866 add_nickname_list_to_smartlist(sl,preferred,1);
1867 smartlist_subtract(sl,excludednodes);
1868 if (excludedsmartlist)
1869 smartlist_subtract(sl,excludedsmartlist);
1870 if (excludedset)
1871 routerset_subtract_routers(sl,excludedset);
1872 choice = smartlist_choose(sl);
1873 smartlist_free(sl);
1875 if (!choice && !strict) {
1876 /* Then give up on our preferred choices: any node
1877 * will do that has the required attributes. */
1878 sl = smartlist_create();
1879 router_add_running_routers_to_smartlist(sl, allow_invalid,
1880 need_uptime, need_capacity,
1881 need_guard);
1882 smartlist_subtract(sl,excludednodes);
1883 if (excludedsmartlist)
1884 smartlist_subtract(sl,excludedsmartlist);
1885 if (excludedset)
1886 routerset_subtract_routers(sl,excludedset);
1888 if (need_capacity || need_guard)
1889 choice = routerlist_sl_choose_by_bandwidth(sl, rule);
1890 else
1891 choice = smartlist_choose(sl);
1893 smartlist_free(sl);
1894 if (!choice && (need_uptime || need_capacity || need_guard)) {
1895 /* try once more -- recurse but with fewer restrictions. */
1896 log_info(LD_CIRC,
1897 "We couldn't find any live%s%s%s routers; falling back "
1898 "to list of all routers.",
1899 need_capacity?", fast":"",
1900 need_uptime?", stable":"",
1901 need_guard?", guard":"");
1902 flags &= ~ (CRN_NEED_UPTIME|CRN_NEED_CAPACITY|CRN_NEED_GUARD);
1903 choice = router_choose_random_node(
1904 NULL, excludedsmartlist, excludedset, flags);
1907 smartlist_free(excludednodes);
1908 if (!choice) {
1909 if (strict) {
1910 log_warn(LD_CIRC, "All preferred nodes were down when trying to choose "
1911 "node, and the Strict[...]Nodes option is set. Failing.");
1912 } else {
1913 log_warn(LD_CIRC,
1914 "No available nodes when trying to choose node. Failing.");
1917 return choice;
1920 /** Helper: Return true iff the <b>identity_digest</b> and <b>nickname</b>
1921 * combination of a router, encoded in hexadecimal, matches <b>hexdigest</b>
1922 * (which is optionally prefixed with a single dollar sign). Return false if
1923 * <b>hexdigest</b> is malformed, or it doesn't match. */
1924 static INLINE int
1925 hex_digest_matches(const char *hexdigest, const char *identity_digest,
1926 const char *nickname, int is_named)
1928 char digest[DIGEST_LEN];
1929 size_t len;
1930 tor_assert(hexdigest);
1931 if (hexdigest[0] == '$')
1932 ++hexdigest;
1934 len = strlen(hexdigest);
1935 if (len < HEX_DIGEST_LEN)
1936 return 0;
1937 else if (len > HEX_DIGEST_LEN &&
1938 (hexdigest[HEX_DIGEST_LEN] == '=' ||
1939 hexdigest[HEX_DIGEST_LEN] == '~')) {
1940 if (strcasecmp(hexdigest+HEX_DIGEST_LEN+1, nickname))
1941 return 0;
1942 if (hexdigest[HEX_DIGEST_LEN] == '=' && !is_named)
1943 return 0;
1946 if (base16_decode(digest, DIGEST_LEN, hexdigest, HEX_DIGEST_LEN)<0)
1947 return 0;
1948 return (!memcmp(digest, identity_digest, DIGEST_LEN));
1951 /** Return true iff the digest of <b>router</b>'s identity key,
1952 * encoded in hexadecimal, matches <b>hexdigest</b> (which is
1953 * optionally prefixed with a single dollar sign). Return false if
1954 * <b>hexdigest</b> is malformed, or it doesn't match. */
1955 static INLINE int
1956 router_hex_digest_matches(routerinfo_t *router, const char *hexdigest)
1958 return hex_digest_matches(hexdigest, router->cache_info.identity_digest,
1959 router->nickname, router->is_named);
1962 /** Return true if <b>router</b>'s nickname matches <b>nickname</b>
1963 * (case-insensitive), or if <b>router's</b> identity key digest
1964 * matches a hexadecimal value stored in <b>nickname</b>. Return
1965 * false otherwise. */
1966 static int
1967 router_nickname_matches(routerinfo_t *router, const char *nickname)
1969 if (nickname[0]!='$' && !strcasecmp(router->nickname, nickname))
1970 return 1;
1971 return router_hex_digest_matches(router, nickname);
1974 /** Return the router in our routerlist whose (case-insensitive)
1975 * nickname or (case-sensitive) hexadecimal key digest is
1976 * <b>nickname</b>. Return NULL if no such router is known.
1978 routerinfo_t *
1979 router_get_by_nickname(const char *nickname, int warn_if_unnamed)
1981 int maybedigest;
1982 char digest[DIGEST_LEN];
1983 routerinfo_t *best_match=NULL;
1984 int n_matches = 0;
1985 const char *named_digest = NULL;
1987 tor_assert(nickname);
1988 if (!routerlist)
1989 return NULL;
1990 if (nickname[0] == '$')
1991 return router_get_by_hexdigest(nickname);
1992 if (!strcasecmp(nickname, UNNAMED_ROUTER_NICKNAME))
1993 return NULL;
1994 if (server_mode(get_options()) &&
1995 !strcasecmp(nickname, get_options()->Nickname))
1996 return router_get_my_routerinfo();
1998 maybedigest = (strlen(nickname) >= HEX_DIGEST_LEN) &&
1999 (base16_decode(digest,DIGEST_LEN,nickname,HEX_DIGEST_LEN) == 0);
2001 if ((named_digest = networkstatus_get_router_digest_by_nickname(nickname))) {
2002 return rimap_get(routerlist->identity_map, named_digest);
2004 if (networkstatus_nickname_is_unnamed(nickname))
2005 return NULL;
2007 /* If we reach this point, there's no canonical value for the nickname. */
2009 SMARTLIST_FOREACH(routerlist->routers, routerinfo_t *, router,
2011 if (!strcasecmp(router->nickname, nickname)) {
2012 ++n_matches;
2013 if (n_matches <= 1 || router->is_running)
2014 best_match = router;
2015 } else if (maybedigest &&
2016 !memcmp(digest, router->cache_info.identity_digest, DIGEST_LEN)
2018 if (router_hex_digest_matches(router, nickname))
2019 return router;
2020 /* If we reach this point, we have a ID=name syntax that matches the
2021 * identity but not the name. That isn't an acceptable match. */
2025 if (best_match) {
2026 if (warn_if_unnamed && n_matches > 1) {
2027 smartlist_t *fps = smartlist_create();
2028 int any_unwarned = 0;
2029 SMARTLIST_FOREACH(routerlist->routers, routerinfo_t *, router,
2031 routerstatus_t *rs;
2032 char *desc;
2033 size_t dlen;
2034 char fp[HEX_DIGEST_LEN+1];
2035 if (strcasecmp(router->nickname, nickname))
2036 continue;
2037 rs = router_get_consensus_status_by_id(
2038 router->cache_info.identity_digest);
2039 if (rs && !rs->name_lookup_warned) {
2040 rs->name_lookup_warned = 1;
2041 any_unwarned = 1;
2043 base16_encode(fp, sizeof(fp),
2044 router->cache_info.identity_digest, DIGEST_LEN);
2045 dlen = 32 + HEX_DIGEST_LEN + strlen(router->address);
2046 desc = tor_malloc(dlen);
2047 tor_snprintf(desc, dlen, "\"$%s\" for the one at %s:%d",
2048 fp, router->address, router->or_port);
2049 smartlist_add(fps, desc);
2051 if (any_unwarned) {
2052 char *alternatives = smartlist_join_strings(fps, "; ",0,NULL);
2053 log_warn(LD_CONFIG,
2054 "There are multiple matches for the nickname \"%s\","
2055 " but none is listed as named by the directory authorities. "
2056 "Choosing one arbitrarily. If you meant one in particular, "
2057 "you should say %s.", nickname, alternatives);
2058 tor_free(alternatives);
2060 SMARTLIST_FOREACH(fps, char *, cp, tor_free(cp));
2061 smartlist_free(fps);
2062 } else if (warn_if_unnamed) {
2063 routerstatus_t *rs = router_get_consensus_status_by_id(
2064 best_match->cache_info.identity_digest);
2065 if (rs && !rs->name_lookup_warned) {
2066 char fp[HEX_DIGEST_LEN+1];
2067 base16_encode(fp, sizeof(fp),
2068 best_match->cache_info.identity_digest, DIGEST_LEN);
2069 log_warn(LD_CONFIG, "You specified a server \"%s\" by name, but this "
2070 "name is not registered, so it could be used by any server, "
2071 "not just the one you meant. "
2072 "To make sure you get the same server in the future, refer to "
2073 "it by key, as \"$%s\".", nickname, fp);
2074 rs->name_lookup_warned = 1;
2077 return best_match;
2080 return NULL;
2083 /** Try to find a routerinfo for <b>digest</b>. If we don't have one,
2084 * return 1. If we do, ask tor_version_as_new_as() for the answer.
2087 router_digest_version_as_new_as(const char *digest, const char *cutoff)
2089 routerinfo_t *router = router_get_by_digest(digest);
2090 if (!router)
2091 return 1;
2092 return tor_version_as_new_as(router->platform, cutoff);
2095 /** Return true iff <b>digest</b> is the digest of the identity key of a
2096 * trusted directory matching at least one bit of <b>type</b>. If <b>type</b>
2097 * is zero, any authority is okay. */
2099 router_digest_is_trusted_dir_type(const char *digest, authority_type_t type)
2101 if (!trusted_dir_servers)
2102 return 0;
2103 if (authdir_mode(get_options()) && router_digest_is_me(digest))
2104 return 1;
2105 SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, ent,
2106 if (!memcmp(digest, ent->digest, DIGEST_LEN)) {
2107 return (!type) || ((type & ent->type) != 0);
2109 return 0;
2112 /** Return true iff <b>addr</b> is the address of one of our trusted
2113 * directory authorities. */
2115 router_addr_is_trusted_dir(uint32_t addr)
2117 if (!trusted_dir_servers)
2118 return 0;
2119 SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, ent,
2120 if (ent->addr == addr)
2121 return 1;
2123 return 0;
2126 /** If hexdigest is correctly formed, base16_decode it into
2127 * digest, which must have DIGEST_LEN space in it.
2128 * Return 0 on success, -1 on failure.
2131 hexdigest_to_digest(const char *hexdigest, char *digest)
2133 if (hexdigest[0]=='$')
2134 ++hexdigest;
2135 if (strlen(hexdigest) < HEX_DIGEST_LEN ||
2136 base16_decode(digest,DIGEST_LEN,hexdigest,HEX_DIGEST_LEN) < 0)
2137 return -1;
2138 return 0;
2141 /** Return the router in our routerlist whose hexadecimal key digest
2142 * is <b>hexdigest</b>. Return NULL if no such router is known. */
2143 routerinfo_t *
2144 router_get_by_hexdigest(const char *hexdigest)
2146 char digest[DIGEST_LEN];
2147 size_t len;
2148 routerinfo_t *ri;
2150 tor_assert(hexdigest);
2151 if (!routerlist)
2152 return NULL;
2153 if (hexdigest[0]=='$')
2154 ++hexdigest;
2155 len = strlen(hexdigest);
2156 if (hexdigest_to_digest(hexdigest, digest) < 0)
2157 return NULL;
2159 ri = router_get_by_digest(digest);
2161 if (ri && len > HEX_DIGEST_LEN) {
2162 if (hexdigest[HEX_DIGEST_LEN] == '=') {
2163 if (strcasecmp(ri->nickname, hexdigest+HEX_DIGEST_LEN+1) ||
2164 !ri->is_named)
2165 return NULL;
2166 } else if (hexdigest[HEX_DIGEST_LEN] == '~') {
2167 if (strcasecmp(ri->nickname, hexdigest+HEX_DIGEST_LEN+1))
2168 return NULL;
2169 } else {
2170 return NULL;
2174 return ri;
2177 /** Return the router in our routerlist whose 20-byte key digest
2178 * is <b>digest</b>. Return NULL if no such router is known. */
2179 routerinfo_t *
2180 router_get_by_digest(const char *digest)
2182 tor_assert(digest);
2184 if (!routerlist) return NULL;
2186 // routerlist_assert_ok(routerlist);
2188 return rimap_get(routerlist->identity_map, digest);
2191 /** Return the router in our routerlist whose 20-byte descriptor
2192 * is <b>digest</b>. Return NULL if no such router is known. */
2193 signed_descriptor_t *
2194 router_get_by_descriptor_digest(const char *digest)
2196 tor_assert(digest);
2198 if (!routerlist) return NULL;
2200 return sdmap_get(routerlist->desc_digest_map, digest);
2203 /** Return the signed descriptor for the router in our routerlist whose
2204 * 20-byte extra-info digest is <b>digest</b>. Return NULL if no such router
2205 * is known. */
2206 signed_descriptor_t *
2207 router_get_by_extrainfo_digest(const char *digest)
2209 tor_assert(digest);
2211 if (!routerlist) return NULL;
2213 return sdmap_get(routerlist->desc_by_eid_map, digest);
2216 /** Return the signed descriptor for the extrainfo_t in our routerlist whose
2217 * extra-info-digest is <b>digest</b>. Return NULL if no such extra-info
2218 * document is known. */
2219 signed_descriptor_t *
2220 extrainfo_get_by_descriptor_digest(const char *digest)
2222 extrainfo_t *ei;
2223 tor_assert(digest);
2224 if (!routerlist) return NULL;
2225 ei = eimap_get(routerlist->extra_info_map, digest);
2226 return ei ? &ei->cache_info : NULL;
2229 /** Return a pointer to the signed textual representation of a descriptor.
2230 * The returned string is not guaranteed to be NUL-terminated: the string's
2231 * length will be in desc-\>signed_descriptor_len.
2233 * If <b>with_annotations</b> is set, the returned string will include
2234 * the annotations
2235 * (if any) preceding the descriptor. This will increase the length of the
2236 * string by desc-\>annotations_len.
2238 * The caller must not free the string returned.
2240 static const char *
2241 signed_descriptor_get_body_impl(signed_descriptor_t *desc,
2242 int with_annotations)
2244 const char *r = NULL;
2245 size_t len = desc->signed_descriptor_len;
2246 off_t offset = desc->saved_offset;
2247 if (with_annotations)
2248 len += desc->annotations_len;
2249 else
2250 offset += desc->annotations_len;
2252 tor_assert(len > 32);
2253 if (desc->saved_location == SAVED_IN_CACHE && routerlist) {
2254 desc_store_t *store = desc_get_store(router_get_routerlist(), desc);
2255 if (store && store->mmap) {
2256 tor_assert(desc->saved_offset + len <= store->mmap->size);
2257 r = store->mmap->data + offset;
2258 } else if (store) {
2259 log_err(LD_DIR, "We couldn't read a descriptor that is supposedly "
2260 "mmaped in our cache. Is another process running in our data "
2261 "directory? Exiting.");
2262 exit(1);
2265 if (!r) /* no mmap, or not in cache. */
2266 r = desc->signed_descriptor_body +
2267 (with_annotations ? 0 : desc->annotations_len);
2269 tor_assert(r);
2270 if (!with_annotations) {
2271 if (memcmp("router ", r, 7) && memcmp("extra-info ", r, 11)) {
2272 char *cp = tor_strndup(r, 64);
2273 log_err(LD_DIR, "descriptor at %p begins with unexpected string %s. "
2274 "Is another process running in our data directory? Exiting.",
2275 desc, escaped(cp));
2276 exit(1);
2280 return r;
2283 /** Return a pointer to the signed textual representation of a descriptor.
2284 * The returned string is not guaranteed to be NUL-terminated: the string's
2285 * length will be in desc-\>signed_descriptor_len.
2287 * The caller must not free the string returned.
2289 const char *
2290 signed_descriptor_get_body(signed_descriptor_t *desc)
2292 return signed_descriptor_get_body_impl(desc, 0);
2295 /** As signed_descriptor_get_body(), but points to the beginning of the
2296 * annotations section rather than the beginning of the descriptor. */
2297 const char *
2298 signed_descriptor_get_annotations(signed_descriptor_t *desc)
2300 return signed_descriptor_get_body_impl(desc, 1);
2303 /** Return the current list of all known routers. */
2304 routerlist_t *
2305 router_get_routerlist(void)
2307 if (PREDICT_UNLIKELY(!routerlist)) {
2308 routerlist = tor_malloc_zero(sizeof(routerlist_t));
2309 routerlist->routers = smartlist_create();
2310 routerlist->old_routers = smartlist_create();
2311 routerlist->identity_map = rimap_new();
2312 routerlist->desc_digest_map = sdmap_new();
2313 routerlist->desc_by_eid_map = sdmap_new();
2314 routerlist->extra_info_map = eimap_new();
2316 routerlist->desc_store.fname_base = "cached-descriptors";
2317 routerlist->desc_store.fname_alt_base = "cached-routers";
2318 routerlist->extrainfo_store.fname_base = "cached-extrainfo";
2320 routerlist->desc_store.type = ROUTER_STORE;
2321 routerlist->extrainfo_store.type = EXTRAINFO_STORE;
2323 routerlist->desc_store.description = "router descriptors";
2324 routerlist->extrainfo_store.description = "extra-info documents";
2326 return routerlist;
2329 /** Free all storage held by <b>router</b>. */
2330 void
2331 routerinfo_free(routerinfo_t *router)
2333 if (!router)
2334 return;
2336 tor_free(router->cache_info.signed_descriptor_body);
2337 tor_free(router->address);
2338 tor_free(router->nickname);
2339 tor_free(router->platform);
2340 tor_free(router->contact_info);
2341 if (router->onion_pkey)
2342 crypto_free_pk_env(router->onion_pkey);
2343 if (router->identity_pkey)
2344 crypto_free_pk_env(router->identity_pkey);
2345 if (router->declared_family) {
2346 SMARTLIST_FOREACH(router->declared_family, char *, s, tor_free(s));
2347 smartlist_free(router->declared_family);
2349 addr_policy_list_free(router->exit_policy);
2351 /* XXXX Remove if this turns out to affect performance. */
2352 memset(router, 77, sizeof(routerinfo_t));
2354 tor_free(router);
2357 /** Release all storage held by <b>extrainfo</b> */
2358 void
2359 extrainfo_free(extrainfo_t *extrainfo)
2361 if (!extrainfo)
2362 return;
2363 tor_free(extrainfo->cache_info.signed_descriptor_body);
2364 tor_free(extrainfo->pending_sig);
2366 /* XXXX remove this if it turns out to slow us down. */
2367 memset(extrainfo, 88, sizeof(extrainfo_t)); /* debug bad memory usage */
2368 tor_free(extrainfo);
2371 /** Release storage held by <b>sd</b>. */
2372 static void
2373 signed_descriptor_free(signed_descriptor_t *sd)
2375 tor_free(sd->signed_descriptor_body);
2377 /* XXXX remove this once more bugs go away. */
2378 memset(sd, 99, sizeof(signed_descriptor_t)); /* Debug bad mem usage */
2379 tor_free(sd);
2382 /** Extract a signed_descriptor_t from a routerinfo, and free the routerinfo.
2384 static signed_descriptor_t *
2385 signed_descriptor_from_routerinfo(routerinfo_t *ri)
2387 signed_descriptor_t *sd = tor_malloc_zero(sizeof(signed_descriptor_t));
2388 memcpy(sd, &(ri->cache_info), sizeof(signed_descriptor_t));
2389 sd->routerlist_index = -1;
2390 ri->cache_info.signed_descriptor_body = NULL;
2391 routerinfo_free(ri);
2392 return sd;
2395 /** Helper: free the storage held by the extrainfo_t in <b>e</b>. */
2396 static void
2397 _extrainfo_free(void *e)
2399 extrainfo_free(e);
2402 /** Free all storage held by a routerlist <b>rl</b>. */
2403 void
2404 routerlist_free(routerlist_t *rl)
2406 tor_assert(rl);
2407 rimap_free(rl->identity_map, NULL);
2408 sdmap_free(rl->desc_digest_map, NULL);
2409 sdmap_free(rl->desc_by_eid_map, NULL);
2410 eimap_free(rl->extra_info_map, _extrainfo_free);
2411 SMARTLIST_FOREACH(rl->routers, routerinfo_t *, r,
2412 routerinfo_free(r));
2413 SMARTLIST_FOREACH(rl->old_routers, signed_descriptor_t *, sd,
2414 signed_descriptor_free(sd));
2415 smartlist_free(rl->routers);
2416 smartlist_free(rl->old_routers);
2417 if (routerlist->desc_store.mmap)
2418 tor_munmap_file(routerlist->desc_store.mmap);
2419 if (routerlist->extrainfo_store.mmap)
2420 tor_munmap_file(routerlist->extrainfo_store.mmap);
2421 tor_free(rl);
2423 router_dir_info_changed();
2426 /** Log information about how much memory is being used for routerlist,
2427 * at log level <b>severity</b>. */
2428 void
2429 dump_routerlist_mem_usage(int severity)
2431 uint64_t livedescs = 0;
2432 uint64_t olddescs = 0;
2433 if (!routerlist)
2434 return;
2435 SMARTLIST_FOREACH(routerlist->routers, routerinfo_t *, r,
2436 livedescs += r->cache_info.signed_descriptor_len);
2437 SMARTLIST_FOREACH(routerlist->old_routers, signed_descriptor_t *, sd,
2438 olddescs += sd->signed_descriptor_len);
2440 log(severity, LD_DIR,
2441 "In %d live descriptors: "U64_FORMAT" bytes. "
2442 "In %d old descriptors: "U64_FORMAT" bytes.",
2443 smartlist_len(routerlist->routers), U64_PRINTF_ARG(livedescs),
2444 smartlist_len(routerlist->old_routers), U64_PRINTF_ARG(olddescs));
2446 #if 0
2448 const smartlist_t *networkstatus_v2_list = networkstatus_get_v2_list();
2449 networkstatus_t *consensus = networkstatus_get_latest_consensus();
2450 log(severity, LD_DIR, "Now let's look through old_descriptors!");
2451 SMARTLIST_FOREACH(routerlist->old_routers, signed_descriptor_t *, sd, {
2452 int in_v2 = 0;
2453 int in_v3 = 0;
2454 char published[ISO_TIME_LEN+1];
2455 char last_valid_until[ISO_TIME_LEN+1];
2456 char last_served_at[ISO_TIME_LEN+1];
2457 char id[HEX_DIGEST_LEN+1];
2458 routerstatus_t *rs;
2459 format_iso_time(published, sd->published_on);
2460 format_iso_time(last_valid_until, sd->last_listed_as_valid_until);
2461 format_iso_time(last_served_at, sd->last_served_at);
2462 base16_encode(id, sizeof(id), sd->identity_digest, DIGEST_LEN);
2463 SMARTLIST_FOREACH(networkstatus_v2_list, networkstatus_v2_t *, ns,
2465 rs = networkstatus_v2_find_entry(ns, sd->identity_digest);
2466 if (rs && !memcmp(rs->descriptor_digest,
2467 sd->signed_descriptor_digest, DIGEST_LEN)) {
2468 in_v2 = 1; break;
2471 if (consensus) {
2472 rs = networkstatus_vote_find_entry(consensus, sd->identity_digest);
2473 if (rs && !memcmp(rs->descriptor_digest,
2474 sd->signed_descriptor_digest, DIGEST_LEN))
2475 in_v3 = 1;
2477 log(severity, LD_DIR,
2478 "Old descriptor for %s (published %s) %sin v2 ns, %sin v3 "
2479 "consensus. Last valid until %s; last served at %s.",
2480 id, published, in_v2 ? "" : "not ", in_v3 ? "" : "not ",
2481 last_valid_until, last_served_at);
2484 #endif
2487 /** Debugging helper: If <b>idx</b> is nonnegative, assert that <b>ri</b> is
2488 * in <b>sl</b> at position <b>idx</b>. Otherwise, search <b>sl</b> for
2489 * <b>ri</b>. Return the index of <b>ri</b> in <b>sl</b>, or -1 if <b>ri</b>
2490 * is not in <b>sl</b>. */
2491 static INLINE int
2492 _routerlist_find_elt(smartlist_t *sl, void *ri, int idx)
2494 if (idx < 0) {
2495 idx = -1;
2496 SMARTLIST_FOREACH(sl, routerinfo_t *, r,
2497 if (r == ri) {
2498 idx = r_sl_idx;
2499 break;
2501 } else {
2502 tor_assert(idx < smartlist_len(sl));
2503 tor_assert(smartlist_get(sl, idx) == ri);
2505 return idx;
2508 /** Insert an item <b>ri</b> into the routerlist <b>rl</b>, updating indices
2509 * as needed. There must be no previous member of <b>rl</b> with the same
2510 * identity digest as <b>ri</b>: If there is, call routerlist_replace
2511 * instead.
2513 static void
2514 routerlist_insert(routerlist_t *rl, routerinfo_t *ri)
2516 routerinfo_t *ri_old;
2518 /* XXXX Remove if this slows us down. */
2519 routerinfo_t *ri_generated = router_get_my_routerinfo();
2520 tor_assert(ri_generated != ri);
2522 tor_assert(ri->cache_info.routerlist_index == -1);
2524 ri_old = rimap_set(rl->identity_map, ri->cache_info.identity_digest, ri);
2525 tor_assert(!ri_old);
2526 sdmap_set(rl->desc_digest_map, ri->cache_info.signed_descriptor_digest,
2527 &(ri->cache_info));
2528 if (!tor_digest_is_zero(ri->cache_info.extra_info_digest))
2529 sdmap_set(rl->desc_by_eid_map, ri->cache_info.extra_info_digest,
2530 &ri->cache_info);
2531 smartlist_add(rl->routers, ri);
2532 ri->cache_info.routerlist_index = smartlist_len(rl->routers) - 1;
2533 router_dir_info_changed();
2534 #ifdef DEBUG_ROUTERLIST
2535 routerlist_assert_ok(rl);
2536 #endif
2539 /** Adds the extrainfo_t <b>ei</b> to the routerlist <b>rl</b>, if there is a
2540 * corresponding router in rl-\>routers or rl-\>old_routers. Return true iff
2541 * we actually inserted <b>ei</b>. Free <b>ei</b> if it isn't inserted. */
2542 static int
2543 extrainfo_insert(routerlist_t *rl, extrainfo_t *ei)
2545 int r = 0;
2546 routerinfo_t *ri = rimap_get(rl->identity_map,
2547 ei->cache_info.identity_digest);
2548 signed_descriptor_t *sd =
2549 sdmap_get(rl->desc_by_eid_map, ei->cache_info.signed_descriptor_digest);
2550 extrainfo_t *ei_tmp;
2553 /* XXXX remove this code if it slows us down. */
2554 extrainfo_t *ei_generated = router_get_my_extrainfo();
2555 tor_assert(ei_generated != ei);
2558 if (!ri) {
2559 /* This router is unknown; we can't even verify the signature. Give up.*/
2560 goto done;
2562 if (routerinfo_incompatible_with_extrainfo(ri, ei, sd, NULL)) {
2563 goto done;
2566 /* Okay, if we make it here, we definitely have a router corresponding to
2567 * this extrainfo. */
2569 ei_tmp = eimap_set(rl->extra_info_map,
2570 ei->cache_info.signed_descriptor_digest,
2571 ei);
2572 r = 1;
2573 if (ei_tmp) {
2574 rl->extrainfo_store.bytes_dropped +=
2575 ei_tmp->cache_info.signed_descriptor_len;
2576 extrainfo_free(ei_tmp);
2579 done:
2580 if (r == 0)
2581 extrainfo_free(ei);
2583 #ifdef DEBUG_ROUTERLIST
2584 routerlist_assert_ok(rl);
2585 #endif
2586 return r;
2589 #define should_cache_old_descriptors() \
2590 directory_caches_dir_info(get_options())
2592 /** If we're a directory cache and routerlist <b>rl</b> doesn't have
2593 * a copy of router <b>ri</b> yet, add it to the list of old (not
2594 * recommended but still served) descriptors. Else free it. */
2595 static void
2596 routerlist_insert_old(routerlist_t *rl, routerinfo_t *ri)
2599 /* XXXX remove this code if it slows us down. */
2600 routerinfo_t *ri_generated = router_get_my_routerinfo();
2601 tor_assert(ri_generated != ri);
2603 tor_assert(ri->cache_info.routerlist_index == -1);
2605 if (should_cache_old_descriptors() &&
2606 ri->purpose == ROUTER_PURPOSE_GENERAL &&
2607 !sdmap_get(rl->desc_digest_map,
2608 ri->cache_info.signed_descriptor_digest)) {
2609 signed_descriptor_t *sd = signed_descriptor_from_routerinfo(ri);
2610 sdmap_set(rl->desc_digest_map, sd->signed_descriptor_digest, sd);
2611 smartlist_add(rl->old_routers, sd);
2612 sd->routerlist_index = smartlist_len(rl->old_routers)-1;
2613 if (!tor_digest_is_zero(sd->extra_info_digest))
2614 sdmap_set(rl->desc_by_eid_map, sd->extra_info_digest, sd);
2615 } else {
2616 routerinfo_free(ri);
2618 #ifdef DEBUG_ROUTERLIST
2619 routerlist_assert_ok(rl);
2620 #endif
2623 /** Remove an item <b>ri</b> from the routerlist <b>rl</b>, updating indices
2624 * as needed. If <b>idx</b> is nonnegative and smartlist_get(rl-&gt;routers,
2625 * idx) == ri, we don't need to do a linear search over the list to decide
2626 * which to remove. We fill the gap in rl-&gt;routers with a later element in
2627 * the list, if any exists. <b>ri</b> is freed.
2629 * If <b>make_old</b> is true, instead of deleting the router, we try adding
2630 * it to rl-&gt;old_routers. */
2631 void
2632 routerlist_remove(routerlist_t *rl, routerinfo_t *ri, int make_old, time_t now)
2634 routerinfo_t *ri_tmp;
2635 extrainfo_t *ei_tmp;
2636 int idx = ri->cache_info.routerlist_index;
2637 tor_assert(0 <= idx && idx < smartlist_len(rl->routers));
2638 tor_assert(smartlist_get(rl->routers, idx) == ri);
2640 /* make sure the rephist module knows that it's not running */
2641 rep_hist_note_router_unreachable(ri->cache_info.identity_digest, now);
2643 ri->cache_info.routerlist_index = -1;
2644 smartlist_del(rl->routers, idx);
2645 if (idx < smartlist_len(rl->routers)) {
2646 routerinfo_t *r = smartlist_get(rl->routers, idx);
2647 r->cache_info.routerlist_index = idx;
2650 ri_tmp = rimap_remove(rl->identity_map, ri->cache_info.identity_digest);
2651 router_dir_info_changed();
2652 tor_assert(ri_tmp == ri);
2654 if (make_old && should_cache_old_descriptors() &&
2655 ri->purpose == ROUTER_PURPOSE_GENERAL) {
2656 signed_descriptor_t *sd;
2657 sd = signed_descriptor_from_routerinfo(ri);
2658 smartlist_add(rl->old_routers, sd);
2659 sd->routerlist_index = smartlist_len(rl->old_routers)-1;
2660 sdmap_set(rl->desc_digest_map, sd->signed_descriptor_digest, sd);
2661 if (!tor_digest_is_zero(sd->extra_info_digest))
2662 sdmap_set(rl->desc_by_eid_map, sd->extra_info_digest, sd);
2663 } else {
2664 signed_descriptor_t *sd_tmp;
2665 sd_tmp = sdmap_remove(rl->desc_digest_map,
2666 ri->cache_info.signed_descriptor_digest);
2667 tor_assert(sd_tmp == &(ri->cache_info));
2668 rl->desc_store.bytes_dropped += ri->cache_info.signed_descriptor_len;
2669 ei_tmp = eimap_remove(rl->extra_info_map,
2670 ri->cache_info.extra_info_digest);
2671 if (ei_tmp) {
2672 rl->extrainfo_store.bytes_dropped +=
2673 ei_tmp->cache_info.signed_descriptor_len;
2674 extrainfo_free(ei_tmp);
2676 if (!tor_digest_is_zero(ri->cache_info.extra_info_digest))
2677 sdmap_remove(rl->desc_by_eid_map, ri->cache_info.extra_info_digest);
2678 routerinfo_free(ri);
2680 #ifdef DEBUG_ROUTERLIST
2681 routerlist_assert_ok(rl);
2682 #endif
2685 /** Remove a signed_descriptor_t <b>sd</b> from <b>rl</b>-\>old_routers, and
2686 * adjust <b>rl</b> as appropriate. <b>idx</b> is -1, or the index of
2687 * <b>sd</b>. */
2688 static void
2689 routerlist_remove_old(routerlist_t *rl, signed_descriptor_t *sd, int idx)
2691 signed_descriptor_t *sd_tmp;
2692 extrainfo_t *ei_tmp;
2693 desc_store_t *store;
2694 if (idx == -1) {
2695 idx = sd->routerlist_index;
2697 tor_assert(0 <= idx && idx < smartlist_len(rl->old_routers));
2698 /* XXXX edmanm's bridge relay triggered the following assert while
2699 * running 0.2.0.12-alpha. If anybody triggers this again, see if we
2700 * can get a backtrace. */
2701 tor_assert(smartlist_get(rl->old_routers, idx) == sd);
2702 tor_assert(idx == sd->routerlist_index);
2704 sd->routerlist_index = -1;
2705 smartlist_del(rl->old_routers, idx);
2706 if (idx < smartlist_len(rl->old_routers)) {
2707 signed_descriptor_t *d = smartlist_get(rl->old_routers, idx);
2708 d->routerlist_index = idx;
2710 sd_tmp = sdmap_remove(rl->desc_digest_map,
2711 sd->signed_descriptor_digest);
2712 tor_assert(sd_tmp == sd);
2713 store = desc_get_store(rl, sd);
2714 if (store)
2715 store->bytes_dropped += sd->signed_descriptor_len;
2717 ei_tmp = eimap_remove(rl->extra_info_map,
2718 sd->extra_info_digest);
2719 if (ei_tmp) {
2720 rl->extrainfo_store.bytes_dropped +=
2721 ei_tmp->cache_info.signed_descriptor_len;
2722 extrainfo_free(ei_tmp);
2724 if (!tor_digest_is_zero(sd->extra_info_digest))
2725 sdmap_remove(rl->desc_by_eid_map, sd->extra_info_digest);
2727 signed_descriptor_free(sd);
2728 #ifdef DEBUG_ROUTERLIST
2729 routerlist_assert_ok(rl);
2730 #endif
2733 /** Remove <b>ri_old</b> from the routerlist <b>rl</b>, and replace it with
2734 * <b>ri_new</b>, updating all index info. If <b>idx</b> is nonnegative and
2735 * smartlist_get(rl-&gt;routers, idx) == ri, we don't need to do a linear
2736 * search over the list to decide which to remove. We put ri_new in the same
2737 * index as ri_old, if possible. ri is freed as appropriate.
2739 * If should_cache_descriptors() is true, instead of deleting the router,
2740 * we add it to rl-&gt;old_routers. */
2741 static void
2742 routerlist_replace(routerlist_t *rl, routerinfo_t *ri_old,
2743 routerinfo_t *ri_new)
2745 int idx;
2747 routerinfo_t *ri_tmp;
2748 extrainfo_t *ei_tmp;
2750 /* XXXX Remove this if it turns out to slow us down. */
2751 routerinfo_t *ri_generated = router_get_my_routerinfo();
2752 tor_assert(ri_generated != ri_new);
2754 tor_assert(ri_old != ri_new);
2755 tor_assert(ri_new->cache_info.routerlist_index == -1);
2757 idx = ri_old->cache_info.routerlist_index;
2758 tor_assert(0 <= idx && idx < smartlist_len(rl->routers));
2759 tor_assert(smartlist_get(rl->routers, idx) == ri_old);
2761 router_dir_info_changed();
2762 if (idx >= 0) {
2763 smartlist_set(rl->routers, idx, ri_new);
2764 ri_old->cache_info.routerlist_index = -1;
2765 ri_new->cache_info.routerlist_index = idx;
2766 /* Check that ri_old is not in rl->routers anymore: */
2767 tor_assert( _routerlist_find_elt(rl->routers, ri_old, -1) == -1 );
2768 } else {
2769 log_warn(LD_BUG, "Appending entry from routerlist_replace.");
2770 routerlist_insert(rl, ri_new);
2771 return;
2773 if (memcmp(ri_old->cache_info.identity_digest,
2774 ri_new->cache_info.identity_digest, DIGEST_LEN)) {
2775 /* digests don't match; digestmap_set won't replace */
2776 rimap_remove(rl->identity_map, ri_old->cache_info.identity_digest);
2778 ri_tmp = rimap_set(rl->identity_map,
2779 ri_new->cache_info.identity_digest, ri_new);
2780 tor_assert(!ri_tmp || ri_tmp == ri_old);
2781 sdmap_set(rl->desc_digest_map,
2782 ri_new->cache_info.signed_descriptor_digest,
2783 &(ri_new->cache_info));
2785 if (!tor_digest_is_zero(ri_new->cache_info.extra_info_digest)) {
2786 sdmap_set(rl->desc_by_eid_map, ri_new->cache_info.extra_info_digest,
2787 &ri_new->cache_info);
2790 if (should_cache_old_descriptors() &&
2791 ri_old->purpose == ROUTER_PURPOSE_GENERAL) {
2792 signed_descriptor_t *sd = signed_descriptor_from_routerinfo(ri_old);
2793 smartlist_add(rl->old_routers, sd);
2794 sd->routerlist_index = smartlist_len(rl->old_routers)-1;
2795 sdmap_set(rl->desc_digest_map, sd->signed_descriptor_digest, sd);
2796 if (!tor_digest_is_zero(sd->extra_info_digest))
2797 sdmap_set(rl->desc_by_eid_map, sd->extra_info_digest, sd);
2798 } else {
2799 if (memcmp(ri_old->cache_info.signed_descriptor_digest,
2800 ri_new->cache_info.signed_descriptor_digest,
2801 DIGEST_LEN)) {
2802 /* digests don't match; digestmap_set didn't replace */
2803 sdmap_remove(rl->desc_digest_map,
2804 ri_old->cache_info.signed_descriptor_digest);
2807 ei_tmp = eimap_remove(rl->extra_info_map,
2808 ri_old->cache_info.extra_info_digest);
2809 if (ei_tmp) {
2810 rl->extrainfo_store.bytes_dropped +=
2811 ei_tmp->cache_info.signed_descriptor_len;
2812 extrainfo_free(ei_tmp);
2814 if (!tor_digest_is_zero(ri_old->cache_info.extra_info_digest)) {
2815 sdmap_remove(rl->desc_by_eid_map,
2816 ri_old->cache_info.extra_info_digest);
2818 rl->desc_store.bytes_dropped += ri_old->cache_info.signed_descriptor_len;
2819 routerinfo_free(ri_old);
2821 #ifdef DEBUG_ROUTERLIST
2822 routerlist_assert_ok(rl);
2823 #endif
2826 /** Extract the descriptor <b>sd</b> from old_routerlist, and re-parse
2827 * it as a fresh routerinfo_t. */
2828 static routerinfo_t *
2829 routerlist_reparse_old(routerlist_t *rl, signed_descriptor_t *sd)
2831 routerinfo_t *ri;
2832 const char *body;
2834 body = signed_descriptor_get_annotations(sd);
2836 ri = router_parse_entry_from_string(body,
2837 body+sd->signed_descriptor_len+sd->annotations_len,
2838 0, 1, NULL);
2839 if (!ri)
2840 return NULL;
2841 memcpy(&ri->cache_info, sd, sizeof(signed_descriptor_t));
2842 sd->signed_descriptor_body = NULL; /* Steal reference. */
2843 ri->cache_info.routerlist_index = -1;
2845 routerlist_remove_old(rl, sd, -1);
2847 return ri;
2850 /** Free all memory held by the routerlist module. */
2851 void
2852 routerlist_free_all(void)
2854 if (routerlist)
2855 routerlist_free(routerlist);
2856 routerlist = NULL;
2857 if (warned_nicknames) {
2858 SMARTLIST_FOREACH(warned_nicknames, char *, cp, tor_free(cp));
2859 smartlist_free(warned_nicknames);
2860 warned_nicknames = NULL;
2862 if (trusted_dir_servers) {
2863 SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, ds,
2864 trusted_dir_server_free(ds));
2865 smartlist_free(trusted_dir_servers);
2866 trusted_dir_servers = NULL;
2868 if (trusted_dir_certs) {
2869 DIGESTMAP_FOREACH(trusted_dir_certs, key, cert_list_t *, cl) {
2870 SMARTLIST_FOREACH(cl->certs, authority_cert_t *, cert,
2871 authority_cert_free(cert));
2872 smartlist_free(cl->certs);
2873 tor_free(cl);
2874 } DIGESTMAP_FOREACH_END;
2875 digestmap_free(trusted_dir_certs, NULL);
2876 trusted_dir_certs = NULL;
2880 /** Forget that we have issued any router-related warnings, so that we'll
2881 * warn again if we see the same errors. */
2882 void
2883 routerlist_reset_warnings(void)
2885 if (!warned_nicknames)
2886 warned_nicknames = smartlist_create();
2887 SMARTLIST_FOREACH(warned_nicknames, char *, cp, tor_free(cp));
2888 smartlist_clear(warned_nicknames); /* now the list is empty. */
2890 networkstatus_reset_warnings();
2893 /** Mark the router with ID <b>digest</b> as running or non-running
2894 * in our routerlist. */
2895 void
2896 router_set_status(const char *digest, int up)
2898 routerinfo_t *router;
2899 routerstatus_t *status;
2900 tor_assert(digest);
2902 SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, d,
2903 if (!memcmp(d->digest, digest, DIGEST_LEN))
2904 d->is_running = up);
2906 router = router_get_by_digest(digest);
2907 if (router) {
2908 log_debug(LD_DIR,"Marking router '%s/%s' as %s.",
2909 router->nickname, router->address, up ? "up" : "down");
2910 if (!up && router_is_me(router) && !we_are_hibernating())
2911 log_warn(LD_NET, "We just marked ourself as down. Are your external "
2912 "addresses reachable?");
2913 router->is_running = up;
2915 status = router_get_consensus_status_by_id(digest);
2916 if (status && status->is_running != up) {
2917 status->is_running = up;
2918 control_event_networkstatus_changed_single(status);
2920 router_dir_info_changed();
2923 /** Add <b>router</b> to the routerlist, if we don't already have it. Replace
2924 * older entries (if any) with the same key. Note: Callers should not hold
2925 * their pointers to <b>router</b> if this function fails; <b>router</b>
2926 * will either be inserted into the routerlist or freed. Similarly, even
2927 * if this call succeeds, they should not hold their pointers to
2928 * <b>router</b> after subsequent calls with other routerinfo's -- they
2929 * might cause the original routerinfo to get freed.
2931 * Returns the status for the operation. Might set *<b>msg</b> if it wants
2932 * the poster of the router to know something.
2934 * If <b>from_cache</b>, this descriptor came from our disk cache. If
2935 * <b>from_fetch</b>, we received it in response to a request we made.
2936 * (If both are false, that means it was uploaded to us as an auth dir
2937 * server or via the controller.)
2939 * This function should be called *after*
2940 * routers_update_status_from_consensus_networkstatus; subsequently, you
2941 * should call router_rebuild_store and routerlist_descriptors_added.
2943 was_router_added_t
2944 router_add_to_routerlist(routerinfo_t *router, const char **msg,
2945 int from_cache, int from_fetch)
2947 const char *id_digest;
2948 int authdir = authdir_mode_handles_descs(get_options(), router->purpose);
2949 int authdir_believes_valid = 0;
2950 routerinfo_t *old_router;
2951 networkstatus_t *consensus = networkstatus_get_latest_consensus();
2952 const smartlist_t *networkstatus_v2_list = networkstatus_get_v2_list();
2953 int in_consensus = 0;
2955 tor_assert(msg);
2957 if (!routerlist)
2958 router_get_routerlist();
2960 id_digest = router->cache_info.identity_digest;
2962 /* Make sure that we haven't already got this exact descriptor. */
2963 if (sdmap_get(routerlist->desc_digest_map,
2964 router->cache_info.signed_descriptor_digest)) {
2965 log_info(LD_DIR,
2966 "Dropping descriptor that we already have for router '%s'",
2967 router->nickname);
2968 *msg = "Router descriptor was not new.";
2969 routerinfo_free(router);
2970 return ROUTER_WAS_NOT_NEW;
2973 if (authdir) {
2974 if (authdir_wants_to_reject_router(router, msg,
2975 !from_cache && !from_fetch)) {
2976 tor_assert(*msg);
2977 routerinfo_free(router);
2978 return ROUTER_AUTHDIR_REJECTS;
2980 authdir_believes_valid = router->is_valid;
2981 } else if (from_fetch) {
2982 /* Only check the descriptor digest against the network statuses when
2983 * we are receiving in response to a fetch. */
2985 if (!signed_desc_digest_is_recognized(&router->cache_info) &&
2986 !routerinfo_is_a_configured_bridge(router)) {
2987 /* We asked for it, so some networkstatus must have listed it when we
2988 * did. Save it if we're a cache in case somebody else asks for it. */
2989 log_info(LD_DIR,
2990 "Received a no-longer-recognized descriptor for router '%s'",
2991 router->nickname);
2992 *msg = "Router descriptor is not referenced by any network-status.";
2994 /* Only journal this desc if we'll be serving it. */
2995 if (!from_cache && should_cache_old_descriptors())
2996 signed_desc_append_to_journal(&router->cache_info,
2997 &routerlist->desc_store);
2998 routerlist_insert_old(routerlist, router);
2999 return ROUTER_NOT_IN_CONSENSUS_OR_NETWORKSTATUS;
3003 /* We no longer need a router with this descriptor digest. */
3004 SMARTLIST_FOREACH(networkstatus_v2_list, networkstatus_v2_t *, ns,
3006 routerstatus_t *rs =
3007 networkstatus_v2_find_entry(ns, router->cache_info.identity_digest);
3008 if (rs && !memcmp(rs->descriptor_digest,
3009 router->cache_info.signed_descriptor_digest,
3010 DIGEST_LEN))
3011 rs->need_to_mirror = 0;
3013 if (consensus) {
3014 routerstatus_t *rs = networkstatus_vote_find_entry(consensus,
3015 router->cache_info.identity_digest);
3016 if (rs && !memcmp(rs->descriptor_digest,
3017 router->cache_info.signed_descriptor_digest,
3018 DIGEST_LEN)) {
3019 in_consensus = 1;
3020 rs->need_to_mirror = 0;
3024 if (router->purpose == ROUTER_PURPOSE_GENERAL &&
3025 consensus && !in_consensus && !authdir) {
3026 /* If it's a general router not listed in the consensus, then don't
3027 * consider replacing the latest router with it. */
3028 if (!from_cache && should_cache_old_descriptors())
3029 signed_desc_append_to_journal(&router->cache_info,
3030 &routerlist->desc_store);
3031 routerlist_insert_old(routerlist, router);
3032 *msg = "Skipping router descriptor: not in consensus.";
3033 return ROUTER_NOT_IN_CONSENSUS;
3036 /* If we have a router with the same identity key, choose the newer one. */
3037 old_router = rimap_get(routerlist->identity_map,
3038 router->cache_info.identity_digest);
3039 if (old_router) {
3040 if (!in_consensus && (router->cache_info.published_on <=
3041 old_router->cache_info.published_on)) {
3042 /* Same key, but old. This one is not listed in the consensus. */
3043 log_debug(LD_DIR, "Skipping not-new descriptor for router '%s'",
3044 router->nickname);
3045 /* Only journal this desc if we'll be serving it. */
3046 if (!from_cache && should_cache_old_descriptors())
3047 signed_desc_append_to_journal(&router->cache_info,
3048 &routerlist->desc_store);
3049 routerlist_insert_old(routerlist, router);
3050 *msg = "Router descriptor was not new.";
3051 return ROUTER_WAS_NOT_NEW;
3052 } else {
3053 /* Same key, and either new, or listed in the consensus. */
3054 log_debug(LD_DIR, "Replacing entry for router '%s/%s' [%s]",
3055 router->nickname, old_router->nickname,
3056 hex_str(id_digest,DIGEST_LEN));
3057 if (router->addr == old_router->addr &&
3058 router->or_port == old_router->or_port) {
3059 /* these carry over when the address and orport are unchanged. */
3060 router->last_reachable = old_router->last_reachable;
3061 router->testing_since = old_router->testing_since;
3063 routerlist_replace(routerlist, old_router, router);
3064 if (!from_cache) {
3065 signed_desc_append_to_journal(&router->cache_info,
3066 &routerlist->desc_store);
3068 directory_set_dirty();
3069 *msg = authdir_believes_valid ? "Valid server updated" :
3070 ("Invalid server updated. (This dirserver is marking your "
3071 "server as unapproved.)");
3072 return ROUTER_ADDED_SUCCESSFULLY;
3076 if (!in_consensus && from_cache &&
3077 router->cache_info.published_on < time(NULL) - OLD_ROUTER_DESC_MAX_AGE) {
3078 *msg = "Router descriptor was really old.";
3079 routerinfo_free(router);
3080 return ROUTER_WAS_NOT_NEW;
3083 /* We haven't seen a router with this identity before. Add it to the end of
3084 * the list. */
3085 routerlist_insert(routerlist, router);
3086 if (!from_cache)
3087 signed_desc_append_to_journal(&router->cache_info,
3088 &routerlist->desc_store);
3089 directory_set_dirty();
3090 return ROUTER_ADDED_SUCCESSFULLY;
3093 /** Insert <b>ei</b> into the routerlist, or free it. Other arguments are
3094 * as for router_add_to_routerlist(). Return ROUTER_ADDED_SUCCESSFULLY iff
3095 * we actually inserted it, ROUTER_BAD_EI otherwise.
3097 was_router_added_t
3098 router_add_extrainfo_to_routerlist(extrainfo_t *ei, const char **msg,
3099 int from_cache, int from_fetch)
3101 int inserted;
3102 (void)from_fetch;
3103 if (msg) *msg = NULL;
3104 /*XXXX022 Do something with msg */
3106 inserted = extrainfo_insert(router_get_routerlist(), ei);
3108 if (inserted && !from_cache)
3109 signed_desc_append_to_journal(&ei->cache_info,
3110 &routerlist->extrainfo_store);
3112 if (inserted)
3113 return ROUTER_ADDED_SUCCESSFULLY;
3114 else
3115 return ROUTER_BAD_EI;
3118 /** Sorting helper: return &lt;0, 0, or &gt;0 depending on whether the
3119 * signed_descriptor_t* in *<b>a</b> has an identity digest preceding, equal
3120 * to, or later than that of *<b>b</b>. */
3121 static int
3122 _compare_old_routers_by_identity(const void **_a, const void **_b)
3124 int i;
3125 const signed_descriptor_t *r1 = *_a, *r2 = *_b;
3126 if ((i = memcmp(r1->identity_digest, r2->identity_digest, DIGEST_LEN)))
3127 return i;
3128 return (int)(r1->published_on - r2->published_on);
3131 /** Internal type used to represent how long an old descriptor was valid,
3132 * where it appeared in the list of old descriptors, and whether it's extra
3133 * old. Used only by routerlist_remove_old_cached_routers_with_id(). */
3134 struct duration_idx_t {
3135 int duration;
3136 int idx;
3137 int old;
3140 /** Sorting helper: compare two duration_idx_t by their duration. */
3141 static int
3142 _compare_duration_idx(const void *_d1, const void *_d2)
3144 const struct duration_idx_t *d1 = _d1;
3145 const struct duration_idx_t *d2 = _d2;
3146 return d1->duration - d2->duration;
3149 /** The range <b>lo</b> through <b>hi</b> inclusive of routerlist->old_routers
3150 * must contain routerinfo_t with the same identity and with publication time
3151 * in ascending order. Remove members from this range until there are no more
3152 * than max_descriptors_per_router() remaining. Start by removing the oldest
3153 * members from before <b>cutoff</b>, then remove members which were current
3154 * for the lowest amount of time. The order of members of old_routers at
3155 * indices <b>lo</b> or higher may be changed.
3157 static void
3158 routerlist_remove_old_cached_routers_with_id(time_t now,
3159 time_t cutoff, int lo, int hi,
3160 digestset_t *retain)
3162 int i, n = hi-lo+1;
3163 unsigned n_extra, n_rmv = 0;
3164 struct duration_idx_t *lifespans;
3165 uint8_t *rmv, *must_keep;
3166 smartlist_t *lst = routerlist->old_routers;
3167 #if 1
3168 const char *ident;
3169 tor_assert(hi < smartlist_len(lst));
3170 tor_assert(lo <= hi);
3171 ident = ((signed_descriptor_t*)smartlist_get(lst, lo))->identity_digest;
3172 for (i = lo+1; i <= hi; ++i) {
3173 signed_descriptor_t *r = smartlist_get(lst, i);
3174 tor_assert(!memcmp(ident, r->identity_digest, DIGEST_LEN));
3176 #endif
3177 /* Check whether we need to do anything at all. */
3179 int mdpr = directory_caches_dir_info(get_options()) ? 2 : 1;
3180 if (n <= mdpr)
3181 return;
3182 n_extra = n - mdpr;
3185 lifespans = tor_malloc_zero(sizeof(struct duration_idx_t)*n);
3186 rmv = tor_malloc_zero(sizeof(uint8_t)*n);
3187 must_keep = tor_malloc_zero(sizeof(uint8_t)*n);
3188 /* Set lifespans to contain the lifespan and index of each server. */
3189 /* Set rmv[i-lo]=1 if we're going to remove a server for being too old. */
3190 for (i = lo; i <= hi; ++i) {
3191 signed_descriptor_t *r = smartlist_get(lst, i);
3192 signed_descriptor_t *r_next;
3193 lifespans[i-lo].idx = i;
3194 if (r->last_listed_as_valid_until >= now ||
3195 (retain && digestset_isin(retain, r->signed_descriptor_digest))) {
3196 must_keep[i-lo] = 1;
3198 if (i < hi) {
3199 r_next = smartlist_get(lst, i+1);
3200 tor_assert(r->published_on <= r_next->published_on);
3201 lifespans[i-lo].duration = (int)(r_next->published_on - r->published_on);
3202 } else {
3203 r_next = NULL;
3204 lifespans[i-lo].duration = INT_MAX;
3206 if (!must_keep[i-lo] && r->published_on < cutoff && n_rmv < n_extra) {
3207 ++n_rmv;
3208 lifespans[i-lo].old = 1;
3209 rmv[i-lo] = 1;
3213 if (n_rmv < n_extra) {
3215 * We aren't removing enough servers for being old. Sort lifespans by
3216 * the duration of liveness, and remove the ones we're not already going to
3217 * remove based on how long they were alive.
3219 qsort(lifespans, n, sizeof(struct duration_idx_t), _compare_duration_idx);
3220 for (i = 0; i < n && n_rmv < n_extra; ++i) {
3221 if (!must_keep[lifespans[i].idx-lo] && !lifespans[i].old) {
3222 rmv[lifespans[i].idx-lo] = 1;
3223 ++n_rmv;
3228 i = hi;
3229 do {
3230 if (rmv[i-lo])
3231 routerlist_remove_old(routerlist, smartlist_get(lst, i), i);
3232 } while (--i >= lo);
3233 tor_free(must_keep);
3234 tor_free(rmv);
3235 tor_free(lifespans);
3238 /** Deactivate any routers from the routerlist that are more than
3239 * ROUTER_MAX_AGE seconds old and not recommended by any networkstatuses;
3240 * remove old routers from the list of cached routers if we have too many.
3242 void
3243 routerlist_remove_old_routers(void)
3245 int i, hi=-1;
3246 const char *cur_id = NULL;
3247 time_t now = time(NULL);
3248 time_t cutoff;
3249 routerinfo_t *router;
3250 signed_descriptor_t *sd;
3251 digestset_t *retain;
3252 int caches = directory_caches_dir_info(get_options());
3253 const networkstatus_t *consensus = networkstatus_get_latest_consensus();
3254 const smartlist_t *networkstatus_v2_list = networkstatus_get_v2_list();
3255 int have_enough_v2;
3257 trusted_dirs_remove_old_certs();
3259 if (!routerlist || !consensus)
3260 return;
3262 // routerlist_assert_ok(routerlist);
3264 /* We need to guess how many router descriptors we will wind up wanting to
3265 retain, so that we can be sure to allocate a large enough Bloom filter
3266 to hold the digest set. Overestimating is fine; underestimating is bad.
3269 /* We'll probably retain everything in the consensus. */
3270 int n_max_retain = smartlist_len(consensus->routerstatus_list);
3271 if (caches && networkstatus_v2_list) {
3272 /* If we care about v2 statuses, we'll retain at most as many as are
3273 listed any of the v2 statues. This will be at least the length of
3274 the largest v2 networkstatus, and in the worst case, this set will be
3275 equal to the sum of the lengths of all v2 consensuses. Take the
3276 worst case.
3278 SMARTLIST_FOREACH(networkstatus_v2_list, networkstatus_v2_t *, ns,
3279 n_max_retain += smartlist_len(ns->entries));
3281 retain = digestset_new(n_max_retain);
3284 cutoff = now - OLD_ROUTER_DESC_MAX_AGE;
3285 /* Build a list of all the descriptors that _anybody_ lists. */
3286 if (caches && networkstatus_v2_list) {
3287 SMARTLIST_FOREACH(networkstatus_v2_list, networkstatus_v2_t *, ns,
3289 /* XXXX The inner loop here gets pretty expensive, and actually shows up
3290 * on some profiles. It may be the reason digestmap_set shows up in
3291 * profiles too. If instead we kept a per-descriptor digest count of
3292 * how many networkstatuses recommended each descriptor, and changed
3293 * that only when the networkstatuses changed, that would be a speed
3294 * improvement, possibly 1-4% if it also removes digestmap_set from the
3295 * profile. Not worth it for 0.1.2.x, though. The new directory
3296 * system will obsolete this whole thing in 0.2.0.x. */
3297 SMARTLIST_FOREACH(ns->entries, routerstatus_t *, rs,
3298 if (rs->published_on >= cutoff)
3299 digestset_add(retain, rs->descriptor_digest));
3303 /* Retain anything listed in the consensus. */
3304 if (consensus) {
3305 SMARTLIST_FOREACH(consensus->routerstatus_list, routerstatus_t *, rs,
3306 if (rs->published_on >= cutoff)
3307 digestset_add(retain, rs->descriptor_digest));
3310 /* If we have a consensus, and nearly as many v2 networkstatuses as we want,
3311 * we should consider pruning current routers that are too old and that
3312 * nobody recommends. (If we don't have a consensus or enough v2
3313 * networkstatuses, then we should get more before we decide to kill
3314 * routers.) */
3315 /* we set this to true iff we don't care about v2 info, or we have enough. */
3316 have_enough_v2 = !caches ||
3317 (networkstatus_v2_list &&
3318 smartlist_len(networkstatus_v2_list) > get_n_v2_authorities() / 2);
3320 if (have_enough_v2 && consensus) {
3321 cutoff = now - ROUTER_MAX_AGE;
3322 /* Remove too-old unrecommended members of routerlist->routers. */
3323 for (i = 0; i < smartlist_len(routerlist->routers); ++i) {
3324 router = smartlist_get(routerlist->routers, i);
3325 if (router->cache_info.published_on <= cutoff &&
3326 router->cache_info.last_listed_as_valid_until < now &&
3327 !digestset_isin(retain,
3328 router->cache_info.signed_descriptor_digest)) {
3329 /* Too old: remove it. (If we're a cache, just move it into
3330 * old_routers.) */
3331 log_info(LD_DIR,
3332 "Forgetting obsolete (too old) routerinfo for router '%s'",
3333 router->nickname);
3334 routerlist_remove(routerlist, router, 1, now);
3335 i--;
3340 //routerlist_assert_ok(routerlist);
3342 /* Remove far-too-old members of routerlist->old_routers. */
3343 cutoff = now - OLD_ROUTER_DESC_MAX_AGE;
3344 for (i = 0; i < smartlist_len(routerlist->old_routers); ++i) {
3345 sd = smartlist_get(routerlist->old_routers, i);
3346 if (sd->published_on <= cutoff &&
3347 sd->last_listed_as_valid_until < now &&
3348 !digestset_isin(retain, sd->signed_descriptor_digest)) {
3349 /* Too old. Remove it. */
3350 routerlist_remove_old(routerlist, sd, i--);
3354 //routerlist_assert_ok(routerlist);
3356 log_info(LD_DIR, "We have %d live routers and %d old router descriptors.",
3357 smartlist_len(routerlist->routers),
3358 smartlist_len(routerlist->old_routers));
3360 /* Now we might have to look at routerlist->old_routers for extraneous
3361 * members. (We'd keep all the members if we could, but we need to save
3362 * space.) First, check whether we have too many router descriptors, total.
3363 * We're okay with having too many for some given router, so long as the
3364 * total number doesn't approach max_descriptors_per_router()*len(router).
3366 if (smartlist_len(routerlist->old_routers) <
3367 smartlist_len(routerlist->routers))
3368 goto done;
3370 /* Sort by identity, then fix indices. */
3371 smartlist_sort(routerlist->old_routers, _compare_old_routers_by_identity);
3372 /* Fix indices. */
3373 for (i = 0; i < smartlist_len(routerlist->old_routers); ++i) {
3374 signed_descriptor_t *r = smartlist_get(routerlist->old_routers, i);
3375 r->routerlist_index = i;
3378 /* Iterate through the list from back to front, so when we remove descriptors
3379 * we don't mess up groups we haven't gotten to. */
3380 for (i = smartlist_len(routerlist->old_routers)-1; i >= 0; --i) {
3381 signed_descriptor_t *r = smartlist_get(routerlist->old_routers, i);
3382 if (!cur_id) {
3383 cur_id = r->identity_digest;
3384 hi = i;
3386 if (memcmp(cur_id, r->identity_digest, DIGEST_LEN)) {
3387 routerlist_remove_old_cached_routers_with_id(now,
3388 cutoff, i+1, hi, retain);
3389 cur_id = r->identity_digest;
3390 hi = i;
3393 if (hi>=0)
3394 routerlist_remove_old_cached_routers_with_id(now, cutoff, 0, hi, retain);
3395 //routerlist_assert_ok(routerlist);
3397 done:
3398 digestset_free(retain);
3399 router_rebuild_store(RRS_DONT_REMOVE_OLD, &routerlist->desc_store);
3400 router_rebuild_store(RRS_DONT_REMOVE_OLD,&routerlist->extrainfo_store);
3403 /** We just added a new set of descriptors. Take whatever extra steps
3404 * we need. */
3405 static void
3406 routerlist_descriptors_added(smartlist_t *sl, int from_cache)
3408 tor_assert(sl);
3409 control_event_descriptors_changed(sl);
3410 SMARTLIST_FOREACH(sl, routerinfo_t *, ri,
3411 if (ri->purpose == ROUTER_PURPOSE_BRIDGE)
3412 learned_bridge_descriptor(ri, from_cache);
3417 * Code to parse a single router descriptor and insert it into the
3418 * routerlist. Return -1 if the descriptor was ill-formed; 0 if the
3419 * descriptor was well-formed but could not be added; and 1 if the
3420 * descriptor was added.
3422 * If we don't add it and <b>msg</b> is not NULL, then assign to
3423 * *<b>msg</b> a static string describing the reason for refusing the
3424 * descriptor.
3426 * This is used only by the controller.
3429 router_load_single_router(const char *s, uint8_t purpose, int cache,
3430 const char **msg)
3432 routerinfo_t *ri;
3433 was_router_added_t r;
3434 smartlist_t *lst;
3435 char annotation_buf[ROUTER_ANNOTATION_BUF_LEN];
3436 tor_assert(msg);
3437 *msg = NULL;
3439 tor_snprintf(annotation_buf, sizeof(annotation_buf),
3440 "@source controller\n"
3441 "@purpose %s\n", router_purpose_to_string(purpose));
3443 if (!(ri = router_parse_entry_from_string(s, NULL, 1, 0, annotation_buf))) {
3444 log_warn(LD_DIR, "Error parsing router descriptor; dropping.");
3445 *msg = "Couldn't parse router descriptor.";
3446 return -1;
3448 tor_assert(ri->purpose == purpose);
3449 if (router_is_me(ri)) {
3450 log_warn(LD_DIR, "Router's identity key matches mine; dropping.");
3451 *msg = "Router's identity key matches mine.";
3452 routerinfo_free(ri);
3453 return 0;
3456 if (!cache) /* obey the preference of the controller */
3457 ri->cache_info.do_not_cache = 1;
3459 lst = smartlist_create();
3460 smartlist_add(lst, ri);
3461 routers_update_status_from_consensus_networkstatus(lst, 0);
3463 r = router_add_to_routerlist(ri, msg, 0, 0);
3464 if (!WRA_WAS_ADDED(r)) {
3465 /* we've already assigned to *msg now, and ri is already freed */
3466 tor_assert(*msg);
3467 if (r == ROUTER_AUTHDIR_REJECTS)
3468 log_warn(LD_DIR, "Couldn't add router to list: %s Dropping.", *msg);
3469 smartlist_free(lst);
3470 return 0;
3471 } else {
3472 routerlist_descriptors_added(lst, 0);
3473 smartlist_free(lst);
3474 log_debug(LD_DIR, "Added router to list");
3475 return 1;
3479 /** Given a string <b>s</b> containing some routerdescs, parse it and put the
3480 * routers into our directory. If saved_location is SAVED_NOWHERE, the routers
3481 * are in response to a query to the network: cache them by adding them to
3482 * the journal.
3484 * Return the number of routers actually added.
3486 * If <b>requested_fingerprints</b> is provided, it must contain a list of
3487 * uppercased fingerprints. Do not update any router whose
3488 * fingerprint is not on the list; after updating a router, remove its
3489 * fingerprint from the list.
3491 * If <b>descriptor_digests</b> is non-zero, then the requested_fingerprints
3492 * are descriptor digests. Otherwise they are identity digests.
3495 router_load_routers_from_string(const char *s, const char *eos,
3496 saved_location_t saved_location,
3497 smartlist_t *requested_fingerprints,
3498 int descriptor_digests,
3499 const char *prepend_annotations)
3501 smartlist_t *routers = smartlist_create(), *changed = smartlist_create();
3502 char fp[HEX_DIGEST_LEN+1];
3503 const char *msg;
3504 int from_cache = (saved_location != SAVED_NOWHERE);
3505 int allow_annotations = (saved_location != SAVED_NOWHERE);
3506 int any_changed = 0;
3508 router_parse_list_from_string(&s, eos, routers, saved_location, 0,
3509 allow_annotations, prepend_annotations);
3511 routers_update_status_from_consensus_networkstatus(routers, !from_cache);
3513 log_info(LD_DIR, "%d elements to add", smartlist_len(routers));
3515 SMARTLIST_FOREACH_BEGIN(routers, routerinfo_t *, ri) {
3516 was_router_added_t r;
3517 char d[DIGEST_LEN];
3518 if (requested_fingerprints) {
3519 base16_encode(fp, sizeof(fp), descriptor_digests ?
3520 ri->cache_info.signed_descriptor_digest :
3521 ri->cache_info.identity_digest,
3522 DIGEST_LEN);
3523 if (smartlist_string_isin(requested_fingerprints, fp)) {
3524 smartlist_string_remove(requested_fingerprints, fp);
3525 } else {
3526 char *requested =
3527 smartlist_join_strings(requested_fingerprints," ",0,NULL);
3528 log_warn(LD_DIR,
3529 "We received a router descriptor with a fingerprint (%s) "
3530 "that we never requested. (We asked for: %s.) Dropping.",
3531 fp, requested);
3532 tor_free(requested);
3533 routerinfo_free(ri);
3534 continue;
3538 memcpy(d, ri->cache_info.signed_descriptor_digest, DIGEST_LEN);
3539 r = router_add_to_routerlist(ri, &msg, from_cache, !from_cache);
3540 if (WRA_WAS_ADDED(r)) {
3541 any_changed++;
3542 smartlist_add(changed, ri);
3543 routerlist_descriptors_added(changed, from_cache);
3544 smartlist_clear(changed);
3545 } else if (WRA_WAS_REJECTED(r)) {
3546 download_status_t *dl_status;
3547 dl_status = router_get_dl_status_by_descriptor_digest(d);
3548 if (dl_status) {
3549 log_info(LD_GENERAL, "Marking router %s as never downloadable",
3550 hex_str(d, DIGEST_LEN));
3551 download_status_mark_impossible(dl_status);
3554 } SMARTLIST_FOREACH_END(ri);
3556 routerlist_assert_ok(routerlist);
3558 if (any_changed)
3559 router_rebuild_store(0, &routerlist->desc_store);
3561 smartlist_free(routers);
3562 smartlist_free(changed);
3564 return any_changed;
3567 /** Parse one or more extrainfos from <b>s</b> (ending immediately before
3568 * <b>eos</b> if <b>eos</b> is present). Other arguments are as for
3569 * router_load_routers_from_string(). */
3570 void
3571 router_load_extrainfo_from_string(const char *s, const char *eos,
3572 saved_location_t saved_location,
3573 smartlist_t *requested_fingerprints,
3574 int descriptor_digests)
3576 smartlist_t *extrainfo_list = smartlist_create();
3577 const char *msg;
3578 int from_cache = (saved_location != SAVED_NOWHERE);
3580 router_parse_list_from_string(&s, eos, extrainfo_list, saved_location, 1, 0,
3581 NULL);
3583 log_info(LD_DIR, "%d elements to add", smartlist_len(extrainfo_list));
3585 SMARTLIST_FOREACH(extrainfo_list, extrainfo_t *, ei, {
3586 was_router_added_t added =
3587 router_add_extrainfo_to_routerlist(ei, &msg, from_cache, !from_cache);
3588 if (WRA_WAS_ADDED(added) && requested_fingerprints) {
3589 char fp[HEX_DIGEST_LEN+1];
3590 base16_encode(fp, sizeof(fp), descriptor_digests ?
3591 ei->cache_info.signed_descriptor_digest :
3592 ei->cache_info.identity_digest,
3593 DIGEST_LEN);
3594 smartlist_string_remove(requested_fingerprints, fp);
3595 /* We silently let people stuff us with extrainfos we didn't ask for,
3596 * so long as we would have wanted them anyway. Since we always fetch
3597 * all the extrainfos we want, and we never actually act on them
3598 * inside Tor, this should be harmless. */
3602 routerlist_assert_ok(routerlist);
3603 router_rebuild_store(0, &router_get_routerlist()->extrainfo_store);
3605 smartlist_free(extrainfo_list);
3608 /** Return true iff any networkstatus includes a descriptor whose digest
3609 * is that of <b>desc</b>. */
3610 static int
3611 signed_desc_digest_is_recognized(signed_descriptor_t *desc)
3613 routerstatus_t *rs;
3614 networkstatus_t *consensus = networkstatus_get_latest_consensus();
3615 int caches = directory_caches_dir_info(get_options());
3616 const smartlist_t *networkstatus_v2_list = networkstatus_get_v2_list();
3618 if (consensus) {
3619 rs = networkstatus_vote_find_entry(consensus, desc->identity_digest);
3620 if (rs && !memcmp(rs->descriptor_digest,
3621 desc->signed_descriptor_digest, DIGEST_LEN))
3622 return 1;
3624 if (caches && networkstatus_v2_list) {
3625 SMARTLIST_FOREACH(networkstatus_v2_list, networkstatus_v2_t *, ns,
3627 if (!(rs = networkstatus_v2_find_entry(ns, desc->identity_digest)))
3628 continue;
3629 if (!memcmp(rs->descriptor_digest,
3630 desc->signed_descriptor_digest, DIGEST_LEN))
3631 return 1;
3634 return 0;
3637 /** Clear all our timeouts for fetching v2 and v3 directory stuff, and then
3638 * give it all a try again. */
3639 void
3640 routerlist_retry_directory_downloads(time_t now)
3642 router_reset_status_download_failures();
3643 router_reset_descriptor_download_failures();
3644 update_networkstatus_downloads(now);
3645 update_router_descriptor_downloads(now);
3648 /** Return 1 if all running sufficiently-stable routers will reject
3649 * addr:port, return 0 if any might accept it. */
3651 router_exit_policy_all_routers_reject(uint32_t addr, uint16_t port,
3652 int need_uptime)
3654 addr_policy_result_t r;
3655 if (!routerlist) return 1;
3657 SMARTLIST_FOREACH(routerlist->routers, routerinfo_t *, router,
3659 if (router->is_running &&
3660 !router_is_unreliable(router, need_uptime, 0, 0)) {
3661 r = compare_addr_to_addr_policy(addr, port, router->exit_policy);
3662 if (r != ADDR_POLICY_REJECTED && r != ADDR_POLICY_PROBABLY_REJECTED)
3663 return 0; /* this one could be ok. good enough. */
3666 return 1; /* all will reject. */
3669 /** Return true iff <b>router</b> does not permit exit streams.
3672 router_exit_policy_rejects_all(routerinfo_t *router)
3674 return router->policy_is_reject_star;
3677 /** Add to the list of authoritative directory servers one at
3678 * <b>address</b>:<b>port</b>, with identity key <b>digest</b>. If
3679 * <b>address</b> is NULL, add ourself. Return the new trusted directory
3680 * server entry on success or NULL if we couldn't add it. */
3681 trusted_dir_server_t *
3682 add_trusted_dir_server(const char *nickname, const char *address,
3683 uint16_t dir_port, uint16_t or_port,
3684 const char *digest, const char *v3_auth_digest,
3685 authority_type_t type)
3687 trusted_dir_server_t *ent;
3688 uint32_t a;
3689 char *hostname = NULL;
3690 size_t dlen;
3691 if (!trusted_dir_servers)
3692 trusted_dir_servers = smartlist_create();
3694 if (!address) { /* The address is us; we should guess. */
3695 if (resolve_my_address(LOG_WARN, get_options(), &a, &hostname) < 0) {
3696 log_warn(LD_CONFIG,
3697 "Couldn't find a suitable address when adding ourself as a "
3698 "trusted directory server.");
3699 return NULL;
3701 } else {
3702 if (tor_lookup_hostname(address, &a)) {
3703 log_warn(LD_CONFIG,
3704 "Unable to lookup address for directory server at '%s'",
3705 address);
3706 return NULL;
3708 hostname = tor_strdup(address);
3711 ent = tor_malloc_zero(sizeof(trusted_dir_server_t));
3712 ent->nickname = nickname ? tor_strdup(nickname) : NULL;
3713 ent->address = hostname;
3714 ent->addr = a;
3715 ent->dir_port = dir_port;
3716 ent->or_port = or_port;
3717 ent->is_running = 1;
3718 ent->type = type;
3719 memcpy(ent->digest, digest, DIGEST_LEN);
3720 if (v3_auth_digest && (type & V3_AUTHORITY))
3721 memcpy(ent->v3_identity_digest, v3_auth_digest, DIGEST_LEN);
3723 dlen = 64 + strlen(hostname) + (nickname?strlen(nickname):0);
3724 ent->description = tor_malloc(dlen);
3725 if (nickname)
3726 tor_snprintf(ent->description, dlen, "directory server \"%s\" at %s:%d",
3727 nickname, hostname, (int)dir_port);
3728 else
3729 tor_snprintf(ent->description, dlen, "directory server at %s:%d",
3730 hostname, (int)dir_port);
3732 ent->fake_status.addr = ent->addr;
3733 memcpy(ent->fake_status.identity_digest, digest, DIGEST_LEN);
3734 if (nickname)
3735 strlcpy(ent->fake_status.nickname, nickname,
3736 sizeof(ent->fake_status.nickname));
3737 else
3738 ent->fake_status.nickname[0] = '\0';
3739 ent->fake_status.dir_port = ent->dir_port;
3740 ent->fake_status.or_port = ent->or_port;
3742 if (ent->or_port)
3743 ent->fake_status.version_supports_begindir = 1;
3744 /* XX021 - wait until authorities are upgraded */
3745 #if 0
3746 ent->fake_status.version_supports_conditional_consensus = 1;
3747 #else
3748 ent->fake_status.version_supports_conditional_consensus = 0;
3749 #endif
3751 smartlist_add(trusted_dir_servers, ent);
3752 router_dir_info_changed();
3753 return ent;
3756 /** Free storage held in <b>cert</b>. */
3757 void
3758 authority_cert_free(authority_cert_t *cert)
3760 if (!cert)
3761 return;
3763 tor_free(cert->cache_info.signed_descriptor_body);
3764 if (cert->signing_key)
3765 crypto_free_pk_env(cert->signing_key);
3766 if (cert->identity_key)
3767 crypto_free_pk_env(cert->identity_key);
3769 tor_free(cert);
3772 /** Free storage held in <b>ds</b>. */
3773 static void
3774 trusted_dir_server_free(trusted_dir_server_t *ds)
3776 tor_free(ds->nickname);
3777 tor_free(ds->description);
3778 tor_free(ds->address);
3779 tor_free(ds);
3782 /** Remove all members from the list of trusted dir servers. */
3783 void
3784 clear_trusted_dir_servers(void)
3786 if (trusted_dir_servers) {
3787 SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, ent,
3788 trusted_dir_server_free(ent));
3789 smartlist_clear(trusted_dir_servers);
3790 } else {
3791 trusted_dir_servers = smartlist_create();
3793 router_dir_info_changed();
3796 /** Return 1 if any trusted dir server supports v1 directories,
3797 * else return 0. */
3799 any_trusted_dir_is_v1_authority(void)
3801 if (trusted_dir_servers)
3802 return get_n_authorities(V1_AUTHORITY) > 0;
3804 return 0;
3807 /** For every current directory connection whose purpose is <b>purpose</b>,
3808 * and where the resource being downloaded begins with <b>prefix</b>, split
3809 * rest of the resource into base16 fingerprints, decode them, and set the
3810 * corresponding elements of <b>result</b> to a nonzero value. */
3811 static void
3812 list_pending_downloads(digestmap_t *result,
3813 int purpose, const char *prefix)
3815 const size_t p_len = strlen(prefix);
3816 smartlist_t *tmp = smartlist_create();
3817 smartlist_t *conns = get_connection_array();
3819 tor_assert(result);
3821 SMARTLIST_FOREACH(conns, connection_t *, conn,
3823 if (conn->type == CONN_TYPE_DIR &&
3824 conn->purpose == purpose &&
3825 !conn->marked_for_close) {
3826 const char *resource = TO_DIR_CONN(conn)->requested_resource;
3827 if (!strcmpstart(resource, prefix))
3828 dir_split_resource_into_fingerprints(resource + p_len,
3829 tmp, NULL, 1, 0);
3832 SMARTLIST_FOREACH(tmp, char *, d,
3834 digestmap_set(result, d, (void*)1);
3835 tor_free(d);
3837 smartlist_free(tmp);
3840 /** For every router descriptor (or extra-info document if <b>extrainfo</b> is
3841 * true) we are currently downloading by descriptor digest, set result[d] to
3842 * (void*)1. */
3843 static void
3844 list_pending_descriptor_downloads(digestmap_t *result, int extrainfo)
3846 int purpose =
3847 extrainfo ? DIR_PURPOSE_FETCH_EXTRAINFO : DIR_PURPOSE_FETCH_SERVERDESC;
3848 list_pending_downloads(result, purpose, "d/");
3851 /** Launch downloads for all the descriptors whose digests are listed
3852 * as digests[i] for lo <= i < hi. (Lo and hi may be out of range.)
3853 * If <b>source</b> is given, download from <b>source</b>; otherwise,
3854 * download from an appropriate random directory server.
3856 static void
3857 initiate_descriptor_downloads(routerstatus_t *source,
3858 int purpose,
3859 smartlist_t *digests,
3860 int lo, int hi, int pds_flags)
3862 int i, n = hi-lo;
3863 char *resource, *cp;
3864 size_t r_len;
3865 if (n <= 0)
3866 return;
3867 if (lo < 0)
3868 lo = 0;
3869 if (hi > smartlist_len(digests))
3870 hi = smartlist_len(digests);
3872 r_len = 8 + (HEX_DIGEST_LEN+1)*n;
3873 cp = resource = tor_malloc(r_len);
3874 memcpy(cp, "d/", 2);
3875 cp += 2;
3876 for (i = lo; i < hi; ++i) {
3877 base16_encode(cp, r_len-(cp-resource),
3878 smartlist_get(digests,i), DIGEST_LEN);
3879 cp += HEX_DIGEST_LEN;
3880 *cp++ = '+';
3882 memcpy(cp-1, ".z", 3);
3884 if (source) {
3885 /* We know which authority we want. */
3886 directory_initiate_command_routerstatus(source, purpose,
3887 ROUTER_PURPOSE_GENERAL,
3888 0, /* not private */
3889 resource, NULL, 0, 0);
3890 } else {
3891 directory_get_from_dirserver(purpose, ROUTER_PURPOSE_GENERAL, resource,
3892 pds_flags);
3894 tor_free(resource);
3897 /** Return 0 if this routerstatus is obsolete, too new, isn't
3898 * running, or otherwise not a descriptor that we would make any
3899 * use of even if we had it. Else return 1. */
3900 static INLINE int
3901 client_would_use_router(routerstatus_t *rs, time_t now, or_options_t *options)
3903 if (!rs->is_running && !options->FetchUselessDescriptors) {
3904 /* If we had this router descriptor, we wouldn't even bother using it.
3905 * But, if we want to have a complete list, fetch it anyway. */
3906 return 0;
3908 if (rs->published_on + options->TestingEstimatedDescriptorPropagationTime
3909 > now) {
3910 /* Most caches probably don't have this descriptor yet. */
3911 return 0;
3913 if (rs->published_on + OLD_ROUTER_DESC_MAX_AGE < now) {
3914 /* We'd drop it immediately for being too old. */
3915 return 0;
3917 return 1;
3920 /** Max amount of hashes to download per request.
3921 * Since squid does not like URLs >= 4096 bytes we limit it to 96.
3922 * 4096 - strlen(http://255.255.255.255/tor/server/d/.z) == 4058
3923 * 4058/41 (40 for the hash and 1 for the + that separates them) => 98
3924 * So use 96 because it's a nice number.
3926 #define MAX_DL_PER_REQUEST 96
3927 /** Don't split our requests so finely that we are requesting fewer than
3928 * this number per server. */
3929 #define MIN_DL_PER_REQUEST 4
3930 /** To prevent a single screwy cache from confusing us by selective reply,
3931 * try to split our requests into at least this this many requests. */
3932 #define MIN_REQUESTS 3
3933 /** If we want fewer than this many descriptors, wait until we
3934 * want more, or until MAX_CLIENT_INTERVAL_WITHOUT_REQUEST has
3935 * passed. */
3936 #define MAX_DL_TO_DELAY 16
3937 /** When directory clients have only a few servers to request, they batch
3938 * them until they have more, or until this amount of time has passed. */
3939 #define MAX_CLIENT_INTERVAL_WITHOUT_REQUEST (10*60)
3941 /** Given a list of router descriptor digests in <b>downloadable</b>, decide
3942 * whether to delay fetching until we have more. If we don't want to delay,
3943 * launch one or more requests to the appropriate directory authorities. */
3944 static void
3945 launch_router_descriptor_downloads(smartlist_t *downloadable, time_t now)
3947 int should_delay = 0, n_downloadable;
3948 or_options_t *options = get_options();
3950 n_downloadable = smartlist_len(downloadable);
3951 if (!directory_fetches_dir_info_early(options)) {
3952 if (n_downloadable >= MAX_DL_TO_DELAY) {
3953 log_debug(LD_DIR,
3954 "There are enough downloadable routerdescs to launch requests.");
3955 should_delay = 0;
3956 } else {
3957 should_delay = (last_routerdesc_download_attempted +
3958 MAX_CLIENT_INTERVAL_WITHOUT_REQUEST) > now;
3959 if (!should_delay && n_downloadable) {
3960 if (last_routerdesc_download_attempted) {
3961 log_info(LD_DIR,
3962 "There are not many downloadable routerdescs, but we've "
3963 "been waiting long enough (%d seconds). Downloading.",
3964 (int)(now-last_routerdesc_download_attempted));
3965 } else {
3966 log_info(LD_DIR,
3967 "There are not many downloadable routerdescs, but we haven't "
3968 "tried downloading descriptors recently. Downloading.");
3973 /* XXX should we consider having even the dir mirrors delay
3974 * a little bit, so we don't load the authorities as much? -RD
3975 * I don't think so. If we do, clients that want those descriptors may
3976 * not actually find them if the caches haven't got them yet. -NM
3979 if (! should_delay && n_downloadable) {
3980 int i, n_per_request;
3981 const char *req_plural = "", *rtr_plural = "";
3982 int pds_flags = PDS_RETRY_IF_NO_SERVERS;
3983 if (! authdir_mode_any_nonhidserv(options)) {
3984 /* If we wind up going to the authorities, we want to only open one
3985 * connection to each authority at a time, so that we don't overload
3986 * them. We do this by setting PDS_NO_EXISTING_SERVERDESC_FETCH
3987 * regardless of whether we're a cache or not; it gets ignored if we're
3988 * not calling router_pick_trusteddirserver.
3990 * Setting this flag can make initiate_descriptor_downloads() ignore
3991 * requests. We need to make sure that we do in fact call
3992 * update_router_descriptor_downloads() later on, once the connections
3993 * have succeeded or failed.
3995 pds_flags |= PDS_NO_EXISTING_SERVERDESC_FETCH;
3998 n_per_request = (n_downloadable+MIN_REQUESTS-1) / MIN_REQUESTS;
3999 if (n_per_request > MAX_DL_PER_REQUEST)
4000 n_per_request = MAX_DL_PER_REQUEST;
4001 if (n_per_request < MIN_DL_PER_REQUEST)
4002 n_per_request = MIN_DL_PER_REQUEST;
4004 if (n_downloadable > n_per_request)
4005 req_plural = rtr_plural = "s";
4006 else if (n_downloadable > 1)
4007 rtr_plural = "s";
4009 log_info(LD_DIR,
4010 "Launching %d request%s for %d router%s, %d at a time",
4011 (n_downloadable+n_per_request-1)/n_per_request,
4012 req_plural, n_downloadable, rtr_plural, n_per_request);
4013 smartlist_sort_digests(downloadable);
4014 for (i=0; i < n_downloadable; i += n_per_request) {
4015 initiate_descriptor_downloads(NULL, DIR_PURPOSE_FETCH_SERVERDESC,
4016 downloadable, i, i+n_per_request,
4017 pds_flags);
4019 last_routerdesc_download_attempted = now;
4023 /** Launch downloads for router status as needed, using the strategy used by
4024 * authorities and caches: based on the v2 networkstatuses we have, download
4025 * every descriptor we don't have but would serve, from a random authority
4026 * that lists it. */
4027 static void
4028 update_router_descriptor_cache_downloads_v2(time_t now)
4030 smartlist_t **downloadable; /* For each authority, what can we dl from it? */
4031 smartlist_t **download_from; /* ... and, what will we dl from it? */
4032 digestmap_t *map; /* Which descs are in progress, or assigned? */
4033 int i, j, n;
4034 int n_download;
4035 or_options_t *options = get_options();
4036 const smartlist_t *networkstatus_v2_list = networkstatus_get_v2_list();
4038 if (! directory_fetches_dir_info_early(options)) {
4039 log_warn(LD_BUG, "Called update_router_descriptor_cache_downloads_v2() "
4040 "on a non-dir-mirror?");
4043 if (!networkstatus_v2_list || !smartlist_len(networkstatus_v2_list))
4044 return;
4046 map = digestmap_new();
4047 n = smartlist_len(networkstatus_v2_list);
4049 downloadable = tor_malloc_zero(sizeof(smartlist_t*) * n);
4050 download_from = tor_malloc_zero(sizeof(smartlist_t*) * n);
4052 /* Set map[d]=1 for the digest of every descriptor that we are currently
4053 * downloading. */
4054 list_pending_descriptor_downloads(map, 0);
4056 /* For the digest of every descriptor that we don't have, and that we aren't
4057 * downloading, add d to downloadable[i] if the i'th networkstatus knows
4058 * about that descriptor, and we haven't already failed to get that
4059 * descriptor from the corresponding authority.
4061 n_download = 0;
4062 SMARTLIST_FOREACH(networkstatus_v2_list, networkstatus_v2_t *, ns,
4064 trusted_dir_server_t *ds;
4065 smartlist_t *dl;
4066 dl = downloadable[ns_sl_idx] = smartlist_create();
4067 download_from[ns_sl_idx] = smartlist_create();
4068 if (ns->published_on + MAX_NETWORKSTATUS_AGE+10*60 < now) {
4069 /* Don't download if the networkstatus is almost ancient. */
4070 /* Actually, I suspect what's happening here is that we ask
4071 * for the descriptor when we have a given networkstatus,
4072 * and then we get a newer networkstatus, and then we receive
4073 * the descriptor. Having a networkstatus actually expire is
4074 * probably a rare event, and we'll probably be happiest if
4075 * we take this clause out. -RD */
4076 continue;
4079 /* Don't try dirservers that we think are down -- we might have
4080 * just tried them and just marked them as down. */
4081 ds = router_get_trusteddirserver_by_digest(ns->identity_digest);
4082 if (ds && !ds->is_running)
4083 continue;
4085 SMARTLIST_FOREACH(ns->entries, routerstatus_t * , rs,
4087 if (!rs->need_to_mirror)
4088 continue;
4089 if (router_get_by_descriptor_digest(rs->descriptor_digest)) {
4090 log_warn(LD_BUG,
4091 "We have a router descriptor, but need_to_mirror=1.");
4092 rs->need_to_mirror = 0;
4093 continue;
4095 if (authdir_mode(options) && dirserv_would_reject_router(rs)) {
4096 rs->need_to_mirror = 0;
4097 continue;
4099 if (digestmap_get(map, rs->descriptor_digest)) {
4100 /* We're downloading it already. */
4101 continue;
4102 } else {
4103 /* We could download it from this guy. */
4104 smartlist_add(dl, rs->descriptor_digest);
4105 ++n_download;
4110 /* At random, assign descriptors to authorities such that:
4111 * - if d is a member of some downloadable[x], d is a member of some
4112 * download_from[y]. (Everything we want to download, we try to download
4113 * from somebody.)
4114 * - If d is a member of download_from[y], d is a member of downloadable[y].
4115 * (We only try to download descriptors from authorities who claim to have
4116 * them.)
4117 * - No d is a member of download_from[x] and download_from[y] s.t. x != y.
4118 * (We don't try to download anything from two authorities concurrently.)
4120 while (n_download) {
4121 int which_ns = crypto_rand_int(n);
4122 smartlist_t *dl = downloadable[which_ns];
4123 int idx;
4124 char *d;
4125 if (!smartlist_len(dl))
4126 continue;
4127 idx = crypto_rand_int(smartlist_len(dl));
4128 d = smartlist_get(dl, idx);
4129 if (! digestmap_get(map, d)) {
4130 smartlist_add(download_from[which_ns], d);
4131 digestmap_set(map, d, (void*) 1);
4133 smartlist_del(dl, idx);
4134 --n_download;
4137 /* Now, we can actually launch our requests. */
4138 for (i=0; i<n; ++i) {
4139 networkstatus_v2_t *ns = smartlist_get(networkstatus_v2_list, i);
4140 trusted_dir_server_t *ds =
4141 router_get_trusteddirserver_by_digest(ns->identity_digest);
4142 smartlist_t *dl = download_from[i];
4143 int pds_flags = PDS_RETRY_IF_NO_SERVERS;
4144 if (! authdir_mode_any_nonhidserv(options))
4145 pds_flags |= PDS_NO_EXISTING_SERVERDESC_FETCH; /* XXXX ignored*/
4147 if (!ds) {
4148 log_warn(LD_BUG, "Networkstatus with no corresponding authority!");
4149 continue;
4151 if (! smartlist_len(dl))
4152 continue;
4153 log_info(LD_DIR, "Requesting %d descriptors from authority \"%s\"",
4154 smartlist_len(dl), ds->nickname);
4155 for (j=0; j < smartlist_len(dl); j += MAX_DL_PER_REQUEST) {
4156 initiate_descriptor_downloads(&(ds->fake_status),
4157 DIR_PURPOSE_FETCH_SERVERDESC, dl, j,
4158 j+MAX_DL_PER_REQUEST, pds_flags);
4162 for (i=0; i<n; ++i) {
4163 smartlist_free(download_from[i]);
4164 smartlist_free(downloadable[i]);
4166 tor_free(download_from);
4167 tor_free(downloadable);
4168 digestmap_free(map,NULL);
4171 /** For any descriptor that we want that's currently listed in the live
4172 * consensus, download it as appropriate. */
4173 static void
4174 update_consensus_router_descriptor_downloads(time_t now)
4176 or_options_t *options = get_options();
4177 digestmap_t *map = NULL;
4178 smartlist_t *no_longer_old = smartlist_create();
4179 smartlist_t *downloadable = smartlist_create();
4180 int authdir = authdir_mode(options);
4181 networkstatus_t *consensus =
4182 networkstatus_get_reasonably_live_consensus(now);
4183 int n_delayed=0, n_have=0, n_would_reject=0, n_wouldnt_use=0,
4184 n_inprogress=0, n_in_oldrouters=0;
4186 if (directory_too_idle_to_fetch_descriptors(options, now))
4187 goto done;
4188 if (!consensus)
4189 goto done;
4191 map = digestmap_new();
4192 list_pending_descriptor_downloads(map, 0);
4193 SMARTLIST_FOREACH(consensus->routerstatus_list, routerstatus_t *, rs,
4195 signed_descriptor_t *sd;
4196 if ((sd = router_get_by_descriptor_digest(rs->descriptor_digest))) {
4197 routerinfo_t *ri;
4198 ++n_have;
4199 if (!(ri = router_get_by_digest(rs->identity_digest)) ||
4200 memcmp(ri->cache_info.signed_descriptor_digest,
4201 sd->signed_descriptor_digest, DIGEST_LEN)) {
4202 /* We have a descriptor with this digest, but either there is no
4203 * entry in routerlist with the same ID (!ri), or there is one,
4204 * but the identity digest differs (memcmp).
4206 smartlist_add(no_longer_old, sd);
4207 ++n_in_oldrouters; /* We have it in old_routers. */
4209 continue; /* We have it already. */
4211 if (digestmap_get(map, rs->descriptor_digest)) {
4212 ++n_inprogress;
4213 continue; /* We have an in-progress download. */
4215 if (!download_status_is_ready(&rs->dl_status, now,
4216 MAX_ROUTERDESC_DOWNLOAD_FAILURES)) {
4217 ++n_delayed; /* Not ready for retry. */
4218 continue;
4220 if (authdir && dirserv_would_reject_router(rs)) {
4221 ++n_would_reject;
4222 continue; /* We would throw it out immediately. */
4224 if (!directory_caches_dir_info(options) &&
4225 !client_would_use_router(rs, now, options)) {
4226 ++n_wouldnt_use;
4227 continue; /* We would never use it ourself. */
4229 smartlist_add(downloadable, rs->descriptor_digest);
4232 if (!authdir_mode_handles_descs(options, ROUTER_PURPOSE_GENERAL)
4233 && smartlist_len(no_longer_old)) {
4234 routerlist_t *rl = router_get_routerlist();
4235 log_info(LD_DIR, "%d router descriptors listed in consensus are "
4236 "currently in old_routers; making them current.",
4237 smartlist_len(no_longer_old));
4238 SMARTLIST_FOREACH(no_longer_old, signed_descriptor_t *, sd, {
4239 const char *msg;
4240 was_router_added_t r;
4241 routerinfo_t *ri = routerlist_reparse_old(rl, sd);
4242 if (!ri) {
4243 log_warn(LD_BUG, "Failed to re-parse a router.");
4244 continue;
4246 r = router_add_to_routerlist(ri, &msg, 1, 0);
4247 if (WRA_WAS_OUTDATED(r)) {
4248 log_warn(LD_DIR, "Couldn't add re-parsed router: %s",
4249 msg?msg:"???");
4252 routerlist_assert_ok(rl);
4255 log_info(LD_DIR,
4256 "%d router descriptors downloadable. %d delayed; %d present "
4257 "(%d of those were in old_routers); %d would_reject; "
4258 "%d wouldnt_use; %d in progress.",
4259 smartlist_len(downloadable), n_delayed, n_have, n_in_oldrouters,
4260 n_would_reject, n_wouldnt_use, n_inprogress);
4262 launch_router_descriptor_downloads(downloadable, now);
4264 digestmap_free(map, NULL);
4265 done:
4266 smartlist_free(downloadable);
4267 smartlist_free(no_longer_old);
4270 /** How often should we launch a server/authority request to be sure of getting
4271 * a guess for our IP? */
4272 /*XXXX021 this info should come from netinfo cells or something, or we should
4273 * do this only when we aren't seeing incoming data. see bug 652. */
4274 #define DUMMY_DOWNLOAD_INTERVAL (20*60)
4276 /** Launch downloads for router status as needed. */
4277 void
4278 update_router_descriptor_downloads(time_t now)
4280 or_options_t *options = get_options();
4281 static time_t last_dummy_download = 0;
4282 if (should_delay_dir_fetches(options))
4283 return;
4284 if (directory_fetches_dir_info_early(options)) {
4285 update_router_descriptor_cache_downloads_v2(now);
4287 update_consensus_router_descriptor_downloads(now);
4289 /* XXXX021 we could be smarter here; see notes on bug 652. */
4290 /* If we're a server that doesn't have a configured address, we rely on
4291 * directory fetches to learn when our address changes. So if we haven't
4292 * tried to get any routerdescs in a long time, try a dummy fetch now. */
4293 if (!options->Address &&
4294 server_mode(options) &&
4295 last_routerdesc_download_attempted + DUMMY_DOWNLOAD_INTERVAL < now &&
4296 last_dummy_download + DUMMY_DOWNLOAD_INTERVAL < now) {
4297 last_dummy_download = now;
4298 directory_get_from_dirserver(DIR_PURPOSE_FETCH_SERVERDESC,
4299 ROUTER_PURPOSE_GENERAL, "authority.z",
4300 PDS_RETRY_IF_NO_SERVERS);
4304 /** Launch extrainfo downloads as needed. */
4305 void
4306 update_extrainfo_downloads(time_t now)
4308 or_options_t *options = get_options();
4309 routerlist_t *rl;
4310 smartlist_t *wanted;
4311 digestmap_t *pending;
4312 int old_routers, i;
4313 int n_no_ei = 0, n_pending = 0, n_have = 0, n_delay = 0;
4314 if (! options->DownloadExtraInfo)
4315 return;
4316 if (should_delay_dir_fetches(options))
4317 return;
4318 if (!router_have_minimum_dir_info())
4319 return;
4321 pending = digestmap_new();
4322 list_pending_descriptor_downloads(pending, 1);
4323 rl = router_get_routerlist();
4324 wanted = smartlist_create();
4325 for (old_routers = 0; old_routers < 2; ++old_routers) {
4326 smartlist_t *lst = old_routers ? rl->old_routers : rl->routers;
4327 for (i = 0; i < smartlist_len(lst); ++i) {
4328 signed_descriptor_t *sd;
4329 char *d;
4330 if (old_routers)
4331 sd = smartlist_get(lst, i);
4332 else
4333 sd = &((routerinfo_t*)smartlist_get(lst, i))->cache_info;
4334 if (sd->is_extrainfo)
4335 continue; /* This should never happen. */
4336 if (old_routers && !router_get_by_digest(sd->identity_digest))
4337 continue; /* Couldn't check the signature if we got it. */
4338 if (sd->extrainfo_is_bogus)
4339 continue;
4340 d = sd->extra_info_digest;
4341 if (tor_digest_is_zero(d)) {
4342 ++n_no_ei;
4343 continue;
4345 if (eimap_get(rl->extra_info_map, d)) {
4346 ++n_have;
4347 continue;
4349 if (!download_status_is_ready(&sd->ei_dl_status, now,
4350 MAX_ROUTERDESC_DOWNLOAD_FAILURES)) {
4351 ++n_delay;
4352 continue;
4354 if (digestmap_get(pending, d)) {
4355 ++n_pending;
4356 continue;
4358 smartlist_add(wanted, d);
4361 digestmap_free(pending, NULL);
4363 log_info(LD_DIR, "Extrainfo download status: %d router with no ei, %d "
4364 "with present ei, %d delaying, %d pending, %d downloadable.",
4365 n_no_ei, n_have, n_delay, n_pending, smartlist_len(wanted));
4367 smartlist_shuffle(wanted);
4368 for (i = 0; i < smartlist_len(wanted); i += MAX_DL_PER_REQUEST) {
4369 initiate_descriptor_downloads(NULL, DIR_PURPOSE_FETCH_EXTRAINFO,
4370 wanted, i, i + MAX_DL_PER_REQUEST,
4371 PDS_RETRY_IF_NO_SERVERS|PDS_NO_EXISTING_SERVERDESC_FETCH);
4374 smartlist_free(wanted);
4377 /** True iff, the last time we checked whether we had enough directory info
4378 * to build circuits, the answer was "yes". */
4379 static int have_min_dir_info = 0;
4380 /** True iff enough has changed since the last time we checked whether we had
4381 * enough directory info to build circuits that our old answer can no longer
4382 * be trusted. */
4383 static int need_to_update_have_min_dir_info = 1;
4384 /** String describing what we're missing before we have enough directory
4385 * info. */
4386 static char dir_info_status[128] = "";
4388 /** Return true iff we have enough networkstatus and router information to
4389 * start building circuits. Right now, this means "more than half the
4390 * networkstatus documents, and at least 1/4 of expected routers." */
4391 //XXX should consider whether we have enough exiting nodes here.
4393 router_have_minimum_dir_info(void)
4395 if (PREDICT_UNLIKELY(need_to_update_have_min_dir_info)) {
4396 update_router_have_minimum_dir_info();
4397 need_to_update_have_min_dir_info = 0;
4399 return have_min_dir_info;
4402 /** Called when our internal view of the directory has changed. This can be
4403 * when the authorities change, networkstatuses change, the list of routerdescs
4404 * changes, or number of running routers changes.
4406 void
4407 router_dir_info_changed(void)
4409 need_to_update_have_min_dir_info = 1;
4410 rend_hsdir_routers_changed();
4413 /** Return a string describing what we're missing before we have enough
4414 * directory info. */
4415 const char *
4416 get_dir_info_status_string(void)
4418 return dir_info_status;
4421 /** Iterate over the servers listed in <b>consensus</b>, and count how many of
4422 * them seem like ones we'd use, and how many of <em>those</em> we have
4423 * descriptors for. Store the former in *<b>num_usable</b> and the latter in
4424 * *<b>num_present</b>. */
4425 static void
4426 count_usable_descriptors(int *num_present, int *num_usable,
4427 const networkstatus_t *consensus,
4428 or_options_t *options, time_t now)
4430 *num_present = 0, *num_usable=0;
4432 SMARTLIST_FOREACH(consensus->routerstatus_list, routerstatus_t *, rs,
4434 if (client_would_use_router(rs, now, options)) {
4435 ++*num_usable; /* the consensus says we want it. */
4436 if (router_get_by_descriptor_digest(rs->descriptor_digest)) {
4437 /* we have the descriptor listed in the consensus. */
4438 ++*num_present;
4443 log_debug(LD_DIR, "%d usable, %d present.", *num_usable, *num_present);
4446 /** We just fetched a new set of descriptors. Compute how far through
4447 * the "loading descriptors" bootstrapping phase we are, so we can inform
4448 * the controller of our progress. */
4450 count_loading_descriptors_progress(void)
4452 int num_present = 0, num_usable=0;
4453 time_t now = time(NULL);
4454 const networkstatus_t *consensus =
4455 networkstatus_get_reasonably_live_consensus(now);
4456 double fraction;
4458 if (!consensus)
4459 return 0; /* can't count descriptors if we have no list of them */
4461 count_usable_descriptors(&num_present, &num_usable,
4462 consensus, get_options(), now);
4464 if (num_usable == 0)
4465 return 0; /* don't div by 0 */
4466 fraction = num_present / (num_usable/4.);
4467 if (fraction > 1.0)
4468 return 0; /* it's not the number of descriptors holding us back */
4469 return BOOTSTRAP_STATUS_LOADING_DESCRIPTORS + (int)
4470 (fraction*(BOOTSTRAP_STATUS_CONN_OR-1 -
4471 BOOTSTRAP_STATUS_LOADING_DESCRIPTORS));
4474 /** Change the value of have_min_dir_info, setting it true iff we have enough
4475 * network and router information to build circuits. Clear the value of
4476 * need_to_update_have_min_dir_info. */
4477 static void
4478 update_router_have_minimum_dir_info(void)
4480 int num_present = 0, num_usable=0;
4481 time_t now = time(NULL);
4482 int res;
4483 or_options_t *options = get_options();
4484 const networkstatus_t *consensus =
4485 networkstatus_get_reasonably_live_consensus(now);
4487 if (!consensus) {
4488 if (!networkstatus_get_latest_consensus())
4489 strlcpy(dir_info_status, "We have no network-status consensus.",
4490 sizeof(dir_info_status));
4491 else
4492 strlcpy(dir_info_status, "We have no recent network-status consensus.",
4493 sizeof(dir_info_status));
4494 res = 0;
4495 goto done;
4498 if (should_delay_dir_fetches(get_options())) {
4499 log_notice(LD_DIR, "no known bridge descriptors running yet; stalling");
4500 strlcpy(dir_info_status, "No live bridge descriptors.",
4501 sizeof(dir_info_status));
4502 res = 0;
4503 goto done;
4506 count_usable_descriptors(&num_present, &num_usable, consensus, options, now);
4508 if (num_present < num_usable/4) {
4509 tor_snprintf(dir_info_status, sizeof(dir_info_status),
4510 "We have only %d/%d usable descriptors.", num_present, num_usable);
4511 res = 0;
4512 control_event_bootstrap(BOOTSTRAP_STATUS_REQUESTING_DESCRIPTORS, 0);
4513 } else if (num_present < 2) {
4514 tor_snprintf(dir_info_status, sizeof(dir_info_status),
4515 "Only %d descriptor%s here and believed reachable!",
4516 num_present, num_present ? "" : "s");
4517 res = 0;
4518 } else {
4519 res = 1;
4522 done:
4523 if (res && !have_min_dir_info) {
4524 log(LOG_NOTICE, LD_DIR,
4525 "We now have enough directory information to build circuits.");
4526 control_event_client_status(LOG_NOTICE, "ENOUGH_DIR_INFO");
4527 control_event_bootstrap(BOOTSTRAP_STATUS_CONN_OR, 0);
4529 if (!res && have_min_dir_info) {
4530 int quiet = directory_too_idle_to_fetch_descriptors(options, now);
4531 log(quiet ? LOG_INFO : LOG_NOTICE, LD_DIR,
4532 "Our directory information is no longer up-to-date "
4533 "enough to build circuits: %s", dir_info_status);
4534 control_event_client_status(LOG_NOTICE, "NOT_ENOUGH_DIR_INFO");
4536 have_min_dir_info = res;
4537 need_to_update_have_min_dir_info = 0;
4540 /** Reset the descriptor download failure count on all routers, so that we
4541 * can retry any long-failed routers immediately.
4543 void
4544 router_reset_descriptor_download_failures(void)
4546 networkstatus_reset_download_failures();
4547 last_routerdesc_download_attempted = 0;
4548 if (!routerlist)
4549 return;
4550 SMARTLIST_FOREACH(routerlist->routers, routerinfo_t *, ri,
4552 download_status_reset(&ri->cache_info.ei_dl_status);
4554 SMARTLIST_FOREACH(routerlist->old_routers, signed_descriptor_t *, sd,
4556 download_status_reset(&sd->ei_dl_status);
4560 /** Any changes in a router descriptor's publication time larger than this are
4561 * automatically non-cosmetic. */
4562 #define ROUTER_MAX_COSMETIC_TIME_DIFFERENCE (12*60*60)
4564 /** We allow uptime to vary from how much it ought to be by this much. */
4565 #define ROUTER_ALLOW_UPTIME_DRIFT (6*60*60)
4567 /** Return true iff the only differences between r1 and r2 are such that
4568 * would not cause a recent (post 0.1.1.6) dirserver to republish.
4571 router_differences_are_cosmetic(routerinfo_t *r1, routerinfo_t *r2)
4573 time_t r1pub, r2pub;
4574 long time_difference;
4575 tor_assert(r1 && r2);
4577 /* r1 should be the one that was published first. */
4578 if (r1->cache_info.published_on > r2->cache_info.published_on) {
4579 routerinfo_t *ri_tmp = r2;
4580 r2 = r1;
4581 r1 = ri_tmp;
4584 /* If any key fields differ, they're different. */
4585 if (strcasecmp(r1->address, r2->address) ||
4586 strcasecmp(r1->nickname, r2->nickname) ||
4587 r1->or_port != r2->or_port ||
4588 r1->dir_port != r2->dir_port ||
4589 r1->purpose != r2->purpose ||
4590 crypto_pk_cmp_keys(r1->onion_pkey, r2->onion_pkey) ||
4591 crypto_pk_cmp_keys(r1->identity_pkey, r2->identity_pkey) ||
4592 strcasecmp(r1->platform, r2->platform) ||
4593 (r1->contact_info && !r2->contact_info) || /* contact_info is optional */
4594 (!r1->contact_info && r2->contact_info) ||
4595 (r1->contact_info && r2->contact_info &&
4596 strcasecmp(r1->contact_info, r2->contact_info)) ||
4597 r1->is_hibernating != r2->is_hibernating ||
4598 r1->has_old_dnsworkers != r2->has_old_dnsworkers ||
4599 cmp_addr_policies(r1->exit_policy, r2->exit_policy))
4600 return 0;
4601 if ((r1->declared_family == NULL) != (r2->declared_family == NULL))
4602 return 0;
4603 if (r1->declared_family && r2->declared_family) {
4604 int i, n;
4605 if (smartlist_len(r1->declared_family)!=smartlist_len(r2->declared_family))
4606 return 0;
4607 n = smartlist_len(r1->declared_family);
4608 for (i=0; i < n; ++i) {
4609 if (strcasecmp(smartlist_get(r1->declared_family, i),
4610 smartlist_get(r2->declared_family, i)))
4611 return 0;
4615 /* Did bandwidth change a lot? */
4616 if ((r1->bandwidthcapacity < r2->bandwidthcapacity/2) ||
4617 (r2->bandwidthcapacity < r1->bandwidthcapacity/2))
4618 return 0;
4620 /* Did the bandwidthrate or bandwidthburst change? */
4621 if ((r1->bandwidthrate != r2->bandwidthrate) ||
4622 (r1->bandwidthburst != r2->bandwidthburst))
4623 return 0;
4625 /* Did more than 12 hours pass? */
4626 if (r1->cache_info.published_on + ROUTER_MAX_COSMETIC_TIME_DIFFERENCE
4627 < r2->cache_info.published_on)
4628 return 0;
4630 /* Did uptime fail to increase by approximately the amount we would think,
4631 * give or take some slop? */
4632 r1pub = r1->cache_info.published_on;
4633 r2pub = r2->cache_info.published_on;
4634 time_difference = labs(r2->uptime - (r1->uptime + (r2pub - r1pub)));
4635 if (time_difference > ROUTER_ALLOW_UPTIME_DRIFT &&
4636 time_difference > r1->uptime * .05 &&
4637 time_difference > r2->uptime * .05)
4638 return 0;
4640 /* Otherwise, the difference is cosmetic. */
4641 return 1;
4644 /** Check whether <b>ri</b> (a.k.a. sd) is a router compatible with the
4645 * extrainfo document
4646 * <b>ei</b>. If no router is compatible with <b>ei</b>, <b>ei</b> should be
4647 * dropped. Return 0 for "compatible", return 1 for "reject, and inform
4648 * whoever uploaded <b>ei</b>, and return -1 for "reject silently.". If
4649 * <b>msg</b> is present, set *<b>msg</b> to a description of the
4650 * incompatibility (if any).
4653 routerinfo_incompatible_with_extrainfo(routerinfo_t *ri, extrainfo_t *ei,
4654 signed_descriptor_t *sd,
4655 const char **msg)
4657 int digest_matches, r=1;
4658 tor_assert(ri);
4659 tor_assert(ei);
4660 if (!sd)
4661 sd = &ri->cache_info;
4663 if (ei->bad_sig) {
4664 if (msg) *msg = "Extrainfo signature was bad, or signed with wrong key.";
4665 return 1;
4668 digest_matches = !memcmp(ei->cache_info.signed_descriptor_digest,
4669 sd->extra_info_digest, DIGEST_LEN);
4671 /* The identity must match exactly to have been generated at the same time
4672 * by the same router. */
4673 if (memcmp(ri->cache_info.identity_digest, ei->cache_info.identity_digest,
4674 DIGEST_LEN)) {
4675 if (msg) *msg = "Extrainfo nickname or identity did not match routerinfo";
4676 goto err; /* different servers */
4679 if (ei->pending_sig) {
4680 char signed_digest[128];
4681 if (crypto_pk_public_checksig(ri->identity_pkey, signed_digest,
4682 ei->pending_sig, ei->pending_sig_len) != DIGEST_LEN ||
4683 memcmp(signed_digest, ei->cache_info.signed_descriptor_digest,
4684 DIGEST_LEN)) {
4685 ei->bad_sig = 1;
4686 tor_free(ei->pending_sig);
4687 if (msg) *msg = "Extrainfo signature bad, or signed with wrong key";
4688 goto err; /* Bad signature, or no match. */
4691 ei->cache_info.send_unencrypted = ri->cache_info.send_unencrypted;
4692 tor_free(ei->pending_sig);
4695 if (ei->cache_info.published_on < sd->published_on) {
4696 if (msg) *msg = "Extrainfo published time did not match routerdesc";
4697 goto err;
4698 } else if (ei->cache_info.published_on > sd->published_on) {
4699 if (msg) *msg = "Extrainfo published time did not match routerdesc";
4700 r = -1;
4701 goto err;
4704 if (!digest_matches) {
4705 if (msg) *msg = "Extrainfo digest did not match value from routerdesc";
4706 goto err; /* Digest doesn't match declared value. */
4709 return 0;
4710 err:
4711 if (digest_matches) {
4712 /* This signature was okay, and the digest was right: This is indeed the
4713 * corresponding extrainfo. But insanely, it doesn't match the routerinfo
4714 * that lists it. Don't try to fetch this one again. */
4715 sd->extrainfo_is_bogus = 1;
4718 return r;
4721 /** Assert that the internal representation of <b>rl</b> is
4722 * self-consistent. */
4723 void
4724 routerlist_assert_ok(routerlist_t *rl)
4726 routerinfo_t *r2;
4727 signed_descriptor_t *sd2;
4728 if (!rl)
4729 return;
4730 SMARTLIST_FOREACH(rl->routers, routerinfo_t *, r,
4732 r2 = rimap_get(rl->identity_map, r->cache_info.identity_digest);
4733 tor_assert(r == r2);
4734 sd2 = sdmap_get(rl->desc_digest_map,
4735 r->cache_info.signed_descriptor_digest);
4736 tor_assert(&(r->cache_info) == sd2);
4737 tor_assert(r->cache_info.routerlist_index == r_sl_idx);
4738 /* XXXX
4740 * Hoo boy. We need to fix this one, and the fix is a bit tricky, so
4741 * commenting this out is just a band-aid.
4743 * The problem is that, although well-behaved router descriptors
4744 * should never have the same value for their extra_info_digest, it's
4745 * possible for ill-behaved routers to claim whatever they like there.
4747 * The real answer is to trash desc_by_eid_map and instead have
4748 * something that indicates for a given extra-info digest we want,
4749 * what its download status is. We'll do that as a part of routerlist
4750 * refactoring once consensus directories are in. For now,
4751 * this rep violation is probably harmless: an adversary can make us
4752 * reset our retry count for an extrainfo, but that's not the end
4753 * of the world. Changing the representation in 0.2.0.x would just
4754 * destabilize the codebase.
4755 if (!tor_digest_is_zero(r->cache_info.extra_info_digest)) {
4756 signed_descriptor_t *sd3 =
4757 sdmap_get(rl->desc_by_eid_map, r->cache_info.extra_info_digest);
4758 tor_assert(sd3 == &(r->cache_info));
4762 SMARTLIST_FOREACH(rl->old_routers, signed_descriptor_t *, sd,
4764 r2 = rimap_get(rl->identity_map, sd->identity_digest);
4765 tor_assert(sd != &(r2->cache_info));
4766 sd2 = sdmap_get(rl->desc_digest_map, sd->signed_descriptor_digest);
4767 tor_assert(sd == sd2);
4768 tor_assert(sd->routerlist_index == sd_sl_idx);
4769 /* XXXX see above.
4770 if (!tor_digest_is_zero(sd->extra_info_digest)) {
4771 signed_descriptor_t *sd3 =
4772 sdmap_get(rl->desc_by_eid_map, sd->extra_info_digest);
4773 tor_assert(sd3 == sd);
4778 RIMAP_FOREACH(rl->identity_map, d, r) {
4779 tor_assert(!memcmp(r->cache_info.identity_digest, d, DIGEST_LEN));
4780 } DIGESTMAP_FOREACH_END;
4781 SDMAP_FOREACH(rl->desc_digest_map, d, sd) {
4782 tor_assert(!memcmp(sd->signed_descriptor_digest, d, DIGEST_LEN));
4783 } DIGESTMAP_FOREACH_END;
4784 SDMAP_FOREACH(rl->desc_by_eid_map, d, sd) {
4785 tor_assert(!tor_digest_is_zero(d));
4786 tor_assert(sd);
4787 tor_assert(!memcmp(sd->extra_info_digest, d, DIGEST_LEN));
4788 } DIGESTMAP_FOREACH_END;
4789 EIMAP_FOREACH(rl->extra_info_map, d, ei) {
4790 signed_descriptor_t *sd;
4791 tor_assert(!memcmp(ei->cache_info.signed_descriptor_digest,
4792 d, DIGEST_LEN));
4793 sd = sdmap_get(rl->desc_by_eid_map,
4794 ei->cache_info.signed_descriptor_digest);
4795 // tor_assert(sd); // XXXX see above
4796 if (sd) {
4797 tor_assert(!memcmp(ei->cache_info.signed_descriptor_digest,
4798 sd->extra_info_digest, DIGEST_LEN));
4800 } DIGESTMAP_FOREACH_END;
4803 /** Allocate and return a new string representing the contact info
4804 * and platform string for <b>router</b>,
4805 * surrounded by quotes and using standard C escapes.
4807 * THIS FUNCTION IS NOT REENTRANT. Don't call it from outside the main
4808 * thread. Also, each call invalidates the last-returned value, so don't
4809 * try log_warn(LD_GENERAL, "%s %s", esc_router_info(a), esc_router_info(b));
4811 * If <b>router</b> is NULL, it just frees its internal memory and returns.
4813 const char *
4814 esc_router_info(routerinfo_t *router)
4816 static char *info=NULL;
4817 char *esc_contact, *esc_platform;
4818 size_t len;
4819 if (info)
4820 tor_free(info);
4821 if (!router)
4822 return NULL; /* we're exiting; just free the memory we use */
4824 esc_contact = esc_for_log(router->contact_info);
4825 esc_platform = esc_for_log(router->platform);
4827 len = strlen(esc_contact)+strlen(esc_platform)+32;
4828 info = tor_malloc(len);
4829 tor_snprintf(info, len, "Contact %s, Platform %s", esc_contact,
4830 esc_platform);
4831 tor_free(esc_contact);
4832 tor_free(esc_platform);
4834 return info;
4837 /** Helper for sorting: compare two routerinfos by their identity
4838 * digest. */
4839 static int
4840 _compare_routerinfo_by_id_digest(const void **a, const void **b)
4842 routerinfo_t *first = *(routerinfo_t **)a, *second = *(routerinfo_t **)b;
4843 return memcmp(first->cache_info.identity_digest,
4844 second->cache_info.identity_digest,
4845 DIGEST_LEN);
4848 /** Sort a list of routerinfo_t in ascending order of identity digest. */
4849 void
4850 routers_sort_by_identity(smartlist_t *routers)
4852 smartlist_sort(routers, _compare_routerinfo_by_id_digest);
4855 /** A routerset specifies constraints on a set of possible routerinfos, based
4856 * on their names, identities, or addresses. It is optimized for determining
4857 * whether a router is a member or not, in O(1+P) time, where P is the number
4858 * of address policy constraints. */
4859 struct routerset_t {
4860 /** A list of strings for the elements of the policy. Each string is either
4861 * a nickname, a hexadecimal identity fingerprint, or an address policy. A
4862 * router belongs to the set if its nickname OR its identity OR its address
4863 * matches an entry here. */
4864 smartlist_t *list;
4865 /** A map from lowercase nicknames of routers in the set to (void*)1 */
4866 strmap_t *names;
4867 /** A map from identity digests routers in the set to (void*)1 */
4868 digestmap_t *digests;
4869 /** An address policy for routers in the set. For implementation reasons,
4870 * a router belongs to the set if it is _rejected_ by this policy. */
4871 smartlist_t *policies;
4873 /** A human-readable description of what this routerset is for. Used in
4874 * log messages. */
4875 char *description;
4877 /** A list of the country codes in this set. */
4878 smartlist_t *country_names;
4879 /** Total number of countries we knew about when we built <b>countries</b>.*/
4880 int n_countries;
4881 /** Bit array mapping the return value of geoip_get_country() to 1 iff the
4882 * country is a member of this routerset. Note that we MUST call
4883 * routerset_refresh_countries() whenever the geoip country list is
4884 * reloaded. */
4885 bitarray_t *countries;
4888 /** Return a new empty routerset. */
4889 routerset_t *
4890 routerset_new(void)
4892 routerset_t *result = tor_malloc_zero(sizeof(routerset_t));
4893 result->list = smartlist_create();
4894 result->names = strmap_new();
4895 result->digests = digestmap_new();
4896 result->policies = smartlist_create();
4897 result->country_names = smartlist_create();
4898 return result;
4901 /** If <b>c</b> is a country code in the form {cc}, return a newly allocated
4902 * string holding the "cc" part. Else, return NULL. */
4903 static char *
4904 routerset_get_countryname(const char *c)
4906 char *country;
4908 if (strlen(c) < 4 || c[0] !='{' || c[3] !='}')
4909 return NULL;
4911 country = tor_strndup(c+1, 2);
4912 tor_strlower(country);
4913 return country;
4916 #if 0
4917 /** Add the GeoIP database's integer index (+1) of a valid two-character
4918 * country code to the routerset's <b>countries</b> bitarray. Return the
4919 * integer index if the country code is valid, -1 otherwise.*/
4920 static int
4921 routerset_add_country(const char *c)
4923 char country[3];
4924 country_t cc;
4926 /* XXXX: Country codes must be of the form \{[a-z\?]{2}\} but this accepts
4927 \{[.]{2}\}. Do we need to be strict? -RH */
4928 /* Nope; if the country code is bad, we'll get 0 when we look it up. */
4930 if (!geoip_is_loaded()) {
4931 log(LOG_WARN, LD_CONFIG, "GeoIP database not loaded: Cannot add country"
4932 "entry %s, ignoring.", c);
4933 return -1;
4936 memcpy(country, c+1, 2);
4937 country[2] = '\0';
4938 tor_strlower(country);
4940 if ((cc=geoip_get_country(country))==-1) {
4941 log(LOG_WARN, LD_CONFIG, "Country code '%s' is not valid, ignoring.",
4942 country);
4944 return cc;
4946 #endif
4948 /** Update the routerset's <b>countries</b> bitarray_t. Called whenever
4949 * the GeoIP database is reloaded.
4951 void
4952 routerset_refresh_countries(routerset_t *target)
4954 int cc;
4955 if (target->countries) {
4956 bitarray_free(target->countries);
4958 if (!geoip_is_loaded()) {
4959 target->countries = NULL;
4960 target->n_countries = 0;
4961 return;
4963 target->n_countries = geoip_get_n_countries();
4964 target->countries = bitarray_init_zero(target->n_countries);
4965 SMARTLIST_FOREACH_BEGIN(target->country_names, const char *, country) {
4966 cc = geoip_get_country(country);
4967 if (cc >= 0) {
4968 tor_assert(cc < target->n_countries);
4969 bitarray_set(target->countries, cc);
4970 } else {
4971 log(LOG_WARN, LD_CONFIG, "Country code '%s' is not recognized.",
4972 country);
4974 } SMARTLIST_FOREACH_END(country);
4977 /** Parse the string <b>s</b> to create a set of routerset entries, and add
4978 * them to <b>target</b>. In log messages, refer to the string as
4979 * <b>description</b>. Return 0 on success, -1 on failure.
4981 * Three kinds of elements are allowed in routersets: nicknames, IP address
4982 * patterns, and fingerprints. They may be surrounded by optional space, and
4983 * must be separated by commas.
4986 routerset_parse(routerset_t *target, const char *s, const char *description)
4988 int r = 0;
4989 int added_countries = 0;
4990 char *countryname;
4991 smartlist_t *list = smartlist_create();
4992 smartlist_split_string(list, s, ",",
4993 SPLIT_SKIP_SPACE | SPLIT_IGNORE_BLANK, 0);
4994 SMARTLIST_FOREACH_BEGIN(list, char *, nick) {
4995 addr_policy_t *p;
4996 if (is_legal_hexdigest(nick)) {
4997 char d[DIGEST_LEN];
4998 if (*nick == '$')
4999 ++nick;
5000 log_debug(LD_CONFIG, "Adding identity %s to %s", nick, description);
5001 base16_decode(d, sizeof(d), nick, HEX_DIGEST_LEN);
5002 digestmap_set(target->digests, d, (void*)1);
5003 } else if (is_legal_nickname(nick)) {
5004 log_debug(LD_CONFIG, "Adding nickname %s to %s", nick, description);
5005 strmap_set_lc(target->names, nick, (void*)1);
5006 } else if ((countryname = routerset_get_countryname(nick)) != NULL) {
5007 log_debug(LD_CONFIG, "Adding country %s to %s", nick,
5008 description);
5009 smartlist_add(target->country_names, countryname);
5010 added_countries = 1;
5011 } else if ((strchr(nick,'.') || strchr(nick, '*')) &&
5012 (p = router_parse_addr_policy_item_from_string(
5013 nick, ADDR_POLICY_REJECT))) {
5014 log_debug(LD_CONFIG, "Adding address %s to %s", nick, description);
5015 smartlist_add(target->policies, p);
5016 } else {
5017 log_warn(LD_CONFIG, "Entry '%s' in %s is misformed.", nick,
5018 description);
5019 r = -1;
5020 tor_free(nick);
5021 SMARTLIST_DEL_CURRENT(list, nick);
5023 } SMARTLIST_FOREACH_END(nick);
5024 smartlist_add_all(target->list, list);
5025 smartlist_free(list);
5026 if (added_countries)
5027 routerset_refresh_countries(target);
5028 return r;
5031 /** DOCDOC */
5032 void
5033 refresh_all_country_info(void)
5035 or_options_t *options = get_options();
5037 if (options->EntryNodes)
5038 routerset_refresh_countries(options->EntryNodes);
5039 if (options->ExitNodes)
5040 routerset_refresh_countries(options->ExitNodes);
5041 if (options->ExcludeNodes)
5042 routerset_refresh_countries(options->ExcludeNodes);
5043 if (options->ExcludeExitNodes)
5044 routerset_refresh_countries(options->ExcludeExitNodes);
5045 if (options->_ExcludeExitNodesUnion)
5046 routerset_refresh_countries(options->_ExcludeExitNodesUnion);
5048 routerlist_refresh_countries();
5051 /** Add all members of the set <b>source</b> to <b>target</b>. */
5052 void
5053 routerset_union(routerset_t *target, const routerset_t *source)
5055 char *s;
5056 tor_assert(target);
5057 if (!source || !source->list)
5058 return;
5059 s = routerset_to_string(source);
5060 routerset_parse(target, s, "other routerset");
5061 tor_free(s);
5064 /** Return true iff <b>set</b> lists only nicknames and digests, and includes
5065 * no IP ranges or countries. */
5067 routerset_is_list(const routerset_t *set)
5069 return smartlist_len(set->country_names) == 0 &&
5070 smartlist_len(set->policies) == 0;
5073 /** Return true iff we need a GeoIP IP-to-country database to make sense of
5074 * <b>set</b>. */
5076 routerset_needs_geoip(const routerset_t *set)
5078 return set && smartlist_len(set->country_names);
5081 /** Return true iff there are no entries in <b>set</b>. */
5082 static int
5083 routerset_is_empty(const routerset_t *set)
5085 return !set || smartlist_len(set->list) == 0;
5088 /** Helper. Return true iff <b>set</b> contains a router based on the other
5089 * provided fields. Return higher values for more specific subentries: a
5090 * single router is more specific than an address range of routers, which is
5091 * more specific in turn than a country code.
5093 * (If country is -1, then we take the country
5094 * from addr.) */
5095 static int
5096 routerset_contains(const routerset_t *set, const tor_addr_t *addr,
5097 uint16_t orport,
5098 const char *nickname, const char *id_digest, int is_named,
5099 country_t country)
5101 if (!set || !set->list) return 0;
5102 (void) is_named; /* not supported */
5103 if (nickname && strmap_get_lc(set->names, nickname))
5104 return 4;
5105 if (id_digest && digestmap_get(set->digests, id_digest))
5106 return 4;
5107 if (addr && compare_tor_addr_to_addr_policy(addr, orport, set->policies)
5108 == ADDR_POLICY_REJECTED)
5109 return 3;
5110 if (set->countries) {
5111 if (country < 0 && addr)
5112 country = geoip_get_country_by_ip(tor_addr_to_ipv4h(addr));
5114 if (country >= 0 && country < set->n_countries &&
5115 bitarray_is_set(set->countries, country))
5116 return 2;
5118 return 0;
5121 /** Return true iff we can tell that <b>ei</b> is a member of <b>set</b>. */
5123 routerset_contains_extendinfo(const routerset_t *set, const extend_info_t *ei)
5125 return routerset_contains(set,
5126 &ei->addr,
5127 ei->port,
5128 ei->nickname,
5129 ei->identity_digest,
5130 -1, /*is_named*/
5131 -1 /*country*/);
5134 /** Return true iff <b>ri</b> is in <b>set</b>. */
5136 routerset_contains_router(const routerset_t *set, routerinfo_t *ri)
5138 tor_addr_t addr;
5139 tor_addr_from_ipv4h(&addr, ri->addr);
5140 return routerset_contains(set,
5141 &addr,
5142 ri->or_port,
5143 ri->nickname,
5144 ri->cache_info.identity_digest,
5145 ri->is_named,
5146 ri->country);
5149 /** Return true iff <b>rs</b> is in <b>set</b>. */
5151 routerset_contains_routerstatus(const routerset_t *set, routerstatus_t *rs)
5153 tor_addr_t addr;
5154 tor_addr_from_ipv4h(&addr, rs->addr);
5155 return routerset_contains(set,
5156 &addr,
5157 rs->or_port,
5158 rs->nickname,
5159 rs->identity_digest,
5160 rs->is_named,
5161 -1);
5164 /** Add every known routerinfo_t that is a member of <b>routerset</b> to
5165 * <b>out</b>. If <b>running_only</b>, only add the running ones. */
5166 void
5167 routerset_get_all_routers(smartlist_t *out, const routerset_t *routerset,
5168 int running_only)
5170 tor_assert(out);
5171 if (!routerset || !routerset->list)
5172 return;
5173 if (!warned_nicknames)
5174 warned_nicknames = smartlist_create();
5175 if (routerset_is_list(routerset)) {
5177 /* No routers are specified by type; all are given by name or digest.
5178 * we can do a lookup in O(len(list)). */
5179 SMARTLIST_FOREACH(routerset->list, const char *, name, {
5180 routerinfo_t *router = router_get_by_nickname(name, 1);
5181 if (router) {
5182 if (!running_only || router->is_running)
5183 smartlist_add(out, router);
5186 } else {
5187 /* We need to iterate over the routerlist to get all the ones of the
5188 * right kind. */
5189 routerlist_t *rl = router_get_routerlist();
5190 SMARTLIST_FOREACH(rl->routers, routerinfo_t *, router, {
5191 if (running_only && !router->is_running)
5192 continue;
5193 if (routerset_contains_router(routerset, router))
5194 smartlist_add(out, router);
5199 /** Add to <b>target</b> every routerinfo_t from <b>source</b> that is in
5200 * <b>include</b>, but not excluded in a more specific fashion by
5201 * <b>exclude</b>. If <b>running_only</b>, only include running routers.
5203 void
5204 routersets_get_disjunction(smartlist_t *target,
5205 const smartlist_t *source,
5206 const routerset_t *include,
5207 const routerset_t *exclude, int running_only)
5209 SMARTLIST_FOREACH(source, routerinfo_t *, router, {
5210 int include_result;
5211 if (running_only && !router->is_running)
5212 continue;
5213 if (!routerset_is_empty(include))
5214 include_result = routerset_contains_router(include, router);
5215 else
5216 include_result = 1;
5218 if (include_result) {
5219 int exclude_result = routerset_contains_router(exclude, router);
5220 if (include_result >= exclude_result)
5221 smartlist_add(target, router);
5226 /** Remove every routerinfo_t from <b>lst</b> that is in <b>routerset</b>. */
5227 void
5228 routerset_subtract_routers(smartlist_t *lst, const routerset_t *routerset)
5230 tor_assert(lst);
5231 if (!routerset)
5232 return;
5233 SMARTLIST_FOREACH(lst, routerinfo_t *, r, {
5234 if (routerset_contains_router(routerset, r)) {
5235 //log_debug(LD_DIR, "Subtracting %s",r->nickname);
5236 SMARTLIST_DEL_CURRENT(lst, r);
5241 /** Return a new string that when parsed by routerset_parse_string() will
5242 * yield <b>set</b>. */
5243 char *
5244 routerset_to_string(const routerset_t *set)
5246 if (!set || !set->list)
5247 return tor_strdup("");
5248 return smartlist_join_strings(set->list, ",", 0, NULL);
5251 /** Helper: return true iff old and new are both NULL, or both non-NULL
5252 * equal routersets. */
5254 routerset_equal(const routerset_t *old, const routerset_t *new)
5256 if (old == NULL && new == NULL)
5257 return 1;
5258 else if (old == NULL || new == NULL)
5259 return 0;
5261 if (smartlist_len(old->list) != smartlist_len(new->list))
5262 return 0;
5264 SMARTLIST_FOREACH(old->list, const char *, cp1, {
5265 const char *cp2 = smartlist_get(new->list, cp1_sl_idx);
5266 if (strcmp(cp1, cp2))
5267 return 0;
5270 return 1;
5272 #if 0
5273 /* XXXX: This won't work if the names/digests are identical but in a
5274 different order. Checking for exact equality would be heavy going,
5275 is it worth it? -RH*/
5276 /* This code is totally bogus; sizeof doesn't work even remotely like this
5277 * code seems to think. Let's revert to a string-based comparison for
5278 * now. -NM*/
5279 if (sizeof(old->names) != sizeof(new->names))
5280 return 0;
5282 if (memcmp(old->names,new->names,sizeof(new->names)))
5283 return 0;
5284 if (sizeof(old->digests) != sizeof(new->digests))
5285 return 0;
5286 if (memcmp(old->digests,new->digests,sizeof(new->digests)))
5287 return 0;
5288 if (sizeof(old->countries) != sizeof(new->countries))
5289 return 0;
5290 if (memcmp(old->countries,new->countries,sizeof(new->countries)))
5291 return 0;
5292 return 1;
5293 #endif
5296 /** Free all storage held in <b>routerset</b>. */
5297 void
5298 routerset_free(routerset_t *routerset)
5300 SMARTLIST_FOREACH(routerset->list, char *, cp, tor_free(cp));
5301 smartlist_free(routerset->list);
5302 SMARTLIST_FOREACH(routerset->policies, addr_policy_t *, p,
5303 addr_policy_free(p));
5304 smartlist_free(routerset->policies);
5305 SMARTLIST_FOREACH(routerset->country_names, char *, cp, tor_free(cp));
5306 smartlist_free(routerset->country_names);
5308 strmap_free(routerset->names, NULL);
5309 digestmap_free(routerset->digests, NULL);
5310 if (routerset->countries)
5311 bitarray_free(routerset->countries);
5312 tor_free(routerset);
5315 /** Refresh the country code of <b>ri</b>. This function MUST be called on
5316 * each router when the GeoIP database is reloaded, and on all new routers. */
5317 void
5318 routerinfo_set_country(routerinfo_t *ri)
5320 ri->country = geoip_get_country_by_ip(ri->addr);
5323 /** Set the country code of all routers in the routerlist. */
5324 void
5325 routerlist_refresh_countries(void)
5327 routerlist_t *rl = router_get_routerlist();
5328 SMARTLIST_FOREACH(rl->routers, routerinfo_t *, ri,
5329 routerinfo_set_country(ri));
5332 /** Determine the routers that are responsible for <b>id</b> (binary) and
5333 * add pointers to those routers' routerstatus_t to <b>responsible_dirs</b>.
5334 * Return -1 if we're returning an empty smartlist, else return 0.
5337 hid_serv_get_responsible_directories(smartlist_t *responsible_dirs,
5338 const char *id)
5340 int start, found, n_added = 0, i;
5341 networkstatus_t *c = networkstatus_get_latest_consensus();
5342 int use_begindir = get_options()->TunnelDirConns;
5343 if (!c || !smartlist_len(c->routerstatus_list)) {
5344 log_warn(LD_REND, "We don't have a consensus, so we can't perform v2 "
5345 "rendezvous operations.");
5346 return -1;
5348 tor_assert(id);
5349 start = networkstatus_vote_find_entry_idx(c, id, &found);
5350 if (start == smartlist_len(c->routerstatus_list)) start = 0;
5351 i = start;
5352 do {
5353 routerstatus_t *r = smartlist_get(c->routerstatus_list, i);
5354 if (r->is_hs_dir) {
5355 if (r->dir_port || use_begindir)
5356 smartlist_add(responsible_dirs, r);
5357 else
5358 log_info(LD_REND, "Not adding router '%s' to list of responsible "
5359 "hidden service directories, because we have no way of "
5360 "reaching it.", r->nickname);
5361 if (++n_added == REND_NUMBER_OF_CONSECUTIVE_REPLICAS)
5362 break;
5364 if (++i == smartlist_len(c->routerstatus_list))
5365 i = 0;
5366 } while (i != start);
5368 /* Even though we don't have the desired number of hidden service
5369 * directories, be happy if we got any. */
5370 return smartlist_len(responsible_dirs) ? 0 : -1;
5373 /** Return true if this node is currently acting as hidden service
5374 * directory, false otherwise. */
5376 hid_serv_acting_as_directory(void)
5378 routerinfo_t *me = router_get_my_routerinfo();
5379 networkstatus_t *c;
5380 routerstatus_t *rs;
5381 if (!me)
5382 return 0;
5383 if (!get_options()->HidServDirectoryV2) {
5384 log_info(LD_REND, "We are not acting as hidden service directory, "
5385 "because we have not been configured as such.");
5386 return 0;
5388 if (!(c = networkstatus_get_latest_consensus())) {
5389 log_info(LD_REND, "There's no consensus, so I can't tell if I'm a hidden "
5390 "service directory");
5391 return 0;
5393 rs = networkstatus_vote_find_entry(c, me->cache_info.identity_digest);
5394 if (!rs) {
5395 log_info(LD_REND, "We're not listed in the consensus, so we're not "
5396 "being a hidden service directory.");
5397 return 0;
5399 if (!rs->is_hs_dir) {
5400 log_info(LD_REND, "We're not listed as a hidden service directory in "
5401 "the consensus, so we won't be one.");
5402 return 0;
5404 return 1;
5407 /** Return true if this node is responsible for storing the descriptor ID
5408 * in <b>query</b> and false otherwise. */
5410 hid_serv_responsible_for_desc_id(const char *query)
5412 routerinfo_t *me;
5413 routerstatus_t *last_rs;
5414 const char *my_id, *last_id;
5415 int result;
5416 smartlist_t *responsible;
5417 if (!hid_serv_acting_as_directory())
5418 return 0;
5419 if (!(me = router_get_my_routerinfo()))
5420 return 0; /* This is redundant, but let's be paranoid. */
5421 my_id = me->cache_info.identity_digest;
5422 responsible = smartlist_create();
5423 if (hid_serv_get_responsible_directories(responsible, query) < 0) {
5424 smartlist_free(responsible);
5425 return 0;
5427 last_rs = smartlist_get(responsible, smartlist_len(responsible)-1);
5428 last_id = last_rs->identity_digest;
5429 result = rend_id_is_in_interval(my_id, query, last_id);
5430 smartlist_free(responsible);
5431 return result;