r12816@catbus: nickm | 2007-05-19 18:21:44 -0400
[tor.git] / src / or / routerlist.c
blobbb2b7d4e00e315caa018811be88c79c77eb14a75
1 /* Copyright (c) 2001 Matej Pfajfar.
2 * Copyright (c) 2001-2004, Roger Dingledine.
3 * Copyright (c) 2004-2007, Roger Dingledine, Nick Mathewson. */
4 /* See LICENSE for licensing information */
5 /* $Id$ */
6 const char routerlist_c_id[] =
7 "$Id$";
9 /**
10 * \file routerlist.c
11 * \brief Code to
12 * maintain and access the global list of routerinfos for known
13 * servers.
14 **/
16 #include "or.h"
18 /****************************************************************************/
20 /* static function prototypes */
21 static routerstatus_t *router_pick_directory_server_impl(int requireother,
22 int fascistfirewall,
23 int prefer_tunnel,
24 int for_v2_directory);
25 static routerstatus_t *router_pick_trusteddirserver_impl(
26 authority_type_t type, int requireother,
27 int fascistfirewall, int prefer_tunnel);
28 static void mark_all_trusteddirservers_up(void);
29 static int router_nickname_matches(routerinfo_t *router, const char *nickname);
30 static void routerstatus_list_update_from_networkstatus(time_t now);
31 static void local_routerstatus_free(local_routerstatus_t *rs);
32 static void trusted_dir_server_free(trusted_dir_server_t *ds);
33 static void update_networkstatus_cache_downloads(time_t now);
34 static void update_networkstatus_client_downloads(time_t now);
35 static int signed_desc_digest_is_recognized(signed_descriptor_t *desc);
36 static void routerlist_assert_ok(routerlist_t *rl);
37 static int have_tried_downloading_all_statuses(int n_failures);
38 static routerstatus_t *networkstatus_find_entry(networkstatus_t *ns,
39 const char *digest);
40 static local_routerstatus_t *router_get_combined_status_by_nickname(
41 const char *nickname,
42 int warn_if_unnamed);
43 static void update_router_have_minimum_dir_info(void);
44 static void router_dir_info_changed(void);
46 /****************************************************************************/
48 /** Global list of a trusted_dir_server_t object for each trusted directory
49 * server. */
50 static smartlist_t *trusted_dir_servers = NULL;
52 /** Global list of all of the routers that we know about. */
53 static routerlist_t *routerlist = NULL;
55 /** Global list of all of the current network_status documents that we know
56 * about. This list is kept sorted by published_on. */
57 static smartlist_t *networkstatus_list = NULL;
59 /** Global list of local_routerstatus_t for each router, known or unknown.
60 * Kept sorted by digest. */
61 static smartlist_t *routerstatus_list = NULL;
63 /** Map from lowercase nickname to digest of named server, if any. */
64 static strmap_t *named_server_map = NULL;
66 /** True iff any member of networkstatus_list has changed since the last time
67 * we called routerstatus_list_update_from_networkstatus(). */
68 static int networkstatus_list_has_changed = 0;
70 /** True iff any element of routerstatus_list has changed since the last
71 * time we called routers_update_all_from_networkstatus().*/
72 static int routerstatus_list_has_changed = 0;
74 /** List of strings for nicknames we've already warned about and that are
75 * still unknown / unavailable. */
76 static smartlist_t *warned_nicknames = NULL;
78 /** List of strings for nicknames or fingerprints we've already warned about
79 * and that are still conflicted. */
80 static smartlist_t *warned_conflicts = NULL;
82 /** The last time we tried to download any routerdesc, or 0 for "never". We
83 * use this to rate-limit download attempts when the number of routerdescs to
84 * download is low. */
85 static time_t last_routerdesc_download_attempted = 0;
87 /** The last time we tried to download a networkstatus, or 0 for "never". We
88 * use this to rate-limit download attempts for directory caches (including
89 * mirrors). Clients don't use this now. */
90 static time_t last_networkstatus_download_attempted = 0;
92 /** True iff we have logged a warning about this OR not being valid or
93 * not being named. */
94 static int have_warned_about_invalid_status = 0;
95 /** True iff we have logged a warning about this OR's version being older than
96 * listed by the authorities */
97 static int have_warned_about_old_version = 0;
98 /** True iff we have logged a warning about this OR's version being newer than
99 * listed by the authorities */
100 static int have_warned_about_new_version = 0;
102 /** Return the number of v2 directory authorities */
103 static INLINE int
104 get_n_v2_authorities(void)
106 int n = 0;
107 if (!trusted_dir_servers)
108 return 0;
109 SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, ds,
110 if (ds->is_v2_authority)
111 ++n);
112 return n;
115 /** Repopulate our list of network_status_t objects from the list cached on
116 * disk. Return 0 on success, -1 on failure. */
118 router_reload_networkstatus(void)
120 char filename[512];
121 smartlist_t *entries;
122 struct stat st;
123 char *s;
124 tor_assert(get_options()->DataDirectory);
125 if (!networkstatus_list)
126 networkstatus_list = smartlist_create();
128 tor_snprintf(filename,sizeof(filename),"%s/cached-status",
129 get_options()->DataDirectory);
130 entries = tor_listdir(filename);
131 SMARTLIST_FOREACH(entries, const char *, fn, {
132 char buf[DIGEST_LEN];
133 if (strlen(fn) != HEX_DIGEST_LEN ||
134 base16_decode(buf, sizeof(buf), fn, strlen(fn))) {
135 log_info(LD_DIR,
136 "Skipping cached-status file with unexpected name \"%s\"",fn);
137 continue;
139 tor_snprintf(filename,sizeof(filename),"%s/cached-status/%s",
140 get_options()->DataDirectory, fn);
141 s = read_file_to_str(filename, 0, &st);
142 if (s) {
143 if (router_set_networkstatus(s, st.st_mtime, NS_FROM_CACHE, NULL)<0) {
144 log_warn(LD_FS, "Couldn't load networkstatus from \"%s\"",filename);
146 tor_free(s);
149 SMARTLIST_FOREACH(entries, char *, fn, tor_free(fn));
150 smartlist_free(entries);
151 networkstatus_list_clean(time(NULL));
152 routers_update_all_from_networkstatus();
153 return 0;
156 /* Router descriptor storage.
158 * Routerdescs are stored in a big file, named "cached-routers". As new
159 * routerdescs arrive, we append them to a journal file named
160 * "cached-routers.new".
162 * From time to time, we replace "cached-routers" with a new file containing
163 * only the live, non-superseded descriptors, and clear cached-routers.new.
165 * On startup, we read both files.
168 /** The size of the router log, in bytes. */
169 static size_t router_journal_len = 0;
170 /** The size of the router store, in bytes. */
171 static size_t router_store_len = 0;
172 /** Total bytes dropped since last rebuild. */
173 static size_t router_bytes_dropped = 0;
175 /** Helper: return 1 iff the router log is so big we want to rebuild the
176 * store. */
177 static int
178 router_should_rebuild_store(void)
180 if (router_store_len > (1<<16))
181 return (router_journal_len > router_store_len / 2 ||
182 router_bytes_dropped > router_store_len / 2);
183 else
184 return router_journal_len > (1<<15);
187 /** Add the <b>len</b>-type router descriptor in <b>s</b> to the router
188 * journal; change its saved_location to SAVED_IN_JOURNAL and set its
189 * offset appropriately. */
190 static int
191 router_append_to_journal(signed_descriptor_t *desc)
193 or_options_t *options = get_options();
194 size_t fname_len = strlen(options->DataDirectory)+32;
195 char *fname = tor_malloc(fname_len);
196 const char *body = signed_descriptor_get_body(desc);
197 size_t len = desc->signed_descriptor_len;
199 tor_snprintf(fname, fname_len, "%s/cached-routers.new",
200 options->DataDirectory);
202 tor_assert(len == strlen(body));
204 if (append_bytes_to_file(fname, body, len, 1)) {
205 log_warn(LD_FS, "Unable to store router descriptor");
206 tor_free(fname);
207 return -1;
209 desc->saved_location = SAVED_IN_JOURNAL;
210 desc->saved_offset = router_journal_len;
212 tor_free(fname);
213 router_journal_len += len;
214 return 0;
217 /** Sorting helper: return &lt;0, 0, or &gt;0 depending on whether the
218 * signed_descriptor_t* in *<b>a</b> is older, the same age as, or newer than
219 * the signed_descriptor_t* in *<b>b</b>. */
220 static int
221 _compare_old_routers_by_age(const void **_a, const void **_b)
223 const signed_descriptor_t *r1 = *_a, *r2 = *_b;
224 return r1->published_on - r2->published_on;
227 /** Sorting helper: return &lt;0, 0, or &gt;0 depending on whether the
228 * routerinfo_t* in *<b>a</b> is older, the same age as, or newer than
229 * the routerinfo_t* in *<b>b</b>. */
230 static int
231 _compare_routers_by_age(const void **_a, const void **_b)
233 const routerinfo_t *r1 = *_a, *r2 = *_b;
234 return r1->cache_info.published_on - r2->cache_info.published_on;
237 /** If the journal is too long, or if <b>force</b> is true, then atomically
238 * replace the router store with the routers currently in our routerlist, and
239 * clear the journal. Return 0 on success, -1 on failure.
241 static int
242 router_rebuild_store(int force)
244 size_t len = 0;
245 or_options_t *options;
246 size_t fname_len;
247 smartlist_t *chunk_list = NULL;
248 char *fname = NULL, *fname_tmp = NULL;
249 int r = -1, i;
250 off_t offset = 0;
251 smartlist_t *old_routers, *routers;
253 if (!force && !router_should_rebuild_store())
254 return 0;
255 if (!routerlist)
256 return 0;
258 /* Don't save deadweight. */
259 routerlist_remove_old_routers();
261 log_info(LD_DIR, "Rebuilding router descriptor cache");
263 options = get_options();
264 fname_len = strlen(options->DataDirectory)+32;
265 fname = tor_malloc(fname_len);
266 fname_tmp = tor_malloc(fname_len);
267 tor_snprintf(fname, fname_len, "%s/cached-routers", options->DataDirectory);
268 tor_snprintf(fname_tmp, fname_len, "%s/cached-routers.tmp",
269 options->DataDirectory);
271 chunk_list = smartlist_create();
273 old_routers = smartlist_create();
274 smartlist_add_all(old_routers, routerlist->old_routers);
275 smartlist_sort(old_routers, _compare_old_routers_by_age);
276 routers = smartlist_create();
277 smartlist_add_all(routers, routerlist->routers);
278 smartlist_sort(routers, _compare_routers_by_age);
279 for (i = 0; i < 2; ++i) {
280 /* We sort the routers by age to enhance locality on disk. */
281 smartlist_t *lst = (i == 0) ? old_routers : routers;
282 /* Now, add the appropriate members to chunk_list */
283 SMARTLIST_FOREACH(lst, void *, ptr,
285 signed_descriptor_t *sd = (i==0) ?
286 ((signed_descriptor_t*)ptr): &((routerinfo_t*)ptr)->cache_info;
287 sized_chunk_t *c;
288 const char *body = signed_descriptor_get_body(sd);
289 if (!body) {
290 log_warn(LD_BUG, "Bug! No descriptor available for router.");
291 goto done;
293 c = tor_malloc(sizeof(sized_chunk_t));
294 c->bytes = body;
295 c->len = sd->signed_descriptor_len;
296 smartlist_add(chunk_list, c);
299 if (write_chunks_to_file(fname_tmp, chunk_list, 1)<0) {
300 log_warn(LD_FS, "Error writing router store to disk.");
301 goto done;
303 /* Our mmap is now invalid. */
304 if (routerlist->mmap_descriptors) {
305 tor_munmap_file(routerlist->mmap_descriptors);
307 if (replace_file(fname_tmp, fname)<0) {
308 log_warn(LD_FS, "Error replacing old router store.");
309 goto done;
312 routerlist->mmap_descriptors = tor_mmap_file(fname);
313 if (! routerlist->mmap_descriptors)
314 log_warn(LD_FS, "Unable to mmap new descriptor file at '%s'.",fname);
316 offset = 0;
317 for (i = 0; i < 2; ++i) {
318 smartlist_t *lst = (i == 0) ? old_routers : routers;
319 SMARTLIST_FOREACH(lst, void *, ptr,
321 signed_descriptor_t *sd = (i==0) ?
322 ((signed_descriptor_t*)ptr): &((routerinfo_t*)ptr)->cache_info;
324 sd->saved_location = SAVED_IN_CACHE;
325 if (routerlist->mmap_descriptors) {
326 tor_free(sd->signed_descriptor_body); // sets it to null
327 sd->saved_offset = offset;
329 offset += sd->signed_descriptor_len;
330 signed_descriptor_get_body(sd);
334 tor_snprintf(fname, fname_len, "%s/cached-routers.new",
335 options->DataDirectory);
337 write_str_to_file(fname, "", 1);
339 r = 0;
340 router_store_len = len;
341 router_journal_len = 0;
342 router_bytes_dropped = 0;
343 done:
344 smartlist_free(old_routers);
345 smartlist_free(routers);
346 tor_free(fname);
347 SMARTLIST_FOREACH(chunk_list, sized_chunk_t *, c, tor_free(c));
348 smartlist_free(chunk_list);
349 return r;
352 /** Load all cached router descriptors from the store. Return 0 on success and
353 * -1 on failure.
356 router_reload_router_list(void)
358 or_options_t *options = get_options();
359 size_t fname_len = strlen(options->DataDirectory)+32;
360 char *fname = tor_malloc(fname_len), *contents = NULL;
362 if (!routerlist)
363 router_get_routerlist(); /* mallocs and inits it in place */
365 router_journal_len = router_store_len = 0;
367 tor_snprintf(fname, fname_len, "%s/cached-routers", options->DataDirectory);
369 if (routerlist->mmap_descriptors) /* get rid of it first */
370 tor_munmap_file(routerlist->mmap_descriptors);
372 routerlist->mmap_descriptors = tor_mmap_file(fname);
373 if (routerlist->mmap_descriptors) {
374 router_store_len = routerlist->mmap_descriptors->size;
375 router_load_routers_from_string(routerlist->mmap_descriptors->data,
376 SAVED_IN_CACHE, NULL);
379 tor_snprintf(fname, fname_len, "%s/cached-routers.new",
380 options->DataDirectory);
381 if (file_status(fname) == FN_FILE)
382 contents = read_file_to_str(fname, RFTS_BIN|RFTS_IGNORE_MISSING, NULL);
383 if (contents) {
384 router_load_routers_from_string(contents,
385 SAVED_IN_JOURNAL, NULL);
386 tor_free(contents);
389 tor_free(fname);
391 if (router_journal_len) {
392 /* Always clear the journal on startup.*/
393 router_rebuild_store(1);
394 } else {
395 /* Don't cache expired routers. (This is in an else because
396 * router_rebuild_store() also calls remove_old_routers().) */
397 routerlist_remove_old_routers();
400 return 0;
403 /** Return a smartlist containing a list of trusted_dir_server_t * for all
404 * known trusted dirservers. Callers must not modify the list or its
405 * contents.
407 smartlist_t *
408 router_get_trusted_dir_servers(void)
410 if (!trusted_dir_servers)
411 trusted_dir_servers = smartlist_create();
413 return trusted_dir_servers;
416 /** Try to find a running dirserver. If there are no running dirservers
417 * in our routerlist and <b>retry_if_no_servers</b> is non-zero,
418 * set all the authoritative ones as running again, and pick one;
419 * if there are then no dirservers at all in our routerlist,
420 * reload the routerlist and try one last time. If for_runningrouters is
421 * true, then only pick a dirserver that can answer runningrouters queries
422 * (that is, a trusted dirserver, or one running 0.0.9rc5-cvs or later).
423 * Don't pick an authority if any non-authority is viable.
424 * Other args are as in router_pick_directory_server_impl().
426 routerstatus_t *
427 router_pick_directory_server(int requireother,
428 int fascistfirewall,
429 int for_v2_directory,
430 int retry_if_no_servers)
432 routerstatus_t *choice;
433 int prefer_tunnel = get_options()->PreferTunneledDirConns;
435 if (!routerlist)
436 return NULL;
438 choice = router_pick_directory_server_impl(requireother, fascistfirewall,
439 prefer_tunnel, for_v2_directory);
440 if (choice || !retry_if_no_servers)
441 return choice;
443 log_info(LD_DIR,
444 "No reachable router entries for dirservers. "
445 "Trying them all again.");
446 /* mark all authdirservers as up again */
447 mark_all_trusteddirservers_up();
448 /* try again */
449 choice = router_pick_directory_server_impl(requireother, fascistfirewall,
450 prefer_tunnel, for_v2_directory);
451 if (choice)
452 return choice;
454 log_info(LD_DIR,"Still no %s router entries. Reloading and trying again.",
455 fascistfirewall ? "reachable" : "known");
456 if (router_reload_router_list()) {
457 return NULL;
459 /* give it one last try */
460 choice = router_pick_directory_server_impl(requireother, fascistfirewall,
461 prefer_tunnel, for_v2_directory);
462 return choice;
465 /** Return the trusted_dir_server_t for the directory authority whose identity
466 * key hashes to <b>digest</b>, or NULL if no such authority is known.
468 trusted_dir_server_t *
469 router_get_trusteddirserver_by_digest(const char *digest)
471 if (!trusted_dir_servers)
472 return NULL;
474 SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, ds,
476 if (!memcmp(ds->digest, digest, DIGEST_LEN))
477 return ds;
480 return NULL;
483 /** Try to find a running trusted dirserver. If there are no running
484 * trusted dirservers and <b>retry_if_no_servers</b> is non-zero,
485 * set them all as running again, and try again.
486 * If <b>need_v1_authority</b> is set, return only trusted servers
487 * that are authorities for the V1 directory protocol.
488 * Other args are as in router_pick_trusteddirserver_impl().
490 routerstatus_t *
491 router_pick_trusteddirserver(authority_type_t type,
492 int requireother,
493 int fascistfirewall,
494 int retry_if_no_servers)
496 routerstatus_t *choice;
497 int prefer_tunnel = get_options()->PreferTunneledDirConns;
499 choice = router_pick_trusteddirserver_impl(type, requireother,
500 fascistfirewall, prefer_tunnel);
501 if (choice || !retry_if_no_servers)
502 return choice;
504 log_info(LD_DIR,
505 "No trusted dirservers are reachable. Trying them all again.");
506 mark_all_trusteddirservers_up();
507 return router_pick_trusteddirserver_impl(type, requireother,
508 fascistfirewall, prefer_tunnel);
511 /** How long do we avoid using a directory server after it's given us a 503? */
512 #define DIR_503_TIMEOUT (60*60)
514 /** Pick a random running valid directory server/mirror from our
515 * routerlist. Don't pick an authority if any non-authorities are viable.
516 * If <b>fascistfirewall</b>, make sure the router we pick is allowed
517 * by our firewall options.
518 * If <b>requireother</b>, it cannot be us. If <b>for_v2_directory</b>,
519 * choose a directory server new enough to support the v2 directory
520 * functionality.
521 * If <b>prefer_tunnel</b>, choose a directory server that is reachable
522 * and supports BEGIN_DIR cells, if possible.
523 * Try to avoid using servers that are overloaded (have returned 503
524 * recently).
526 static routerstatus_t *
527 router_pick_directory_server_impl(int requireother, int fascistfirewall,
528 int prefer_tunnel, int for_v2_directory)
530 routerstatus_t *result;
531 smartlist_t *direct, *tunnel;
532 smartlist_t *trusted_direct, *trusted_tunnel;
533 smartlist_t *overloaded_direct, *overloaded_tunnel;
534 time_t now = time(NULL);
536 if (!routerstatus_list)
537 return NULL;
539 direct = smartlist_create();
540 tunnel = smartlist_create();
541 trusted_direct = smartlist_create();
542 trusted_tunnel = smartlist_create();
543 overloaded_direct = smartlist_create();
544 overloaded_tunnel = smartlist_create();
546 /* Find all the running dirservers we know about. */
547 SMARTLIST_FOREACH(routerstatus_list, local_routerstatus_t *, _local_status,
549 routerstatus_t *status = &(_local_status->status);
550 int is_trusted;
551 int is_overloaded = _local_status->last_dir_503_at + DIR_503_TIMEOUT > now;
552 if (!status->is_running || !status->dir_port || !status->is_valid)
553 continue;
554 if (status->is_bad_directory)
555 continue;
556 if (requireother && router_digest_is_me(status->identity_digest))
557 continue;
558 is_trusted = router_digest_is_trusted_dir(status->identity_digest);
559 if (for_v2_directory && !(status->is_v2_dir || is_trusted))
560 continue;
561 if (fascistfirewall &&
562 prefer_tunnel &&
563 status->version_supports_begindir &&
564 router_get_by_digest(status->identity_digest) &&
565 fascist_firewall_allows_address_or(status->addr, status->or_port))
566 smartlist_add(is_trusted ? trusted_tunnel :
567 is_overloaded ? overloaded_tunnel : tunnel, status);
568 else if (!fascistfirewall || (fascistfirewall &&
569 fascist_firewall_allows_address_dir(status->addr,
570 status->dir_port)))
571 smartlist_add(is_trusted ? trusted_direct :
572 is_overloaded ? overloaded_direct : direct, status);
575 if (smartlist_len(tunnel)) {
576 result = routerstatus_sl_choose_by_bandwidth(tunnel);
577 } else if (smartlist_len(overloaded_tunnel)) {
578 result = routerstatus_sl_choose_by_bandwidth(overloaded_tunnel);
579 } else if (smartlist_len(trusted_tunnel)) {
580 /* FFFF We don't distinguish between trusteds and overloaded trusteds
581 * yet. Maybe one day we should. */
582 /* FFFF We also don't load balance over authorities yet. I think this
583 * is a feature, but it could easily be a bug. -RD */
584 result = smartlist_choose(trusted_tunnel);
585 } else if (smartlist_len(direct)) {
586 result = routerstatus_sl_choose_by_bandwidth(direct);
587 } else if (smartlist_len(overloaded_direct)) {
588 result = routerstatus_sl_choose_by_bandwidth(overloaded_direct);
589 } else {
590 result = smartlist_choose(trusted_direct);
592 smartlist_free(direct);
593 smartlist_free(tunnel);
594 smartlist_free(trusted_direct);
595 smartlist_free(trusted_tunnel);
596 smartlist_free(overloaded_direct);
597 smartlist_free(overloaded_tunnel);
598 return result;
601 /** Choose randomly from among the trusted dirservers that are up. If
602 * <b>fascistfirewall</b>, make sure the port we pick is allowed by our
603 * firewall options. If <b>requireother</b>, it cannot be us. If
604 * <b>need_v1_authority</b>, choose a trusted authority for the v1 directory
605 * system.
607 static routerstatus_t *
608 router_pick_trusteddirserver_impl(authority_type_t type,
609 int requireother, int fascistfirewall,
610 int prefer_tunnel)
612 smartlist_t *direct, *tunnel;
613 smartlist_t *overloaded_direct, *overloaded_tunnel;
614 routerinfo_t *me = router_get_my_routerinfo();
615 routerstatus_t *result;
616 time_t now = time(NULL);
618 direct = smartlist_create();
619 tunnel = smartlist_create();
620 overloaded_direct = smartlist_create();
621 overloaded_tunnel = smartlist_create();
623 if (!trusted_dir_servers)
624 return NULL;
626 SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, d,
628 int is_overloaded =
629 d->fake_status.last_dir_503_at + DIR_503_TIMEOUT > now;
630 if (!d->is_running) continue;
631 if (type == V1_AUTHORITY && !d->is_v1_authority)
632 continue;
633 if (type == V2_AUTHORITY && !d->is_v2_authority)
634 continue;
635 if (type == HIDSERV_AUTHORITY && !d->is_hidserv_authority)
636 continue;
637 if (requireother && me && router_digest_is_me(d->digest))
638 continue;
640 if (fascistfirewall &&
641 prefer_tunnel &&
642 d->or_port &&
643 router_get_by_digest(d->digest) &&
644 fascist_firewall_allows_address_or(d->addr, d->or_port))
645 smartlist_add(is_overloaded ? overloaded_tunnel : tunnel,
646 &d->fake_status.status);
647 else if (!fascistfirewall || (fascistfirewall &&
648 fascist_firewall_allows_address_dir(d->addr,
649 d->dir_port)))
650 smartlist_add(is_overloaded ? overloaded_direct : direct,
651 &d->fake_status.status);
654 if (smartlist_len(tunnel)) {
655 result = smartlist_choose(tunnel);
656 } else if (smartlist_len(overloaded_tunnel)) {
657 result = smartlist_choose(overloaded_tunnel);
658 } else if (smartlist_len(direct)) {
659 result = smartlist_choose(direct);
660 } else {
661 result = smartlist_choose(overloaded_direct);
664 smartlist_free(direct);
665 smartlist_free(tunnel);
666 smartlist_free(overloaded_direct);
667 smartlist_free(overloaded_tunnel);
668 return result;
671 /** Go through and mark the authoritative dirservers as up. */
672 static void
673 mark_all_trusteddirservers_up(void)
675 if (routerlist) {
676 SMARTLIST_FOREACH(routerlist->routers, routerinfo_t *, router,
677 if (router_digest_is_trusted_dir(router->cache_info.identity_digest) &&
678 router->dir_port > 0) {
679 router->is_running = 1;
682 if (trusted_dir_servers) {
683 SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, dir,
685 local_routerstatus_t *rs;
686 dir->is_running = 1;
687 dir->n_networkstatus_failures = 0;
688 dir->fake_status.last_dir_503_at = 0;
689 rs = router_get_combined_status_by_digest(dir->digest);
690 if (rs && !rs->status.is_running) {
691 rs->status.is_running = 1;
692 rs->last_dir_503_at = 0;
693 control_event_networkstatus_changed_single(rs);
697 last_networkstatus_download_attempted = 0;
698 router_dir_info_changed();
701 /** Reset all internal variables used to count failed downloads of network
702 * status objects. */
703 void
704 router_reset_status_download_failures(void)
706 mark_all_trusteddirservers_up();
709 /** Look through the routerlist and identify routers that
710 * advertise the same /16 network address as <b>router</b>.
711 * Add each of them to <b>sl</b>.
713 static void
714 routerlist_add_network_family(smartlist_t *sl, routerinfo_t *router)
716 SMARTLIST_FOREACH(routerlist->routers, routerinfo_t *, r,
718 if (router != r &&
719 (router->addr & 0xffff0000) == (r->addr & 0xffff0000))
720 smartlist_add(sl, r);
724 /** Add all the family of <b>router</b> to the smartlist <b>sl</b>.
725 * This is used to make sure we don't pick siblings in a single path.
727 void
728 routerlist_add_family(smartlist_t *sl, routerinfo_t *router)
730 routerinfo_t *r;
731 config_line_t *cl;
732 or_options_t *options = get_options();
734 /* First, add any routers with similar network addresses. */
735 if (options->EnforceDistinctSubnets)
736 routerlist_add_network_family(sl, router);
738 if (!router->declared_family)
739 return;
741 /* Add every r such that router declares familyness with r, and r
742 * declares familyhood with router. */
743 SMARTLIST_FOREACH(router->declared_family, const char *, n,
745 if (!(r = router_get_by_nickname(n, 0)))
746 continue;
747 if (!r->declared_family)
748 continue;
749 SMARTLIST_FOREACH(r->declared_family, const char *, n2,
751 if (router_nickname_matches(router, n2))
752 smartlist_add(sl, r);
756 /* If the user declared any families locally, honor those too. */
757 for (cl = get_options()->NodeFamilies; cl; cl = cl->next) {
758 if (router_nickname_is_in_list(router, cl->value)) {
759 add_nickname_list_to_smartlist(sl, cl->value, 0);
764 /** Given a (possibly NULL) comma-and-whitespace separated list of nicknames,
765 * see which nicknames in <b>list</b> name routers in our routerlist, and add
766 * the routerinfos for those routers to <b>sl</b>. If <b>must_be_running</b>,
767 * only include routers that we think are running.
768 * Warn if any non-Named routers are specified by nickname.
770 void
771 add_nickname_list_to_smartlist(smartlist_t *sl, const char *list,
772 int must_be_running)
774 routerinfo_t *router;
775 smartlist_t *nickname_list;
776 int have_dir_info = router_have_minimum_dir_info();
778 if (!list)
779 return; /* nothing to do */
780 tor_assert(sl);
782 nickname_list = smartlist_create();
783 if (!warned_nicknames)
784 warned_nicknames = smartlist_create();
786 smartlist_split_string(nickname_list, list, ",",
787 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
789 SMARTLIST_FOREACH(nickname_list, const char *, nick, {
790 int warned;
791 if (!is_legal_nickname_or_hexdigest(nick)) {
792 log_warn(LD_CONFIG, "Nickname '%s' is misformed; skipping", nick);
793 continue;
795 router = router_get_by_nickname(nick, 1);
796 warned = smartlist_string_isin(warned_nicknames, nick);
797 if (router) {
798 if (!must_be_running || router->is_running) {
799 smartlist_add(sl,router);
801 } else if (!router_get_combined_status_by_nickname(nick,1)) {
802 if (!warned) {
803 log_fn(have_dir_info ? LOG_WARN : LOG_INFO, LD_CONFIG,
804 "Nickname list includes '%s' which isn't a known router.",nick);
805 smartlist_add(warned_nicknames, tor_strdup(nick));
809 SMARTLIST_FOREACH(nickname_list, char *, nick, tor_free(nick));
810 smartlist_free(nickname_list);
813 /** Return 1 iff any member of the (possibly NULL) comma-separated list
814 * <b>list</b> is an acceptable nickname or hexdigest for <b>router</b>. Else
815 * return 0.
818 router_nickname_is_in_list(routerinfo_t *router, const char *list)
820 smartlist_t *nickname_list;
821 int v = 0;
823 if (!list)
824 return 0; /* definitely not */
825 tor_assert(router);
827 nickname_list = smartlist_create();
828 smartlist_split_string(nickname_list, list, ",",
829 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
830 SMARTLIST_FOREACH(nickname_list, const char *, cp,
831 if (router_nickname_matches(router, cp)) {v=1;break;});
832 SMARTLIST_FOREACH(nickname_list, char *, cp, tor_free(cp));
833 smartlist_free(nickname_list);
834 return v;
837 /** Add every suitable router from our routerlist to <b>sl</b>, so that
838 * we can pick a node for a circuit.
840 static void
841 router_add_running_routers_to_smartlist(smartlist_t *sl, int allow_invalid,
842 int need_uptime, int need_capacity,
843 int need_guard)
845 if (!routerlist)
846 return;
848 SMARTLIST_FOREACH(routerlist->routers, routerinfo_t *, router,
850 if (router->is_running &&
851 router->purpose == ROUTER_PURPOSE_GENERAL &&
852 (router->is_valid || allow_invalid) &&
853 !router_is_unreliable(router, need_uptime,
854 need_capacity, need_guard)) {
855 /* If it's running, and it's suitable according to the
856 * other flags we had in mind */
857 smartlist_add(sl, router);
862 /** Look through the routerlist until we find a router that has my key.
863 Return it. */
864 routerinfo_t *
865 routerlist_find_my_routerinfo(void)
867 if (!routerlist)
868 return NULL;
870 SMARTLIST_FOREACH(routerlist->routers, routerinfo_t *, router,
872 if (router_is_me(router))
873 return router;
875 return NULL;
878 /** Find a router that's up, that has this IP address, and
879 * that allows exit to this address:port, or return NULL if there
880 * isn't a good one.
882 routerinfo_t *
883 router_find_exact_exit_enclave(const char *address, uint16_t port)
885 uint32_t addr;
886 struct in_addr in;
888 if (!tor_inet_aton(address, &in))
889 return NULL; /* it's not an IP already */
890 addr = ntohl(in.s_addr);
892 SMARTLIST_FOREACH(routerlist->routers, routerinfo_t *, router,
894 if (router->is_running &&
895 router->addr == addr &&
896 compare_addr_to_addr_policy(addr, port, router->exit_policy) ==
897 ADDR_POLICY_ACCEPTED)
898 return router;
900 return NULL;
903 /** Return 1 if <b>router</b> is not suitable for these parameters, else 0.
904 * If <b>need_uptime</b> is non-zero, we require a minimum uptime.
905 * If <b>need_capacity</b> is non-zero, we require a minimum advertised
906 * bandwidth.
907 * If <b>need_guard</b>, we require that the router is a possible entry guard.
910 router_is_unreliable(routerinfo_t *router, int need_uptime,
911 int need_capacity, int need_guard)
913 if (need_uptime && !router->is_stable)
914 return 1;
915 if (need_capacity && !router->is_fast)
916 return 1;
917 if (need_guard && !router->is_possible_guard)
918 return 1;
919 return 0;
922 /** Return the smaller of the router's configured BandwidthRate
923 * and its advertised capacity. */
924 uint32_t
925 router_get_advertised_bandwidth(routerinfo_t *router)
927 if (router->bandwidthcapacity < router->bandwidthrate)
928 return router->bandwidthcapacity;
929 return router->bandwidthrate;
932 /** Do not weight any declared bandwidth more than this much when picking
933 * routers by bandwidth. */
934 #define MAX_BELIEVABLE_BANDWIDTH 1500000 /* 1.5 MB/sec */
936 /** Helper function:
937 * choose a random element of smartlist <b>sl</b>, weighted by
938 * the advertised bandwidth of each element.
940 * If <b>statuses</b> is zero, then <b>sl</b> is a list of
941 * routerinfo_t's. Otherwise it's a list of routerstatus_t's.
943 * If <b>for_exit</b>, we're picking an exit node: consider all nodes'
944 * bandwidth equally regardless of their Exit status. If not <b>for_exit</b>,
945 * we're picking a non-exit node: weight exit-node's bandwidth downwards
946 * depending on the smallness of the fraction of Exit-to-total bandwidth.
948 static void *
949 smartlist_choose_by_bandwidth(smartlist_t *sl, int for_exit, int statuses)
951 int i;
952 routerinfo_t *router;
953 routerstatus_t *status;
954 int32_t *bandwidths;
955 int is_exit;
956 uint64_t total_nonexit_bw = 0, total_exit_bw = 0, total_bw = 0;
957 uint64_t rand_bw, tmp;
958 double exit_weight;
959 int n_unknown = 0;
961 /* First count the total bandwidth weight, and make a list
962 * of each value. <0 means "unknown; no routerinfo." We use the
963 * bits of negative values to remember whether the router was fast (-x)&1
964 * and whether it was an exit (-x)&2. Yes, it's a hack. */
965 bandwidths = tor_malloc(sizeof(int32_t)*smartlist_len(sl));
967 /* Iterate over all the routerinfo_t or routerstatus_t, and */
968 for (i = 0; i < smartlist_len(sl); ++i) {
969 /* first, learn what bandwidth we think i has */
970 int is_known = 1;
971 int32_t flags = 0;
972 uint32_t this_bw = 0;
973 if (statuses) {
974 /* need to extract router info */
975 status = smartlist_get(sl, i);
976 router = router_get_by_digest(status->identity_digest);
977 is_exit = status->is_exit;
978 if (router) {
979 this_bw = router_get_advertised_bandwidth(router);
980 } else { /* guess */
981 is_known = 0;
982 flags = status->is_fast ? 1 : 0;
983 flags |= is_exit ? 2 : 0;
985 } else {
986 router = smartlist_get(sl, i);
987 is_exit = router->is_exit;
988 this_bw = router_get_advertised_bandwidth(router);
990 /* if they claim something huge, don't believe it */
991 if (this_bw > MAX_BELIEVABLE_BANDWIDTH)
992 this_bw = MAX_BELIEVABLE_BANDWIDTH;
993 if (is_known) {
994 bandwidths[i] = (int32_t) this_bw; // safe since MAX_BELIEVABLE<INT32_MAX
995 if (is_exit)
996 total_exit_bw += this_bw;
997 else
998 total_nonexit_bw += this_bw;
999 } else {
1000 ++n_unknown;
1001 bandwidths[i] = -flags;
1005 /* Now, fill in the unknown values. */
1006 if (n_unknown) {
1007 int32_t avg_fast, avg_slow;
1008 if (total_exit_bw+total_nonexit_bw) {
1009 /* if there's some bandwidth, there's at least one known router,
1010 * so no worries about div by 0 here */
1011 int n_known = smartlist_len(sl)-n_unknown;
1012 avg_fast = avg_slow = (int32_t)
1013 ((total_exit_bw+total_nonexit_bw)/((uint64_t) n_known));
1014 } else {
1015 avg_fast = 40000;
1016 avg_slow = 20000;
1018 for (i=0; i<smartlist_len(sl); ++i) {
1019 int32_t bw = bandwidths[i];
1020 if (bw>=0)
1021 continue;
1022 is_exit = ((-bw)&2);
1023 bandwidths[i] = ((-bw)&1) ? avg_fast : avg_slow;
1024 if (is_exit)
1025 total_exit_bw += bandwidths[i];
1026 else
1027 total_nonexit_bw += bandwidths[i];
1031 /* If there's no bandwidth at all, pick at random. */
1032 if (!(total_exit_bw+total_nonexit_bw)) {
1033 tor_free(bandwidths);
1034 return smartlist_choose(sl);
1037 /* Figure out how to weight exits. */
1038 if (for_exit) {
1039 /* If we're choosing an exit node, exit bandwidth counts fully. */
1040 exit_weight = 1.0;
1041 total_bw = total_exit_bw + total_nonexit_bw;
1042 } else if (total_exit_bw < total_nonexit_bw / 2) {
1043 /* If we're choosing a relay and exits are greatly outnumbered, ignore
1044 * them. */
1045 exit_weight = 0.0;
1046 total_bw = total_nonexit_bw;
1047 } else {
1048 /* If we're choosing a relay and exits aren't outnumbered use the formula
1049 * from path-spec. */
1050 uint64_t leftover = (total_exit_bw - total_nonexit_bw / 2);
1051 exit_weight = U64_TO_DBL(leftover) /
1052 U64_TO_DBL(leftover + total_nonexit_bw);
1053 total_bw = total_nonexit_bw +
1054 DBL_TO_U64(exit_weight * U64_TO_DBL(total_exit_bw));
1057 log_debug(LD_CIRC, "Total bw = "U64_FORMAT", total exit bw = "U64_FORMAT
1058 ", total nonexit bw = "U64_FORMAT", exit weight = %lf "
1059 "(for exit == %d)",
1060 U64_PRINTF_ARG(total_bw), U64_PRINTF_ARG(total_exit_bw),
1061 U64_PRINTF_ARG(total_nonexit_bw), exit_weight, for_exit);
1064 /* Almost done: choose a random value from the bandwidth weights. */
1065 rand_bw = crypto_rand_uint64(total_bw);
1067 /* Last, count through sl until we get to the element we picked */
1068 tmp = 0;
1069 for (i=0; i < smartlist_len(sl); i++) {
1070 if (statuses) {
1071 status = smartlist_get(sl, i);
1072 is_exit = status->is_exit;
1073 } else {
1074 router = smartlist_get(sl, i);
1075 is_exit = router->is_exit;
1077 if (is_exit)
1078 tmp += ((uint64_t)(bandwidths[i] * exit_weight));
1079 else
1080 tmp += bandwidths[i];
1081 if (tmp >= rand_bw)
1082 break;
1084 tor_free(bandwidths);
1085 return smartlist_get(sl, i);
1088 /** Choose a random element of router list <b>sl</b>, weighted by
1089 * the advertised bandwidth of each router.
1091 routerinfo_t *
1092 routerlist_sl_choose_by_bandwidth(smartlist_t *sl, int for_exit)
1094 return smartlist_choose_by_bandwidth(sl, for_exit, 0);
1097 /** Choose a random element of status list <b>sl</b>, weighted by
1098 * the advertised bandwidth of each status.
1100 routerstatus_t *
1101 routerstatus_sl_choose_by_bandwidth(smartlist_t *sl)
1103 return smartlist_choose_by_bandwidth(sl, 1, 1);
1106 /** Return a random running router from the routerlist. If any node
1107 * named in <b>preferred</b> is available, pick one of those. Never
1108 * pick a node named in <b>excluded</b>, or whose routerinfo is in
1109 * <b>excludedsmartlist</b>, even if they are the only nodes
1110 * available. If <b>strict</b> is true, never pick any node besides
1111 * those in <b>preferred</b>.
1112 * If <b>need_uptime</b> is non-zero and any router has more than
1113 * a minimum uptime, return one of those.
1114 * If <b>need_capacity</b> is non-zero, weight your choice by the
1115 * advertised capacity of each router.
1116 * If ! <b>allow_invalid</b>, consider only Valid routers.
1117 * If <b>need_guard</b>, consider only Guard routers.
1118 * If <b>weight_for_exit</b>, we weight bandwidths as if picking an exit node,
1119 * otherwise we weight bandwidths for picking a relay node (that is, possibly
1120 * discounting exit nodes).
1122 routerinfo_t *
1123 router_choose_random_node(const char *preferred,
1124 const char *excluded,
1125 smartlist_t *excludedsmartlist,
1126 int need_uptime, int need_capacity,
1127 int need_guard,
1128 int allow_invalid, int strict,
1129 int weight_for_exit)
1131 smartlist_t *sl, *excludednodes;
1132 routerinfo_t *choice = NULL;
1134 excludednodes = smartlist_create();
1135 add_nickname_list_to_smartlist(excludednodes,excluded,0);
1137 /* Try the preferred nodes first. Ignore need_uptime and need_capacity
1138 * and need_guard, since the user explicitly asked for these nodes. */
1139 if (preferred) {
1140 sl = smartlist_create();
1141 add_nickname_list_to_smartlist(sl,preferred,1);
1142 smartlist_subtract(sl,excludednodes);
1143 if (excludedsmartlist)
1144 smartlist_subtract(sl,excludedsmartlist);
1145 choice = smartlist_choose(sl);
1146 smartlist_free(sl);
1148 if (!choice && !strict) {
1149 /* Then give up on our preferred choices: any node
1150 * will do that has the required attributes. */
1151 sl = smartlist_create();
1152 router_add_running_routers_to_smartlist(sl, allow_invalid,
1153 need_uptime, need_capacity,
1154 need_guard);
1155 smartlist_subtract(sl,excludednodes);
1156 if (excludedsmartlist)
1157 smartlist_subtract(sl,excludedsmartlist);
1159 if (need_capacity)
1160 choice = routerlist_sl_choose_by_bandwidth(sl, weight_for_exit);
1161 else
1162 choice = smartlist_choose(sl);
1164 smartlist_free(sl);
1165 if (!choice && (need_uptime || need_capacity || need_guard)) {
1166 /* try once more -- recurse but with fewer restrictions. */
1167 log_info(LD_CIRC,
1168 "We couldn't find any live%s%s%s routers; falling back "
1169 "to list of all routers.",
1170 need_capacity?", fast":"",
1171 need_uptime?", stable":"",
1172 need_guard?", guard":"");
1173 choice = router_choose_random_node(
1174 NULL, excluded, excludedsmartlist,
1175 0, 0, 0, allow_invalid, 0, weight_for_exit);
1178 smartlist_free(excludednodes);
1179 if (!choice) {
1180 if (strict) {
1181 log_warn(LD_CIRC, "All preferred nodes were down when trying to choose "
1182 "node, and the Strict[...]Nodes option is set. Failing.");
1183 } else {
1184 log_warn(LD_CIRC,
1185 "No available nodes when trying to choose node. Failing.");
1188 return choice;
1191 /** Return true iff the digest of <b>router</b>'s identity key,
1192 * encoded in hexadecimal, matches <b>hexdigest</b> (which is
1193 * optionally prefixed with a single dollar sign). Return false if
1194 * <b>hexdigest</b> is malformed, or it doesn't match. */
1195 static INLINE int
1196 router_hex_digest_matches(routerinfo_t *router, const char *hexdigest)
1198 char digest[DIGEST_LEN];
1199 size_t len;
1200 tor_assert(hexdigest);
1201 if (hexdigest[0] == '$')
1202 ++hexdigest;
1204 len = strlen(hexdigest);
1205 if (len < HEX_DIGEST_LEN)
1206 return 0;
1207 else if (len > HEX_DIGEST_LEN &&
1208 (hexdigest[HEX_DIGEST_LEN] == '=' ||
1209 hexdigest[HEX_DIGEST_LEN] == '~')) {
1210 if (strcasecmp(hexdigest+HEX_DIGEST_LEN+1, router->nickname))
1211 return 0;
1212 if (hexdigest[HEX_DIGEST_LEN] == '=' && !router->is_named)
1213 return 0;
1216 if (base16_decode(digest, DIGEST_LEN, hexdigest, HEX_DIGEST_LEN)<0)
1217 return 0;
1218 return (!memcmp(digest, router->cache_info.identity_digest, DIGEST_LEN));
1221 /** Return true if <b>router</b>'s nickname matches <b>nickname</b>
1222 * (case-insensitive), or if <b>router's</b> identity key digest
1223 * matches a hexadecimal value stored in <b>nickname</b>. Return
1224 * false otherwise. */
1225 static int
1226 router_nickname_matches(routerinfo_t *router, const char *nickname)
1228 if (nickname[0]!='$' && !strcasecmp(router->nickname, nickname))
1229 return 1;
1230 return router_hex_digest_matches(router, nickname);
1233 /** Return the router in our routerlist whose (case-insensitive)
1234 * nickname or (case-sensitive) hexadecimal key digest is
1235 * <b>nickname</b>. Return NULL if no such router is known.
1237 routerinfo_t *
1238 router_get_by_nickname(const char *nickname, int warn_if_unnamed)
1240 int maybedigest;
1241 char digest[DIGEST_LEN];
1242 routerinfo_t *best_match=NULL;
1243 int n_matches = 0;
1244 char *named_digest = NULL;
1246 tor_assert(nickname);
1247 if (!routerlist)
1248 return NULL;
1249 if (nickname[0] == '$')
1250 return router_get_by_hexdigest(nickname);
1251 if (!strcasecmp(nickname, UNNAMED_ROUTER_NICKNAME))
1252 return NULL;
1253 if (server_mode(get_options()) &&
1254 !strcasecmp(nickname, get_options()->Nickname))
1255 return router_get_my_routerinfo();
1257 maybedigest = (strlen(nickname) >= HEX_DIGEST_LEN) &&
1258 (base16_decode(digest,DIGEST_LEN,nickname,HEX_DIGEST_LEN) == 0);
1260 if (named_server_map &&
1261 (named_digest = strmap_get_lc(named_server_map, nickname))) {
1262 return digestmap_get(routerlist->identity_map, named_digest);
1265 SMARTLIST_FOREACH(routerlist->routers, routerinfo_t *, router,
1267 if (!strcasecmp(router->nickname, nickname)) {
1268 ++n_matches;
1269 if (n_matches <= 1 || router->is_running)
1270 best_match = router;
1271 } else if (maybedigest &&
1272 !memcmp(digest, router->cache_info.identity_digest, DIGEST_LEN)
1274 if (router_hex_digest_matches(router, nickname))
1275 return router;
1276 else
1277 best_match = router; // XXXX NM not exactly right.
1281 if (best_match) {
1282 if (warn_if_unnamed && n_matches > 1) {
1283 smartlist_t *fps = smartlist_create();
1284 int any_unwarned = 0;
1285 SMARTLIST_FOREACH(routerlist->routers, routerinfo_t *, router,
1287 local_routerstatus_t *rs;
1288 char *desc;
1289 size_t dlen;
1290 char fp[HEX_DIGEST_LEN+1];
1291 if (strcasecmp(router->nickname, nickname))
1292 continue;
1293 rs = router_get_combined_status_by_digest(
1294 router->cache_info.identity_digest);
1295 if (rs && !rs->name_lookup_warned) {
1296 rs->name_lookup_warned = 1;
1297 any_unwarned = 1;
1299 base16_encode(fp, sizeof(fp),
1300 router->cache_info.identity_digest, DIGEST_LEN);
1301 dlen = 32 + HEX_DIGEST_LEN + strlen(router->address);
1302 desc = tor_malloc(dlen);
1303 tor_snprintf(desc, dlen, "\"$%s\" for the one at %s:%d",
1304 fp, router->address, router->or_port);
1305 smartlist_add(fps, desc);
1307 if (any_unwarned) {
1308 char *alternatives = smartlist_join_strings(fps, "; ",0,NULL);
1309 log_warn(LD_CONFIG,
1310 "There are multiple matches for the nickname \"%s\","
1311 " but none is listed as named by the directory authorities. "
1312 "Choosing one arbitrarily. If you meant one in particular, "
1313 "you should say %s.", nickname, alternatives);
1314 tor_free(alternatives);
1316 SMARTLIST_FOREACH(fps, char *, cp, tor_free(cp));
1317 smartlist_free(fps);
1318 } else if (warn_if_unnamed) {
1319 local_routerstatus_t *rs = router_get_combined_status_by_digest(
1320 best_match->cache_info.identity_digest);
1321 if (rs && !rs->name_lookup_warned) {
1322 char fp[HEX_DIGEST_LEN+1];
1323 base16_encode(fp, sizeof(fp),
1324 best_match->cache_info.identity_digest, DIGEST_LEN);
1325 log_warn(LD_CONFIG, "You specified a server \"%s\" by name, but this "
1326 "name is not registered, so it could be used by any server, "
1327 "not just the one you meant. "
1328 "To make sure you get the same server in the future, refer to "
1329 "it by key, as \"$%s\".", nickname, fp);
1330 rs->name_lookup_warned = 1;
1333 return best_match;
1336 return NULL;
1339 /** Try to find a routerinfo for <b>digest</b>. If we don't have one,
1340 * return 1. If we do, ask tor_version_as_new_as() for the answer.
1343 router_digest_version_as_new_as(const char *digest, const char *cutoff)
1345 routerinfo_t *router = router_get_by_digest(digest);
1346 if (!router)
1347 return 1;
1348 return tor_version_as_new_as(router->platform, cutoff);
1351 /** Return true iff <b>digest</b> is the digest of the identity key of
1352 * a trusted directory. */
1354 router_digest_is_trusted_dir(const char *digest)
1356 if (!trusted_dir_servers)
1357 return 0;
1358 if (get_options()->AuthoritativeDir &&
1359 router_digest_is_me(digest))
1360 return 1;
1361 SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, ent,
1362 if (!memcmp(digest, ent->digest, DIGEST_LEN)) return 1);
1363 return 0;
1366 /** Return the router in our routerlist whose hexadecimal key digest
1367 * is <b>hexdigest</b>. Return NULL if no such router is known. */
1368 routerinfo_t *
1369 router_get_by_hexdigest(const char *hexdigest)
1371 char digest[DIGEST_LEN];
1372 size_t len;
1373 routerinfo_t *ri;
1375 tor_assert(hexdigest);
1376 if (!routerlist)
1377 return NULL;
1378 if (hexdigest[0]=='$')
1379 ++hexdigest;
1380 len = strlen(hexdigest);
1381 if (len < HEX_DIGEST_LEN ||
1382 base16_decode(digest,DIGEST_LEN,hexdigest,HEX_DIGEST_LEN) < 0)
1383 return NULL;
1385 ri = router_get_by_digest(digest);
1387 if (len > HEX_DIGEST_LEN) {
1388 if (hexdigest[HEX_DIGEST_LEN] == '=') {
1389 if (strcasecmp(ri->nickname, hexdigest+HEX_DIGEST_LEN+1) ||
1390 !ri->is_named)
1391 return NULL;
1392 } else if (hexdigest[HEX_DIGEST_LEN] == '~') {
1393 if (strcasecmp(ri->nickname, hexdigest+HEX_DIGEST_LEN+1))
1394 return NULL;
1395 } else {
1396 return NULL;
1400 return ri;
1403 /** Return the router in our routerlist whose 20-byte key digest
1404 * is <b>digest</b>. Return NULL if no such router is known. */
1405 routerinfo_t *
1406 router_get_by_digest(const char *digest)
1408 tor_assert(digest);
1410 if (!routerlist) return NULL;
1412 // routerlist_assert_ok(routerlist);
1414 return digestmap_get(routerlist->identity_map, digest);
1417 /** Return the router in our routerlist whose 20-byte descriptor
1418 * is <b>digest</b>. Return NULL if no such router is known. */
1419 signed_descriptor_t *
1420 router_get_by_descriptor_digest(const char *digest)
1422 tor_assert(digest);
1424 if (!routerlist) return NULL;
1426 return digestmap_get(routerlist->desc_digest_map, digest);
1429 /** Return a pointer to the signed textual representation of a descriptor.
1430 * The returned string is not guaranteed to be NUL-terminated: the string's
1431 * length will be in desc-\>signed_descriptor_len. */
1432 const char *
1433 signed_descriptor_get_body(signed_descriptor_t *desc)
1435 const char *r;
1436 size_t len = desc->signed_descriptor_len;
1437 tor_assert(len > 32);
1438 if (desc->saved_location == SAVED_IN_CACHE && routerlist &&
1439 routerlist->mmap_descriptors) {
1440 tor_assert(desc->saved_offset + len <= routerlist->mmap_descriptors->size);
1441 r = routerlist->mmap_descriptors->data + desc->saved_offset;
1442 } else {
1443 r = desc->signed_descriptor_body;
1445 tor_assert(r);
1446 tor_assert(!memcmp("router ", r, 7));
1447 #if 0
1448 tor_assert(!memcmp("\n-----END SIGNATURE-----\n",
1449 r + len - 25, 25));
1450 #endif
1452 return r;
1455 /** Return the current list of all known routers. */
1456 routerlist_t *
1457 router_get_routerlist(void)
1459 if (!routerlist) {
1460 routerlist = tor_malloc_zero(sizeof(routerlist_t));
1461 routerlist->routers = smartlist_create();
1462 routerlist->old_routers = smartlist_create();
1463 routerlist->identity_map = digestmap_new();
1464 routerlist->desc_digest_map = digestmap_new();
1466 return routerlist;
1469 /** Free all storage held by <b>router</b>. */
1470 void
1471 routerinfo_free(routerinfo_t *router)
1473 if (!router)
1474 return;
1476 tor_free(router->cache_info.signed_descriptor_body);
1477 tor_free(router->address);
1478 tor_free(router->nickname);
1479 tor_free(router->platform);
1480 tor_free(router->contact_info);
1481 if (router->onion_pkey)
1482 crypto_free_pk_env(router->onion_pkey);
1483 if (router->identity_pkey)
1484 crypto_free_pk_env(router->identity_pkey);
1485 if (router->declared_family) {
1486 SMARTLIST_FOREACH(router->declared_family, char *, s, tor_free(s));
1487 smartlist_free(router->declared_family);
1489 addr_policy_free(router->exit_policy);
1490 tor_free(router);
1493 /** Release storage held by <b>sd</b>. */
1494 static void
1495 signed_descriptor_free(signed_descriptor_t *sd)
1497 tor_free(sd->signed_descriptor_body);
1498 tor_free(sd);
1501 /** Extract a signed_descriptor_t from a routerinfo, and free the routerinfo.
1503 static signed_descriptor_t *
1504 signed_descriptor_from_routerinfo(routerinfo_t *ri)
1506 signed_descriptor_t *sd = tor_malloc_zero(sizeof(signed_descriptor_t));
1507 memcpy(sd, &(ri->cache_info), sizeof(signed_descriptor_t));
1508 ri->cache_info.signed_descriptor_body = NULL;
1509 routerinfo_free(ri);
1510 return sd;
1513 /** Free all storage held by a routerlist <b>rl</b> */
1514 void
1515 routerlist_free(routerlist_t *rl)
1517 tor_assert(rl);
1518 digestmap_free(rl->identity_map, NULL);
1519 digestmap_free(rl->desc_digest_map, NULL);
1520 SMARTLIST_FOREACH(rl->routers, routerinfo_t *, r,
1521 routerinfo_free(r));
1522 SMARTLIST_FOREACH(rl->old_routers, signed_descriptor_t *, sd,
1523 signed_descriptor_free(sd));
1524 smartlist_free(rl->routers);
1525 smartlist_free(rl->old_routers);
1526 if (routerlist->mmap_descriptors)
1527 tor_munmap_file(routerlist->mmap_descriptors);
1528 tor_free(rl);
1530 router_dir_info_changed();
1533 void
1534 dump_routerlist_mem_usage(int severity)
1536 uint64_t livedescs = 0;
1537 uint64_t olddescs = 0;
1538 if (!routerlist)
1539 return;
1540 SMARTLIST_FOREACH(routerlist->routers, routerinfo_t *, r,
1541 livedescs += r->cache_info.signed_descriptor_len);
1542 SMARTLIST_FOREACH(routerlist->old_routers, signed_descriptor_t *, sd,
1543 olddescs += sd->signed_descriptor_len);
1545 log(severity, LD_GENERAL,
1546 "In %d live descriptors: "U64_FORMAT" bytes. "
1547 "In %d old descriptors: "U64_FORMAT" bytes.",
1548 smartlist_len(routerlist->routers), U64_PRINTF_ARG(livedescs),
1549 smartlist_len(routerlist->old_routers), U64_PRINTF_ARG(olddescs));
1552 /** Return the greatest number of routerdescs we'll hold for any given router.
1554 static int
1555 max_descriptors_per_router(void)
1557 int n_authorities = get_n_v2_authorities();
1558 return (n_authorities < 5) ? 5 : n_authorities;
1561 /** Return non-zero if we have a lot of extra descriptors in our
1562 * routerlist, and should get rid of some of them. Else return 0.
1564 * We should be careful to not return true too eagerly, since we
1565 * could churn. By using "+1" below, we make sure this function
1566 * only returns true at most every smartlist_len(rl-\>routers)
1567 * new descriptors.
1569 static INLINE int
1570 routerlist_is_overfull(routerlist_t *rl)
1572 return smartlist_len(rl->old_routers) >
1573 smartlist_len(rl->routers)*(max_descriptors_per_router()+1);
1576 static INLINE int
1577 _routerlist_find_elt(smartlist_t *sl, void *ri, int idx)
1579 if (idx < 0 || smartlist_get(sl, idx) != ri) {
1580 idx = -1;
1581 SMARTLIST_FOREACH(sl, routerinfo_t *, r,
1582 if (r == ri) {
1583 idx = r_sl_idx;
1584 break;
1587 return idx;
1590 /** Insert an item <b>ri</b> into the routerlist <b>rl</b>, updating indices
1591 * as needed. */
1592 static void
1593 routerlist_insert(routerlist_t *rl, routerinfo_t *ri)
1595 digestmap_set(rl->identity_map, ri->cache_info.identity_digest, ri);
1596 digestmap_set(rl->desc_digest_map, ri->cache_info.signed_descriptor_digest,
1597 &(ri->cache_info));
1598 smartlist_add(rl->routers, ri);
1599 ri->routerlist_index = smartlist_len(rl->routers) - 1;
1600 router_dir_info_changed();
1601 // routerlist_assert_ok(rl);
1604 /** If we're a directory cache and routerlist <b>rl</b> doesn't have
1605 * a copy of router <b>ri</b> yet, add it to the list of old (not
1606 * recommended but still served) descriptors. Else free it. */
1607 static void
1608 routerlist_insert_old(routerlist_t *rl, routerinfo_t *ri)
1610 if (get_options()->DirPort &&
1611 !digestmap_get(rl->desc_digest_map,
1612 ri->cache_info.signed_descriptor_digest)) {
1613 signed_descriptor_t *sd = signed_descriptor_from_routerinfo(ri);
1614 digestmap_set(rl->desc_digest_map, sd->signed_descriptor_digest, sd);
1615 smartlist_add(rl->old_routers, sd);
1616 } else {
1617 routerinfo_free(ri);
1619 // routerlist_assert_ok(rl);
1622 /** Remove an item <b>ri</b> from the routerlist <b>rl</b>, updating indices
1623 * as needed. If <b>idx</b> is nonnegative and smartlist_get(rl-&gt;routers,
1624 * idx) == ri, we don't need to do a linear search over the list to decide
1625 * which to remove. We fill the gap in rl-&gt;routers with a later element in
1626 * the list, if any exists. <b>ri</b> is freed. */
1627 void
1628 routerlist_remove(routerlist_t *rl, routerinfo_t *ri, int idx, int make_old)
1630 routerinfo_t *ri_tmp;
1631 idx = _routerlist_find_elt(rl->routers, ri, idx);
1632 if (idx < 0)
1633 return;
1634 ri->routerlist_index = -1;
1635 smartlist_del(rl->routers, idx);
1636 if (idx < smartlist_len(rl->routers)) {
1637 routerinfo_t *r = smartlist_get(rl->routers, idx);
1638 r->routerlist_index = idx;
1641 ri_tmp = digestmap_remove(rl->identity_map, ri->cache_info.identity_digest);
1642 router_dir_info_changed();
1643 tor_assert(ri_tmp == ri);
1644 if (make_old && get_options()->DirPort) {
1645 signed_descriptor_t *sd;
1646 sd = signed_descriptor_from_routerinfo(ri);
1647 smartlist_add(rl->old_routers, sd);
1648 digestmap_set(rl->desc_digest_map, sd->signed_descriptor_digest, sd);
1649 } else {
1650 ri_tmp = digestmap_remove(rl->desc_digest_map,
1651 ri->cache_info.signed_descriptor_digest);
1652 tor_assert(ri_tmp == ri);
1653 router_bytes_dropped += ri->cache_info.signed_descriptor_len;
1654 routerinfo_free(ri);
1656 // routerlist_assert_ok(rl);
1659 /** DOCDOC */
1660 static void
1661 routerlist_remove_old(routerlist_t *rl, signed_descriptor_t *sd, int idx)
1663 signed_descriptor_t *sd_tmp;
1664 idx = _routerlist_find_elt(rl->old_routers, sd, idx);
1665 if (idx < 0)
1666 return;
1667 smartlist_del(rl->old_routers, idx);
1668 sd_tmp = digestmap_remove(rl->desc_digest_map,
1669 sd->signed_descriptor_digest);
1670 tor_assert(sd_tmp == sd);
1671 router_bytes_dropped += sd->signed_descriptor_len;
1672 signed_descriptor_free(sd);
1673 // routerlist_assert_ok(rl);
1676 /** Remove <b>ri_old</b> from the routerlist <b>rl</b>, and replace it with
1677 * <b>ri_new</b>, updating all index info. If <b>idx</b> is nonnegative and
1678 * smartlist_get(rl-&gt;routers, idx) == ri, we don't need to do a linear
1679 * search over the list to decide which to remove. We put ri_new in the same
1680 * index as ri_old, if possible. ri is freed as appropriate. */
1681 static void
1682 routerlist_replace(routerlist_t *rl, routerinfo_t *ri_old,
1683 routerinfo_t *ri_new, int idx, int make_old)
1685 tor_assert(ri_old != ri_new);
1686 idx = _routerlist_find_elt(rl->routers, ri_old, idx);
1687 router_dir_info_changed();
1688 if (idx >= 0) {
1689 smartlist_set(rl->routers, idx, ri_new);
1690 ri_old->routerlist_index = -1;
1691 ri_new->routerlist_index = idx;
1692 } else {
1693 log_warn(LD_BUG, "Appending entry from routerlist_replace.");
1694 routerlist_insert(rl, ri_new);
1695 return;
1697 if (memcmp(ri_old->cache_info.identity_digest,
1698 ri_new->cache_info.identity_digest, DIGEST_LEN)) {
1699 /* digests don't match; digestmap_set won't replace */
1700 digestmap_remove(rl->identity_map, ri_old->cache_info.identity_digest);
1702 digestmap_set(rl->identity_map, ri_new->cache_info.identity_digest, ri_new);
1703 digestmap_set(rl->desc_digest_map,
1704 ri_new->cache_info.signed_descriptor_digest, &(ri_new->cache_info));
1706 if (make_old && get_options()->DirPort) {
1707 signed_descriptor_t *sd = signed_descriptor_from_routerinfo(ri_old);
1708 smartlist_add(rl->old_routers, sd);
1709 digestmap_set(rl->desc_digest_map, sd->signed_descriptor_digest, sd);
1710 } else {
1711 if (memcmp(ri_old->cache_info.signed_descriptor_digest,
1712 ri_new->cache_info.signed_descriptor_digest,
1713 DIGEST_LEN)) {
1714 /* digests don't match; digestmap_set didn't replace */
1715 digestmap_remove(rl->desc_digest_map,
1716 ri_old->cache_info.signed_descriptor_digest);
1718 routerinfo_free(ri_old);
1720 // routerlist_assert_ok(rl);
1723 /** Free all memory held by the routerlist module. */
1724 void
1725 routerlist_free_all(void)
1727 if (routerlist)
1728 routerlist_free(routerlist);
1729 routerlist = NULL;
1730 if (warned_nicknames) {
1731 SMARTLIST_FOREACH(warned_nicknames, char *, cp, tor_free(cp));
1732 smartlist_free(warned_nicknames);
1733 warned_nicknames = NULL;
1735 if (warned_conflicts) {
1736 SMARTLIST_FOREACH(warned_conflicts, char *, cp, tor_free(cp));
1737 smartlist_free(warned_conflicts);
1738 warned_conflicts = NULL;
1740 if (trusted_dir_servers) {
1741 SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, ds,
1742 trusted_dir_server_free(ds));
1743 smartlist_free(trusted_dir_servers);
1744 trusted_dir_servers = NULL;
1746 if (networkstatus_list) {
1747 SMARTLIST_FOREACH(networkstatus_list, networkstatus_t *, ns,
1748 networkstatus_free(ns));
1749 smartlist_free(networkstatus_list);
1750 networkstatus_list = NULL;
1752 if (routerstatus_list) {
1753 SMARTLIST_FOREACH(routerstatus_list, local_routerstatus_t *, rs,
1754 local_routerstatus_free(rs));
1755 smartlist_free(routerstatus_list);
1756 routerstatus_list = NULL;
1758 if (named_server_map) {
1759 strmap_free(named_server_map, _tor_free);
1763 /** Free all storage held by the routerstatus object <b>rs</b>. */
1764 void
1765 routerstatus_free(routerstatus_t *rs)
1767 tor_free(rs);
1770 /** Free all storage held by the local_routerstatus object <b>rs</b>. */
1771 static void
1772 local_routerstatus_free(local_routerstatus_t *rs)
1774 tor_free(rs);
1777 /** Free all storage held by the networkstatus object <b>ns</b>. */
1778 void
1779 networkstatus_free(networkstatus_t *ns)
1781 tor_free(ns->source_address);
1782 tor_free(ns->contact);
1783 if (ns->signing_key)
1784 crypto_free_pk_env(ns->signing_key);
1785 tor_free(ns->client_versions);
1786 tor_free(ns->server_versions);
1787 if (ns->entries) {
1788 SMARTLIST_FOREACH(ns->entries, routerstatus_t *, rs,
1789 routerstatus_free(rs));
1790 smartlist_free(ns->entries);
1792 tor_free(ns);
1795 /** Forget that we have issued any router-related warnings, so that we'll
1796 * warn again if we see the same errors. */
1797 void
1798 routerlist_reset_warnings(void)
1800 if (!warned_nicknames)
1801 warned_nicknames = smartlist_create();
1802 SMARTLIST_FOREACH(warned_nicknames, char *, cp, tor_free(cp));
1803 smartlist_clear(warned_nicknames); /* now the list is empty. */
1805 if (!warned_conflicts)
1806 warned_conflicts = smartlist_create();
1807 SMARTLIST_FOREACH(warned_conflicts, char *, cp, tor_free(cp));
1808 smartlist_clear(warned_conflicts); /* now the list is empty. */
1810 if (!routerstatus_list)
1811 routerstatus_list = smartlist_create();
1812 SMARTLIST_FOREACH(routerstatus_list, local_routerstatus_t *, rs,
1813 rs->name_lookup_warned = 0);
1815 have_warned_about_invalid_status = 0;
1816 have_warned_about_old_version = 0;
1817 have_warned_about_new_version = 0;
1820 /** Mark the router with ID <b>digest</b> as running or non-running
1821 * in our routerlist. */
1822 void
1823 router_set_status(const char *digest, int up)
1825 routerinfo_t *router;
1826 local_routerstatus_t *status;
1827 tor_assert(digest);
1829 SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, d,
1830 if (!memcmp(d->digest, digest, DIGEST_LEN))
1831 d->is_running = up);
1833 router = router_get_by_digest(digest);
1834 if (router) {
1835 log_debug(LD_DIR,"Marking router '%s' as %s.",
1836 router->nickname, up ? "up" : "down");
1837 if (!up && router_is_me(router) && !we_are_hibernating())
1838 log_warn(LD_NET, "We just marked ourself as down. Are your external "
1839 "addresses reachable?");
1840 router->is_running = up;
1842 status = router_get_combined_status_by_digest(digest);
1843 if (status && status->status.is_running != up) {
1844 status->status.is_running = up;
1845 control_event_networkstatus_changed_single(status);
1847 router_dir_info_changed();
1850 /** Add <b>router</b> to the routerlist, if we don't already have it. Replace
1851 * older entries (if any) with the same key. Note: Callers should not hold
1852 * their pointers to <b>router</b> if this function fails; <b>router</b>
1853 * will either be inserted into the routerlist or freed.
1855 * Returns >= 0 if the router was added; less than 0 if it was not.
1857 * If we're returning non-zero, then assign to *<b>msg</b> a static string
1858 * describing the reason for not liking the routerinfo.
1860 * If the return value is less than -1, there was a problem with the
1861 * routerinfo. If the return value is equal to -1, then the routerinfo was
1862 * fine, but out-of-date. If the return value is equal to 1, the
1863 * routerinfo was accepted, but we should notify the generator of the
1864 * descriptor using the message *<b>msg</b>.
1866 * If <b>from_cache</b>, this descriptor came from our disk cache. If
1867 * <b>from_fetch</b>, we received it in response to a request we made.
1868 * (If both are false, that means it was uploaded to us as an auth dir
1869 * server or via the controller.)
1871 * This function should be called *after*
1872 * routers_update_status_from_networkstatus; subsequently, you should call
1873 * router_rebuild_store and control_event_descriptors_changed.
1876 router_add_to_routerlist(routerinfo_t *router, const char **msg,
1877 int from_cache, int from_fetch)
1879 const char *id_digest;
1880 int authdir = get_options()->AuthoritativeDir;
1881 int authdir_believes_valid = 0;
1882 routerinfo_t *old_router;
1884 tor_assert(msg);
1886 if (!routerlist)
1887 router_get_routerlist();
1888 if (!networkstatus_list)
1889 networkstatus_list = smartlist_create();
1891 id_digest = router->cache_info.identity_digest;
1893 /* Make sure that we haven't already got this exact descriptor. */
1894 if (digestmap_get(routerlist->desc_digest_map,
1895 router->cache_info.signed_descriptor_digest)) {
1896 log_info(LD_DIR,
1897 "Dropping descriptor that we already have for router '%s'",
1898 router->nickname);
1899 *msg = "Router descriptor was not new.";
1900 routerinfo_free(router);
1901 return -1;
1904 if (routerlist_is_overfull(routerlist))
1905 routerlist_remove_old_routers();
1907 if (authdir) {
1908 if (authdir_wants_to_reject_router(router, msg,
1909 !from_cache && !from_fetch)) {
1910 tor_assert(*msg);
1911 routerinfo_free(router);
1912 return -2;
1914 authdir_believes_valid = router->is_valid;
1915 } else if (from_fetch) {
1916 /* Only check the descriptor digest against the network statuses when
1917 * we are receiving in response to a fetch. */
1919 if (!signed_desc_digest_is_recognized(&router->cache_info)) {
1920 /* We asked for it, so some networkstatus must have listed it when we
1921 * did. Save it if we're a cache in case somebody else asks for it. */
1922 log_info(LD_DIR,
1923 "Received a no-longer-recognized descriptor for router '%s'",
1924 router->nickname);
1925 *msg = "Router descriptor is not referenced by any network-status.";
1927 /* Only journal this desc if we'll be serving it. */
1928 if (!from_cache && get_options()->DirPort)
1929 router_append_to_journal(&router->cache_info);
1930 routerlist_insert_old(routerlist, router);
1931 return -1;
1935 /* We no longer need a router with this descriptor digest. */
1936 SMARTLIST_FOREACH(networkstatus_list, networkstatus_t *, ns,
1938 routerstatus_t *rs =
1939 networkstatus_find_entry(ns, router->cache_info.identity_digest);
1940 if (rs && !memcmp(rs->descriptor_digest,
1941 router->cache_info.signed_descriptor_digest,
1942 DIGEST_LEN))
1943 rs->need_to_mirror = 0;
1946 /* If we have a router with the same identity key, choose the newer one. */
1947 old_router = digestmap_get(routerlist->identity_map,
1948 router->cache_info.identity_digest);
1949 if (old_router) {
1950 int pos = old_router->routerlist_index;
1951 tor_assert(smartlist_get(routerlist->routers, pos) == old_router);
1953 if (router->cache_info.published_on <=
1954 old_router->cache_info.published_on) {
1955 /* Same key, but old */
1956 log_debug(LD_DIR, "Skipping not-new descriptor for router '%s'",
1957 router->nickname);
1958 /* Only journal this desc if we'll be serving it. */
1959 if (!from_cache && get_options()->DirPort)
1960 router_append_to_journal(&router->cache_info);
1961 routerlist_insert_old(routerlist, router);
1962 *msg = "Router descriptor was not new.";
1963 return -1;
1964 } else {
1965 /* Same key, new. */
1966 int unreachable = 0;
1967 log_debug(LD_DIR, "Replacing entry for router '%s/%s' [%s]",
1968 router->nickname, old_router->nickname,
1969 hex_str(id_digest,DIGEST_LEN));
1970 if (router->addr == old_router->addr &&
1971 router->or_port == old_router->or_port) {
1972 /* these carry over when the address and orport are unchanged.*/
1973 router->last_reachable = old_router->last_reachable;
1974 router->testing_since = old_router->testing_since;
1975 router->num_unreachable_notifications =
1976 old_router->num_unreachable_notifications;
1978 if (authdir && !from_cache && !from_fetch &&
1979 router_have_minimum_dir_info() &&
1980 dirserv_thinks_router_is_blatantly_unreachable(router,
1981 time(NULL))) {
1982 if (router->num_unreachable_notifications >= 3) {
1983 unreachable = 1;
1984 log_notice(LD_DIR, "Notifying server '%s' that it's unreachable. "
1985 "(ContactInfo '%s', platform '%s').",
1986 router->nickname,
1987 router->contact_info ? router->contact_info : "",
1988 router->platform ? router->platform : "");
1989 } else {
1990 log_info(LD_DIR,"'%s' may be unreachable -- the %d previous "
1991 "descriptors were thought to be unreachable.",
1992 router->nickname, router->num_unreachable_notifications);
1993 router->num_unreachable_notifications++;
1996 routerlist_replace(routerlist, old_router, router, pos, 1);
1997 if (!from_cache) {
1998 router_append_to_journal(&router->cache_info);
2000 directory_set_dirty();
2001 *msg = unreachable ? "Dirserver believes your ORPort is unreachable" :
2002 authdir_believes_valid ? "Valid server updated" :
2003 ("Invalid server updated. (This dirserver is marking your "
2004 "server as unapproved.)");
2005 return unreachable ? 1 : 0;
2009 /* We haven't seen a router with this identity before. Add it to the end of
2010 * the list. */
2011 routerlist_insert(routerlist, router);
2012 if (!from_cache)
2013 router_append_to_journal(&router->cache_info);
2014 directory_set_dirty();
2015 return 0;
2018 /** Sorting helper: return &lt;0, 0, or &gt;0 depending on whether the
2019 * signed_descriptor_t* in *<b>a</b> has an identity digest preceding, equal
2020 * to, or later than that of *<b>b</b>. */
2021 static int
2022 _compare_old_routers_by_identity(const void **_a, const void **_b)
2024 int i;
2025 const signed_descriptor_t *r1 = *_a, *r2 = *_b;
2026 if ((i = memcmp(r1->identity_digest, r2->identity_digest, DIGEST_LEN)))
2027 return i;
2028 return r1->published_on - r2->published_on;
2031 /** Internal type used to represent how long an old descriptor was valid,
2032 * where it appeared in the list of old descriptors, and whether it's extra
2033 * old. Used only by routerlist_remove_old_cached_routers_with_id(). */
2034 struct duration_idx_t {
2035 int duration;
2036 int idx;
2037 int old;
2040 /** Sorting helper: compare two duration_idx_t by their duration. */
2041 static int
2042 _compare_duration_idx(const void *_d1, const void *_d2)
2044 const struct duration_idx_t *d1 = _d1;
2045 const struct duration_idx_t *d2 = _d2;
2046 return d1->duration - d2->duration;
2049 /** The range <b>lo</b> through <b>hi</b> inclusive of routerlist->old_routers
2050 * must contain routerinfo_t with the same identity and with publication time
2051 * in ascending order. Remove members from this range until there are no more
2052 * than max_descriptors_per_router() remaining. Start by removing the oldest
2053 * members from before <b>cutoff</b>, then remove members which were current
2054 * for the lowest amount of time. The order of members of old_routers at
2055 * indices <b>lo</b> or higher may be changed.
2057 static void
2058 routerlist_remove_old_cached_routers_with_id(time_t cutoff, int lo, int hi,
2059 digestmap_t *retain)
2061 int i, n = hi-lo+1, n_extra;
2062 int n_rmv = 0;
2063 struct duration_idx_t *lifespans;
2064 uint8_t *rmv, *must_keep;
2065 smartlist_t *lst = routerlist->old_routers;
2066 #if 1
2067 const char *ident;
2068 tor_assert(hi < smartlist_len(lst));
2069 tor_assert(lo <= hi);
2070 ident = ((signed_descriptor_t*)smartlist_get(lst, lo))->identity_digest;
2071 for (i = lo+1; i <= hi; ++i) {
2072 signed_descriptor_t *r = smartlist_get(lst, i);
2073 tor_assert(!memcmp(ident, r->identity_digest, DIGEST_LEN));
2075 #endif
2077 /* Check whether we need to do anything at all. */
2078 n_extra = n - max_descriptors_per_router();
2079 if (n_extra <= 0)
2080 return;
2082 lifespans = tor_malloc_zero(sizeof(struct duration_idx_t)*n);
2083 rmv = tor_malloc_zero(sizeof(uint8_t)*n);
2084 must_keep = tor_malloc_zero(sizeof(uint8_t)*n);
2085 /* Set lifespans to contain the lifespan and index of each server. */
2086 /* Set rmv[i-lo]=1 if we're going to remove a server for being too old. */
2087 for (i = lo; i <= hi; ++i) {
2088 signed_descriptor_t *r = smartlist_get(lst, i);
2089 signed_descriptor_t *r_next;
2090 lifespans[i-lo].idx = i;
2091 if (retain && digestmap_get(retain, r->signed_descriptor_digest)) {
2092 must_keep[i-lo] = 1;
2094 if (i < hi) {
2095 r_next = smartlist_get(lst, i+1);
2096 tor_assert(r->published_on <= r_next->published_on);
2097 lifespans[i-lo].duration = (r_next->published_on - r->published_on);
2098 } else {
2099 r_next = NULL;
2100 lifespans[i-lo].duration = INT_MAX;
2102 if (!must_keep[i-lo] && r->published_on < cutoff && n_rmv < n_extra) {
2103 ++n_rmv;
2104 lifespans[i-lo].old = 1;
2105 rmv[i-lo] = 1;
2109 if (n_rmv < n_extra) {
2111 * We aren't removing enough servers for being old. Sort lifespans by
2112 * the duration of liveness, and remove the ones we're not already going to
2113 * remove based on how long they were alive.
2115 qsort(lifespans, n, sizeof(struct duration_idx_t), _compare_duration_idx);
2116 for (i = 0; i < n && n_rmv < n_extra; ++i) {
2117 if (!must_keep[lifespans[i].idx-lo] && !lifespans[i].old) {
2118 rmv[lifespans[i].idx-lo] = 1;
2119 ++n_rmv;
2124 for (i = hi; i >= lo; --i) {
2125 if (rmv[i-lo])
2126 routerlist_remove_old(routerlist, smartlist_get(lst, i), i);
2128 tor_free(must_keep);
2129 tor_free(rmv);
2130 tor_free(lifespans);
2133 /** Deactivate any routers from the routerlist that are more than
2134 * ROUTER_MAX_AGE seconds old and not recommended by any networkstatuses;
2135 * remove old routers from the list of cached routers if we have too many.
2137 void
2138 routerlist_remove_old_routers(void)
2140 int i, hi=-1;
2141 const char *cur_id = NULL;
2142 time_t now = time(NULL);
2143 time_t cutoff;
2144 routerinfo_t *router;
2145 signed_descriptor_t *sd;
2146 digestmap_t *retain;
2147 if (!routerlist || !networkstatus_list)
2148 return;
2150 routerlist_assert_ok(routerlist);
2152 retain = digestmap_new();
2153 cutoff = now - OLD_ROUTER_DESC_MAX_AGE;
2154 /* Build a list of all the descriptors that _anybody_ recommends. */
2155 SMARTLIST_FOREACH(networkstatus_list, networkstatus_t *, ns,
2157 /* XXXX The inner loop here gets pretty expensive, and actually shows up
2158 * on some profiles. It may be the reason digestmap_set shows up in
2159 * profiles too. If instead we kept a per-descriptor digest count of
2160 * how many networkstatuses recommended each descriptor, and changed
2161 * that only when the networkstatuses changed, that would be a speed
2162 * improvement, possibly 1-4% if it also removes digestmap_set from the
2163 * profile. Not worth it for 0.1.2.x, though. The new directory
2164 * system will obsolete this whole thing in 0.2.0.x. */
2165 SMARTLIST_FOREACH(ns->entries, routerstatus_t *, rs,
2166 if (rs->published_on >= cutoff)
2167 digestmap_set(retain, rs->descriptor_digest, (void*)1));
2170 /* If we have a bunch of networkstatuses, we should consider pruning current
2171 * routers that are too old and that nobody recommends. (If we don't have
2172 * enough networkstatuses, then we should get more before we decide to kill
2173 * routers.) */
2174 if (smartlist_len(networkstatus_list) > get_n_v2_authorities() / 2) {
2175 cutoff = now - ROUTER_MAX_AGE;
2176 /* Remove too-old unrecommended members of routerlist->routers. */
2177 for (i = 0; i < smartlist_len(routerlist->routers); ++i) {
2178 router = smartlist_get(routerlist->routers, i);
2179 if (router->cache_info.published_on <= cutoff &&
2180 !digestmap_get(retain,router->cache_info.signed_descriptor_digest)) {
2181 /* Too old: remove it. (If we're a cache, just move it into
2182 * old_routers.) */
2183 log_info(LD_DIR,
2184 "Forgetting obsolete (too old) routerinfo for router '%s'",
2185 router->nickname);
2186 routerlist_remove(routerlist, router, i--, 1);
2191 routerlist_assert_ok(routerlist);
2193 /* Remove far-too-old members of routerlist->old_routers. */
2194 cutoff = now - OLD_ROUTER_DESC_MAX_AGE;
2195 for (i = 0; i < smartlist_len(routerlist->old_routers); ++i) {
2196 sd = smartlist_get(routerlist->old_routers, i);
2197 if (sd->published_on <= cutoff &&
2198 !digestmap_get(retain, sd->signed_descriptor_digest)) {
2199 /* Too old. Remove it. */
2200 routerlist_remove_old(routerlist, sd, i--);
2204 routerlist_assert_ok(routerlist);
2206 /* Now we might have to look at routerlist->old_routers for extraneous
2207 * members. (We'd keep all the members if we could, but we need to save
2208 * space.) First, check whether we have too many router descriptors, total.
2209 * We're okay with having too many for some given router, so long as the
2210 * total number doesn't approach max_descriptors_per_router()*len(router).
2212 if (smartlist_len(routerlist->old_routers) <
2213 smartlist_len(routerlist->routers) * (max_descriptors_per_router() - 1))
2214 goto done;
2216 smartlist_sort(routerlist->old_routers, _compare_old_routers_by_identity);
2218 /* Iterate through the list from back to front, so when we remove descriptors
2219 * we don't mess up groups we haven't gotten to. */
2220 for (i = smartlist_len(routerlist->old_routers)-1; i >= 0; --i) {
2221 signed_descriptor_t *r = smartlist_get(routerlist->old_routers, i);
2222 if (!cur_id) {
2223 cur_id = r->identity_digest;
2224 hi = i;
2226 if (memcmp(cur_id, r->identity_digest, DIGEST_LEN)) {
2227 routerlist_remove_old_cached_routers_with_id(cutoff, i+1, hi, retain);
2228 cur_id = r->identity_digest;
2229 hi = i;
2232 if (hi>=0)
2233 routerlist_remove_old_cached_routers_with_id(cutoff, 0, hi, retain);
2234 routerlist_assert_ok(routerlist);
2236 done:
2237 digestmap_free(retain, NULL);
2241 * Code to parse a single router descriptor and insert it into the
2242 * routerlist. Return -1 if the descriptor was ill-formed; 0 if the
2243 * descriptor was well-formed but could not be added; and 1 if the
2244 * descriptor was added.
2246 * If we don't add it and <b>msg</b> is not NULL, then assign to
2247 * *<b>msg</b> a static string describing the reason for refusing the
2248 * descriptor.
2250 * This is used only by the controller.
2253 router_load_single_router(const char *s, uint8_t purpose, const char **msg)
2255 routerinfo_t *ri;
2256 int r;
2257 smartlist_t *lst;
2258 tor_assert(msg);
2259 *msg = NULL;
2261 if (!(ri = router_parse_entry_from_string(s, NULL, 1))) {
2262 log_warn(LD_DIR, "Error parsing router descriptor; dropping.");
2263 *msg = "Couldn't parse router descriptor.";
2264 return -1;
2266 ri->purpose = purpose;
2267 if (router_is_me(ri)) {
2268 log_warn(LD_DIR, "Router's identity key matches mine; dropping.");
2269 *msg = "Router's identity key matches mine.";
2270 routerinfo_free(ri);
2271 return 0;
2274 lst = smartlist_create();
2275 smartlist_add(lst, ri);
2276 routers_update_status_from_networkstatus(lst, 0);
2278 if ((r=router_add_to_routerlist(ri, msg, 0, 0))<0) {
2279 /* we've already assigned to *msg now, and ri is already freed */
2280 tor_assert(*msg);
2281 if (r < -1)
2282 log_warn(LD_DIR, "Couldn't add router to list: %s Dropping.", *msg);
2283 smartlist_free(lst);
2284 return 0;
2285 } else {
2286 control_event_descriptors_changed(lst);
2287 smartlist_free(lst);
2288 log_debug(LD_DIR, "Added router to list");
2289 return 1;
2293 /** Given a string <b>s</b> containing some routerdescs, parse it and put the
2294 * routers into our directory. If saved_location is SAVED_NOWHERE, the routers
2295 * are in response to a query to the network: cache them by adding them to
2296 * the journal.
2298 * If <b>requested_fingerprints</b> is provided, it must contain a list of
2299 * uppercased identity fingerprints. Do not update any router whose
2300 * fingerprint is not on the list; after updating a router, remove its
2301 * fingerprint from the list.
2303 void
2304 router_load_routers_from_string(const char *s, saved_location_t saved_location,
2305 smartlist_t *requested_fingerprints)
2307 smartlist_t *routers = smartlist_create(), *changed = smartlist_create();
2308 char fp[HEX_DIGEST_LEN+1];
2309 const char *msg;
2310 int from_cache = (saved_location != SAVED_NOWHERE);
2312 router_parse_list_from_string(&s, routers, saved_location);
2314 routers_update_status_from_networkstatus(routers, !from_cache);
2316 log_info(LD_DIR, "%d elements to add", smartlist_len(routers));
2318 SMARTLIST_FOREACH(routers, routerinfo_t *, ri,
2320 base16_encode(fp, sizeof(fp), ri->cache_info.signed_descriptor_digest,
2321 DIGEST_LEN);
2322 if (requested_fingerprints) {
2323 if (smartlist_string_isin(requested_fingerprints, fp)) {
2324 smartlist_string_remove(requested_fingerprints, fp);
2325 } else {
2326 char *requested =
2327 smartlist_join_strings(requested_fingerprints," ",0,NULL);
2328 log_warn(LD_DIR,
2329 "We received a router descriptor with a fingerprint (%s) "
2330 "that we never requested. (We asked for: %s.) Dropping.",
2331 fp, requested);
2332 tor_free(requested);
2333 routerinfo_free(ri);
2334 continue;
2338 if (router_add_to_routerlist(ri, &msg, from_cache, !from_cache) >= 0)
2339 smartlist_add(changed, ri);
2342 if (smartlist_len(changed))
2343 control_event_descriptors_changed(changed);
2345 routerlist_assert_ok(routerlist);
2346 router_rebuild_store(0);
2348 smartlist_free(routers);
2349 smartlist_free(changed);
2352 /** Helper: return a newly allocated string containing the name of the filename
2353 * where we plan to cache the network status with the given identity digest. */
2354 char *
2355 networkstatus_get_cache_filename(const char *identity_digest)
2357 const char *datadir = get_options()->DataDirectory;
2358 size_t len = strlen(datadir)+64;
2359 char fp[HEX_DIGEST_LEN+1];
2360 char *fn = tor_malloc(len+1);
2361 base16_encode(fp, HEX_DIGEST_LEN+1, identity_digest, DIGEST_LEN);
2362 tor_snprintf(fn, len, "%s/cached-status/%s",datadir,fp);
2363 return fn;
2366 /** Helper for smartlist_sort: Compare two networkstatus objects by
2367 * publication date. */
2368 static int
2369 _compare_networkstatus_published_on(const void **_a, const void **_b)
2371 const networkstatus_t *a = *_a, *b = *_b;
2372 if (a->published_on < b->published_on)
2373 return -1;
2374 else if (a->published_on > b->published_on)
2375 return 1;
2376 else
2377 return 0;
2380 /** Add the parsed neworkstatus in <b>ns</b> (with original document in
2381 * <b>s</b> to the disk cache (and the in-memory directory server cache) as
2382 * appropriate. */
2383 static int
2384 add_networkstatus_to_cache(const char *s,
2385 networkstatus_source_t source,
2386 networkstatus_t *ns)
2388 if (source != NS_FROM_CACHE) {
2389 char *fn = networkstatus_get_cache_filename(ns->identity_digest);
2390 if (write_str_to_file(fn, s, 0)<0) {
2391 log_notice(LD_FS, "Couldn't write cached network status to \"%s\"", fn);
2393 tor_free(fn);
2396 if (get_options()->DirPort)
2397 dirserv_set_cached_networkstatus_v2(s,
2398 ns->identity_digest,
2399 ns->published_on);
2401 return 0;
2404 /** How far in the future do we allow a network-status to get before removing
2405 * it? (seconds) */
2406 #define NETWORKSTATUS_ALLOW_SKEW (24*60*60)
2408 /** Given a string <b>s</b> containing a network status that we received at
2409 * <b>arrived_at</b> from <b>source</b>, try to parse it, see if we want to
2410 * store it, and put it into our cache as necessary.
2412 * If <b>source</b> is NS_FROM_DIR or NS_FROM_CACHE, do not replace our
2413 * own networkstatus_t (if we're an authoritative directory server).
2415 * If <b>source</b> is NS_FROM_CACHE, do not write our networkstatus_t to the
2416 * cache.
2418 * If <b>requested_fingerprints</b> is provided, it must contain a list of
2419 * uppercased identity fingerprints. Do not update any networkstatus whose
2420 * fingerprint is not on the list; after updating a networkstatus, remove its
2421 * fingerprint from the list.
2423 * Return 0 on success, -1 on failure.
2425 * Callers should make sure that routers_update_all_from_networkstatus() is
2426 * invoked after this function succeeds.
2429 router_set_networkstatus(const char *s, time_t arrived_at,
2430 networkstatus_source_t source, smartlist_t *requested_fingerprints)
2432 networkstatus_t *ns;
2433 int i, found;
2434 time_t now;
2435 int skewed = 0;
2436 trusted_dir_server_t *trusted_dir = NULL;
2437 const char *source_desc = NULL;
2438 char fp[HEX_DIGEST_LEN+1];
2439 char published[ISO_TIME_LEN+1];
2441 ns = networkstatus_parse_from_string(s);
2442 if (!ns) {
2443 log_warn(LD_DIR, "Couldn't parse network status.");
2444 return -1;
2446 base16_encode(fp, HEX_DIGEST_LEN+1, ns->identity_digest, DIGEST_LEN);
2447 if (!(trusted_dir =
2448 router_get_trusteddirserver_by_digest(ns->identity_digest)) ||
2449 !trusted_dir->is_v2_authority) {
2450 log_info(LD_DIR, "Network status was signed, but not by an authoritative "
2451 "directory we recognize.");
2452 if (!get_options()->DirPort) {
2453 networkstatus_free(ns);
2454 return 0;
2456 source_desc = fp;
2457 } else {
2458 source_desc = trusted_dir->description;
2460 now = time(NULL);
2461 if (arrived_at > now)
2462 arrived_at = now;
2464 ns->received_on = arrived_at;
2466 format_iso_time(published, ns->published_on);
2468 if (ns->published_on > now + NETWORKSTATUS_ALLOW_SKEW) {
2469 log_warn(LD_GENERAL, "Network status from %s was published in the future "
2470 "(%s GMT). Somebody is skewed here: check your clock. "
2471 "Not caching.",
2472 source_desc, published);
2473 control_event_general_status(LOG_WARN,
2474 "CLOCK_SKEW SOURCE=NETWORKSTATUS:%s:%d",
2475 ns->source_address, ns->source_dirport);
2476 skewed = 1;
2479 if (!networkstatus_list)
2480 networkstatus_list = smartlist_create();
2482 if ( (source == NS_FROM_DIR_BY_FP || source == NS_FROM_DIR_ALL) &&
2483 router_digest_is_me(ns->identity_digest)) {
2484 /* Don't replace our own networkstatus when we get it from somebody else.*/
2485 networkstatus_free(ns);
2486 return 0;
2489 if (requested_fingerprints) {
2490 if (smartlist_string_isin(requested_fingerprints, fp)) {
2491 smartlist_string_remove(requested_fingerprints, fp);
2492 } else {
2493 if (source != NS_FROM_DIR_ALL) {
2494 char *requested =
2495 smartlist_join_strings(requested_fingerprints," ",0,NULL);
2496 log_warn(LD_DIR,
2497 "We received a network status with a fingerprint (%s) that we "
2498 "never requested. (We asked for: %s.) Dropping.",
2499 fp, requested);
2500 tor_free(requested);
2501 return 0;
2506 if (!trusted_dir) {
2507 if (!skewed && get_options()->DirPort) {
2508 /* We got a non-trusted networkstatus, and we're a directory cache.
2509 * This means that we asked an authority, and it told us about another
2510 * authority we didn't recognize. */
2511 log_info(LD_DIR,
2512 "We do not recognize authority (%s) but we are willing "
2513 "to cache it", fp);
2514 add_networkstatus_to_cache(s, source, ns);
2515 networkstatus_free(ns);
2517 return 0;
2520 if (source != NS_FROM_CACHE && trusted_dir)
2521 trusted_dir->n_networkstatus_failures = 0;
2523 found = 0;
2524 for (i=0; i < smartlist_len(networkstatus_list); ++i) {
2525 networkstatus_t *old_ns = smartlist_get(networkstatus_list, i);
2527 if (!memcmp(old_ns->identity_digest, ns->identity_digest, DIGEST_LEN)) {
2528 if (!memcmp(old_ns->networkstatus_digest,
2529 ns->networkstatus_digest, DIGEST_LEN)) {
2530 /* Same one we had before. */
2531 networkstatus_free(ns);
2532 tor_assert(trusted_dir);
2533 log_info(LD_DIR,
2534 "Not replacing network-status from %s (published %s); "
2535 "we already have it.",
2536 trusted_dir->description, published);
2537 if (old_ns->received_on < arrived_at) {
2538 if (source != NS_FROM_CACHE) {
2539 char *fn;
2540 fn = networkstatus_get_cache_filename(old_ns->identity_digest);
2541 /* We use mtime to tell when it arrived, so update that. */
2542 touch_file(fn);
2543 tor_free(fn);
2545 old_ns->received_on = arrived_at;
2547 ++trusted_dir->n_networkstatus_failures;
2548 return 0;
2549 } else if (old_ns->published_on >= ns->published_on) {
2550 char old_published[ISO_TIME_LEN+1];
2551 format_iso_time(old_published, old_ns->published_on);
2552 tor_assert(trusted_dir);
2553 log_info(LD_DIR,
2554 "Not replacing network-status from %s (published %s);"
2555 " we have a newer one (published %s) for this authority.",
2556 trusted_dir->description, published,
2557 old_published);
2558 networkstatus_free(ns);
2559 ++trusted_dir->n_networkstatus_failures;
2560 return 0;
2561 } else {
2562 networkstatus_free(old_ns);
2563 smartlist_set(networkstatus_list, i, ns);
2564 found = 1;
2565 break;
2570 if (!found)
2571 smartlist_add(networkstatus_list, ns);
2573 SMARTLIST_FOREACH(ns->entries, routerstatus_t *, rs,
2575 if (!router_get_by_descriptor_digest(rs->descriptor_digest))
2576 rs->need_to_mirror = 1;
2579 log_info(LD_DIR, "Setting networkstatus %s %s (published %s)",
2580 source == NS_FROM_CACHE?"cached from":
2581 ((source == NS_FROM_DIR_BY_FP || source == NS_FROM_DIR_ALL) ?
2582 "downloaded from":"generated for"),
2583 trusted_dir->description, published);
2584 networkstatus_list_has_changed = 1;
2585 router_dir_info_changed();
2587 smartlist_sort(networkstatus_list, _compare_networkstatus_published_on);
2589 if (!skewed)
2590 add_networkstatus_to_cache(s, source, ns);
2592 networkstatus_list_update_recent(now);
2594 return 0;
2597 /** How old do we allow a network-status to get before removing it
2598 * completely? */
2599 #define MAX_NETWORKSTATUS_AGE (10*24*60*60)
2600 /** Remove all very-old network_status_t objects from memory and from the
2601 * disk cache. */
2602 void
2603 networkstatus_list_clean(time_t now)
2605 int i;
2606 if (!networkstatus_list)
2607 return;
2609 for (i = 0; i < smartlist_len(networkstatus_list); ++i) {
2610 networkstatus_t *ns = smartlist_get(networkstatus_list, i);
2611 char *fname = NULL;
2612 if (ns->published_on + MAX_NETWORKSTATUS_AGE > now)
2613 continue;
2614 /* Okay, this one is too old. Remove it from the list, and delete it
2615 * from the cache. */
2616 smartlist_del(networkstatus_list, i--);
2617 fname = networkstatus_get_cache_filename(ns->identity_digest);
2618 if (file_status(fname) == FN_FILE) {
2619 log_info(LD_DIR, "Removing too-old networkstatus in %s", fname);
2620 unlink(fname);
2622 tor_free(fname);
2623 if (get_options()->DirPort) {
2624 dirserv_set_cached_networkstatus_v2(NULL, ns->identity_digest, 0);
2626 networkstatus_free(ns);
2627 router_dir_info_changed();
2630 /* And now go through the directory cache for any cached untrusted
2631 * networkstatuses and other network info. */
2632 dirserv_clear_old_networkstatuses(now - MAX_NETWORKSTATUS_AGE);
2633 dirserv_clear_old_v1_info(now);
2636 /** Helper for bsearching a list of routerstatus_t pointers.*/
2637 static int
2638 _compare_digest_to_routerstatus_entry(const void *_key, const void **_member)
2640 const char *key = _key;
2641 const routerstatus_t *rs = *_member;
2642 return memcmp(key, rs->identity_digest, DIGEST_LEN);
2645 /** Return the entry in <b>ns</b> for the identity digest <b>digest</b>, or
2646 * NULL if none was found. */
2647 static routerstatus_t *
2648 networkstatus_find_entry(networkstatus_t *ns, const char *digest)
2650 return smartlist_bsearch(ns->entries, digest,
2651 _compare_digest_to_routerstatus_entry);
2654 /** Return the consensus view of the status of the router whose digest is
2655 * <b>digest</b>, or NULL if we don't know about any such router. */
2656 local_routerstatus_t *
2657 router_get_combined_status_by_digest(const char *digest)
2659 if (!routerstatus_list)
2660 return NULL;
2661 return smartlist_bsearch(routerstatus_list, digest,
2662 _compare_digest_to_routerstatus_entry);
2665 /** Return a newly allocated list of the local_routerstatus_t for all routers
2666 * where we believe that the digest of their current descriptor is some digest
2667 * listed in <b>digests</b>. */
2668 smartlist_t *
2669 router_get_combined_status_by_descriptor_digests(smartlist_t *digests)
2671 digestmap_t *map;
2672 smartlist_t *result;
2674 if (!routerstatus_list)
2675 return NULL;
2677 map = digestmap_new();
2678 result = smartlist_create();
2679 SMARTLIST_FOREACH(digests, const char *, d, digestmap_set(map, d, (void*)1));
2681 SMARTLIST_FOREACH(routerstatus_list, local_routerstatus_t *, lrs, {
2682 if (digestmap_get(map, lrs->status.descriptor_digest))
2683 smartlist_add(result, lrs);
2686 digestmap_free(map, NULL);
2687 return result;
2690 /** Given a nickname (possibly verbose, possibly a hexadecimal digest), return
2691 * the corresponding local_routerstatus_t, or NULL if none exists. Warn the
2692 * user if <b>warn_if_unnamed</b> is set, and they have specified a router by
2693 * nickname, but the Named flag isn't set for that router. */
2694 static local_routerstatus_t *
2695 router_get_combined_status_by_nickname(const char *nickname,
2696 int warn_if_unnamed)
2698 char digest[DIGEST_LEN];
2699 local_routerstatus_t *best=NULL;
2700 smartlist_t *matches=NULL;
2702 if (!routerstatus_list || !nickname)
2703 return NULL;
2705 if (nickname[0] == '$') {
2706 if (base16_decode(digest, DIGEST_LEN, nickname+1, strlen(nickname))<0)
2707 return NULL;
2708 return router_get_combined_status_by_digest(digest);
2709 } else if (strlen(nickname) == HEX_DIGEST_LEN &&
2710 (base16_decode(digest, DIGEST_LEN, nickname+1, strlen(nickname))==0)) {
2711 return router_get_combined_status_by_digest(digest);
2714 matches = smartlist_create();
2715 SMARTLIST_FOREACH(routerstatus_list, local_routerstatus_t *, lrs,
2717 if (!strcasecmp(lrs->status.nickname, nickname)) {
2718 if (lrs->status.is_named) {
2719 smartlist_free(matches);
2720 return lrs;
2721 } else {
2722 smartlist_add(matches, lrs);
2723 best = lrs;
2728 if (smartlist_len(matches)>1 && warn_if_unnamed) {
2729 int any_unwarned=0;
2730 SMARTLIST_FOREACH(matches, local_routerstatus_t *, lrs,
2732 if (! lrs->name_lookup_warned) {
2733 lrs->name_lookup_warned=1;
2734 any_unwarned=1;
2737 if (any_unwarned) {
2738 log_warn(LD_CONFIG,"There are multiple matches for the nickname \"%s\","
2739 " but none is listed as named by the directory authorites. "
2740 "Choosing one arbitrarily.", nickname);
2742 } else if (warn_if_unnamed && best && !best->name_lookup_warned) {
2743 char fp[HEX_DIGEST_LEN+1];
2744 base16_encode(fp, sizeof(fp),
2745 best->status.identity_digest, DIGEST_LEN);
2746 log_warn(LD_CONFIG,
2747 "When looking up a status, you specified a server \"%s\" by name, "
2748 "but the directory authorities do not have any key registered for "
2749 "this nickname -- so it could be used by any server, "
2750 "not just the one you meant. "
2751 "To make sure you get the same server in the future, refer to "
2752 "it by key, as \"$%s\".", nickname, fp);
2753 best->name_lookup_warned = 1;
2755 smartlist_free(matches);
2756 return best;
2759 /** Find a routerstatus_t that corresponds to <b>hexdigest</b>, if
2760 * any. Prefer ones that belong to authorities. */
2761 routerstatus_t *
2762 routerstatus_get_by_hexdigest(const char *hexdigest)
2764 char digest[DIGEST_LEN];
2765 local_routerstatus_t *rs;
2766 trusted_dir_server_t *ds;
2768 if (strlen(hexdigest) < HEX_DIGEST_LEN ||
2769 base16_decode(digest,DIGEST_LEN,hexdigest,HEX_DIGEST_LEN) < 0)
2770 return NULL;
2771 if ((ds = router_get_trusteddirserver_by_digest(digest)))
2772 return &(ds->fake_status.status);
2773 if ((rs = router_get_combined_status_by_digest(digest)))
2774 return &(rs->status);
2775 return NULL;
2778 /** Return true iff any networkstatus includes a descriptor whose digest
2779 * is that of <b>desc</b>. */
2780 static int
2781 signed_desc_digest_is_recognized(signed_descriptor_t *desc)
2783 routerstatus_t *rs;
2784 if (!networkstatus_list)
2785 return 0;
2787 SMARTLIST_FOREACH(networkstatus_list, networkstatus_t *, ns,
2789 if (!(rs = networkstatus_find_entry(ns, desc->identity_digest)))
2790 continue;
2791 if (!memcmp(rs->descriptor_digest,
2792 desc->signed_descriptor_digest, DIGEST_LEN))
2793 return 1;
2795 return 0;
2798 /** How frequently do directory authorities re-download fresh networkstatus
2799 * documents? */
2800 #define AUTHORITY_NS_CACHE_INTERVAL (5*60)
2802 /** How frequently do non-authority directory caches re-download fresh
2803 * networkstatus documents? */
2804 #define NONAUTHORITY_NS_CACHE_INTERVAL (15*60)
2806 /** We are a directory server, and so cache network_status documents.
2807 * Initiate downloads as needed to update them. For authorities, this means
2808 * asking each trusted directory for its network-status. For caches, this
2809 * means asking a random authority for all network-statuses.
2811 static void
2812 update_networkstatus_cache_downloads(time_t now)
2814 int authority = authdir_mode(get_options());
2815 int interval =
2816 authority ? AUTHORITY_NS_CACHE_INTERVAL : NONAUTHORITY_NS_CACHE_INTERVAL;
2818 if (last_networkstatus_download_attempted + interval >= now)
2819 return;
2820 if (!trusted_dir_servers)
2821 return;
2823 last_networkstatus_download_attempted = now;
2825 if (authority) {
2826 /* An authority launches a separate connection for everybody. */
2827 SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, ds,
2829 char resource[HEX_DIGEST_LEN+6]; /* fp/hexdigit.z\0 */
2830 if (!ds->is_v2_authority)
2831 continue;
2832 if (router_digest_is_me(ds->digest))
2833 continue;
2834 if (connection_get_by_type_addr_port_purpose(
2835 CONN_TYPE_DIR, ds->addr, ds->dir_port,
2836 DIR_PURPOSE_FETCH_NETWORKSTATUS)) {
2837 /* We are already fetching this one. */
2838 continue;
2840 strlcpy(resource, "fp/", sizeof(resource));
2841 base16_encode(resource+3, sizeof(resource)-3, ds->digest, DIGEST_LEN);
2842 strlcat(resource, ".z", sizeof(resource));
2843 directory_initiate_command_routerstatus(
2844 &ds->fake_status.status, DIR_PURPOSE_FETCH_NETWORKSTATUS,
2845 0, /* Not private */
2846 resource,
2847 NULL, 0 /* No payload. */);
2849 } else {
2850 /* A non-authority cache launches one connection to a random authority. */
2851 /* (Check whether we're currently fetching network-status objects.) */
2852 if (!connection_get_by_type_purpose(CONN_TYPE_DIR,
2853 DIR_PURPOSE_FETCH_NETWORKSTATUS))
2854 directory_get_from_dirserver(DIR_PURPOSE_FETCH_NETWORKSTATUS,"all.z",1);
2858 /** How long (in seconds) does a client wait after getting a network status
2859 * before downloading the next in sequence? */
2860 #define NETWORKSTATUS_CLIENT_DL_INTERVAL (30*60)
2861 /** How many times do we allow a networkstatus download to fail before we
2862 * assume that the authority isn't publishing? */
2863 #define NETWORKSTATUS_N_ALLOWABLE_FAILURES 3
2864 /** We are not a directory cache or authority. Update our network-status list
2865 * by launching a new directory fetch for enough network-status documents "as
2866 * necessary". See function comments for implementation details.
2868 static void
2869 update_networkstatus_client_downloads(time_t now)
2871 int n_live = 0, n_dirservers, n_running_dirservers, needed = 0;
2872 int fetch_latest = 0;
2873 int most_recent_idx = -1;
2874 trusted_dir_server_t *most_recent = NULL;
2875 time_t most_recent_received = 0;
2876 char *resource, *cp;
2877 size_t resource_len;
2878 smartlist_t *missing;
2880 if (connection_get_by_type_purpose(CONN_TYPE_DIR,
2881 DIR_PURPOSE_FETCH_NETWORKSTATUS))
2882 return;
2884 /* This is a little tricky. We want to download enough network-status
2885 * objects so that we have all of them under
2886 * NETWORKSTATUS_MAX_AGE publication time. We want to download a new
2887 * *one* if the most recent one's publication time is under
2888 * NETWORKSTATUS_CLIENT_DL_INTERVAL.
2890 if (!get_n_v2_authorities())
2891 return;
2892 n_dirservers = n_running_dirservers = 0;
2893 missing = smartlist_create();
2894 SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, ds,
2896 networkstatus_t *ns = networkstatus_get_by_digest(ds->digest);
2897 if (!ds->is_v2_authority)
2898 continue;
2899 ++n_dirservers;
2900 if (ds->n_networkstatus_failures > NETWORKSTATUS_N_ALLOWABLE_FAILURES)
2901 continue;
2902 ++n_running_dirservers;
2903 if (ns && ns->published_on > now-NETWORKSTATUS_MAX_AGE)
2904 ++n_live;
2905 else
2906 smartlist_add(missing, ds->digest);
2907 if (ns && (!most_recent || ns->received_on > most_recent_received)) {
2908 most_recent_idx = ds_sl_idx; /* magic variable from FOREACH */
2909 most_recent = ds;
2910 most_recent_received = ns->received_on;
2914 /* Also, download at least 1 every NETWORKSTATUS_CLIENT_DL_INTERVAL. */
2915 if (!smartlist_len(missing) &&
2916 most_recent_received < now-NETWORKSTATUS_CLIENT_DL_INTERVAL) {
2917 log_info(LD_DIR, "Our most recent network-status document (from %s) "
2918 "is %d seconds old; downloading another.",
2919 most_recent?most_recent->description:"nobody",
2920 (int)(now-most_recent_received));
2921 fetch_latest = 1;
2922 needed = 1;
2923 } else if (smartlist_len(missing)) {
2924 log_info(LD_DIR, "For %d/%d running directory servers, we have %d live"
2925 " network-status documents. Downloading %d.",
2926 n_running_dirservers, n_dirservers, n_live,
2927 smartlist_len(missing));
2928 needed = smartlist_len(missing);
2929 } else {
2930 smartlist_free(missing);
2931 return;
2934 /* If no networkstatus was found, choose a dirserver at random as "most
2935 * recent". */
2936 if (most_recent_idx<0)
2937 most_recent_idx = crypto_rand_int(smartlist_len(trusted_dir_servers));
2939 if (fetch_latest) {
2940 int i;
2941 int n_failed = 0;
2942 for (i = most_recent_idx + 1; 1; ++i) {
2943 trusted_dir_server_t *ds;
2944 if (i >= smartlist_len(trusted_dir_servers))
2945 i = 0;
2946 ds = smartlist_get(trusted_dir_servers, i);
2947 if (! ds->is_v2_authority)
2948 continue;
2949 if (n_failed >= n_dirservers) {
2950 log_info(LD_DIR, "All authorities have failed. Not trying any.");
2951 smartlist_free(missing);
2952 return;
2954 if (ds->n_networkstatus_failures > NETWORKSTATUS_N_ALLOWABLE_FAILURES) {
2955 ++n_failed;
2956 continue;
2958 smartlist_add(missing, ds->digest);
2959 break;
2963 /* Build a request string for all the resources we want. */
2964 resource_len = smartlist_len(missing) * (HEX_DIGEST_LEN+1) + 6;
2965 resource = tor_malloc(resource_len);
2966 memcpy(resource, "fp/", 3);
2967 cp = resource+3;
2968 smartlist_sort_digests(missing);
2969 needed = smartlist_len(missing);
2970 SMARTLIST_FOREACH(missing, const char *, d,
2972 base16_encode(cp, HEX_DIGEST_LEN+1, d, DIGEST_LEN);
2973 cp += HEX_DIGEST_LEN;
2974 --needed;
2975 if (needed)
2976 *cp++ = '+';
2978 memcpy(cp, ".z", 3);
2979 directory_get_from_dirserver(DIR_PURPOSE_FETCH_NETWORKSTATUS, resource, 1);
2980 tor_free(resource);
2981 smartlist_free(missing);
2984 /** Launch requests for networkstatus documents as appropriate. */
2985 void
2986 update_networkstatus_downloads(time_t now)
2988 or_options_t *options = get_options();
2989 if (options->DirPort)
2990 update_networkstatus_cache_downloads(now);
2991 else
2992 update_networkstatus_client_downloads(now);
2995 /** Return 1 if all running sufficiently-stable routers will reject
2996 * addr:port, return 0 if any might accept it. */
2998 router_exit_policy_all_routers_reject(uint32_t addr, uint16_t port,
2999 int need_uptime)
3001 addr_policy_result_t r;
3002 if (!routerlist) return 1;
3004 SMARTLIST_FOREACH(routerlist->routers, routerinfo_t *, router,
3006 if (router->is_running &&
3007 !router_is_unreliable(router, need_uptime, 0, 0)) {
3008 r = compare_addr_to_addr_policy(addr, port, router->exit_policy);
3009 if (r != ADDR_POLICY_REJECTED && r != ADDR_POLICY_PROBABLY_REJECTED)
3010 return 0; /* this one could be ok. good enough. */
3013 return 1; /* all will reject. */
3016 /** Return true iff <b>router</b> does not permit exit streams.
3019 router_exit_policy_rejects_all(routerinfo_t *router)
3021 return compare_addr_to_addr_policy(0, 0, router->exit_policy)
3022 == ADDR_POLICY_REJECTED;
3025 /** Add to the list of authorized directory servers one at
3026 * <b>address</b>:<b>port</b>, with identity key <b>digest</b>. If
3027 * <b>address</b> is NULL, add ourself. */
3028 void
3029 add_trusted_dir_server(const char *nickname, const char *address,
3030 uint16_t dir_port, uint16_t or_port,
3031 const char *digest, int is_v1_authority,
3032 int is_v2_authority, int is_hidserv_authority)
3034 trusted_dir_server_t *ent;
3035 uint32_t a;
3036 char *hostname = NULL;
3037 size_t dlen;
3038 if (!trusted_dir_servers)
3039 trusted_dir_servers = smartlist_create();
3041 if (!address) { /* The address is us; we should guess. */
3042 if (resolve_my_address(LOG_WARN, get_options(), &a, &hostname) < 0) {
3043 log_warn(LD_CONFIG,
3044 "Couldn't find a suitable address when adding ourself as a "
3045 "trusted directory server.");
3046 return;
3048 } else {
3049 if (tor_lookup_hostname(address, &a)) {
3050 log_warn(LD_CONFIG,
3051 "Unable to lookup address for directory server at '%s'",
3052 address);
3053 return;
3055 hostname = tor_strdup(address);
3056 a = ntohl(a);
3059 ent = tor_malloc_zero(sizeof(trusted_dir_server_t));
3060 ent->nickname = nickname ? tor_strdup(nickname) : NULL;
3061 ent->address = hostname;
3062 ent->addr = a;
3063 ent->dir_port = dir_port;
3064 ent->or_port = or_port;
3065 ent->is_running = 1;
3066 ent->is_v1_authority = is_v1_authority;
3067 ent->is_v2_authority = is_v2_authority;
3068 ent->is_hidserv_authority = is_hidserv_authority;
3069 memcpy(ent->digest, digest, DIGEST_LEN);
3071 dlen = 64 + strlen(hostname) + (nickname?strlen(nickname):0);
3072 ent->description = tor_malloc(dlen);
3073 if (nickname)
3074 tor_snprintf(ent->description, dlen, "directory server \"%s\" at %s:%d",
3075 nickname, hostname, (int)dir_port);
3076 else
3077 tor_snprintf(ent->description, dlen, "directory server at %s:%d",
3078 hostname, (int)dir_port);
3080 ent->fake_status.status.addr = ent->addr;
3081 memcpy(ent->fake_status.status.identity_digest, digest, DIGEST_LEN);
3082 if (nickname)
3083 strlcpy(ent->fake_status.status.nickname, nickname,
3084 sizeof(ent->fake_status.status.nickname));
3085 else
3086 ent->fake_status.status.nickname[0] = '\0';
3087 ent->fake_status.status.dir_port = ent->dir_port;
3088 ent->fake_status.status.or_port = ent->or_port;
3090 smartlist_add(trusted_dir_servers, ent);
3091 router_dir_info_changed();
3094 /** Free storage held in <b>ds</b> */
3095 static void
3096 trusted_dir_server_free(trusted_dir_server_t *ds)
3098 tor_free(ds->nickname);
3099 tor_free(ds->description);
3100 tor_free(ds->address);
3101 tor_free(ds);
3104 /** Remove all members from the list of trusted dir servers. */
3105 void
3106 clear_trusted_dir_servers(void)
3108 if (trusted_dir_servers) {
3109 SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, ent,
3110 trusted_dir_server_free(ent));
3111 smartlist_clear(trusted_dir_servers);
3112 } else {
3113 trusted_dir_servers = smartlist_create();
3115 router_dir_info_changed();
3118 /** Return 1 if any trusted dir server supports v1 directories,
3119 * else return 0. */
3121 any_trusted_dir_is_v1_authority(void)
3123 if (trusted_dir_servers)
3124 SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, ent,
3125 if (ent->is_v1_authority) return 1);
3126 return 0;
3129 /** Return the network status with a given identity digest. */
3130 networkstatus_t *
3131 networkstatus_get_by_digest(const char *digest)
3133 SMARTLIST_FOREACH(networkstatus_list, networkstatus_t *, ns,
3135 if (!memcmp(ns->identity_digest, digest, DIGEST_LEN))
3136 return ns;
3138 return NULL;
3141 /** We believe networkstatuses more recent than this when they tell us that
3142 * our server is broken, invalid, obsolete, etc. */
3143 #define SELF_OPINION_INTERVAL (90*60)
3145 /** Result of checking whether a version is recommended. */
3146 typedef struct combined_version_status_t {
3147 /** How many networkstatuses claim to know about versions? */
3148 int n_versioning;
3149 /** What do the majority of networkstatuses believe about this version? */
3150 version_status_t consensus;
3151 /** How many networkstatuses constitute the majority? */
3152 int n_concurring;
3153 } combined_version_status_t;
3155 /** Return a string naming the versions of Tor recommended by
3156 * more than half the versioning networkstatuses. */
3157 static char *
3158 compute_recommended_versions(time_t now, int client,
3159 const char *my_version,
3160 combined_version_status_t *status_out)
3162 int n_seen;
3163 char *current;
3164 smartlist_t *combined, *recommended;
3165 int n_versioning, n_recommending;
3166 char *result;
3167 /** holds the compromise status taken among all non-recommending
3168 * authorities */
3169 version_status_t consensus = VS_RECOMMENDED;
3170 (void) now; /* right now, we consider *all* statuses, regardless of age. */
3172 tor_assert(my_version);
3173 tor_assert(status_out);
3175 memset(status_out, 0, sizeof(combined_version_status_t));
3177 if (!networkstatus_list)
3178 return tor_strdup("<none>");
3180 combined = smartlist_create();
3181 n_versioning = n_recommending = 0;
3182 SMARTLIST_FOREACH(networkstatus_list, networkstatus_t *, ns,
3184 const char *vers;
3185 smartlist_t *versions;
3186 version_status_t status;
3187 if (! ns->recommends_versions)
3188 continue;
3189 n_versioning++;
3190 vers = client ? ns->client_versions : ns->server_versions;
3191 if (!vers)
3192 continue;
3193 versions = smartlist_create();
3194 smartlist_split_string(versions, vers, ",",
3195 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
3196 sort_version_list(versions, 1);
3197 smartlist_add_all(combined, versions);
3198 smartlist_free(versions);
3200 /* now, check _our_ version */
3201 status = tor_version_is_obsolete(my_version, vers);
3202 if (status == VS_RECOMMENDED)
3203 n_recommending++;
3204 consensus = version_status_join(status, consensus);
3207 sort_version_list(combined, 0);
3209 current = NULL;
3210 n_seen = 0;
3211 recommended = smartlist_create();
3212 SMARTLIST_FOREACH(combined, char *, cp,
3214 if (current && !strcmp(cp, current)) {
3215 ++n_seen;
3216 } else {
3217 if (n_seen > n_versioning/2 && current)
3218 smartlist_add(recommended, current);
3219 n_seen = 0;
3220 current = cp;
3223 if (n_seen > n_versioning/2 && current)
3224 smartlist_add(recommended, current);
3226 result = smartlist_join_strings(recommended, ", ", 0, NULL);
3228 SMARTLIST_FOREACH(combined, char *, cp, tor_free(cp));
3229 smartlist_free(combined);
3230 smartlist_free(recommended);
3232 status_out->n_versioning = n_versioning;
3233 if (n_recommending > n_versioning/2) {
3234 status_out->consensus = VS_RECOMMENDED;
3235 status_out->n_concurring = n_recommending;
3236 } else {
3237 status_out->consensus = consensus;
3238 status_out->n_concurring = n_versioning - n_recommending;
3241 return result;
3244 /** How many times do we have to fail at getting a networkstatus we can't find
3245 * before we're willing to believe it's okay to set up router statuses? */
3246 #define N_NS_ATTEMPTS_TO_SET_ROUTERS 4
3247 /** How many times do we have to fail at getting a networkstatus we can't find
3248 * before we're willing to believe it's okay to check our version? */
3249 #define N_NS_ATTEMPTS_TO_CHECK_VERSION 4
3251 /** If the network-status list has changed since the last time we called this
3252 * function, update the status of every routerinfo from the network-status
3253 * list.
3255 void
3256 routers_update_all_from_networkstatus(void)
3258 routerinfo_t *me;
3259 time_t now;
3260 if (!routerlist || !networkstatus_list ||
3261 (!networkstatus_list_has_changed && !routerstatus_list_has_changed))
3262 return;
3264 router_dir_info_changed();
3266 now = time(NULL);
3267 if (networkstatus_list_has_changed)
3268 routerstatus_list_update_from_networkstatus(now);
3270 routers_update_status_from_networkstatus(routerlist->routers, 0);
3272 me = router_get_my_routerinfo();
3273 if (me && !have_warned_about_invalid_status &&
3274 have_tried_downloading_all_statuses(N_NS_ATTEMPTS_TO_SET_ROUTERS)) {
3275 int n_recent = 0, n_listing = 0, n_valid = 0, n_named = 0, n_naming = 0;
3276 routerstatus_t *rs;
3277 SMARTLIST_FOREACH(networkstatus_list, networkstatus_t *, ns,
3279 if (ns->received_on + SELF_OPINION_INTERVAL < now)
3280 continue;
3281 ++n_recent;
3282 if (ns->binds_names)
3283 ++n_naming;
3284 if (!(rs = networkstatus_find_entry(ns, me->cache_info.identity_digest)))
3285 continue;
3286 ++n_listing;
3287 if (rs->is_valid)
3288 ++n_valid;
3289 if (rs->is_named)
3290 ++n_named;
3293 if (n_listing) {
3294 if (n_valid <= n_listing/2) {
3295 log_info(LD_GENERAL,
3296 "%d/%d recent statements from directory authorities list us "
3297 "as unapproved. Are you misconfigured?",
3298 n_listing-n_valid, n_listing);
3299 have_warned_about_invalid_status = 1;
3300 } else if (n_naming && !n_named) {
3301 log_info(LD_GENERAL, "0/%d name-binding directory authorities "
3302 "recognize your nickname. Please consider sending your "
3303 "nickname and identity fingerprint to the tor-ops.",
3304 n_naming);
3305 have_warned_about_invalid_status = 1;
3310 entry_guards_compute_status();
3312 if (!have_warned_about_old_version &&
3313 have_tried_downloading_all_statuses(N_NS_ATTEMPTS_TO_CHECK_VERSION)) {
3314 combined_version_status_t st;
3315 int is_server = server_mode(get_options());
3316 char *recommended;
3318 recommended = compute_recommended_versions(now, !is_server, VERSION, &st);
3320 if (st.n_versioning) {
3321 if (st.consensus == VS_RECOMMENDED) {
3322 log_info(LD_GENERAL, "%d/%d statements from version-listing "
3323 "directory authorities say my version is ok.",
3324 st.n_concurring, st.n_versioning);
3325 } else if (st.consensus == VS_NEW || st.consensus == VS_NEW_IN_SERIES) {
3326 if (!have_warned_about_new_version) {
3327 log_notice(LD_GENERAL, "This version of Tor (%s) is newer than any "
3328 "recommended version%s, according to %d/%d version-listing "
3329 "network statuses. Versions recommended by more than %d "
3330 "authorit%s are: %s",
3331 VERSION,
3332 st.consensus == VS_NEW_IN_SERIES ? " in its series" : "",
3333 st.n_concurring, st.n_versioning, st.n_versioning/2,
3334 st.n_versioning/2 > 1 ? "ies" : "y", recommended);
3335 have_warned_about_new_version = 1;
3336 control_event_general_status(LOG_WARN, "DANGEROUS_VERSION "
3337 "CURRENT=%s REASON=%s RECOMMENDED=\"%s\"",
3338 VERSION, "NEW", recommended);
3340 } else {
3341 log_warn(LD_GENERAL, "Please upgrade! "
3342 "This version of Tor (%s) is %s, according to %d/%d version-"
3343 "listing network statuses. Versions recommended by "
3344 "at least %d authorit%s are: %s",
3345 VERSION,
3346 st.consensus == VS_OLD ? "obsolete" : "not recommended",
3347 st.n_concurring, st.n_versioning, st.n_versioning/2,
3348 st.n_versioning/2 > 1 ? "ies" : "y", recommended);
3349 have_warned_about_old_version = 1;
3350 control_event_general_status(LOG_WARN, "DANGEROUS_VERSION "
3351 "CURRENT=%s REASON=%s RECOMMENDED=\"%s\"",
3352 VERSION, st.consensus == VS_OLD ? "OLD" : "UNRECOMMENDED",
3353 recommended);
3356 tor_free(recommended);
3359 routerstatus_list_has_changed = 0;
3362 /** Allow any network-status newer than this to influence our view of who's
3363 * running. */
3364 #define DEFAULT_RUNNING_INTERVAL (60*60)
3365 /** If possible, always allow at least this many network-statuses to influence
3366 * our view of who's running. */
3367 #define MIN_TO_INFLUENCE_RUNNING 3
3369 /** Change the is_recent field of each member of networkstatus_list so that
3370 * all members more recent than DEFAULT_RUNNING_INTERVAL are recent, and
3371 * at least the MIN_TO_INFLUENCE_RUNNING most recent members are recent, and no
3372 * others are recent. Set networkstatus_list_has_changed if anything happened.
3374 void
3375 networkstatus_list_update_recent(time_t now)
3377 int n_statuses, n_recent, changed, i;
3378 char published[ISO_TIME_LEN+1];
3380 if (!networkstatus_list)
3381 return;
3383 n_statuses = smartlist_len(networkstatus_list);
3384 n_recent = 0;
3385 changed = 0;
3386 for (i=n_statuses-1; i >= 0; --i) {
3387 networkstatus_t *ns = smartlist_get(networkstatus_list, i);
3388 trusted_dir_server_t *ds =
3389 router_get_trusteddirserver_by_digest(ns->identity_digest);
3390 const char *src = ds?ds->description:ns->source_address;
3391 if (n_recent < MIN_TO_INFLUENCE_RUNNING ||
3392 ns->published_on + DEFAULT_RUNNING_INTERVAL > now) {
3393 if (!ns->is_recent) {
3394 format_iso_time(published, ns->published_on);
3395 log_info(LD_DIR,
3396 "Networkstatus from %s (published %s) is now \"recent\"",
3397 src, published);
3398 changed = 1;
3400 ns->is_recent = 1;
3401 ++n_recent;
3402 } else {
3403 if (ns->is_recent) {
3404 format_iso_time(published, ns->published_on);
3405 log_info(LD_DIR,
3406 "Networkstatus from %s (published %s) is "
3407 "no longer \"recent\"",
3408 src, published);
3409 changed = 1;
3410 ns->is_recent = 0;
3414 if (changed) {
3415 networkstatus_list_has_changed = 1;
3416 router_dir_info_changed();
3420 /** Helper for routerstatus_list_update_from_networkstatus: remember how many
3421 * authorities recommend a given descriptor digest. */
3422 typedef struct {
3423 routerstatus_t *rs;
3424 int count;
3425 } desc_digest_count_t;
3427 /** Update our view of router status (as stored in routerstatus_list) from the
3428 * current set of network status documents (as stored in networkstatus_list).
3429 * Do nothing unless the network status list has changed since the last time
3430 * this function was called.
3432 static void
3433 routerstatus_list_update_from_networkstatus(time_t now)
3435 or_options_t *options = get_options();
3436 int n_trusted, n_statuses, n_recent = 0, n_naming = 0;
3437 int n_listing_bad_exits = 0, n_listing_bad_directories = 0;
3438 int i, j, warned;
3439 int *index, *size;
3440 networkstatus_t **networkstatus;
3441 smartlist_t *result, *changed_list;
3442 strmap_t *name_map;
3443 char conflict[DIGEST_LEN]; /* Sentinel value */
3444 desc_digest_count_t *digest_counts = NULL;
3446 /* compute which network statuses will have a vote now */
3447 networkstatus_list_update_recent(now);
3448 router_dir_info_changed();
3450 if (!networkstatus_list_has_changed)
3451 return;
3452 if (!networkstatus_list)
3453 networkstatus_list = smartlist_create();
3454 if (!routerstatus_list)
3455 routerstatus_list = smartlist_create();
3456 if (!trusted_dir_servers)
3457 trusted_dir_servers = smartlist_create();
3458 if (!warned_conflicts)
3459 warned_conflicts = smartlist_create();
3461 n_statuses = smartlist_len(networkstatus_list);
3462 n_trusted = get_n_v2_authorities();
3464 if (n_statuses <= n_trusted/2) {
3465 /* Not enough statuses to adjust status. */
3466 log_info(LD_DIR,
3467 "Not enough statuses to update router status list. (%d/%d)",
3468 n_statuses, n_trusted);
3469 return;
3472 log_info(LD_DIR, "Rebuilding router status list.");
3474 index = tor_malloc(sizeof(int)*n_statuses);
3475 size = tor_malloc(sizeof(int)*n_statuses);
3476 networkstatus = tor_malloc(sizeof(networkstatus_t *)*n_statuses);
3477 for (i = 0; i < n_statuses; ++i) {
3478 index[i] = 0;
3479 networkstatus[i] = smartlist_get(networkstatus_list, i);
3480 size[i] = smartlist_len(networkstatus[i]->entries);
3481 if (networkstatus[i]->binds_names)
3482 ++n_naming;
3483 if (networkstatus[i]->is_recent)
3484 ++n_recent;
3485 if (networkstatus[i]->lists_bad_exits)
3486 ++n_listing_bad_exits;
3487 if (networkstatus[i]->lists_bad_directories)
3488 ++n_listing_bad_directories;
3491 /** Iterate over all entries in all networkstatuses, and build
3492 * name_map as a map from lc nickname to identity digest. If there
3493 * is a conflict on that nickname, map the lc nickname to conflict.
3495 name_map = strmap_new();
3496 /* Clear the global map... */
3497 if (named_server_map)
3498 strmap_free(named_server_map, _tor_free);
3499 named_server_map = strmap_new();
3500 memset(conflict, 0xff, sizeof(conflict));
3501 for (i = 0; i < n_statuses; ++i) {
3502 if (!networkstatus[i]->binds_names)
3503 continue;
3504 SMARTLIST_FOREACH(networkstatus[i]->entries, routerstatus_t *, rs,
3506 const char *other_digest;
3507 if (!rs->is_named)
3508 continue;
3509 other_digest = strmap_get_lc(name_map, rs->nickname);
3510 warned = smartlist_string_isin(warned_conflicts, rs->nickname);
3511 if (!other_digest) {
3512 strmap_set_lc(name_map, rs->nickname, rs->identity_digest);
3513 strmap_set_lc(named_server_map, rs->nickname,
3514 tor_memdup(rs->identity_digest, DIGEST_LEN));
3515 if (warned)
3516 smartlist_string_remove(warned_conflicts, rs->nickname);
3517 } else if (memcmp(other_digest, rs->identity_digest, DIGEST_LEN) &&
3518 other_digest != conflict) {
3519 if (!warned) {
3520 char *d;
3521 int should_warn = options->DirPort && options->AuthoritativeDir;
3522 char fp1[HEX_DIGEST_LEN+1];
3523 char fp2[HEX_DIGEST_LEN+1];
3524 base16_encode(fp1, sizeof(fp1), other_digest, DIGEST_LEN);
3525 base16_encode(fp2, sizeof(fp2), rs->identity_digest, DIGEST_LEN);
3526 log_fn(should_warn ? LOG_WARN : LOG_INFO, LD_DIR,
3527 "Naming authorities disagree about which key goes with %s. "
3528 "($%s vs $%s)",
3529 rs->nickname, fp1, fp2);
3530 strmap_set_lc(name_map, rs->nickname, conflict);
3531 d = strmap_remove_lc(named_server_map, rs->nickname);
3532 tor_free(d);
3533 smartlist_add(warned_conflicts, tor_strdup(rs->nickname));
3535 } else {
3536 if (warned)
3537 smartlist_string_remove(warned_conflicts, rs->nickname);
3542 result = smartlist_create();
3543 changed_list = smartlist_create();
3544 digest_counts = tor_malloc_zero(sizeof(desc_digest_count_t)*n_statuses);
3546 /* Iterate through all of the sorted routerstatus lists in lockstep.
3547 * Invariants:
3548 * - For 0 <= i < n_statuses: index[i] is an index into
3549 * networkstatus[i]->entries, which has size[i] elements.
3550 * - For i1, i2, j such that 0 <= i1 < n_statuses, 0 <= i2 < n_statues, 0 <=
3551 * j < index[i1]: networkstatus[i1]->entries[j]->identity_digest <
3552 * networkstatus[i2]->entries[index[i2]]->identity_digest.
3554 * (That is, the indices are always advanced past lower digest before
3555 * higher.)
3557 while (1) {
3558 int n_running=0, n_named=0, n_valid=0, n_listing=0;
3559 int n_v2_dir=0, n_fast=0, n_stable=0, n_exit=0, n_guard=0, n_bad_exit=0;
3560 int n_bad_directory=0;
3561 int n_version_known=0, n_supports_begindir=0;
3562 int n_desc_digests=0, highest_count=0;
3563 const char *the_name = NULL;
3564 local_routerstatus_t *rs_out, *rs_old;
3565 routerstatus_t *rs, *most_recent;
3566 networkstatus_t *ns;
3567 const char *lowest = NULL;
3569 /* Find out which of the digests appears first. */
3570 for (i = 0; i < n_statuses; ++i) {
3571 if (index[i] < size[i]) {
3572 rs = smartlist_get(networkstatus[i]->entries, index[i]);
3573 if (!lowest || memcmp(rs->identity_digest, lowest, DIGEST_LEN)<0)
3574 lowest = rs->identity_digest;
3577 if (!lowest) {
3578 /* We're out of routers. Great! */
3579 break;
3581 /* Okay. The routers at networkstatus[i]->entries[index[i]] whose digests
3582 * match "lowest" are next in order. Iterate over them, incrementing those
3583 * index[i] as we go. */
3584 for (i = 0; i < n_statuses; ++i) {
3585 if (index[i] >= size[i])
3586 continue;
3587 ns = networkstatus[i];
3588 rs = smartlist_get(ns->entries, index[i]);
3589 if (memcmp(rs->identity_digest, lowest, DIGEST_LEN))
3590 continue;
3591 /* At this point, we know that we're looking at a routersatus with
3592 * identity "lowest".
3594 ++index[i];
3595 ++n_listing;
3596 /* Should we name this router? Only if all the names from naming
3597 * authorities match. */
3598 if (rs->is_named && ns->binds_names) {
3599 if (!the_name)
3600 the_name = rs->nickname;
3601 if (!strcasecmp(rs->nickname, the_name)) {
3602 ++n_named;
3603 } else if (strcmp(the_name,"**mismatch**")) {
3604 char hd[HEX_DIGEST_LEN+1];
3605 base16_encode(hd, HEX_DIGEST_LEN+1, rs->identity_digest, DIGEST_LEN);
3606 if (! smartlist_string_isin(warned_conflicts, hd)) {
3607 log_warn(LD_DIR,
3608 "Naming authorities disagree about nicknames for $%s "
3609 "(\"%s\" vs \"%s\")",
3610 hd, the_name, rs->nickname);
3611 smartlist_add(warned_conflicts, tor_strdup(hd));
3613 the_name = "**mismatch**";
3616 /* Keep a running count of how often which descriptor digests
3617 * appear. */
3618 for (j = 0; j < n_desc_digests; ++j) {
3619 if (!memcmp(rs->descriptor_digest,
3620 digest_counts[j].rs->descriptor_digest, DIGEST_LEN)) {
3621 if (++digest_counts[j].count > highest_count)
3622 highest_count = digest_counts[j].count;
3623 goto found;
3626 digest_counts[n_desc_digests].rs = rs;
3627 digest_counts[n_desc_digests].count = 1;
3628 if (!highest_count)
3629 highest_count = 1;
3630 ++n_desc_digests;
3631 found:
3632 /* Now tally up the easily-tallied flags. */
3633 if (rs->is_valid)
3634 ++n_valid;
3635 if (rs->is_running && ns->is_recent)
3636 ++n_running;
3637 if (rs->is_exit)
3638 ++n_exit;
3639 if (rs->is_fast)
3640 ++n_fast;
3641 if (rs->is_possible_guard)
3642 ++n_guard;
3643 if (rs->is_stable)
3644 ++n_stable;
3645 if (rs->is_v2_dir)
3646 ++n_v2_dir;
3647 if (rs->is_bad_exit)
3648 ++n_bad_exit;
3649 if (rs->is_bad_directory)
3650 ++n_bad_directory;
3651 if (rs->version_known)
3652 ++n_version_known;
3653 if (rs->version_supports_begindir)
3654 ++n_supports_begindir;
3656 /* Go over the descriptor digests and figure out which descriptor we
3657 * want. */
3658 most_recent = NULL;
3659 for (i = 0; i < n_desc_digests; ++i) {
3660 /* If any digest appears twice or more, ignore those that don't.*/
3661 if (highest_count >= 2 && digest_counts[i].count < 2)
3662 continue;
3663 if (!most_recent ||
3664 digest_counts[i].rs->published_on > most_recent->published_on)
3665 most_recent = digest_counts[i].rs;
3667 rs_out = tor_malloc_zero(sizeof(local_routerstatus_t));
3668 memcpy(&rs_out->status, most_recent, sizeof(routerstatus_t));
3669 /* Copy status info about this router, if we had any before. */
3670 if ((rs_old = router_get_combined_status_by_digest(lowest))) {
3671 if (!memcmp(rs_out->status.descriptor_digest,
3672 most_recent->descriptor_digest, DIGEST_LEN)) {
3673 rs_out->n_download_failures = rs_old->n_download_failures;
3674 rs_out->next_attempt_at = rs_old->next_attempt_at;
3676 rs_out->name_lookup_warned = rs_old->name_lookup_warned;
3677 rs_out->last_dir_503_at = rs_old->last_dir_503_at;
3679 smartlist_add(result, rs_out);
3680 log_debug(LD_DIR, "Router '%s' is listed by %d/%d directories, "
3681 "named by %d/%d, validated by %d/%d, and %d/%d recent "
3682 "directories think it's running.",
3683 rs_out->status.nickname,
3684 n_listing, n_statuses, n_named, n_naming, n_valid, n_statuses,
3685 n_running, n_recent);
3686 rs_out->status.is_named = 0;
3687 if (the_name && strcmp(the_name, "**mismatch**") && n_named > 0) {
3688 const char *d = strmap_get_lc(name_map, the_name);
3689 if (d && d != conflict)
3690 rs_out->status.is_named = 1;
3691 if (smartlist_string_isin(warned_conflicts, rs_out->status.nickname))
3692 smartlist_string_remove(warned_conflicts, rs_out->status.nickname);
3694 if (rs_out->status.is_named)
3695 strlcpy(rs_out->status.nickname, the_name,
3696 sizeof(rs_out->status.nickname));
3697 rs_out->status.is_valid = n_valid > n_statuses/2;
3698 rs_out->status.is_running = n_running > n_recent/2;
3699 rs_out->status.is_exit = n_exit > n_statuses/2;
3700 rs_out->status.is_fast = n_fast > n_statuses/2;
3701 rs_out->status.is_possible_guard = n_guard > n_statuses/2;
3702 rs_out->status.is_stable = n_stable > n_statuses/2;
3703 rs_out->status.is_v2_dir = n_v2_dir > n_statuses/2;
3704 rs_out->status.is_bad_exit = n_bad_exit > n_listing_bad_exits/2;
3705 rs_out->status.is_bad_directory =
3706 n_bad_directory > n_listing_bad_directories/2;
3707 rs_out->status.version_known = n_version_known > 0;
3708 rs_out->status.version_supports_begindir =
3709 n_supports_begindir > n_version_known/2;
3710 if (!rs_old || memcmp(rs_old, rs_out, sizeof(local_routerstatus_t)))
3711 smartlist_add(changed_list, rs_out);
3713 SMARTLIST_FOREACH(routerstatus_list, local_routerstatus_t *, rs,
3714 local_routerstatus_free(rs));
3716 smartlist_free(routerstatus_list);
3717 routerstatus_list = result;
3719 tor_free(networkstatus);
3720 tor_free(index);
3721 tor_free(size);
3722 tor_free(digest_counts);
3723 strmap_free(name_map, NULL);
3725 networkstatus_list_has_changed = 0;
3726 routerstatus_list_has_changed = 1;
3728 control_event_networkstatus_changed(changed_list);
3729 smartlist_free(changed_list);
3732 /** Given a list <b>routers</b> of routerinfo_t *, update each routers's
3733 * is_named, is_valid, and is_running fields according to our current
3734 * networkstatus_t documents. */
3735 void
3736 routers_update_status_from_networkstatus(smartlist_t *routers,
3737 int reset_failures)
3739 trusted_dir_server_t *ds;
3740 local_routerstatus_t *rs;
3741 or_options_t *options = get_options();
3742 int authdir = options->AuthoritativeDir;
3743 int namingdir = options->AuthoritativeDir &&
3744 options->NamingAuthoritativeDir;
3746 if (!routerstatus_list)
3747 return;
3749 SMARTLIST_FOREACH(routers, routerinfo_t *, router,
3751 const char *digest = router->cache_info.identity_digest;
3752 rs = router_get_combined_status_by_digest(digest);
3753 ds = router_get_trusteddirserver_by_digest(digest);
3755 if (!rs)
3756 continue;
3758 if (!namingdir)
3759 router->is_named = rs->status.is_named;
3761 if (!authdir) {
3762 /* If we're not an authdir, believe others. */
3763 router->is_valid = rs->status.is_valid;
3764 router->is_running = rs->status.is_running;
3765 router->is_fast = rs->status.is_fast;
3766 router->is_stable = rs->status.is_stable;
3767 router->is_possible_guard = rs->status.is_possible_guard;
3768 router->is_exit = rs->status.is_exit;
3769 router->is_bad_exit = rs->status.is_bad_exit;
3771 if (router->is_running && ds) {
3772 ds->n_networkstatus_failures = 0;
3774 if (reset_failures) {
3775 rs->n_download_failures = 0;
3776 rs->next_attempt_at = 0;
3779 router_dir_info_changed();
3782 /** For every router descriptor we are currently downloading by descriptor
3783 * digest, set result[d] to 1. */
3784 static void
3785 list_pending_descriptor_downloads(digestmap_t *result)
3787 const char *prefix = "d/";
3788 size_t p_len = strlen(prefix);
3789 int i, n_conns;
3790 connection_t **carray;
3791 smartlist_t *tmp = smartlist_create();
3793 tor_assert(result);
3794 get_connection_array(&carray, &n_conns);
3796 for (i = 0; i < n_conns; ++i) {
3797 connection_t *conn = carray[i];
3798 if (conn->type == CONN_TYPE_DIR &&
3799 conn->purpose == DIR_PURPOSE_FETCH_SERVERDESC &&
3800 !conn->marked_for_close) {
3801 const char *resource = TO_DIR_CONN(conn)->requested_resource;
3802 if (!strcmpstart(resource, prefix))
3803 dir_split_resource_into_fingerprints(resource + p_len,
3804 tmp, NULL, 1, 0);
3807 SMARTLIST_FOREACH(tmp, char *, d,
3809 digestmap_set(result, d, (void*)1);
3810 tor_free(d);
3812 smartlist_free(tmp);
3815 /** Launch downloads for all the descriptors whose digests are listed
3816 * as digests[i] for lo <= i < hi. (Lo and hi may be out of range.)
3817 * If <b>source</b> is given, download from <b>source</b>; otherwise,
3818 * download from an appropriate random directory server.
3820 static void
3821 initiate_descriptor_downloads(routerstatus_t *source,
3822 smartlist_t *digests,
3823 int lo, int hi)
3825 int i, n = hi-lo;
3826 char *resource, *cp;
3827 size_t r_len;
3828 if (n <= 0)
3829 return;
3830 if (lo < 0)
3831 lo = 0;
3832 if (hi > smartlist_len(digests))
3833 hi = smartlist_len(digests);
3835 r_len = 8 + (HEX_DIGEST_LEN+1)*n;
3836 cp = resource = tor_malloc(r_len);
3837 memcpy(cp, "d/", 2);
3838 cp += 2;
3839 for (i = lo; i < hi; ++i) {
3840 base16_encode(cp, r_len-(cp-resource),
3841 smartlist_get(digests,i), DIGEST_LEN);
3842 cp += HEX_DIGEST_LEN;
3843 *cp++ = '+';
3845 memcpy(cp-1, ".z", 3);
3847 if (source) {
3848 /* We know which authority we want. */
3849 directory_initiate_command_routerstatus(source,
3850 DIR_PURPOSE_FETCH_SERVERDESC,
3851 0, /* not private */
3852 resource, NULL, 0);
3853 } else {
3854 directory_get_from_dirserver(DIR_PURPOSE_FETCH_SERVERDESC,
3855 resource,
3858 tor_free(resource);
3861 /** Clients don't download any descriptor this recent, since it will probably
3862 * not have propageted to enough caches. */
3863 #define ESTIMATED_PROPAGATION_TIME (10*60)
3865 /** Return 0 if this routerstatus is obsolete, too new, isn't
3866 * running, or otherwise not a descriptor that we would make any
3867 * use of even if we had it. Else return 1. */
3868 static INLINE int
3869 client_would_use_router(routerstatus_t *rs, time_t now, or_options_t *options)
3871 if (!rs->is_running && !options->FetchUselessDescriptors) {
3872 /* If we had this router descriptor, we wouldn't even bother using it.
3873 * But, if we want to have a complete list, fetch it anyway. */
3874 return 0;
3876 if (rs->published_on + ESTIMATED_PROPAGATION_TIME > now) {
3877 /* Most caches probably don't have this descriptor yet. */
3878 return 0;
3880 return 1;
3883 /** Return new list of ID fingerprints for routers that we (as a client) would
3884 * like to download.
3886 static smartlist_t *
3887 router_list_client_downloadable(void)
3889 int n_downloadable = 0;
3890 smartlist_t *downloadable = smartlist_create();
3891 digestmap_t *downloading;
3892 time_t now = time(NULL);
3893 /* these are just used for logging */
3894 int n_not_ready = 0, n_in_progress = 0, n_uptodate = 0, n_wouldnt_use = 0;
3895 or_options_t *options = get_options();
3897 if (!routerstatus_list)
3898 return downloadable;
3900 downloading = digestmap_new();
3901 list_pending_descriptor_downloads(downloading);
3903 routerstatus_list_update_from_networkstatus(now);
3904 SMARTLIST_FOREACH(routerstatus_list, local_routerstatus_t *, rs,
3906 routerinfo_t *ri;
3907 if (router_get_by_descriptor_digest(rs->status.descriptor_digest)) {
3908 /* We have the 'best' descriptor for this router. */
3909 ++n_uptodate;
3910 } else if (!client_would_use_router(&rs->status, now, options)) {
3911 /* We wouldn't want this descriptor even if we got it. */
3912 ++n_wouldnt_use;
3913 } else if (digestmap_get(downloading, rs->status.descriptor_digest)) {
3914 /* We're downloading this one now. */
3915 ++n_in_progress;
3916 } else if ((ri = router_get_by_digest(rs->status.identity_digest)) &&
3917 ri->cache_info.published_on > rs->status.published_on) {
3918 /* Oddly, we have a descriptor more recent than the 'best' one, but it
3919 was once best. So that's okay. */
3920 ++n_uptodate;
3921 } else if (rs->next_attempt_at > now) {
3922 /* We failed too recently to try again. */
3923 ++n_not_ready;
3924 } else {
3925 /* Okay, time to try it. */
3926 smartlist_add(downloadable, rs->status.descriptor_digest);
3927 ++n_downloadable;
3931 #if 0
3932 log_info(LD_DIR,
3933 "%d router descriptors are downloadable. "
3934 "%d are in progress. %d are up-to-date. "
3935 "%d are non-useful. %d failed too recently to retry.",
3936 n_downloadable, n_in_progress, n_uptodate,
3937 n_wouldnt_use, n_not_ready);
3938 #endif
3940 digestmap_free(downloading, NULL);
3941 return downloadable;
3944 /** Initiate new router downloads as needed, using the strategy for
3945 * non-directory-servers.
3947 * We don't launch any downloads if there are fewer than MAX_DL_TO_DELAY
3948 * descriptors to get and less than MAX_CLIENT_INTERVAL_WITHOUT_REQUEST
3949 * seconds have passed.
3951 * Otherwise, we ask for all descriptors that we think are different from what
3952 * we have, and that we don't currently have an in-progress download attempt
3953 * for. */
3954 static void
3955 update_router_descriptor_client_downloads(time_t now)
3957 /** Max amount of hashes to download per request.
3958 * Since squid does not like URLs >= 4096 bytes we limit it to 96.
3959 * 4096 - strlen(http://255.255.255.255/tor/server/d/.z) == 4058
3960 * 4058/41 (40 for the hash and 1 for the + that separates them) => 98
3961 * So use 96 because it's a nice number.
3963 #define MAX_DL_PER_REQUEST 96
3964 /** Don't split our requests so finely that we are requesting fewer than
3965 * this number per server. */
3966 #define MIN_DL_PER_REQUEST 4
3967 /** To prevent a single screwy cache from confusing us by selective reply,
3968 * try to split our requests into at least this this many requests. */
3969 #define MIN_REQUESTS 3
3970 /** If we want fewer than this many descriptors, wait until we
3971 * want more, or until MAX_CLIENT_INTERVAL_WITHOUT_REQUEST has
3972 * passed. */
3973 #define MAX_DL_TO_DELAY 16
3974 /** When directory clients have only a few servers to request, they batch
3975 * them until they have more, or until this amount of time has passed. */
3976 #define MAX_CLIENT_INTERVAL_WITHOUT_REQUEST (10*60)
3977 smartlist_t *downloadable = NULL;
3978 int should_delay, n_downloadable;
3979 or_options_t *options = get_options();
3981 if (options->DirPort) {
3982 log_warn(LD_BUG,
3983 "Called router_descriptor_client_downloads() on a dir mirror?");
3986 if (rep_hist_circbuilding_dormant(now)) {
3987 log_info(LD_CIRC, "Skipping descriptor downloads: we haven't needed "
3988 "any circuits lately.");
3989 return;
3992 if (networkstatus_list &&
3993 smartlist_len(networkstatus_list) <= get_n_v2_authorities()/2) {
3994 log_info(LD_DIR,
3995 "Not enough networkstatus documents to launch requests.");
3996 return;
3999 downloadable = router_list_client_downloadable();
4000 n_downloadable = smartlist_len(downloadable);
4001 if (n_downloadable >= MAX_DL_TO_DELAY) {
4002 log_debug(LD_DIR,
4003 "There are enough downloadable routerdescs to launch requests.");
4004 should_delay = 0;
4005 } else if (n_downloadable == 0) {
4006 // log_debug(LD_DIR, "No routerdescs need to be downloaded.");
4007 should_delay = 1;
4008 } else {
4009 should_delay = (last_routerdesc_download_attempted +
4010 MAX_CLIENT_INTERVAL_WITHOUT_REQUEST) > now;
4011 if (!should_delay) {
4012 if (last_routerdesc_download_attempted) {
4013 log_info(LD_DIR,
4014 "There are not many downloadable routerdescs, but we've "
4015 "been waiting long enough (%d seconds). Downloading.",
4016 (int)(now-last_routerdesc_download_attempted));
4017 } else {
4018 log_info(LD_DIR,
4019 "There are not many downloadable routerdescs, but we haven't "
4020 "tried downloading descriptors recently. Downloading.");
4025 if (! should_delay) {
4026 int i, n_per_request;
4027 n_per_request = (n_downloadable+MIN_REQUESTS-1) / MIN_REQUESTS;
4028 if (n_per_request > MAX_DL_PER_REQUEST)
4029 n_per_request = MAX_DL_PER_REQUEST;
4030 if (n_per_request < MIN_DL_PER_REQUEST)
4031 n_per_request = MIN_DL_PER_REQUEST;
4033 log_info(LD_DIR,
4034 "Launching %d request%s for %d router%s, %d at a time",
4035 (n_downloadable+n_per_request-1)/n_per_request,
4036 n_downloadable>n_per_request?"s":"",
4037 n_downloadable, n_downloadable>1?"s":"", n_per_request);
4038 smartlist_sort_digests(downloadable);
4039 for (i=0; i < n_downloadable; i += n_per_request) {
4040 initiate_descriptor_downloads(NULL, downloadable, i, i+n_per_request);
4042 last_routerdesc_download_attempted = now;
4044 smartlist_free(downloadable);
4047 /** Launch downloads for router status as needed, using the strategy used by
4048 * authorities and caches: download every descriptor we don't have but would
4049 * serve, from a random authority that lists it. */
4050 static void
4051 update_router_descriptor_cache_downloads(time_t now)
4053 smartlist_t **downloadable; /* For each authority, what can we dl from it? */
4054 smartlist_t **download_from; /* ... and, what will we dl from it? */
4055 digestmap_t *map; /* Which descs are in progress, or assigned? */
4056 int i, j, n;
4057 int n_download;
4058 or_options_t *options = get_options();
4059 (void) now;
4061 if (!options->DirPort) {
4062 log_warn(LD_BUG, "Called update_router_descriptor_cache_downloads() "
4063 "on a non-dir-mirror?");
4066 if (!networkstatus_list || !smartlist_len(networkstatus_list))
4067 return;
4069 map = digestmap_new();
4070 n = smartlist_len(networkstatus_list);
4072 downloadable = tor_malloc_zero(sizeof(smartlist_t*) * n);
4073 download_from = tor_malloc_zero(sizeof(smartlist_t*) * n);
4075 /* Set map[d]=1 for the digest of every descriptor that we are currently
4076 * downloading. */
4077 list_pending_descriptor_downloads(map);
4079 /* For the digest of every descriptor that we don't have, and that we aren't
4080 * downloading, add d to downloadable[i] if the i'th networkstatus knows
4081 * about that descriptor, and we haven't already failed to get that
4082 * descriptor from the corresponding authority.
4084 n_download = 0;
4085 SMARTLIST_FOREACH(networkstatus_list, networkstatus_t *, ns,
4087 trusted_dir_server_t *ds;
4088 smartlist_t *dl;
4089 dl = downloadable[ns_sl_idx] = smartlist_create();
4090 download_from[ns_sl_idx] = smartlist_create();
4091 if (ns->published_on + MAX_NETWORKSTATUS_AGE+10*60 < now) {
4092 /* Don't download if the networkstatus is almost ancient. */
4093 /* Actually, I suspect what's happening here is that we ask
4094 * for the descriptor when we have a given networkstatus,
4095 * and then we get a newer networkstatus, and then we receive
4096 * the descriptor. Having a networkstatus actually expire is
4097 * probably a rare event, and we'll probably be happiest if
4098 * we take this clause out. -RD */
4099 continue;
4102 /* Don't try dirservers that we think are down -- we might have
4103 * just tried them and just marked them as down. */
4104 ds = router_get_trusteddirserver_by_digest(ns->identity_digest);
4105 if (ds && !ds->is_running)
4106 continue;
4108 SMARTLIST_FOREACH(ns->entries, routerstatus_t * , rs,
4110 if (!rs->need_to_mirror)
4111 continue;
4112 if (router_get_by_descriptor_digest(rs->descriptor_digest)) {
4113 log_warn(LD_BUG,
4114 "Bug: We have a router descriptor, but need_to_mirror=1.");
4115 rs->need_to_mirror = 0;
4116 continue;
4118 if (options->AuthoritativeDir && dirserv_would_reject_router(rs)) {
4119 rs->need_to_mirror = 0;
4120 continue;
4122 if (digestmap_get(map, rs->descriptor_digest)) {
4123 /* We're downloading it already. */
4124 continue;
4125 } else {
4126 /* We could download it from this guy. */
4127 smartlist_add(dl, rs->descriptor_digest);
4128 ++n_download;
4133 /* At random, assign descriptors to authorities such that:
4134 * - if d is a member of some downloadable[x], d is a member of some
4135 * download_from[y]. (Everything we want to download, we try to download
4136 * from somebody.)
4137 * - If d is a member of download_from[y], d is a member of downloadable[y].
4138 * (We only try to download descriptors from authorities who claim to have
4139 * them.)
4140 * - No d is a member of download_from[x] and download_from[y] s.t. x != y.
4141 * (We don't try to download anything from two authorities concurrently.)
4143 while (n_download) {
4144 int which_ns = crypto_rand_int(n);
4145 smartlist_t *dl = downloadable[which_ns];
4146 int idx;
4147 char *d;
4148 if (!smartlist_len(dl))
4149 continue;
4150 idx = crypto_rand_int(smartlist_len(dl));
4151 d = smartlist_get(dl, idx);
4152 if (! digestmap_get(map, d)) {
4153 smartlist_add(download_from[which_ns], d);
4154 digestmap_set(map, d, (void*) 1);
4156 smartlist_del(dl, idx);
4157 --n_download;
4160 /* Now, we can actually launch our requests. */
4161 for (i=0; i<n; ++i) {
4162 networkstatus_t *ns = smartlist_get(networkstatus_list, i);
4163 trusted_dir_server_t *ds =
4164 router_get_trusteddirserver_by_digest(ns->identity_digest);
4165 smartlist_t *dl = download_from[i];
4166 if (!ds) {
4167 log_warn(LD_BUG, "Networkstatus with no corresponding authority!");
4168 continue;
4170 if (! smartlist_len(dl))
4171 continue;
4172 log_info(LD_DIR, "Requesting %d descriptors from authority \"%s\"",
4173 smartlist_len(dl), ds->nickname);
4174 for (j=0; j < smartlist_len(dl); j += MAX_DL_PER_REQUEST) {
4175 initiate_descriptor_downloads(&(ds->fake_status.status), dl, j,
4176 j+MAX_DL_PER_REQUEST);
4180 for (i=0; i<n; ++i) {
4181 smartlist_free(download_from[i]);
4182 smartlist_free(downloadable[i]);
4184 tor_free(download_from);
4185 tor_free(downloadable);
4186 digestmap_free(map,NULL);
4189 /** Launch downloads for router status as needed. */
4190 void
4191 update_router_descriptor_downloads(time_t now)
4193 or_options_t *options = get_options();
4194 if (options->DirPort) {
4195 update_router_descriptor_cache_downloads(now);
4196 } else {
4197 update_router_descriptor_client_downloads(now);
4201 /** Return the number of routerstatus_t in <b>entries</b> that we'd actually
4202 * use. */
4203 static int
4204 routerstatus_count_usable_entries(smartlist_t *entries)
4206 int count = 0;
4207 time_t now = time(NULL);
4208 or_options_t *options = get_options();
4209 SMARTLIST_FOREACH(entries, routerstatus_t *, rs,
4210 if (client_would_use_router(rs, now, options)) count++);
4211 return count;
4214 /** True iff, the last time we checked whether we had enough directory info
4215 * to build circuits, the answer was "yes". */
4216 static int have_min_dir_info = 0;
4217 /** True iff enough has changed since the last time we checked whether we had
4218 * enough directory info to build circuits that our old answer can no longer
4219 * be trusted. */
4220 static int need_to_update_have_min_dir_info = 1;
4222 /** Return true iff we have enough networkstatus and router information to
4223 * start building circuits. Right now, this means "more than half the
4224 * networkstatus documents, and at least 1/4 of expected routers." */
4225 //XXX should consider whether we have enough exiting nodes here.
4227 router_have_minimum_dir_info(void)
4229 if (PREDICT(need_to_update_have_min_dir_info, 0)) {
4230 update_router_have_minimum_dir_info();
4231 need_to_update_have_min_dir_info = 0;
4233 return have_min_dir_info;
4236 /** Called when our internal view of the directory has changed. This can be
4237 * when the authorities change, networkstatuses change, the list of routerdescs
4238 * changes, or number of running routers changes.
4240 static void
4241 router_dir_info_changed(void)
4243 need_to_update_have_min_dir_info = 1;
4246 /** Change the value of have_min_dir_info, setting it true iff we have enough
4247 * network and router information to build circuits. Clear the value of
4248 * need_to_update_have_min_dir_info. */
4249 static void
4250 update_router_have_minimum_dir_info(void)
4252 int tot = 0, num_running = 0;
4253 int n_ns, n_authorities, res, avg;
4254 time_t now = time(NULL);
4255 if (!networkstatus_list || !routerlist) {
4256 res = 0;
4257 goto done;
4259 routerlist_remove_old_routers();
4260 networkstatus_list_clean(now);
4262 n_authorities = get_n_v2_authorities();
4263 n_ns = smartlist_len(networkstatus_list);
4264 if (n_ns<=n_authorities/2) {
4265 log_info(LD_DIR,
4266 "We have %d of %d network statuses, and we want "
4267 "more than %d.", n_ns, n_authorities, n_authorities/2);
4268 res = 0;
4269 goto done;
4271 SMARTLIST_FOREACH(networkstatus_list, networkstatus_t *, ns,
4272 tot += routerstatus_count_usable_entries(ns->entries));
4273 avg = tot / n_ns;
4274 if (!routerstatus_list)
4275 routerstatus_list = smartlist_create();
4276 SMARTLIST_FOREACH(routerstatus_list, local_routerstatus_t *, rs,
4278 if (rs->status.is_running)
4279 num_running++;
4281 res = smartlist_len(routerlist->routers) >= (avg/4) && num_running > 2;
4282 done:
4283 if (res && !have_min_dir_info) {
4284 log(LOG_NOTICE, LD_DIR,
4285 "We now have enough directory information to build circuits.");
4286 control_event_client_status(LOG_NOTICE, "ENOUGH_DIR_INFO");
4288 if (!res && have_min_dir_info) {
4289 log(LOG_NOTICE, LD_DIR,"Our directory information is no longer up-to-date "
4290 "enough to build circuits.%s",
4291 num_running > 2 ? "" : " (Not enough servers seem reachable -- "
4292 "is your network connection down?)");
4293 control_event_client_status(LOG_NOTICE, "NOT_ENOUGH_DIR_INFO");
4295 have_min_dir_info = res;
4298 /** Return true iff we have downloaded, or attempted to download at least
4299 * n_failures times, a network status for each authority. */
4300 static int
4301 have_tried_downloading_all_statuses(int n_failures)
4303 if (!trusted_dir_servers)
4304 return 0;
4306 SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, ds,
4308 if (!ds->is_v2_authority)
4309 continue;
4310 /* If we don't have the status, and we haven't failed to get the status,
4311 * we haven't tried to get the status. */
4312 if (!networkstatus_get_by_digest(ds->digest) &&
4313 ds->n_networkstatus_failures <= n_failures)
4314 return 0;
4317 return 1;
4320 /** Reset the descriptor download failure count on all routers, so that we
4321 * can retry any long-failed routers immediately.
4323 void
4324 router_reset_descriptor_download_failures(void)
4326 if (!routerstatus_list)
4327 return;
4328 SMARTLIST_FOREACH(routerstatus_list, local_routerstatus_t *, rs,
4330 rs->n_download_failures = 0;
4331 rs->next_attempt_at = 0;
4333 tor_assert(networkstatus_list);
4334 SMARTLIST_FOREACH(networkstatus_list, networkstatus_t *, ns,
4335 SMARTLIST_FOREACH(ns->entries, routerstatus_t *, rs,
4337 if (!router_get_by_descriptor_digest(rs->descriptor_digest))
4338 rs->need_to_mirror = 1;
4339 }));
4340 last_routerdesc_download_attempted = 0;
4343 /** Any changes in a router descriptor's publication time larger than this are
4344 * automatically non-cosmetic. */
4345 #define ROUTER_MAX_COSMETIC_TIME_DIFFERENCE (12*60*60)
4347 /** We allow uptime to vary from how much it ought to be by this much. */
4348 #define ROUTER_ALLOW_UPTIME_DRIFT (6*60*60)
4350 /** Return true iff the only differences between r1 and r2 are such that
4351 * would not cause a recent (post 0.1.1.6) dirserver to republish.
4354 router_differences_are_cosmetic(routerinfo_t *r1, routerinfo_t *r2)
4356 time_t r1pub, r2pub;
4357 int time_difference;
4358 tor_assert(r1 && r2);
4360 /* r1 should be the one that was published first. */
4361 if (r1->cache_info.published_on > r2->cache_info.published_on) {
4362 routerinfo_t *ri_tmp = r2;
4363 r2 = r1;
4364 r1 = ri_tmp;
4367 /* If any key fields differ, they're different. */
4368 if (strcasecmp(r1->address, r2->address) ||
4369 strcasecmp(r1->nickname, r2->nickname) ||
4370 r1->or_port != r2->or_port ||
4371 r1->dir_port != r2->dir_port ||
4372 crypto_pk_cmp_keys(r1->onion_pkey, r2->onion_pkey) ||
4373 crypto_pk_cmp_keys(r1->identity_pkey, r2->identity_pkey) ||
4374 strcasecmp(r1->platform, r2->platform) ||
4375 (r1->contact_info && !r2->contact_info) || /* contact_info is optional */
4376 (!r1->contact_info && r2->contact_info) ||
4377 (r1->contact_info && r2->contact_info &&
4378 strcasecmp(r1->contact_info, r2->contact_info)) ||
4379 r1->is_hibernating != r2->is_hibernating ||
4380 r1->has_old_dnsworkers != r2->has_old_dnsworkers ||
4381 cmp_addr_policies(r1->exit_policy, r2->exit_policy))
4382 return 0;
4383 if ((r1->declared_family == NULL) != (r2->declared_family == NULL))
4384 return 0;
4385 if (r1->declared_family && r2->declared_family) {
4386 int i, n;
4387 if (smartlist_len(r1->declared_family)!=smartlist_len(r2->declared_family))
4388 return 0;
4389 n = smartlist_len(r1->declared_family);
4390 for (i=0; i < n; ++i) {
4391 if (strcasecmp(smartlist_get(r1->declared_family, i),
4392 smartlist_get(r2->declared_family, i)))
4393 return 0;
4397 /* Did bandwidth change a lot? */
4398 if ((r1->bandwidthcapacity < r2->bandwidthcapacity/2) ||
4399 (r2->bandwidthcapacity < r1->bandwidthcapacity/2))
4400 return 0;
4402 /* Did more than 12 hours pass? */
4403 if (r1->cache_info.published_on + ROUTER_MAX_COSMETIC_TIME_DIFFERENCE
4404 < r2->cache_info.published_on)
4405 return 0;
4407 /* Did uptime fail to increase by approximately the amount we would think,
4408 * give or take some slop? */
4409 r1pub = r1->cache_info.published_on;
4410 r2pub = r2->cache_info.published_on;
4411 time_difference = abs(r2->uptime - (r1->uptime + (r2pub - r1pub)));
4412 if (time_difference > ROUTER_ALLOW_UPTIME_DRIFT &&
4413 time_difference > r1->uptime * .05 &&
4414 time_difference > r2->uptime * .05)
4415 return 0;
4417 /* Otherwise, the difference is cosmetic. */
4418 return 1;
4421 /** Generate networkstatus lines for a single routerstatus_t object, and
4422 * return the result in a newly allocated string. Used only by controller
4423 * interface (for now.) */
4424 /* XXXX This should eventually merge into generate_v2_networkstatus() */
4425 char *
4426 networkstatus_getinfo_helper_single(routerstatus_t *rs)
4428 char buf[192];
4429 int r;
4430 struct in_addr in;
4432 int f_authority;
4433 char published[ISO_TIME_LEN+1];
4434 char ipaddr[INET_NTOA_BUF_LEN];
4435 char identity64[BASE64_DIGEST_LEN+1];
4436 char digest64[BASE64_DIGEST_LEN+1];
4438 format_iso_time(published, rs->published_on);
4439 digest_to_base64(identity64, rs->identity_digest);
4440 digest_to_base64(digest64, rs->descriptor_digest);
4441 in.s_addr = htonl(rs->addr);
4442 tor_inet_ntoa(&in, ipaddr, sizeof(ipaddr));
4444 f_authority = router_digest_is_trusted_dir(rs->identity_digest);
4446 r = tor_snprintf(buf, sizeof(buf),
4447 "r %s %s %s %s %s %d %d\n"
4448 "s%s%s%s%s%s%s%s%s%s%s\n",
4449 rs->nickname,
4450 identity64,
4451 digest64,
4452 published,
4453 ipaddr,
4454 (int)rs->or_port,
4455 (int)rs->dir_port,
4457 f_authority?" Authority":"",
4458 rs->is_bad_exit?" BadExit":"",
4459 rs->is_exit?" Exit":"",
4460 rs->is_fast?" Fast":"",
4461 rs->is_possible_guard?" Guard":"",
4462 rs->is_named?" Named":"",
4463 rs->is_stable?" Stable":"",
4464 rs->is_running?" Running":"",
4465 rs->is_valid?" Valid":"",
4466 rs->is_v2_dir?" V2Dir":"");
4467 if (r<0)
4468 log_warn(LD_BUG, "Not enough space in buffer.");
4470 return tor_strdup(buf);
4473 /** If <b>question</b> is a string beginning with "ns/" in a format the
4474 * control interface expects for a GETINFO question, set *<b>answer</b> to a
4475 * newly-allocated string containing networkstatus lines for the appropriate
4476 * ORs. Return 0 on success, -1 on unrecognized question format. */
4478 getinfo_helper_networkstatus(control_connection_t *conn,
4479 const char *question, char **answer)
4481 local_routerstatus_t *status;
4482 (void) conn;
4484 if (!routerstatus_list) {
4485 *answer = tor_strdup("");
4486 return 0;
4489 if (!strcmp(question, "ns/all")) {
4490 smartlist_t *statuses = smartlist_create();
4491 SMARTLIST_FOREACH(routerstatus_list, local_routerstatus_t *, lrs,
4493 routerstatus_t *rs = &(lrs->status);
4494 smartlist_add(statuses, networkstatus_getinfo_helper_single(rs));
4496 *answer = smartlist_join_strings(statuses, "", 0, NULL);
4497 SMARTLIST_FOREACH(statuses, char *, cp, tor_free(cp));
4498 smartlist_free(statuses);
4499 return 0;
4500 } else if (!strcmpstart(question, "ns/id/")) {
4501 char d[DIGEST_LEN];
4503 if (base16_decode(d, DIGEST_LEN, question+6, strlen(question+6)))
4504 return -1;
4505 status = router_get_combined_status_by_digest(d);
4506 } else if (!strcmpstart(question, "ns/name/")) {
4507 status = router_get_combined_status_by_nickname(question+8, 0);
4508 } else {
4509 return -1;
4512 if (status) {
4513 *answer = networkstatus_getinfo_helper_single(&status->status);
4515 return 0;
4518 /** Assert that the internal representation of <b>rl</b> is
4519 * self-consistent. */
4520 static void
4521 routerlist_assert_ok(routerlist_t *rl)
4523 digestmap_iter_t *iter;
4524 routerinfo_t *r2;
4525 signed_descriptor_t *sd2;
4526 if (!rl)
4527 return;
4528 SMARTLIST_FOREACH(rl->routers, routerinfo_t *, r,
4530 r2 = digestmap_get(rl->identity_map, r->cache_info.identity_digest);
4531 tor_assert(r == r2);
4532 sd2 = digestmap_get(rl->desc_digest_map,
4533 r->cache_info.signed_descriptor_digest);
4534 tor_assert(&(r->cache_info) == sd2);
4535 tor_assert(r->routerlist_index == r_sl_idx);
4537 SMARTLIST_FOREACH(rl->old_routers, signed_descriptor_t *, sd,
4539 r2 = digestmap_get(rl->identity_map, sd->identity_digest);
4540 tor_assert(sd != &(r2->cache_info));
4541 sd2 = digestmap_get(rl->desc_digest_map, sd->signed_descriptor_digest);
4542 tor_assert(sd == sd2);
4544 iter = digestmap_iter_init(rl->identity_map);
4545 while (!digestmap_iter_done(iter)) {
4546 const char *d;
4547 void *_r;
4548 routerinfo_t *r;
4549 digestmap_iter_get(iter, &d, &_r);
4550 r = _r;
4551 tor_assert(!memcmp(r->cache_info.identity_digest, d, DIGEST_LEN));
4552 iter = digestmap_iter_next(rl->identity_map, iter);
4554 iter = digestmap_iter_init(rl->desc_digest_map);
4555 while (!digestmap_iter_done(iter)) {
4556 const char *d;
4557 void *_sd;
4558 signed_descriptor_t *sd;
4559 digestmap_iter_get(iter, &d, &_sd);
4560 sd = _sd;
4561 tor_assert(!memcmp(sd->signed_descriptor_digest, d, DIGEST_LEN));
4562 iter = digestmap_iter_next(rl->desc_digest_map, iter);
4566 /** Allocate and return a new string representing the contact info
4567 * and platform string for <b>router</b>,
4568 * surrounded by quotes and using standard C escapes.
4570 * THIS FUNCTION IS NOT REENTRANT. Don't call it from outside the main
4571 * thread. Also, each call invalidates the last-returned value, so don't
4572 * try log_warn(LD_GENERAL, "%s %s", esc_router_info(a), esc_router_info(b));
4574 const char *
4575 esc_router_info(routerinfo_t *router)
4577 static char *info;
4578 char *esc_contact, *esc_platform;
4579 size_t len;
4580 if (info)
4581 tor_free(info);
4583 esc_contact = esc_for_log(router->contact_info);
4584 esc_platform = esc_for_log(router->platform);
4586 len = strlen(esc_contact)+strlen(esc_platform)+32;
4587 info = tor_malloc(len);
4588 tor_snprintf(info, len, "Contact %s, Platform %s", esc_contact,
4589 esc_platform);
4590 tor_free(esc_contact);
4591 tor_free(esc_platform);
4593 return info;