Clients should not download descriptors for non-running descriptors.
[tor.git] / src / or / routerlist.c
blob387df36fae7df535b78bf02fa0cba7689c7b9d9f
1 /* Copyright 2001 Matej Pfajfar.
2 * Copyright 2001-2004 Roger Dingledine.
3 * Copyright 2004-2005 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 for_v2_directory);
24 static routerstatus_t *router_pick_trusteddirserver_impl(
25 int need_v1_authority, int requireother, int fascistfirewall);
26 static void mark_all_trusteddirservers_up(void);
27 static int router_nickname_is_in_list(routerinfo_t *router, const char *list);
28 static int router_nickname_matches(routerinfo_t *router, const char *nickname);
29 static void routerstatus_list_update_from_networkstatus(time_t now);
30 static void local_routerstatus_free(local_routerstatus_t *rs);
31 static void trusted_dir_server_free(trusted_dir_server_t *ds);
32 static void update_networkstatus_cache_downloads(time_t now);
33 static void update_networkstatus_client_downloads(time_t now);
34 static int signed_desc_digest_is_recognized(signed_descriptor_t *desc);
35 static void routerlist_assert_ok(routerlist_t *rl);
37 #define MAX_DESCRIPTORS_PER_ROUTER 5
39 /****************************************************************************/
41 /** Global list of a trusted_dir_server_t object for each trusted directory
42 * server. */
43 static smartlist_t *trusted_dir_servers = NULL;
45 /** Global list of all of the routers that we know about. */
46 static routerlist_t *routerlist = NULL;
48 /** Global list of all of the current network_status documents that we know
49 * about. This list is kept sorted by published_on. */
50 static smartlist_t *networkstatus_list = NULL;
52 /** Global list of local_routerstatus_t for each router, known or unknown. */
53 static smartlist_t *routerstatus_list = NULL;
55 /** True iff any member of networkstatus_list has changed since the last time
56 * we called routerstatus_list_update_from_networkstatus(). */
57 static int networkstatus_list_has_changed = 0;
59 /** True iff any element of routerstatus_list has changed since the last
60 * time we called routers_update_all_from_networkstatus().*/
61 static int routerstatus_list_has_changed = 0;
63 /** List of strings for nicknames we've already warned about and that are
64 * still unknown / unavailable. */
65 static smartlist_t *warned_nicknames = NULL;
67 /** List of strings for nicknames or fingerprints we've already warned about
68 * and that are still conflicted. */
69 static smartlist_t *warned_conflicts = NULL;
71 /** The last time we tried to download any routerdesc, or 0 for "never". We
72 * use this to rate-limit download attempts when the number of routerdescs to
73 * download is low. */
74 static time_t last_routerdesc_download_attempted = 0;
76 /** The last time we tried to download a networkstatus, or 0 for "never". We
77 * use this to rate-limit download attempts for directory caches (including
78 * mirrors). Clients don't use this now. */
79 static time_t last_networkstatus_download_attempted = 0;
81 /* DOCDOC */
82 static int have_warned_about_unverified_status = 0;
83 static int have_warned_about_old_version = 0;
84 static int have_warned_about_new_version = 0;
86 /** Repopulate our list of network_status_t objects from the list cached on
87 * disk. Return 0 on success, -1 on failure. */
88 int
89 router_reload_networkstatus(void)
91 char filename[512];
92 struct stat st;
93 smartlist_t *entries;
94 char *s;
95 tor_assert(get_options()->DataDirectory);
96 if (!networkstatus_list)
97 networkstatus_list = smartlist_create();
99 tor_snprintf(filename,sizeof(filename),"%s/cached-status",
100 get_options()->DataDirectory);
101 entries = tor_listdir(filename);
102 SMARTLIST_FOREACH(entries, const char *, fn, {
103 char buf[DIGEST_LEN];
104 if (strlen(fn) != HEX_DIGEST_LEN ||
105 base16_decode(buf, sizeof(buf), fn, strlen(fn))) {
106 info(LD_DIR,
107 "Skipping cached-status file with unexpected name \"%s\"",fn);
108 continue;
110 tor_snprintf(filename,sizeof(filename),"%s/cached-status/%s",
111 get_options()->DataDirectory, fn);
112 s = read_file_to_str(filename, 0);
113 if (s) {
114 stat(filename, &st);
115 if (router_set_networkstatus(s, st.st_mtime, NS_FROM_CACHE, NULL)<0) {
116 warn(LD_FS, "Couldn't load networkstatus from \"%s\"",filename);
118 tor_free(s);
121 SMARTLIST_FOREACH(entries, char *, fn, tor_free(fn));
122 smartlist_free(entries);
123 networkstatus_list_clean(time(NULL));
124 routers_update_all_from_networkstatus();
125 return 0;
128 /* Router descriptor storage.
130 * Routerdescs are stored in a big file, named "cached-routers". As new
131 * routerdescs arrive, we append them to a journal file named
132 * "cached-routers.new".
134 * From time to time, we replace "cached-routers" with a new file containing
135 * only the live, non-superseded descriptors, and clear cached-routers.new.
137 * On startup, we read both files.
140 /** The size of the router log, in bytes. */
141 static size_t router_journal_len = 0;
142 /** The size of the router store, in bytes. */
143 static size_t router_store_len = 0;
144 /** Total bytes dropped since last rebuild. */
145 static size_t router_bytes_dropped = 0;
147 /** Helper: return 1 iff the router log is so big we want to rebuild the
148 * store. */
149 static int
150 router_should_rebuild_store(void)
152 if (router_store_len > (1<<16))
153 return (router_journal_len > router_store_len / 2 ||
154 router_bytes_dropped > router_store_len / 2);
155 else
156 return router_journal_len > (1<<15);
159 /** Add the <b>len</b>-type router descriptor in <b>s</b> to the router
160 * journal. */
161 static int
162 router_append_to_journal(signed_descriptor_t *desc)
164 or_options_t *options = get_options();
165 size_t fname_len = strlen(options->DataDirectory)+32;
166 char *fname = tor_malloc(fname_len);
167 const char *body = signed_descriptor_get_body(desc);
168 size_t len = desc->signed_descriptor_len;
170 tor_snprintf(fname, fname_len, "%s/cached-routers.new",
171 options->DataDirectory);
173 tor_assert(len == strlen(body));
175 if (append_bytes_to_file(fname, body, len, 0)) {
176 warn(LD_FS, "Unable to store router descriptor");
177 tor_free(fname);
178 return -1;
181 tor_free(fname);
182 router_journal_len += len;
183 return 0;
186 /** If the journal is too long, or if <b>force</b> is true, then atomically
187 * replace the router store with the routers currently in our routerlist, and
188 * clear the journal. Return 0 on success, -1 on failure.
190 static int
191 router_rebuild_store(int force)
193 size_t len = 0;
194 or_options_t *options;
195 size_t fname_len;
196 smartlist_t *chunk_list = NULL;
197 char *fname = NULL;
198 int r = -1, i;
200 if (!force && !router_should_rebuild_store())
201 return 0;
202 if (!routerlist)
203 return 0;
205 /* Don't save deadweight. */
206 routerlist_remove_old_routers();
208 options = get_options();
209 fname_len = strlen(options->DataDirectory)+32;
210 fname = tor_malloc(fname_len);
211 tor_snprintf(fname, fname_len, "%s/cached-routers", options->DataDirectory);
212 chunk_list = smartlist_create();
214 for (i = 0; i < 2; ++i) {
215 smartlist_t *lst = (i == 0) ? routerlist->old_routers :
216 routerlist->routers;
217 SMARTLIST_FOREACH(lst, void *, ptr,
219 signed_descriptor_t *sd = (i==0) ?
220 ((signed_descriptor_t*)ptr): &((routerinfo_t*)ptr)->cache_info;
221 sized_chunk_t *c;
222 const char *body = signed_descriptor_get_body(sd);
223 if (!body) {
224 warn(LD_BUG, "Bug! No descriptor available for router.");
225 goto done;
227 c = tor_malloc(sizeof(sized_chunk_t));
228 c->bytes = body;
229 c->len = sd->signed_descriptor_len;
230 smartlist_add(chunk_list, c);
233 if (write_chunks_to_file(fname, chunk_list, 0)<0) {
234 warn(LD_FS, "Error writing router store to disk.");
235 goto done;
238 tor_snprintf(fname, fname_len, "%s/cached-routers.new",
239 options->DataDirectory);
241 write_str_to_file(fname, "", 0);
243 r = 0;
244 router_store_len = len;
245 router_journal_len = 0;
246 router_bytes_dropped = 0;
247 done:
248 tor_free(fname);
249 if (chunk_list) {
250 SMARTLIST_FOREACH(chunk_list, sized_chunk_t *, c, tor_free(c));
251 smartlist_free(chunk_list);
253 return r;
256 /* Load all cached router descriptors from the store. Return 0 on success and
257 * -1 on failure.
260 router_reload_router_list(void)
262 or_options_t *options = get_options();
263 size_t fname_len = strlen(options->DataDirectory)+32;
264 char *fname = tor_malloc(fname_len);
265 struct stat st;
266 int j;
268 if (!routerlist)
269 router_get_routerlist(); /* mallocs and inits it in place */
271 router_journal_len = router_store_len = 0;
273 for (j = 0; j < 2; ++j) {
274 char *contents;
275 tor_snprintf(fname, fname_len,
276 (j==0)?"%s/cached-routers":"%s/cached-routers.new",
277 options->DataDirectory);
278 contents = read_file_to_str(fname, 0);
279 if (contents) {
280 stat(fname, &st);
281 if (j==0)
282 router_store_len = st.st_size;
283 else
284 router_journal_len = st.st_size;
285 router_load_routers_from_string(contents, 1, NULL);
286 tor_free(contents);
289 tor_free(fname);
291 if (router_journal_len) {
292 /* Always clear the journal on startup.*/
293 router_rebuild_store(1);
294 } else {
295 /* Don't cache expired routers. (This is in an else because
296 * router_rebuild_store() also calls remove_old_routers().) */
297 routerlist_remove_old_routers();
300 return 0;
303 /** Set *<b>outp</b> to a smartlist containing a list of
304 * trusted_dir_server_t * for all known trusted dirservers. Callers
305 * must not modify the list or its contents.
307 void
308 router_get_trusted_dir_servers(smartlist_t **outp)
310 if (!trusted_dir_servers)
311 trusted_dir_servers = smartlist_create();
313 *outp = trusted_dir_servers;
316 /** Try to find a running dirserver. If there are no running dirservers
317 * in our routerlist and <b>retry_if_no_servers</b> is non-zero,
318 * set all the authoritative ones as running again, and pick one;
319 * if there are then no dirservers at all in our routerlist,
320 * reload the routerlist and try one last time. If for_runningrouters is
321 * true, then only pick a dirserver that can answer runningrouters queries
322 * (that is, a trusted dirserver, or one running 0.0.9rc5-cvs or later).
323 * Don't pick an authority if any non-authority is viable.
324 * Other args are as in router_pick_directory_server_impl().
326 routerstatus_t *
327 router_pick_directory_server(int requireother,
328 int fascistfirewall,
329 int for_v2_directory,
330 int retry_if_no_servers)
332 routerstatus_t *choice;
334 if (!routerlist)
335 return NULL;
337 choice = router_pick_directory_server_impl(requireother, fascistfirewall,
338 for_v2_directory);
339 if (choice || !retry_if_no_servers)
340 return choice;
342 info(LD_DIR,
343 "No reachable router entries for dirservers. Trying them all again.");
344 /* mark all authdirservers as up again */
345 mark_all_trusteddirservers_up();
346 /* try again */
347 choice = router_pick_directory_server_impl(requireother, fascistfirewall,
348 for_v2_directory);
349 if (choice)
350 return choice;
352 info(LD_DIR,"Still no %s router entries. Reloading and trying again.",
353 fascistfirewall ? "reachable" : "known");
354 if (router_reload_router_list()) {
355 return NULL;
357 /* give it one last try */
358 choice = router_pick_directory_server_impl(requireother, fascistfirewall,
359 for_v2_directory);
360 return choice;
363 /** Return the trusted_dir_server_t for the directory authority whose identity
364 * key hashes to <b>digest</b>, or NULL if no such authority is known.
366 trusted_dir_server_t *
367 router_get_trusteddirserver_by_digest(const char *digest)
369 if (!trusted_dir_servers)
370 return NULL;
372 SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, ds,
374 if (!memcmp(ds->digest, digest, DIGEST_LEN))
375 return ds;
378 return NULL;
381 /** Try to find a running trusted dirserver. If there are no running
382 * trusted dirservers and <b>retry_if_no_servers</b> is non-zero,
383 * set them all as running again, and try again.
384 * If <b>need_v1_authority</b> is set, return only trusted servers
385 * that are authorities for the V1 directory protocol.
386 * Other args are as in router_pick_trusteddirserver_impl().
388 routerstatus_t *
389 router_pick_trusteddirserver(int need_v1_authority,
390 int requireother,
391 int fascistfirewall,
392 int retry_if_no_servers)
394 routerstatus_t *choice;
396 choice = router_pick_trusteddirserver_impl(need_v1_authority,
397 requireother, fascistfirewall);
398 if (choice || !retry_if_no_servers)
399 return choice;
401 info(LD_DIR,"No trusted dirservers are reachable. Trying them all again.");
402 mark_all_trusteddirservers_up();
403 return router_pick_trusteddirserver_impl(need_v1_authority,
404 requireother, fascistfirewall);
407 /** Pick a random running verified directory server/mirror from our
408 * routerlist. Don't pick an authority if any non-authorities are viable.
409 * If <b>fascistfirewall</b>,
410 * make sure the router we pick is allowed by our firewall options.
411 * If <b>requireother</b>, it cannot be us. If <b>for_v2_directory</b>,
412 * choose a directory server new enough to support the v2 directory
413 * functionality.
415 static routerstatus_t *
416 router_pick_directory_server_impl(int requireother, int fascistfirewall,
417 int for_v2_directory)
419 routerstatus_t *result;
420 smartlist_t *sl;
421 smartlist_t *trusted;
423 if (!routerstatus_list)
424 return NULL;
426 /* Find all the running dirservers we know about. */
427 sl = smartlist_create();
428 trusted = smartlist_create();
429 SMARTLIST_FOREACH(routerstatus_list, local_routerstatus_t *, _local_status,
431 routerstatus_t *status = &(_local_status->status);
432 int is_trusted;
433 if (!status->is_running || !status->dir_port || !status->is_valid)
434 continue;
435 if (requireother && router_digest_is_me(status->identity_digest))
436 continue;
437 if (fascistfirewall) {
438 if (!fascist_firewall_allows_address(status->addr, status->dir_port))
439 continue;
441 is_trusted = router_digest_is_trusted_dir(status->identity_digest);
442 if (for_v2_directory && !(status->is_v2_dir || is_trusted))
443 continue;
444 smartlist_add(is_trusted ? trusted : sl, status);
447 if (smartlist_len(sl))
448 result = smartlist_choose(sl);
449 else
450 result = smartlist_choose(trusted);
451 smartlist_free(sl);
452 smartlist_free(trusted);
453 return result;
456 /** Choose randomly from among the trusted dirservers that are up. If
457 * <b>fascistfirewall</b>, make sure the port we pick is allowed by our
458 * firewall options. If <b>requireother</b>, it cannot be us. If
459 * <b>need_v1_authority</b>, choose a trusted authority for the v1 directory
460 * system.
462 static routerstatus_t *
463 router_pick_trusteddirserver_impl(int need_v1_authority,
464 int requireother, int fascistfirewall)
466 smartlist_t *sl;
467 routerinfo_t *me;
468 routerstatus_t *rs;
469 sl = smartlist_create();
470 me = router_get_my_routerinfo();
472 if (!trusted_dir_servers)
473 return NULL;
475 SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, d,
477 if (!d->is_running) continue;
478 if (need_v1_authority && !d->is_v1_authority)
479 continue;
480 if (requireother && me && router_digest_is_me(d->digest))
481 continue;
482 if (fascistfirewall) {
483 if (!fascist_firewall_allows_address(d->addr, d->dir_port))
484 continue;
486 smartlist_add(sl, &d->fake_status);
489 rs = smartlist_choose(sl);
490 smartlist_free(sl);
491 return rs;
494 /** Go through and mark the authoritative dirservers as up. */
495 static void
496 mark_all_trusteddirservers_up(void)
498 if (routerlist) {
499 SMARTLIST_FOREACH(routerlist->routers, routerinfo_t *, router,
500 if (router_digest_is_trusted_dir(router->cache_info.identity_digest) &&
501 router->dir_port > 0) {
502 router->is_running = 1;
505 if (trusted_dir_servers) {
506 SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, dir,
508 local_routerstatus_t *rs;
509 dir->is_running = 1;
510 dir->n_networkstatus_failures = 0;
511 rs = router_get_combined_status_by_digest(dir->digest);
512 if (rs)
513 rs->status.is_running = 1;
516 last_networkstatus_download_attempted = 0;
519 /** Reset all internal variables used to count failed downloads of network
520 * status objects. */
521 void
522 router_reset_status_download_failures(void)
524 mark_all_trusteddirservers_up();
527 #if 0
528 /** Return 0 if \\exists an authoritative dirserver that's currently
529 * thought to be running, else return 1.
531 /* XXXX Nobody calls this function. Should it go away? */
533 all_trusted_directory_servers_down(void)
535 if (!trusted_dir_servers)
536 return 1;
537 SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, dir,
538 if (dir->is_running) return 0);
539 return 1;
541 #endif
543 /** Add all the family of <b>router</b> to the smartlist <b>sl</b>.
544 * This is used to make sure we don't pick siblings in a single path.
546 void
547 routerlist_add_family(smartlist_t *sl, routerinfo_t *router)
549 routerinfo_t *r;
550 config_line_t *cl;
552 if (!router->declared_family)
553 return;
555 /* Add every r such that router declares familyness with r, and r
556 * declares familyhood with router. */
557 SMARTLIST_FOREACH(router->declared_family, const char *, n,
559 if (!(r = router_get_by_nickname(n, 0)))
560 continue;
561 if (!r->declared_family)
562 continue;
563 SMARTLIST_FOREACH(r->declared_family, const char *, n2,
565 if (router_nickname_matches(router, n2))
566 smartlist_add(sl, r);
570 /* If the user declared any families locally, honor those too. */
571 for (cl = get_options()->NodeFamilies; cl; cl = cl->next) {
572 if (router_nickname_is_in_list(router, cl->value)) {
573 add_nickname_list_to_smartlist(sl, cl->value, 0, 1, 1);
578 /** Given a comma-and-whitespace separated list of nicknames, see which
579 * nicknames in <b>list</b> name routers in our routerlist that are
580 * currently running. Add the routerinfos for those routers to <b>sl</b>.
582 void
583 add_nickname_list_to_smartlist(smartlist_t *sl, const char *list,
584 int must_be_running,
585 int warn_if_down, int warn_if_unnamed)
587 routerinfo_t *router;
588 smartlist_t *nickname_list;
589 int have_dir_info = router_have_minimum_dir_info();
591 if (!list)
592 return; /* nothing to do */
593 tor_assert(sl);
595 nickname_list = smartlist_create();
596 if (!warned_nicknames)
597 warned_nicknames = smartlist_create();
599 smartlist_split_string(nickname_list, list, ",",
600 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
602 SMARTLIST_FOREACH(nickname_list, const char *, nick, {
603 int warned;
604 if (!is_legal_nickname_or_hexdigest(nick)) {
605 warn(LD_CONFIG, "Nickname '%s' is misformed; skipping", nick);
606 continue;
608 router = router_get_by_nickname(nick, warn_if_unnamed);
609 warned = smartlist_string_isin(warned_nicknames, nick);
610 if (router) {
611 if (!must_be_running || router->is_running) {
612 smartlist_add(sl,router);
613 if (warned)
614 smartlist_string_remove(warned_nicknames, nick);
615 } else {
616 if (!warned) {
617 log_fn(warn_if_down ? LOG_WARN : LOG_DEBUG, LD_CONFIG,
618 "Nickname list includes '%s' which is known but down.",nick);
619 smartlist_add(warned_nicknames, tor_strdup(nick));
622 } else {
623 if (!warned) {
624 log_fn(have_dir_info ? LOG_WARN : LOG_INFO, LD_CONFIG,
625 "Nickname list includes '%s' which isn't a known router.",nick);
626 smartlist_add(warned_nicknames, tor_strdup(nick));
630 SMARTLIST_FOREACH(nickname_list, char *, nick, tor_free(nick));
631 smartlist_free(nickname_list);
634 /** Return 1 iff any member of the comma-separated list <b>list</b> is an
635 * acceptable nickname or hexdigest for <b>router</b>. Else return 0.
637 static int
638 router_nickname_is_in_list(routerinfo_t *router, const char *list)
640 smartlist_t *nickname_list;
641 int v = 0;
643 if (!list)
644 return 0; /* definitely not */
645 tor_assert(router);
647 nickname_list = smartlist_create();
648 smartlist_split_string(nickname_list, list, ",",
649 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
650 SMARTLIST_FOREACH(nickname_list, const char *, cp,
651 if (router_nickname_matches(router, cp)) {v=1;break;});
652 SMARTLIST_FOREACH(nickname_list, char *, cp, tor_free(cp));
653 smartlist_free(nickname_list);
654 return v;
657 /** Add every router from our routerlist that is currently running to
658 * <b>sl</b>.
660 static void
661 router_add_running_routers_to_smartlist(smartlist_t *sl, int allow_unverified,
662 int need_uptime, int need_capacity)
664 if (!routerlist)
665 return;
667 SMARTLIST_FOREACH(routerlist->routers, routerinfo_t *, router,
669 if (router->is_running &&
670 (router->is_verified ||
671 (allow_unverified &&
672 !router_is_unreliable(router, need_uptime, need_capacity)))) {
673 /* If it's running, and either it's verified or we're ok picking
674 * unverified routers and this one is suitable.
676 smartlist_add(sl, router);
681 /** Look through the routerlist until we find a router that has my key.
682 Return it. */
683 routerinfo_t *
684 routerlist_find_my_routerinfo(void)
686 if (!routerlist)
687 return NULL;
689 SMARTLIST_FOREACH(routerlist->routers, routerinfo_t *, router,
691 if (router_is_me(router))
692 return router;
694 return NULL;
697 /** Find a router that's up, that has this IP address, and
698 * that allows exit to this address:port, or return NULL if there
699 * isn't a good one.
701 routerinfo_t *
702 router_find_exact_exit_enclave(const char *address, uint16_t port)
704 uint32_t addr;
705 struct in_addr in;
707 if (!tor_inet_aton(address, &in))
708 return NULL; /* it's not an IP already */
709 addr = ntohl(in.s_addr);
711 SMARTLIST_FOREACH(routerlist->routers, routerinfo_t *, router,
713 if (router->is_running &&
714 router->addr == addr &&
715 router_compare_addr_to_addr_policy(addr, port, router->exit_policy) ==
716 ADDR_POLICY_ACCEPTED)
717 return router;
719 return NULL;
722 /** Return 1 if <b>router</b> is not suitable for these parameters, else 0.
723 * If <b>need_uptime</b> is non-zero, we require a minimum uptime.
724 * If <b>need_capacity</b> is non-zero, we require a minimum advertised
725 * bandwidth.
728 router_is_unreliable(routerinfo_t *router, int need_uptime, int need_capacity)
730 if (need_uptime && !router->is_stable)
731 return 1;
732 if (need_capacity && !router->is_fast)
733 return 1;
734 return 0;
737 /** Remove from routerlist <b>sl</b> all routers who have a low uptime. */
738 static void
739 routerlist_sl_remove_unreliable_routers(smartlist_t *sl)
741 int i;
742 routerinfo_t *router;
744 for (i = 0; i < smartlist_len(sl); ++i) {
745 router = smartlist_get(sl, i);
746 if (router_is_unreliable(router, 1, 0)) {
747 // log(LOG_DEBUG, "Router '%s' has insufficient uptime; deleting.",
748 // router->nickname);
749 smartlist_del(sl, i--);
754 #define MAX_BELIEVABLE_BANDWIDTH 1500000 /* 1.5 MB/sec */
756 /** Choose a random element of router list <b>sl</b>, weighted by
757 * the advertised bandwidth of each router.
759 routerinfo_t *
760 routerlist_sl_choose_by_bandwidth(smartlist_t *sl)
762 int i;
763 routerinfo_t *router;
764 smartlist_t *bandwidths;
765 uint32_t this_bw, tmp, total_bw=0, rand_bw;
766 uint32_t *p;
768 /* First count the total bandwidth weight, and make a smartlist
769 * of each value. */
770 bandwidths = smartlist_create();
771 for (i = 0; i < smartlist_len(sl); ++i) {
772 router = smartlist_get(sl, i);
773 this_bw = (router->bandwidthcapacity < router->bandwidthrate) ?
774 router->bandwidthcapacity : router->bandwidthrate;
775 /* if they claim something huge, don't believe it */
776 if (this_bw > MAX_BELIEVABLE_BANDWIDTH)
777 this_bw = MAX_BELIEVABLE_BANDWIDTH;
778 p = tor_malloc(sizeof(uint32_t));
779 *p = this_bw;
780 smartlist_add(bandwidths, p);
781 total_bw += this_bw;
783 if (!total_bw) {
784 SMARTLIST_FOREACH(bandwidths, uint32_t*, p, tor_free(p));
785 smartlist_free(bandwidths);
786 return smartlist_choose(sl);
788 /* Second, choose a random value from the bandwidth weights. */
789 rand_bw = crypto_rand_int(total_bw);
790 /* Last, count through sl until we get to the element we picked */
791 tmp = 0;
792 for (i=0; ; i++) {
793 tor_assert(i < smartlist_len(sl));
794 p = smartlist_get(bandwidths, i);
795 tmp += *p;
796 if (tmp >= rand_bw)
797 break;
799 SMARTLIST_FOREACH(bandwidths, uint32_t*, p, tor_free(p));
800 smartlist_free(bandwidths);
801 return (routerinfo_t *)smartlist_get(sl, i);
804 /** Return a random running router from the routerlist. If any node
805 * named in <b>preferred</b> is available, pick one of those. Never
806 * pick a node named in <b>excluded</b>, or whose routerinfo is in
807 * <b>excludedsmartlist</b>, even if they are the only nodes
808 * available. If <b>strict</b> is true, never pick any node besides
809 * those in <b>preferred</b>.
810 * If <b>need_uptime</b> is non-zero and any router has more than
811 * a minimum uptime, return one of those.
812 * If <b>need_capacity</b> is non-zero, weight your choice by the
813 * advertised capacity of each router.
815 routerinfo_t *
816 router_choose_random_node(const char *preferred,
817 const char *excluded,
818 smartlist_t *excludedsmartlist,
819 int need_uptime, int need_capacity,
820 int allow_unverified, int strict)
822 smartlist_t *sl, *excludednodes;
823 routerinfo_t *choice = NULL;
825 excludednodes = smartlist_create();
826 add_nickname_list_to_smartlist(excludednodes,excluded,0,0,1);
828 /* Try the preferred nodes first. Ignore need_uptime and need_capacity,
829 * since the user explicitly asked for these nodes. */
830 if (preferred) {
831 sl = smartlist_create();
832 add_nickname_list_to_smartlist(sl,preferred,1,1,1);
833 smartlist_subtract(sl,excludednodes);
834 if (excludedsmartlist)
835 smartlist_subtract(sl,excludedsmartlist);
836 choice = smartlist_choose(sl);
837 smartlist_free(sl);
839 if (!choice && !strict) {
840 /* Then give up on our preferred choices: any node
841 * will do that has the required attributes. */
842 sl = smartlist_create();
843 router_add_running_routers_to_smartlist(sl, allow_unverified,
844 need_uptime, need_capacity);
845 smartlist_subtract(sl,excludednodes);
846 if (excludedsmartlist)
847 smartlist_subtract(sl,excludedsmartlist);
848 if (need_uptime)
849 routerlist_sl_remove_unreliable_routers(sl);
850 if (need_capacity)
851 choice = routerlist_sl_choose_by_bandwidth(sl);
852 else
853 choice = smartlist_choose(sl);
854 smartlist_free(sl);
855 if (!choice && (need_uptime || need_capacity)) {
856 /* try once more -- recurse but with fewer restrictions. */
857 info(LD_CIRC, "We couldn't find any live%s%s routers; falling back "
858 "to list of all routers.",
859 need_capacity?", fast":"",
860 need_uptime?", stable":"");
861 choice = router_choose_random_node(
862 NULL, excluded, excludedsmartlist, 0, 0, allow_unverified, 0);
865 smartlist_free(excludednodes);
866 if (!choice)
867 warn(LD_CIRC,"No available nodes when trying to choose node. Failing.");
868 return choice;
871 /** Return true iff the digest of <b>router</b>'s identity key,
872 * encoded in hexadecimal, matches <b>hexdigest</b> (which is
873 * optionally prefixed with a single dollar sign). Return false if
874 * <b>hexdigest</b> is malformed, or it doesn't match. */
875 static INLINE int
876 router_hex_digest_matches(routerinfo_t *router, const char *hexdigest)
878 char digest[DIGEST_LEN];
879 tor_assert(hexdigest);
880 if (hexdigest[0] == '$')
881 ++hexdigest;
883 /* XXXXNM Any place that uses this inside a loop could probably do better. */
884 if (strlen(hexdigest) != HEX_DIGEST_LEN ||
885 base16_decode(digest, DIGEST_LEN, hexdigest, HEX_DIGEST_LEN)<0)
886 return 0;
887 return (!memcmp(digest, router->cache_info.identity_digest, DIGEST_LEN));
890 /** Return true if <b>router</b>'s nickname matches <b>nickname</b>
891 * (case-insensitive), or if <b>router's</b> identity key digest
892 * matches a hexadecimal value stored in <b>nickname</b>. Return
893 * false otherwise. */
894 static int
895 router_nickname_matches(routerinfo_t *router, const char *nickname)
897 if (nickname[0]!='$' && !strcasecmp(router->nickname, nickname))
898 return 1;
899 return router_hex_digest_matches(router, nickname);
902 /** Return the router in our routerlist whose (case-insensitive)
903 * nickname or (case-sensitive) hexadecimal key digest is
904 * <b>nickname</b>. Return NULL if no such router is known.
906 routerinfo_t *
907 router_get_by_nickname(const char *nickname, int warn_if_unnamed)
909 int maybedigest;
910 char digest[DIGEST_LEN];
911 routerinfo_t *best_match=NULL;
912 int n_matches = 0;
914 tor_assert(nickname);
915 if (!routerlist)
916 return NULL;
917 if (nickname[0] == '$')
918 return router_get_by_hexdigest(nickname);
919 if (server_mode(get_options()) &&
920 !strcasecmp(nickname, get_options()->Nickname))
921 return router_get_my_routerinfo();
923 maybedigest = (strlen(nickname) == HEX_DIGEST_LEN) &&
924 (base16_decode(digest,DIGEST_LEN,nickname,HEX_DIGEST_LEN) == 0);
926 SMARTLIST_FOREACH(routerlist->routers, routerinfo_t *, router,
928 if (!strcasecmp(router->nickname, nickname)) {
929 if (router->is_named)
930 return router;
931 else {
932 ++n_matches;
933 best_match = router;
935 } else if (maybedigest &&
936 !memcmp(digest, router->cache_info.identity_digest, DIGEST_LEN)
938 return router;
942 if (best_match) {
943 if (warn_if_unnamed && n_matches > 1) {
944 smartlist_t *fps = smartlist_create();
945 int any_unwarned = 0;
946 SMARTLIST_FOREACH(routerlist->routers, routerinfo_t *, router,
948 local_routerstatus_t *rs;
949 char *desc;
950 size_t dlen;
951 char fp[HEX_DIGEST_LEN+1];
952 if (strcasecmp(router->nickname, nickname))
953 continue;
954 rs = router_get_combined_status_by_digest(
955 router->cache_info.identity_digest);
956 if (!rs->name_lookup_warned) {
957 rs->name_lookup_warned = 1;
958 any_unwarned = 1;
960 base16_encode(fp, sizeof(fp),
961 router->cache_info.identity_digest, DIGEST_LEN);
962 dlen = 32 + HEX_DIGEST_LEN + strlen(router->address);
963 desc = tor_malloc(dlen);
964 tor_snprintf(desc, dlen, "\"$%s\" for the one at %s:%d",
965 fp, router->address, router->or_port);
966 smartlist_add(fps, desc);
968 if (any_unwarned) {
969 char *alternatives = smartlist_join_strings(fps, "; ",0,NULL);
970 warn(LD_CONFIG, "There are multiple matches for the nickname \"%s\","
971 " but none is listed as named by the directory authories. "
972 "Choosing one arbitrarily. If you meant one in particular, "
973 "you should say %s.", nickname, alternatives);
974 tor_free(alternatives);
976 SMARTLIST_FOREACH(fps, char *, cp, tor_free(cp));
977 smartlist_free(fps);
978 } else if (warn_if_unnamed) {
979 local_routerstatus_t *rs = router_get_combined_status_by_digest(
980 best_match->cache_info.identity_digest);
981 if (rs && !rs->name_lookup_warned) {
982 char fp[HEX_DIGEST_LEN+1];
983 base16_encode(fp, sizeof(fp),
984 best_match->cache_info.identity_digest, DIGEST_LEN);
985 warn(LD_CONFIG, "You specified a server \"%s\" by name, but the "
986 "directory authorities do not have a listing for this name. "
987 "To make sure you get the same server in the future, refer to "
988 "it by key, as \"$%s\".", nickname, fp);
989 rs->name_lookup_warned = 1;
992 return best_match;
995 return NULL;
998 /** Try to find a routerinfo for <b>digest</b>. If we don't have one,
999 * return 1. If we do, ask tor_version_as_new_as() for the answer.
1002 router_digest_version_as_new_as(const char *digest, const char *cutoff)
1004 routerinfo_t *router = router_get_by_digest(digest);
1005 if (!router)
1006 return 1;
1007 return tor_version_as_new_as(router->platform, cutoff);
1010 /** Return true iff <b>digest</b> is the digest of the identity key of
1011 * a trusted directory. */
1013 router_digest_is_trusted_dir(const char *digest)
1015 if (!trusted_dir_servers)
1016 return 0;
1017 SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, ent,
1018 if (!memcmp(digest, ent->digest, DIGEST_LEN)) return 1);
1019 return 0;
1022 /** Return the router in our routerlist whose hexadecimal key digest
1023 * is <b>hexdigest</b>. Return NULL if no such router is known. */
1024 routerinfo_t *
1025 router_get_by_hexdigest(const char *hexdigest)
1027 char digest[DIGEST_LEN];
1029 tor_assert(hexdigest);
1030 if (!routerlist)
1031 return NULL;
1032 if (hexdigest[0]=='$')
1033 ++hexdigest;
1034 if (strlen(hexdigest) != HEX_DIGEST_LEN ||
1035 base16_decode(digest,DIGEST_LEN,hexdigest,HEX_DIGEST_LEN) < 0)
1036 return NULL;
1038 return router_get_by_digest(digest);
1041 /** Return the router in our routerlist whose 20-byte key digest
1042 * is <b>digest</b>. Return NULL if no such router is known. */
1043 routerinfo_t *
1044 router_get_by_digest(const char *digest)
1046 tor_assert(digest);
1048 if (!routerlist) return NULL;
1050 // routerlist_assert_ok(routerlist);
1052 return digestmap_get(routerlist->identity_map, digest);
1055 /** Return the router in our routerlist whose 20-byte descriptor
1056 * is <b>digest</b>. Return NULL if no such router is known. */
1057 signed_descriptor_t *
1058 router_get_by_descriptor_digest(const char *digest)
1060 tor_assert(digest);
1062 if (!routerlist) return NULL;
1064 return digestmap_get(routerlist->desc_digest_map, digest);
1067 const char *
1068 signed_descriptor_get_body(signed_descriptor_t *desc)
1070 return desc->signed_descriptor_body;
1073 /** Return the current list of all known routers. */
1074 routerlist_t *
1075 router_get_routerlist(void)
1077 if (!routerlist) {
1078 routerlist = tor_malloc_zero(sizeof(routerlist_t));
1079 routerlist->routers = smartlist_create();
1080 routerlist->old_routers = smartlist_create();
1081 routerlist->identity_map = digestmap_new();
1082 routerlist->desc_digest_map = digestmap_new();
1084 return routerlist;
1087 /** Free all storage held by <b>router</b>. */
1088 void
1089 routerinfo_free(routerinfo_t *router)
1091 if (!router)
1092 return;
1094 tor_free(router->cache_info.signed_descriptor_body);
1095 tor_free(router->address);
1096 tor_free(router->nickname);
1097 tor_free(router->platform);
1098 tor_free(router->contact_info);
1099 if (router->onion_pkey)
1100 crypto_free_pk_env(router->onion_pkey);
1101 if (router->identity_pkey)
1102 crypto_free_pk_env(router->identity_pkey);
1103 if (router->declared_family) {
1104 SMARTLIST_FOREACH(router->declared_family, char *, s, tor_free(s));
1105 smartlist_free(router->declared_family);
1107 addr_policy_free(router->exit_policy);
1108 tor_free(router);
1111 /** Release storage held by <b>sd</b>. */
1112 static void
1113 signed_descriptor_free(signed_descriptor_t *sd)
1115 tor_free(sd->signed_descriptor_body);
1116 tor_free(sd);
1119 /** Extract a signed_descriptor_t from a routerinfo, and free the routerinfo.
1121 static signed_descriptor_t *
1122 signed_descriptor_from_routerinfo(routerinfo_t *ri)
1124 signed_descriptor_t *sd = tor_malloc_zero(sizeof(signed_descriptor_t));
1125 memcpy(sd, &(ri->cache_info), sizeof(signed_descriptor_t));
1126 ri->cache_info.signed_descriptor_body = NULL;
1127 routerinfo_free(ri);
1128 return sd;
1131 /** Free all storage held by a routerlist <b>rl</b> */
1132 void
1133 routerlist_free(routerlist_t *rl)
1135 tor_assert(rl);
1136 digestmap_free(rl->identity_map, NULL);
1137 digestmap_free(rl->desc_digest_map, NULL);
1138 SMARTLIST_FOREACH(rl->routers, routerinfo_t *, r,
1139 routerinfo_free(r));
1140 SMARTLIST_FOREACH(rl->old_routers, signed_descriptor_t *, sd,
1141 signed_descriptor_free(sd));
1142 smartlist_free(rl->routers);
1143 smartlist_free(rl->old_routers);
1144 tor_free(rl);
1147 void
1148 dump_routerlist_mem_usage(int severity)
1150 uint64_t livedescs = 0;
1151 uint64_t olddescs = 0;
1152 if (!routerlist)
1153 return;
1154 SMARTLIST_FOREACH(routerlist->routers, routerinfo_t *, r,
1155 livedescs += r->cache_info.signed_descriptor_len);
1156 SMARTLIST_FOREACH(routerlist->old_routers, signed_descriptor_t *, sd,
1157 olddescs += sd->signed_descriptor_len);
1159 log(severity, LD_GENERAL,
1160 "In %d live descriptors: "U64_FORMAT" bytes. "
1161 "In %d old descriptors: "U64_FORMAT" bytes.",
1162 smartlist_len(routerlist->routers), U64_PRINTF_ARG(livedescs),
1163 smartlist_len(routerlist->old_routers), U64_PRINTF_ARG(olddescs));
1166 /** Return non-zero if we have a lot of extra descriptors in our
1167 * routerlist, and should get rid of some of them. Else return 0.
1169 * We should be careful to not return true too eagerly, since we
1170 * could churn. By using "+1" below, we make sure this function
1171 * only returns true at most every smartlist_len(rl-\>routers)
1172 * new descriptors.
1174 static INLINE int
1175 routerlist_is_overfull(routerlist_t *rl)
1177 return smartlist_len(rl->old_routers) >
1178 smartlist_len(rl->routers)*(MAX_DESCRIPTORS_PER_ROUTER+1);
1181 static INLINE int
1182 _routerlist_find_elt(smartlist_t *sl, void *ri, int idx)
1184 if (idx < 0 || smartlist_get(sl, idx) != ri) {
1185 idx = -1;
1186 SMARTLIST_FOREACH(sl, routerinfo_t *, r,
1187 if (r == ri) {
1188 idx = r_sl_idx;
1189 break;
1192 return idx;
1195 /** Insert an item <b>ri</b> into the routerlist <b>rl</b>, updating indices
1196 * as needed. */
1197 static void
1198 routerlist_insert(routerlist_t *rl, routerinfo_t *ri)
1200 digestmap_set(rl->identity_map, ri->cache_info.identity_digest, ri);
1201 digestmap_set(rl->desc_digest_map, ri->cache_info.signed_descriptor_digest,
1202 &(ri->cache_info));
1203 smartlist_add(rl->routers, ri);
1204 // routerlist_assert_ok(rl);
1207 static void
1208 routerlist_insert_old(routerlist_t *rl, routerinfo_t *ri)
1210 if (get_options()->DirPort &&
1211 !digestmap_get(rl->desc_digest_map,
1212 ri->cache_info.signed_descriptor_digest)) {
1213 signed_descriptor_t *sd = signed_descriptor_from_routerinfo(ri);
1214 digestmap_set(rl->desc_digest_map, sd->signed_descriptor_digest, sd);
1215 smartlist_add(rl->old_routers, sd);
1216 } else {
1217 routerinfo_free(ri);
1219 // routerlist_assert_ok(rl);
1222 /** Remove an item <b>ri</b> into the routerlist <b>rl</b>, updating indices
1223 * as needed. If <b>idx</b> is nonnegative and smartlist_get(rl-&gt;routers,
1224 * idx) == ri, we don't need to do a linear search over the list to decide
1225 * which to remove. We fill the gap in rl-&gt;routers with a later element in
1226 * the list, if any exists. <b>ri</b> is freed. */
1227 void
1228 routerlist_remove(routerlist_t *rl, routerinfo_t *ri, int idx, int make_old)
1230 routerinfo_t *ri_tmp;
1231 idx = _routerlist_find_elt(rl->routers, ri, idx);
1232 if (idx < 0)
1233 return;
1234 smartlist_del(rl->routers, idx);
1235 ri_tmp = digestmap_remove(rl->identity_map, ri->cache_info.identity_digest);
1236 tor_assert(ri_tmp == ri);
1237 if (make_old && get_options()->DirPort) {
1238 signed_descriptor_t *sd;
1239 sd = signed_descriptor_from_routerinfo(ri);
1240 smartlist_add(rl->old_routers, sd);
1241 digestmap_set(rl->desc_digest_map, sd->signed_descriptor_digest, sd);
1242 } else {
1243 ri_tmp = digestmap_remove(rl->desc_digest_map,
1244 ri->cache_info.signed_descriptor_digest);
1245 tor_assert(ri_tmp == ri);
1246 router_bytes_dropped += ri->cache_info.signed_descriptor_len;
1247 routerinfo_free(ri);
1249 // routerlist_assert_ok(rl);
1252 static void
1253 routerlist_remove_old(routerlist_t *rl, signed_descriptor_t *sd, int idx)
1255 signed_descriptor_t *sd_tmp;
1256 idx = _routerlist_find_elt(rl->old_routers, sd, idx);
1257 if (idx < 0)
1258 return;
1259 smartlist_del(rl->old_routers, idx);
1260 sd_tmp = digestmap_remove(rl->desc_digest_map,
1261 sd->signed_descriptor_digest);
1262 tor_assert(sd_tmp == sd);
1263 router_bytes_dropped += sd->signed_descriptor_len;
1264 signed_descriptor_free(sd);
1265 // routerlist_assert_ok(rl);
1268 /** Remove <b>ri_old</b> from the routerlist <b>rl</b>, and replace it with
1269 * <b>ri_new</b>, updating all index info. If <b>idx</b> is nonnegative and
1270 * smartlist_get(rl-&gt;routers, idx) == ri, we don't need to do a linear
1271 * search over the list to decide which to remove. We put ri_new in the same
1272 * index as ri_old, if possible. ri is freed as appropriate. */
1273 static void
1274 routerlist_replace(routerlist_t *rl, routerinfo_t *ri_old,
1275 routerinfo_t *ri_new, int idx, int make_old)
1277 tor_assert(ri_old != ri_new);
1278 idx = _routerlist_find_elt(rl->routers, ri_old, idx);
1279 if (idx >= 0) {
1280 smartlist_set(rl->routers, idx, ri_new);
1281 } else {
1282 warn(LD_BUG, "Appending entry from routerlist_replace.");
1283 routerlist_insert(rl, ri_new);
1284 return;
1286 if (memcmp(ri_old->cache_info.identity_digest,
1287 ri_new->cache_info.identity_digest, DIGEST_LEN)) {
1288 /* digests don't match; digestmap_set won't replace */
1289 digestmap_remove(rl->identity_map, ri_old->cache_info.identity_digest);
1291 digestmap_set(rl->identity_map, ri_new->cache_info.identity_digest, ri_new);
1292 digestmap_set(rl->desc_digest_map,
1293 ri_new->cache_info.signed_descriptor_digest, &(ri_new->cache_info));
1295 if (make_old && get_options()->DirPort) {
1296 signed_descriptor_t *sd = signed_descriptor_from_routerinfo(ri_old);
1297 smartlist_add(rl->old_routers, sd);
1298 digestmap_set(rl->desc_digest_map, sd->signed_descriptor_digest, sd);
1299 } else {
1300 if (memcmp(ri_old->cache_info.signed_descriptor_digest,
1301 ri_new->cache_info.signed_descriptor_digest,
1302 DIGEST_LEN)) {
1303 /* digests don't match; digestmap_set didn't replace */
1304 digestmap_remove(rl->desc_digest_map,
1305 ri_old->cache_info.signed_descriptor_digest);
1307 routerinfo_free(ri_old);
1309 // routerlist_assert_ok(rl);
1312 /** Free all memory held by the routerlist module. */
1313 void
1314 routerlist_free_all(void)
1316 if (routerlist)
1317 routerlist_free(routerlist);
1318 routerlist = NULL;
1319 if (warned_nicknames) {
1320 SMARTLIST_FOREACH(warned_nicknames, char *, cp, tor_free(cp));
1321 smartlist_free(warned_nicknames);
1322 warned_nicknames = NULL;
1324 if (warned_conflicts) {
1325 SMARTLIST_FOREACH(warned_conflicts, char *, cp, tor_free(cp));
1326 smartlist_free(warned_conflicts);
1327 warned_conflicts = NULL;
1329 if (trusted_dir_servers) {
1330 SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, ds,
1331 trusted_dir_server_free(ds));
1332 smartlist_free(trusted_dir_servers);
1333 trusted_dir_servers = NULL;
1335 if (networkstatus_list) {
1336 SMARTLIST_FOREACH(networkstatus_list, networkstatus_t *, ns,
1337 networkstatus_free(ns));
1338 smartlist_free(networkstatus_list);
1339 networkstatus_list = NULL;
1341 if (routerstatus_list) {
1342 SMARTLIST_FOREACH(routerstatus_list, local_routerstatus_t *, rs,
1343 local_routerstatus_free(rs));
1344 smartlist_free(routerstatus_list);
1345 routerstatus_list = NULL;
1349 /** Free all storage held by the routerstatus object <b>rs</b>. */
1350 void
1351 routerstatus_free(routerstatus_t *rs)
1353 tor_free(rs);
1356 /** Free all storage held by the local_routerstatus object <b>rs</b>. */
1357 static void
1358 local_routerstatus_free(local_routerstatus_t *rs)
1360 tor_free(rs);
1363 /** Free all storage held by the networkstatus object <b>ns</b>. */
1364 void
1365 networkstatus_free(networkstatus_t *ns)
1367 tor_free(ns->source_address);
1368 tor_free(ns->contact);
1369 if (ns->signing_key)
1370 crypto_free_pk_env(ns->signing_key);
1371 tor_free(ns->client_versions);
1372 tor_free(ns->server_versions);
1373 if (ns->entries) {
1374 SMARTLIST_FOREACH(ns->entries, routerstatus_t *, rs,
1375 routerstatus_free(rs));
1376 smartlist_free(ns->entries);
1378 tor_free(ns);
1381 /** Forget that we have issued any router-related warnings, so that we'll
1382 * warn again if we see the same errors. */
1383 void
1384 routerlist_reset_warnings(void)
1386 if (!warned_nicknames)
1387 warned_nicknames = smartlist_create();
1388 SMARTLIST_FOREACH(warned_nicknames, char *, cp, tor_free(cp));
1389 smartlist_clear(warned_nicknames); /* now the list is empty. */
1391 if (!warned_conflicts)
1392 warned_conflicts = smartlist_create();
1393 SMARTLIST_FOREACH(warned_conflicts, char *, cp, tor_free(cp));
1394 smartlist_clear(warned_conflicts); /* now the list is empty. */
1396 if (!routerstatus_list)
1397 routerstatus_list = smartlist_create();
1398 SMARTLIST_FOREACH(routerstatus_list, local_routerstatus_t *, rs,
1399 rs->name_lookup_warned = 0);
1401 have_warned_about_unverified_status = 0;
1402 have_warned_about_old_version = 0;
1403 have_warned_about_new_version = 0;
1406 /** Mark the router with ID <b>digest</b> as non-running in our routerlist. */
1407 void
1408 router_mark_as_down(const char *digest)
1410 routerinfo_t *router;
1411 local_routerstatus_t *status;
1412 tor_assert(digest);
1414 SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, d,
1415 if (!memcmp(d->digest, digest, DIGEST_LEN))
1416 d->is_running = 0);
1418 router = router_get_by_digest(digest);
1419 if (router) {
1420 debug(LD_DIR,"Marking router '%s' as down.",router->nickname);
1421 if (router_is_me(router) && !we_are_hibernating())
1422 warn(LD_NET, "We just marked ourself as down. Are your external "
1423 "addresses reachable?");
1424 router->is_running = 0;
1426 status = router_get_combined_status_by_digest(digest);
1427 if (status) {
1428 status->status.is_running = 0;
1432 /** Add <b>router</b> to the routerlist, if we don't already have it. Replace
1433 * older entries (if any) with the same key. Note: Callers should not hold
1434 * their pointers to <b>router</b> if this function fails; <b>router</b>
1435 * will either be inserted into the routerlist or freed.
1437 * Returns >= 0 if the router was added; less than 0 if it was not.
1439 * If we're returning non-zero, then assign to *<b>msg</b> a static string
1440 * describing the reason for not liking the routerinfo.
1442 * If the return value is less than -1, there was a problem with the
1443 * routerinfo. If the return value is equal to -1, then the routerinfo was
1444 * fine, but out-of-date. If the return value is equal to 1, the
1445 * routerinfo was accepted, but we should notify the generator of the
1446 * descriptor using the message *<b>msg</b>.
1448 * If <b>from_cache</b>, this descriptor came from our disk cache. If
1449 * <b>from_fetch</b>, we received it in response to a request we made.
1450 * (If both are false, that means it was uploaded to us as an auth dir
1451 * server or via the controller.)
1453 * This function should be called *after*
1454 * routers_update_status_from_networkstatus; subsequently, you should call
1455 * router_rebuild_store and control_event_descriptors_changed.
1457 * XXXX never replace your own descriptor.
1460 router_add_to_routerlist(routerinfo_t *router, const char **msg,
1461 int from_cache, int from_fetch)
1463 int i;
1464 char id_digest[DIGEST_LEN];
1465 int authdir = get_options()->AuthoritativeDir;
1466 int authdir_verified = 0;
1468 tor_assert(msg);
1470 if (!routerlist)
1471 router_get_routerlist();
1473 /* XXXX NM If this assert doesn't trigger, we should remove the id_digest
1474 * local. */
1475 crypto_pk_get_digest(router->identity_pkey, id_digest);
1476 tor_assert(!memcmp(id_digest, router->cache_info.identity_digest,
1477 DIGEST_LEN));
1479 /* Make sure that we haven't already got this exact descriptor. */
1480 if (digestmap_get(routerlist->desc_digest_map,
1481 router->cache_info.signed_descriptor_digest)) {
1482 info(LD_DIR, "Dropping descriptor that we already have for router '%s'",
1483 router->nickname);
1484 *msg = "Router descriptor was not new.";
1485 routerinfo_free(router);
1486 return -1;
1489 if (routerlist_is_overfull(routerlist))
1490 routerlist_remove_old_routers();
1492 if (authdir) {
1493 if (authdir_wants_to_reject_router(router, msg,
1494 !from_cache && !from_fetch)) {
1495 tor_assert(*msg);
1496 routerinfo_free(router);
1497 return -2;
1499 authdir_verified = router->is_verified;
1500 } else if (from_fetch) {
1501 /* Only check the descriptor digest against the network statuses when
1502 * we are receiving in response to a fetch. */
1503 if (!signed_desc_digest_is_recognized(&router->cache_info)) {
1504 warn(LD_DIR, "Dropping unrecognized descriptor for router '%s'",
1505 router->nickname);
1506 *msg = "Router descriptor is not referenced by any network-status.";
1507 routerinfo_free(router);
1508 return -1;
1512 /* If we have a router with this name, and the identity key is the same,
1513 * choose the newer one. If the identity key has changed, and one of the
1514 * routers is named, drop the unnamed ones. (If more than one are named,
1515 * drop the old ones.)
1517 for (i = 0; i < smartlist_len(routerlist->routers); ++i) {
1518 routerinfo_t *old_router = smartlist_get(routerlist->routers, i);
1519 if (!crypto_pk_cmp_keys(router->identity_pkey,old_router->identity_pkey)) {
1520 if (router->cache_info.published_on <=
1521 old_router->cache_info.published_on) {
1522 /* Same key, but old */
1523 debug(LD_DIR, "Skipping not-new descriptor for router '%s'",
1524 router->nickname);
1525 routerlist_insert_old(routerlist, router);
1526 *msg = "Router descriptor was not new.";
1527 return -1;
1528 } else {
1529 /* Same key, new. */
1530 int unreachable = 0;
1531 debug(LD_DIR, "Replacing entry for router '%s/%s' [%s]",
1532 router->nickname, old_router->nickname,
1533 hex_str(id_digest,DIGEST_LEN));
1534 if (router->addr == old_router->addr &&
1535 router->or_port == old_router->or_port) {
1536 /* these carry over when the address and orport are unchanged.*/
1537 router->last_reachable = old_router->last_reachable;
1538 router->testing_since = old_router->testing_since;
1539 router->num_unreachable_notifications =
1540 old_router->num_unreachable_notifications;
1542 if (authdir &&
1543 dirserv_thinks_router_is_blatantly_unreachable(router,
1544 time(NULL))) {
1545 if (router->num_unreachable_notifications >= 3) {
1546 unreachable = 1;
1547 notice(LD_DIR, "Notifying server '%s' that it's unreachable. "
1548 "(ContactInfo '%s', platform '%s').",
1549 router->nickname,
1550 router->contact_info ? router->contact_info : "",
1551 router->platform ? router->platform : "");
1552 } else {
1553 info(LD_DIR,"'%s' may be unreachable -- the %d previous "
1554 "descriptors were thought to be unreachable.",
1555 router->nickname, router->num_unreachable_notifications);
1556 router->num_unreachable_notifications++;
1559 routerlist_replace(routerlist, old_router, router, i, 1);
1560 if (!from_cache) {
1561 router_append_to_journal(&router->cache_info);
1563 directory_set_dirty();
1564 *msg = unreachable ? "Dirserver believes your ORPort is unreachable" :
1565 authdir_verified ? "Verified server updated" :
1566 ("Unverified server updated. (Have you sent us your key "
1567 "fingerprint?)");
1568 return unreachable ? 1 : 0;
1570 } else if (!strcasecmp(router->nickname, old_router->nickname)) {
1571 /* nicknames match, keys don't. */
1572 if (router->is_named) {
1573 /* The new verified router replaces the old one; remove the
1574 * old one. And carry on to the end of the list, in case
1575 * there are more old unverified routers with this nickname
1577 /* mark-for-close connections using the old key, so we can
1578 * make new ones with the new key.
1580 connection_t *conn;
1581 while ((conn = connection_or_get_by_identity_digest(
1582 old_router->cache_info.identity_digest))) {
1583 // And LD_OR? XXXXNM
1584 info(LD_DIR,"Closing conn to router '%s'; there is now a named "
1585 "router with that name.",
1586 old_router->nickname);
1587 connection_mark_for_close(conn);
1589 routerlist_remove(routerlist, old_router, i--, 0);
1590 } else if (old_router->is_named) {
1591 /* Can't replace a verified router with an unverified one. */
1592 debug(LD_DIR, "Skipping unverified entry for verified router '%s'",
1593 router->nickname);
1594 routerinfo_free(router);
1595 *msg =
1596 "Already have named router with same nickname and different key.";
1597 return -2;
1601 /* We haven't seen a router with this name before. Add it to the end of
1602 * the list. */
1603 routerlist_insert(routerlist, router);
1604 if (!from_cache)
1605 router_append_to_journal(&router->cache_info);
1606 directory_set_dirty();
1607 return 0;
1610 static int
1611 _compare_old_routers_by_identity(const void **_a, const void **_b)
1613 int i;
1614 const signed_descriptor_t *r1 = *_a, *r2 = *_b;
1615 if ((i = memcmp(r1->identity_digest, r2->identity_digest, DIGEST_LEN)))
1616 return i;
1617 return r1->published_on - r2->published_on;
1620 struct duration_idx_t {
1621 int duration;
1622 int idx;
1623 int old;
1626 static int
1627 _compare_duration_idx(const void *_d1, const void *_d2)
1629 const struct duration_idx_t *d1 = _d1;
1630 const struct duration_idx_t *d2 = _d2;
1631 return d1->duration - d2->duration;
1634 /** The range <b>lo</b> through <b>hi</b> inclusive of routerlist->old_routers
1635 * must contain routerinfo_t with the same identity and with publication time
1636 * in ascending order. Remove members from this range until there are no more
1637 * than MAX_DESCRIPTORS_PER_ROUTER remaining. Start by removing the oldest
1638 * members from before <b>cutoff</b>, then remove members which were current
1639 * for the lowest amount of time. The order of members of old_routers at
1640 * indices <b>lo</b> or higher may be changed.
1642 static void
1643 routerlist_remove_old_cached_routers_with_id(time_t cutoff, int lo, int hi,
1644 digestmap_t *retain)
1646 int i, n = hi-lo+1, n_extra;
1647 int n_rmv = 0;
1648 struct duration_idx_t *lifespans;
1649 uint8_t *rmv, *must_keep;
1650 smartlist_t *lst = routerlist->old_routers;
1651 #if 1
1652 const char *ident;
1653 tor_assert(hi < smartlist_len(lst));
1654 tor_assert(lo <= hi);
1655 ident = ((signed_descriptor_t*)smartlist_get(lst, lo))->identity_digest;
1656 for (i = lo+1; i <= hi; ++i) {
1657 signed_descriptor_t *r = smartlist_get(lst, i);
1658 tor_assert(!memcmp(ident, r->identity_digest, DIGEST_LEN));
1660 #endif
1662 /* Check whether we need to do anything at all. */
1663 n_extra = n - MAX_DESCRIPTORS_PER_ROUTER;
1664 if (n_extra <= 0)
1665 return;
1667 lifespans = tor_malloc_zero(sizeof(struct duration_idx_t)*n);
1668 rmv = tor_malloc_zero(sizeof(uint8_t)*n);
1669 must_keep = tor_malloc_zero(sizeof(uint8_t)*n);
1670 /* Set lifespans to contain the lifespan and index of each server. */
1671 /* Set rmv[i-lo]=1 if we're going to remove a server for being too old. */
1672 for (i = lo; i <= hi; ++i) {
1673 signed_descriptor_t *r = smartlist_get(lst, i);
1674 signed_descriptor_t *r_next;
1675 lifespans[i-lo].idx = i;
1676 if (retain && digestmap_get(retain, r->signed_descriptor_digest)) {
1677 must_keep[i-lo] = 1;
1679 if (i < hi) {
1680 r_next = smartlist_get(lst, i+1);
1681 tor_assert(r->published_on <= r_next->published_on);
1682 lifespans[i-lo].duration = (r_next->published_on - r->published_on);
1683 } else {
1684 r_next = NULL;
1685 lifespans[i-lo].duration = INT_MAX;
1687 if (!must_keep[i-lo] && r->published_on < cutoff && n_rmv < n_extra) {
1688 ++n_rmv;
1689 lifespans[i-lo].old = 1;
1690 rmv[i-lo] = 1;
1694 if (n_rmv < n_extra) {
1696 * We aren't removing enough servers for being old. Sort lifespans by
1697 * the duration of liveness, and remove the ones we're not already going to
1698 * remove based on how long they were alive.
1700 qsort(lifespans, n, sizeof(struct duration_idx_t), _compare_duration_idx);
1701 for (i = 0; i < n && n_rmv < n_extra; ++i) {
1702 if (!must_keep[lifespans[i].idx-lo] && !lifespans[i].old) {
1703 rmv[lifespans[i].idx-lo] = 1;
1704 ++n_rmv;
1709 for (i = hi; i >= lo; --i) {
1710 if (rmv[i-lo])
1711 routerlist_remove_old(routerlist, smartlist_get(lst, i), i);
1713 tor_free(must_keep);
1714 tor_free(rmv);
1715 tor_free(lifespans);
1718 /** Deactivate any routers from the routerlist that are more than
1719 * ROUTER_MAX_AGE seconds old; remove old routers from the list of
1720 * cached routers if we have too many.
1722 void
1723 routerlist_remove_old_routers(void)
1725 int i, hi=-1;
1726 const char *cur_id = NULL;
1727 time_t now, cutoff;
1728 routerinfo_t *router;
1729 signed_descriptor_t *sd;
1730 digestmap_t *retain;
1731 or_options_t *options = get_options();
1732 if (!routerlist || !networkstatus_list)
1733 return;
1735 retain = digestmap_new();
1736 if (server_mode(options) && options->DirPort) {
1737 SMARTLIST_FOREACH(networkstatus_list, networkstatus_t *, ns,
1739 SMARTLIST_FOREACH(ns->entries, routerstatus_t *, rs,
1740 digestmap_set(retain, rs->descriptor_digest, (void*)1));
1744 now = time(NULL);
1745 cutoff = now - ROUTER_MAX_AGE;
1746 /* Remove too-old members of routerlist->routers. */
1747 for (i = 0; i < smartlist_len(routerlist->routers); ++i) {
1748 router = smartlist_get(routerlist->routers, i);
1749 if (router->cache_info.published_on <= cutoff &&
1750 !digestmap_get(retain, router->cache_info.signed_descriptor_digest)) {
1751 /* Too old. Remove it. */
1752 info(LD_DIR, "Forgetting obsolete (too old) routerinfo for router '%s'",
1753 router->nickname);
1754 routerlist_remove(routerlist, router, i--, 1);
1758 /* Remove far-too-old members of routerlist->old_routers. */
1759 cutoff = now - OLD_ROUTER_DESC_MAX_AGE;
1760 for (i = 0; i < smartlist_len(routerlist->old_routers); ++i) {
1761 sd = smartlist_get(routerlist->old_routers, i);
1762 if (sd->published_on <= cutoff &&
1763 !digestmap_get(retain, sd->signed_descriptor_digest)) {
1764 /* Too old. Remove it. */
1765 routerlist_remove_old(routerlist, sd, i--);
1769 /* Now we're looking at routerlist->old_routers for extraneous
1770 * members. (We'd keep all the members if we could, but we'd like to save
1771 * space.) First, check whether we have too many router descriptors, total.
1772 * We're okay with having too many for some given router, so long as the
1773 * total number doesn't approach MAX_DESCRIPTORS_PER_ROUTER*len(router).
1775 if (smartlist_len(routerlist->old_routers) <
1776 smartlist_len(routerlist->routers) * (MAX_DESCRIPTORS_PER_ROUTER - 1))
1777 goto done;
1779 smartlist_sort(routerlist->old_routers, _compare_old_routers_by_identity);
1781 /* Iterate through the list from back to front, so when we remove descriptors
1782 * we don't mess up groups we haven't gotten to. */
1783 for (i = smartlist_len(routerlist->old_routers)-1; i >= 0; --i) {
1784 signed_descriptor_t *r = smartlist_get(routerlist->old_routers, i);
1785 if (!cur_id) {
1786 cur_id = r->identity_digest;
1787 hi = i;
1789 if (memcmp(cur_id, r->identity_digest, DIGEST_LEN)) {
1790 routerlist_remove_old_cached_routers_with_id(cutoff, i+1, hi, retain);
1791 cur_id = r->identity_digest;
1792 hi = i;
1795 if (hi>=0)
1796 routerlist_remove_old_cached_routers_with_id(cutoff, 0, hi, retain);
1797 routerlist_assert_ok(routerlist);
1799 done:
1800 digestmap_free(retain, NULL);
1804 * Code to parse a single router descriptor and insert it into the
1805 * routerlist. Return -1 if the descriptor was ill-formed; 0 if the
1806 * descriptor was well-formed but could not be added; and 1 if the
1807 * descriptor was added.
1809 * If we don't add it and <b>msg</b> is not NULL, then assign to
1810 * *<b>msg</b> a static string describing the reason for refusing the
1811 * descriptor.
1813 * This is used only by the controller.
1816 router_load_single_router(const char *s, const char **msg)
1818 routerinfo_t *ri;
1819 smartlist_t *lst;
1820 tor_assert(msg);
1821 *msg = NULL;
1823 if (!(ri = router_parse_entry_from_string(s, NULL))) {
1824 warn(LD_DIR, "Error parsing router descriptor; dropping.");
1825 *msg = "Couldn't parse router descriptor.";
1826 return -1;
1828 if (router_is_me(ri)) {
1829 warn(LD_DIR, "Router's identity key matches mine; dropping.");
1830 *msg = "Router's identity key matches mine.";
1831 routerinfo_free(ri);
1832 return 0;
1835 lst = smartlist_create();
1836 smartlist_add(lst, ri);
1837 routers_update_status_from_networkstatus(lst, 0);
1839 if (router_add_to_routerlist(ri, msg, 0, 0)<0) {
1840 warn(LD_DIR, "Couldn't add router to list: %s Dropping.",
1841 *msg?*msg:"(No message).");
1842 /* we've already assigned to *msg now, and ri is already freed */
1843 smartlist_free(lst);
1844 return 0;
1845 } else {
1846 control_event_descriptors_changed(lst);
1847 smartlist_free(lst);
1848 debug(LD_DIR, "Added router to list");
1849 return 1;
1853 /** Given a string <b>s</b> containing some routerdescs, parse it and put the
1854 * routers into our directory. If <b>from_cache</b> is false, the routers
1855 * are in response to a query to the network: cache them.
1857 * If <b>requested_fingerprints</b> is provided, it must contain a list of
1858 * uppercased identity fingerprints. Do not update any router whose
1859 * fingerprint is not on the list; after updating a router, remove its
1860 * fingerprint from the list.
1862 void
1863 router_load_routers_from_string(const char *s, int from_cache,
1864 smartlist_t *requested_fingerprints)
1866 smartlist_t *routers = smartlist_create(), *changed = smartlist_create();
1867 char fp[HEX_DIGEST_LEN+1];
1868 const char *msg;
1870 router_parse_list_from_string(&s, routers);
1872 routers_update_status_from_networkstatus(routers, !from_cache);
1874 info(LD_DIR, "%d elements to add", smartlist_len(routers));
1876 SMARTLIST_FOREACH(routers, routerinfo_t *, ri,
1878 base16_encode(fp, sizeof(fp), ri->cache_info.signed_descriptor_digest,
1879 DIGEST_LEN);
1880 if (requested_fingerprints) {
1881 if (smartlist_string_isin(requested_fingerprints, fp)) {
1882 smartlist_string_remove(requested_fingerprints, fp);
1883 } else {
1884 char *requested =
1885 smartlist_join_strings(requested_fingerprints," ",0,NULL);
1886 warn(LD_DIR,
1887 "We received a router descriptor with a fingerprint (%s) "
1888 "that we never requested. (We asked for: %s.) Dropping.",
1889 fp, requested);
1890 tor_free(requested);
1891 routerinfo_free(ri);
1892 continue;
1896 if (router_add_to_routerlist(ri, &msg, from_cache, !from_cache) >= 0)
1897 smartlist_add(changed, ri);
1900 if (smartlist_len(changed))
1901 control_event_descriptors_changed(changed);
1903 routerlist_assert_ok(routerlist);
1904 router_rebuild_store(0);
1906 smartlist_free(routers);
1907 smartlist_free(changed);
1910 /** Helper: return a newly allocated string containing the name of the filename
1911 * where we plan to cache <b>ns</b>. */
1912 static char *
1913 networkstatus_get_cache_filename(const networkstatus_t *ns)
1915 const char *datadir = get_options()->DataDirectory;
1916 size_t len = strlen(datadir)+64;
1917 char fp[HEX_DIGEST_LEN+1];
1918 char *fn = tor_malloc(len+1);
1919 base16_encode(fp, HEX_DIGEST_LEN+1, ns->identity_digest, DIGEST_LEN);
1920 tor_snprintf(fn, len, "%s/cached-status/%s",datadir,fp);
1921 return fn;
1924 /** Helper for smartlist_sort: Compare two networkstatus objects by
1925 * publication date. */
1926 static int
1927 _compare_networkstatus_published_on(const void **_a, const void **_b)
1929 const networkstatus_t *a = *_a, *b = *_b;
1930 if (a->published_on < b->published_on)
1931 return -1;
1932 else if (a->published_on > b->published_on)
1933 return 1;
1934 else
1935 return 0;
1938 /** Add the parsed neworkstatus in <b>ns</b> (with original document in
1939 * <b>s</b> to the disk cache (and the in-memory directory server cache) as
1940 * appropriate. */
1941 static int
1942 add_networkstatus_to_cache(const char *s,
1943 networkstatus_source_t source,
1944 networkstatus_t *ns)
1946 if (source != NS_FROM_CACHE) {
1947 char *fn = networkstatus_get_cache_filename(ns);
1948 if (write_str_to_file(fn, s, 0)<0) {
1949 notice(LD_FS, "Couldn't write cached network status to \"%s\"", fn);
1951 tor_free(fn);
1954 if (get_options()->DirPort)
1955 dirserv_set_cached_networkstatus_v2(s,
1956 ns->identity_digest,
1957 ns->published_on);
1959 return 0;
1962 /** How far in the future do we allow a network-status to get before removing
1963 * it? (seconds) */
1964 #define NETWORKSTATUS_ALLOW_SKEW (48*60*60)
1965 /** Given a string <b>s</b> containing a network status that we received at
1966 * <b>arrived_at</b> from <b>source</b>, try to parse it, see if we want to
1967 * store it, and put it into our cache is necessary.
1969 * If <b>source</b> is NS_FROM_DIR or NS_FROM_CACHE, do not replace our
1970 * own networkstatus_t (if we're a directory server).
1972 * If <b>source</b> is NS_FROM_CACHE, do not write our networkstatus_t to the
1973 * cache.
1975 * If <b>requested_fingerprints</b> is provided, it must contain a list of
1976 * uppercased identity fingerprints. Do not update any networkstatus whose
1977 * fingerprint is not on the list; after updating a networkstatus, remove its
1978 * fingerprint from the list.
1980 * Return 0 on success, -1 on failure.
1982 * Callers should make sure that routers_update_all_from_networkstatus() is
1983 * invoked after this function succeeds.
1986 router_set_networkstatus(const char *s, time_t arrived_at,
1987 networkstatus_source_t source, smartlist_t *requested_fingerprints)
1989 networkstatus_t *ns;
1990 int i, found;
1991 time_t now;
1992 int skewed = 0;
1993 trusted_dir_server_t *trusted_dir = NULL;
1994 const char *source_desc = NULL;
1995 char fp[HEX_DIGEST_LEN+1];
1996 char published[ISO_TIME_LEN+1];
1998 ns = networkstatus_parse_from_string(s);
1999 if (!ns) {
2000 warn(LD_DIR, "Couldn't parse network status.");
2001 return -1;
2003 base16_encode(fp, HEX_DIGEST_LEN+1, ns->identity_digest, DIGEST_LEN);
2004 if (!(trusted_dir =
2005 router_get_trusteddirserver_by_digest(ns->identity_digest))) {
2006 info(LD_DIR, "Network status was signed, but not by an authoritative "
2007 "directory we recognize.");
2008 if (!get_options()->DirPort) {
2009 networkstatus_free(ns);
2010 return 0;
2012 source_desc = fp;
2013 } else {
2014 source_desc = trusted_dir->description;
2016 now = time(NULL);
2017 if (arrived_at > now)
2018 arrived_at = now;
2020 ns->received_on = arrived_at;
2022 format_iso_time(published, ns->published_on);
2024 if (ns->published_on > now + NETWORKSTATUS_ALLOW_SKEW) {
2025 warn(LD_GENERAL, "Network status from %s was published in the future "
2026 "(%s GMT). Somebody is skewed here: check your clock. Not caching.",
2027 source_desc, published);
2028 skewed = 1;
2031 if (!networkstatus_list)
2032 networkstatus_list = smartlist_create();
2034 if (source == NS_FROM_DIR && router_digest_is_me(ns->identity_digest)) {
2035 /* Don't replace our own networkstatus when we get it from somebody else.*/
2036 networkstatus_free(ns);
2037 return 0;
2040 if (requested_fingerprints) {
2041 if (smartlist_string_isin(requested_fingerprints, fp)) {
2042 smartlist_string_remove(requested_fingerprints, fp);
2043 } else {
2044 char *requested =
2045 smartlist_join_strings(requested_fingerprints," ",0,NULL);
2046 warn(LD_DIR,
2047 "We received a network status with a fingerprint (%s) that we "
2048 "never requested. (We asked for: %s.) Dropping.", fp, requested);
2049 tor_free(requested);
2050 return 0;
2054 if (!trusted_dir) {
2055 if (!skewed && get_options()->DirPort) {
2056 add_networkstatus_to_cache(s, source, ns);
2057 networkstatus_free(ns);
2059 return 0;
2062 if (source != NS_FROM_CACHE && trusted_dir)
2063 trusted_dir->n_networkstatus_failures = 0;
2065 found = 0;
2066 for (i=0; i < smartlist_len(networkstatus_list); ++i) {
2067 networkstatus_t *old_ns = smartlist_get(networkstatus_list, i);
2069 if (!memcmp(old_ns->identity_digest, ns->identity_digest, DIGEST_LEN)) {
2070 if (!memcmp(old_ns->networkstatus_digest,
2071 ns->networkstatus_digest, DIGEST_LEN)) {
2072 /* Same one we had before. */
2073 networkstatus_free(ns);
2074 info(LD_DIR,
2075 "Not replacing network-status from %s (published %s); "
2076 "we already have it.",
2077 trusted_dir->description, published);
2078 if (old_ns->received_on < arrived_at) {
2079 if (source != NS_FROM_CACHE) {
2080 char *fn = networkstatus_get_cache_filename(old_ns);
2081 /* We use mtime to tell when it arrived, so update that. */
2082 touch_file(fn);
2083 tor_free(fn);
2085 old_ns->received_on = arrived_at;
2087 return 0;
2088 } else if (old_ns->published_on >= ns->published_on) {
2089 char old_published[ISO_TIME_LEN+1];
2090 format_iso_time(old_published, old_ns->published_on);
2091 info(LD_DIR,
2092 "Not replacing network-status from %s (published %s);"
2093 " we have a newer one (published %s) for this authority.",
2094 trusted_dir->description, published,
2095 old_published);
2096 networkstatus_free(ns);
2097 return 0;
2098 } else {
2099 networkstatus_free(old_ns);
2100 smartlist_set(networkstatus_list, i, ns);
2101 found = 1;
2102 break;
2107 if (!found)
2108 smartlist_add(networkstatus_list, ns);
2110 SMARTLIST_FOREACH(ns->entries, routerstatus_t *, rs,
2112 if (!router_get_by_descriptor_digest(rs->descriptor_digest))
2113 rs->need_to_mirror = 1;
2116 info(LD_DIR, "Setting networkstatus %s %s (published %s)",
2117 source == NS_FROM_CACHE?"cached from":
2118 (source==NS_FROM_DIR?"downloaded from":"generated for"),
2119 trusted_dir->description, published);
2120 networkstatus_list_has_changed = 1;
2122 smartlist_sort(networkstatus_list, _compare_networkstatus_published_on);
2124 if (!skewed)
2125 add_networkstatus_to_cache(s, source, ns);
2127 networkstatus_list_update_recent(now);
2129 return 0;
2132 /** How old do we allow a network-status to get before removing it
2133 * completely? */
2134 #define MAX_NETWORKSTATUS_AGE (10*24*60*60)
2135 /** Remove all very-old network_status_t objects from memory and from the
2136 * disk cache. */
2137 void
2138 networkstatus_list_clean(time_t now)
2140 int i;
2141 if (!networkstatus_list)
2142 return;
2144 for (i = 0; i < smartlist_len(networkstatus_list); ++i) {
2145 networkstatus_t *ns = smartlist_get(networkstatus_list, i);
2146 char *fname = NULL;;
2147 if (ns->published_on + MAX_NETWORKSTATUS_AGE > now)
2148 continue;
2149 /* Okay, this one is too old. Remove it from the list, and delete it
2150 * from the cache. */
2151 smartlist_del(networkstatus_list, i--);
2152 fname = networkstatus_get_cache_filename(ns);
2153 if (file_status(fname) == FN_FILE) {
2154 info(LD_DIR, "Removing too-old networkstatus in %s", fname);
2155 unlink(fname);
2157 tor_free(fname);
2158 if (get_options()->DirPort) {
2159 dirserv_set_cached_networkstatus_v2(NULL, ns->identity_digest, 0);
2161 networkstatus_free(ns);
2165 /** Helper for bsearching a list of routerstatus_t pointers.*/
2166 static int
2167 _compare_digest_to_routerstatus_entry(const void *_key, const void **_member)
2169 const char *key = _key;
2170 const routerstatus_t *rs = *_member;
2171 return memcmp(key, rs->identity_digest, DIGEST_LEN);
2174 /** Return the entry in <b>ns</b> for the identity digest <b>digest</b>, or
2175 * NULL if none was found. */
2176 static routerstatus_t *
2177 networkstatus_find_entry(networkstatus_t *ns, const char *digest)
2179 return smartlist_bsearch(ns->entries, digest,
2180 _compare_digest_to_routerstatus_entry);
2183 /** Return the consensus view of the status of the router whose digest is
2184 * <b>digest</b>, or NULL if we don't know about any such router. */
2185 local_routerstatus_t *
2186 router_get_combined_status_by_digest(const char *digest)
2188 if (!routerstatus_list)
2189 return NULL;
2190 return smartlist_bsearch(routerstatus_list, digest,
2191 _compare_digest_to_routerstatus_entry);
2194 /** Return true iff any networkstatus includes a descriptor whose digest
2195 * is that of <b>desc</b>. */
2196 static int
2197 signed_desc_digest_is_recognized(signed_descriptor_t *desc)
2199 routerstatus_t *rs;
2200 if (!networkstatus_list)
2201 return 0;
2203 SMARTLIST_FOREACH(networkstatus_list, networkstatus_t *, ns,
2205 if (!(rs = networkstatus_find_entry(ns, desc->identity_digest)))
2206 continue;
2207 if (!memcmp(rs->descriptor_digest,
2208 desc->signed_descriptor_digest, DIGEST_LEN))
2209 return 1;
2211 return 0;
2214 /* XXXX These should be configurable, perhaps? NM */
2215 #define AUTHORITY_NS_CACHE_INTERVAL 5*60
2216 #define NONAUTHORITY_NS_CACHE_INTERVAL 15*60
2217 /** We are a directory server, and so cache network_status documents.
2218 * Initiate downloads as needed to update them. For authorities, this means
2219 * asking each trusted directory for its network-status. For caches, this
2220 * means asking a random authority for all network-statuses.
2222 static void
2223 update_networkstatus_cache_downloads(time_t now)
2225 int authority = authdir_mode(get_options());
2226 int interval =
2227 authority ? AUTHORITY_NS_CACHE_INTERVAL : NONAUTHORITY_NS_CACHE_INTERVAL;
2229 if (last_networkstatus_download_attempted + interval >= now)
2230 return;
2231 if (!trusted_dir_servers)
2232 return;
2234 last_networkstatus_download_attempted = now;
2236 if (authority) {
2237 /* An authority launches a separate connection for everybody. */
2238 SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, ds,
2240 char resource[HEX_DIGEST_LEN+6];
2241 if (router_digest_is_me(ds->digest))
2242 continue;
2243 if (connection_get_by_type_addr_port_purpose(
2244 CONN_TYPE_DIR, ds->addr, ds->dir_port,
2245 DIR_PURPOSE_FETCH_NETWORKSTATUS)) {
2246 /* We are already fetching this one. */
2247 continue;
2249 strlcpy(resource, "fp/", sizeof(resource));
2250 base16_encode(resource+3, sizeof(resource)-3, ds->digest, DIGEST_LEN);
2251 strlcat(resource, ".z", sizeof(resource));
2252 directory_initiate_command_routerstatus(
2253 &ds->fake_status, DIR_PURPOSE_FETCH_NETWORKSTATUS,
2254 0, /* Not private */
2255 resource,
2256 NULL, 0 /* No payload. */);
2258 } else {
2259 /* A non-authority cache launches one connection to a random authority. */
2260 /* (Check whether we're currently fetching network-status objects.) */
2261 if (!connection_get_by_type_purpose(CONN_TYPE_DIR,
2262 DIR_PURPOSE_FETCH_NETWORKSTATUS))
2263 directory_get_from_dirserver(DIR_PURPOSE_FETCH_NETWORKSTATUS,"all.z",1);
2267 /*XXXX Should these be configurable? NM*/
2268 /** How old (in seconds) can a network-status be before we try replacing it? */
2269 #define NETWORKSTATUS_MAX_VALIDITY (48*60*60)
2270 /** How long (in seconds) does a client wait after getting a network status
2271 * before downloading the next in sequence? */
2272 #define NETWORKSTATUS_CLIENT_DL_INTERVAL (30*60)
2273 /* How many times do we allow a networkstatus download to fail before we
2274 * assume that the authority isn't publishing? */
2275 #define NETWORKSTATUS_N_ALLOWABLE_FAILURES 3
2276 /** We are not a directory cache or authority. Update our network-status list
2277 * by launching a new directory fetch for enough network-status documents "as
2278 * necessary". See function comments for implementation details.
2280 static void
2281 update_networkstatus_client_downloads(time_t now)
2283 int n_live = 0, needed = 0, n_running_dirservers, n_dirservers, i;
2284 int most_recent_idx = -1;
2285 trusted_dir_server_t *most_recent = NULL;
2286 time_t most_recent_received = 0;
2287 char *resource, *cp;
2288 size_t resource_len;
2290 if (connection_get_by_type_purpose(CONN_TYPE_DIR,
2291 DIR_PURPOSE_FETCH_NETWORKSTATUS))
2292 return;
2294 /* This is a little tricky. We want to download enough network-status
2295 * objects so that we have at least half of them under
2296 * NETWORKSTATUS_MAX_VALIDITY publication time. We want to download a new
2297 * *one* if the most recent one's publication time is under
2298 * NETWORKSTATUS_CLIENT_DL_INTERVAL.
2300 if (!trusted_dir_servers || !smartlist_len(trusted_dir_servers))
2301 return;
2302 n_dirservers = n_running_dirservers = smartlist_len(trusted_dir_servers);
2303 SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, ds,
2305 networkstatus_t *ns = networkstatus_get_by_digest(ds->digest);
2306 if (!ns)
2307 continue;
2308 if (ds->n_networkstatus_failures > NETWORKSTATUS_N_ALLOWABLE_FAILURES) {
2309 --n_running_dirservers;
2310 continue;
2312 if (ns->published_on > now-NETWORKSTATUS_MAX_VALIDITY)
2313 ++n_live;
2314 if (!most_recent || ns->received_on > most_recent_received) {
2315 most_recent_idx = ds_sl_idx; /* magic variable from FOREACH */
2316 most_recent = ds;
2317 most_recent_received = ns->received_on;
2321 /* Download enough so we have at least half live, but no more than all the
2322 * trusted dirservers we know.
2324 if (n_live < (n_dirservers/2)+1)
2325 needed = (n_dirservers/2)+1-n_live;
2326 if (needed > n_running_dirservers)
2327 needed = n_running_dirservers;
2329 if (needed)
2330 info(LD_DIR, "For %d/%d running directory servers, we have %d live"
2331 " network-status documents. Downloading %d.",
2332 n_running_dirservers, n_dirservers, n_live, needed);
2334 /* Also, download at least 1 every NETWORKSTATUS_CLIENT_DL_INTERVAL. */
2335 if (n_running_dirservers &&
2336 most_recent_received < now-NETWORKSTATUS_CLIENT_DL_INTERVAL &&
2337 needed < 1) {
2338 info(LD_DIR, "Our most recent network-status document (from %s) "
2339 "is %d seconds old; downloading another.",
2340 most_recent?most_recent->description:"nobody",
2341 (int)(now-most_recent_received));
2342 needed = 1;
2345 if (!needed)
2346 return;
2348 /* If no networkstatus was found, choose a dirserver at random as "most
2349 * recent". */
2350 if (most_recent_idx<0)
2351 most_recent_idx = crypto_rand_int(n_dirservers);
2353 /* Build a request string for all the resources we want. */
2354 resource_len = needed * (HEX_DIGEST_LEN+1) + 6;
2355 resource = tor_malloc(resource_len);
2356 memcpy(resource, "fp/", 3);
2357 cp = resource+3;
2358 for (i = most_recent_idx+1; needed; ++i) {
2359 trusted_dir_server_t *ds;
2360 if (i >= n_dirservers)
2361 i = 0;
2362 ds = smartlist_get(trusted_dir_servers, i);
2363 if (ds->n_networkstatus_failures > NETWORKSTATUS_N_ALLOWABLE_FAILURES)
2364 continue;
2365 base16_encode(cp, HEX_DIGEST_LEN+1, ds->digest, DIGEST_LEN);
2366 cp += HEX_DIGEST_LEN;
2367 --needed;
2368 if (needed)
2369 *cp++ = '+';
2371 memcpy(cp, ".z", 3);
2372 directory_get_from_dirserver(DIR_PURPOSE_FETCH_NETWORKSTATUS, resource, 1);
2373 tor_free(resource);
2376 /** Launch requests for networkstatus documents as appropriate. */
2377 void
2378 update_networkstatus_downloads(time_t now)
2380 or_options_t *options = get_options();
2381 if (server_mode(options) && options->DirPort)
2382 update_networkstatus_cache_downloads(time(NULL));
2383 else
2384 update_networkstatus_client_downloads(time(NULL));
2387 /** Decide whether a given addr:port is definitely accepted,
2388 * definitely rejected, probably accepted, or probably rejected by a
2389 * given policy. If <b>addr</b> is 0, we don't know the IP of the
2390 * target address. If <b>port</b> is 0, we don't know the port of the
2391 * target address.
2393 * For now, the algorithm is pretty simple: we look for definite and
2394 * uncertain matches. The first definite match is what we guess; if
2395 * it was preceded by no uncertain matches of the opposite policy,
2396 * then the guess is definite; otherwise it is probable. (If we
2397 * have a known addr and port, all matches are definite; if we have an
2398 * unknown addr/port, any address/port ranges other than "all" are
2399 * uncertain.)
2401 * We could do better by assuming that some ranges never match typical
2402 * addresses (127.0.0.1, and so on). But we'll try this for now.
2404 addr_policy_result_t
2405 router_compare_addr_to_addr_policy(uint32_t addr, uint16_t port,
2406 addr_policy_t *policy)
2408 int maybe_reject = 0;
2409 int maybe_accept = 0;
2410 int match = 0;
2411 int maybe = 0;
2412 addr_policy_t *tmpe;
2414 for (tmpe=policy; tmpe; tmpe=tmpe->next) {
2415 maybe = 0;
2416 if (!addr) {
2417 /* Address is unknown. */
2418 if ((port >= tmpe->prt_min && port <= tmpe->prt_max) ||
2419 (!port && tmpe->prt_min<=1 && tmpe->prt_max>=65535)) {
2420 /* The port definitely matches. */
2421 if (tmpe->msk == 0) {
2422 match = 1;
2423 } else {
2424 maybe = 1;
2426 } else if (!port) {
2427 /* The port maybe matches. */
2428 maybe = 1;
2430 } else {
2431 /* Address is known */
2432 if ((addr & tmpe->msk) == (tmpe->addr & tmpe->msk)) {
2433 if (port >= tmpe->prt_min && port <= tmpe->prt_max) {
2434 /* Exact match for the policy */
2435 match = 1;
2436 } else if (!port) {
2437 maybe = 1;
2441 if (maybe) {
2442 if (tmpe->policy_type == ADDR_POLICY_REJECT)
2443 maybe_reject = 1;
2444 else
2445 maybe_accept = 1;
2447 if (match) {
2448 if (tmpe->policy_type == ADDR_POLICY_ACCEPT) {
2449 /* If we already hit a clause that might trigger a 'reject', than we
2450 * can't be sure of this certain 'accept'.*/
2451 return maybe_reject ? ADDR_POLICY_PROBABLY_ACCEPTED :
2452 ADDR_POLICY_ACCEPTED;
2453 } else {
2454 return maybe_accept ? ADDR_POLICY_PROBABLY_REJECTED :
2455 ADDR_POLICY_REJECTED;
2459 /* accept all by default. */
2460 return maybe_reject ? ADDR_POLICY_PROBABLY_ACCEPTED : ADDR_POLICY_ACCEPTED;
2463 /** Return 1 if all running sufficiently-stable routers will reject
2464 * addr:port, return 0 if any might accept it. */
2466 router_exit_policy_all_routers_reject(uint32_t addr, uint16_t port,
2467 int need_uptime)
2469 addr_policy_result_t r;
2470 if (!routerlist) return 1;
2472 SMARTLIST_FOREACH(routerlist->routers, routerinfo_t *, router,
2474 if (router->is_running &&
2475 !router_is_unreliable(router, need_uptime, 0)) {
2476 r = router_compare_addr_to_addr_policy(addr, port, router->exit_policy);
2477 if (r != ADDR_POLICY_REJECTED && r != ADDR_POLICY_PROBABLY_REJECTED)
2478 return 0; /* this one could be ok. good enough. */
2481 return 1; /* all will reject. */
2485 * If <b>policy</b> implicitly allows connections to any port in the
2486 * IP set <b>addr</b>/<b>mask</b>, then set *<b>policy_out</b> to the
2487 * part of the policy that allows it, and return 1. Else return 0.
2489 * A policy allows an IP:Port combination <em>implicitly</em> if
2490 * it is included in a *: pattern, or in a fallback pattern.
2492 static int
2493 policy_includes_addr_mask_implicitly(addr_policy_t *policy,
2494 uint32_t addr, uint32_t mask,
2495 addr_policy_t **policy_out)
2497 uint32_t addr2;
2498 tor_assert(policy_out);
2499 addr &= mask;
2500 addr2 = addr | ~mask;
2501 for (; policy; policy=policy->next) {
2502 /* Does this policy cover all of the address range we're looking at? */
2503 /* Boolean logic time: range X is contained in range Y if, for
2504 * each bit B, all possible values of B in X are values of B in Y.
2505 * In "addr", we have every fixed bit set to its value, and every
2506 * free bit set to 0. In "addr2", we have every fixed bit set to
2507 * its value, and every free bit set to 1. So if addr and addr2 are
2508 * both in the policy, the range is covered by the policy.
2510 uint32_t p_addr = policy->addr & policy->msk;
2511 if (p_addr == (addr & policy->msk) &&
2512 p_addr == (addr2 & policy->msk) &&
2513 (policy->prt_min <= 1 && policy->prt_max == 65535)) {
2514 return 0;
2516 /* Does this policy cover some of the address range we're looking at? */
2517 /* Boolean logic time: range X and range Y intersect if there is
2518 * some z such that z & Xmask == Xaddr and z & Ymask == Yaddr.
2519 * This is FALSE iff there is some bit b where Xmask == yMask == 1
2520 * and Xaddr != Yaddr. So if X intersects with Y iff at every
2521 * place where Xmask&Ymask==1, Xaddr == Yaddr, or equivalently,
2522 * Xaddr&Xmask&Ymask == Yaddr&Xmask&Ymask.
2524 if ((policy->addr & policy->msk & mask) == (addr & policy->msk) &&
2525 policy->policy_type == ADDR_POLICY_ACCEPT) {
2526 *policy_out = policy;
2527 return 1;
2530 *policy_out = NULL;
2531 return 1;
2534 /** If <b>policy</b> implicitly allows connections to any port on
2535 * 127.*, 192.168.*, etc, then warn (if <b>should_warn</b> is set) and return
2536 * true. Else return false.
2539 exit_policy_implicitly_allows_local_networks(addr_policy_t *policy,
2540 int should_warn)
2542 addr_policy_t *p;
2543 int r=0,i;
2544 static struct {
2545 uint32_t addr; uint32_t mask; const char *network;
2546 } private_networks[] = {
2547 { 0x7f000000, 0xff000000, "localhost (127.0.0.0/8)" },
2548 { 0x0a000000, 0xff000000, "addresses in private network 10.0.0.0/8" },
2549 { 0xa9fe0000, 0xffff0000, "addresses in private network 169.254.0.0/16" },
2550 { 0xac100000, 0xfff00000, "addresses in private network 172.16.0.0/12" },
2551 { 0xc0a80000, 0xffff0000, "addresses in private network 192.168.0.0/16" },
2552 { 0,0,NULL},
2554 for (i=0; private_networks[i].addr; ++i) {
2555 p = NULL;
2556 /* log_fn(LOG_INFO,"Checking network %s", private_networks[i].network); */
2557 if (policy_includes_addr_mask_implicitly(
2558 policy, private_networks[i].addr, private_networks[i].mask, &p)) {
2559 if (should_warn)
2560 warn(LD_CONFIG, "Exit policy %s implicitly accepts %s",
2561 p?p->string:"(default)",
2562 private_networks[i].network);
2563 r = 1;
2567 return r;
2570 /** Return true iff <b>router</b> does not permit exit streams.
2573 router_exit_policy_rejects_all(routerinfo_t *router)
2575 return router_compare_addr_to_addr_policy(0, 0, router->exit_policy)
2576 == ADDR_POLICY_REJECTED;
2579 /** Add to the list of authorized directory servers one at
2580 * <b>address</b>:<b>port</b>, with identity key <b>digest</b>. If
2581 * <b>address</b> is NULL, add ourself. */
2582 void
2583 add_trusted_dir_server(const char *nickname, const char *address,
2584 uint16_t port, const char *digest, int supports_v1)
2586 trusted_dir_server_t *ent;
2587 uint32_t a;
2588 char *hostname = NULL;
2589 size_t dlen;
2590 if (!trusted_dir_servers)
2591 trusted_dir_servers = smartlist_create();
2593 if (!address) { /* The address is us; we should guess. */
2594 if (resolve_my_address(get_options(), &a, &hostname) < 0) {
2595 warn(LD_CONFIG,
2596 "Couldn't find a suitable address when adding ourself as a "
2597 "trusted directory server.");
2598 return;
2600 } else {
2601 if (tor_lookup_hostname(address, &a)) {
2602 warn(LD_CONFIG, "Unable to lookup address for directory server at '%s'",
2603 address);
2604 return;
2606 hostname = tor_strdup(address);
2607 a = ntohl(a);
2610 ent = tor_malloc_zero(sizeof(trusted_dir_server_t));
2611 ent->nickname = nickname ? tor_strdup(nickname) : NULL;
2612 ent->address = hostname;
2613 ent->addr = a;
2614 ent->dir_port = port;
2615 ent->is_running = 1;
2616 ent->is_v1_authority = supports_v1;
2617 memcpy(ent->digest, digest, DIGEST_LEN);
2619 dlen = 64 + strlen(hostname) + (nickname?strlen(nickname):0);
2620 ent->description = tor_malloc(dlen);
2621 if (nickname)
2622 tor_snprintf(ent->description, dlen, "directory server \"%s\" at %s:%d",
2623 nickname, hostname, (int)port);
2624 else
2625 tor_snprintf(ent->description, dlen, "directory server at %s:%d",
2626 hostname, (int)port);
2628 ent->fake_status.addr = ent->addr;
2629 memcpy(ent->fake_status.identity_digest, digest, DIGEST_LEN);
2630 if (nickname)
2631 strlcpy(ent->fake_status.nickname, nickname,
2632 sizeof(ent->fake_status.nickname));
2633 else
2634 ent->fake_status.nickname[0] = '\0';
2635 ent->fake_status.dir_port = ent->dir_port;
2637 smartlist_add(trusted_dir_servers, ent);
2640 /** Free storage held in <b>ds</b> */
2641 void
2642 trusted_dir_server_free(trusted_dir_server_t *ds)
2644 tor_free(ds->nickname);
2645 tor_free(ds->description);
2646 tor_free(ds->address);
2647 tor_free(ds);
2650 /** Remove all members from the list of trusted dir servers. */
2651 void
2652 clear_trusted_dir_servers(void)
2654 if (trusted_dir_servers) {
2655 SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, ent,
2656 trusted_dir_server_free(ent));
2657 smartlist_clear(trusted_dir_servers);
2658 } else {
2659 trusted_dir_servers = smartlist_create();
2663 /** Return the network status with a given identity digest. */
2664 networkstatus_t *
2665 networkstatus_get_by_digest(const char *digest)
2667 SMARTLIST_FOREACH(networkstatus_list, networkstatus_t *, ns,
2669 if (!memcmp(ns->identity_digest, digest, DIGEST_LEN))
2670 return ns;
2672 return NULL;
2675 /** If the network-status list has changed since the last time we called this
2676 * function, update the status of every routerinfo from the network-status
2677 * list.
2679 void
2680 routers_update_all_from_networkstatus(void)
2682 #define SELF_OPINION_INTERVAL 90*60
2683 routerinfo_t *me;
2684 time_t now;
2685 if (!routerlist || !networkstatus_list ||
2686 (!networkstatus_list_has_changed && !routerstatus_list_has_changed))
2687 return;
2689 now = time(NULL);
2690 if (networkstatus_list_has_changed)
2691 routerstatus_list_update_from_networkstatus(now);
2693 routers_update_status_from_networkstatus(routerlist->routers, 0);
2695 me = router_get_my_routerinfo();
2696 if (me && !have_warned_about_unverified_status) {
2697 int n_recent = 0, n_listing = 0, n_valid = 0, n_named = 0;
2698 routerstatus_t *rs;
2699 SMARTLIST_FOREACH(networkstatus_list, networkstatus_t *, ns,
2701 if (ns->received_on + SELF_OPINION_INTERVAL < now)
2702 continue;
2703 ++n_recent;
2704 if (!(rs = networkstatus_find_entry(ns, me->cache_info.identity_digest)))
2705 continue;
2706 ++n_listing;
2707 if (rs->is_valid)
2708 ++n_valid;
2709 if (rs->is_named)
2710 ++n_named;
2713 if (n_recent >= 2 && n_listing >= 2) {
2714 /* XXX When we have more than 3 dirservers, these warnings
2715 * might become spurious depending on which combination of
2716 * network-statuses we have. Perhaps we should wait until we
2717 * have tried all of them? -RD */
2718 if (n_valid <= n_recent/2) {
2719 warn(LD_GENERAL,
2720 "%d/%d recent directory servers list us as invalid. Please "
2721 "consider sending your identity fingerprint to the tor-ops.",
2722 n_recent-n_valid, n_recent);
2723 have_warned_about_unverified_status = 1;
2724 } else if (!n_named) { // (n_named <= n_recent/2) {
2725 warn(LD_GENERAL, "0/%d recent directory servers recognize this "
2726 "server. Please consider sending your identity fingerprint to "
2727 "the tor-ops.",
2728 n_recent);
2729 have_warned_about_unverified_status = 1;
2734 entry_guards_set_status_from_directory();
2736 if (!have_warned_about_old_version) {
2737 int n_recent = 0;
2738 int n_recommended = 0;
2739 int is_server = server_mode(get_options());
2740 version_status_t consensus = VS_RECOMMENDED;
2741 SMARTLIST_FOREACH(networkstatus_list, networkstatus_t *, ns,
2743 version_status_t vs;
2744 if (!ns->recommends_versions ||
2745 ns->received_on + SELF_OPINION_INTERVAL < now )
2746 continue;
2747 vs = tor_version_is_obsolete(
2748 VERSION, is_server ? ns->server_versions : ns->client_versions);
2749 if (vs == VS_RECOMMENDED)
2750 ++n_recommended;
2751 if (n_recent++ == 0) {
2752 consensus = vs;
2753 } else if (consensus != vs) {
2754 consensus = version_status_join(consensus, vs);
2757 if (n_recent > 2 && n_recommended < n_recent/2) {
2758 if (consensus == VS_NEW || consensus == VS_NEW_IN_SERIES) {
2759 if (!have_warned_about_new_version) {
2760 notice(LD_GENERAL, "This version of Tor (%s) is newer than any "
2761 "recommended version%s, according to %d/%d recent network "
2762 "statuses.",
2763 VERSION,
2764 consensus == VS_NEW_IN_SERIES ? " in its series" : "",
2765 n_recent-n_recommended, n_recent);
2766 have_warned_about_new_version = 1;
2768 } else {
2769 notice(LD_GENERAL, "This version of Tor (%s) is %s, according to "
2770 "%d/%d recent network statuses.",
2771 VERSION, consensus == VS_OLD ? "obsolete" : "not recommended",
2772 n_recent-n_recommended, n_recent);
2773 have_warned_about_old_version = 1;
2775 } else {
2776 info(LD_GENERAL, "%d/%d recent directories think my version is ok.",
2777 n_recommended, n_recent);
2781 routerstatus_list_has_changed = 0;
2784 /** Allow any network-status newer than this to influence our view of who's
2785 * running. */
2786 #define DEFAULT_RUNNING_INTERVAL 60*60
2787 /** If possible, always allow at least this many network-statuses to influence
2788 * our view of who's running. */
2789 #define MIN_TO_INFLUENCE_RUNNING 3
2791 /** Change the is_recent field of each member of networkstatus_list so that
2792 * all members more recent than DEFAULT_RUNNING_INTERVAL are recent, and
2793 * at least the MIN_TO_INFLUENCE_RUNNING most recent members are resent, and no
2794 * others are recent. Set networkstatus_list_has_changed if anything happeed.
2796 void
2797 networkstatus_list_update_recent(time_t now)
2799 int n_statuses, n_recent, changed, i;
2800 char published[ISO_TIME_LEN+1];
2802 if (!networkstatus_list)
2803 return;
2805 n_statuses = smartlist_len(networkstatus_list);
2806 n_recent = 0;
2807 changed = 0;
2808 for (i=n_statuses-1; i >= 0; --i) {
2809 networkstatus_t *ns = smartlist_get(networkstatus_list, i);
2810 trusted_dir_server_t *ds =
2811 router_get_trusteddirserver_by_digest(ns->identity_digest);
2812 const char *src = ds?ds->description:ns->source_address;
2813 if (n_recent < MIN_TO_INFLUENCE_RUNNING ||
2814 ns->published_on + DEFAULT_RUNNING_INTERVAL > now) {
2815 if (!ns->is_recent) {
2816 format_iso_time(published, ns->published_on);
2817 info(LD_DIR,
2818 "Networkstatus from %s (published %s) is now \"recent\"",
2819 src, published);
2820 changed = 1;
2822 ns->is_recent = 1;
2823 ++n_recent;
2824 } else {
2825 if (ns->is_recent) {
2826 format_iso_time(published, ns->published_on);
2827 info(LD_DIR,
2828 "Networkstatus from %s (published %s) is no longer \"recent\"",
2829 src, published);
2830 changed = 1;
2831 ns->is_recent = 0;
2835 if (changed)
2836 networkstatus_list_has_changed = 1;
2839 /** Helper for routerstatus_list_update_from_networkstatus: remember how many
2840 * authorities recommend a given descriptor digest. */
2841 typedef struct {
2842 routerstatus_t *rs;
2843 int count;
2844 } desc_digest_count_t;
2846 /** Update our view of router status (as stored in routerstatus_list) from the
2847 * current set of network status documents (as stored in networkstatus_list).
2848 * Do nothing unless the network status list has changed since the last time
2849 * this function was called.
2851 static void
2852 routerstatus_list_update_from_networkstatus(time_t now)
2854 or_options_t *options = get_options();
2855 int n_trusted, n_statuses, n_recent = 0, n_naming = 0;
2856 int i, j, warned;
2857 int *index, *size;
2858 networkstatus_t **networkstatus;
2859 smartlist_t *result;
2860 strmap_t *name_map;
2861 char conflict[DIGEST_LEN]; /* Sentinel value */
2862 desc_digest_count_t *digest_counts = NULL;
2864 networkstatus_list_update_recent(now);
2866 if (!networkstatus_list_has_changed)
2867 return;
2868 if (!networkstatus_list)
2869 networkstatus_list = smartlist_create();
2870 if (!routerstatus_list)
2871 routerstatus_list = smartlist_create();
2872 if (!trusted_dir_servers)
2873 trusted_dir_servers = smartlist_create();
2874 if (!warned_conflicts)
2875 warned_conflicts = smartlist_create();
2877 n_trusted = smartlist_len(trusted_dir_servers);
2878 n_statuses = smartlist_len(networkstatus_list);
2880 if (n_statuses < (n_trusted/2)+1) {
2881 /* Not enough statuses to adjust status. */
2882 notice(LD_DIR,"Not enough statuses to update router status list. (%d/%d)",
2883 n_statuses, n_trusted);
2884 return;
2887 info(LD_DIR, "Rebuilding router status list.");
2889 index = tor_malloc(sizeof(int)*n_statuses);
2890 size = tor_malloc(sizeof(int)*n_statuses);
2891 networkstatus = tor_malloc(sizeof(networkstatus_t *)*n_statuses);
2892 for (i = 0; i < n_statuses; ++i) {
2893 index[i] = 0;
2894 networkstatus[i] = smartlist_get(networkstatus_list, i);
2895 size[i] = smartlist_len(networkstatus[i]->entries);
2896 if (networkstatus[i]->binds_names)
2897 ++n_naming;
2898 if (networkstatus[i]->is_recent)
2899 ++n_recent;
2902 /** Iterate over all entries in all networkstatuses, and build
2903 * name_map as a map from lc nickname to identity digest. If there
2904 * is a conflict on that nickname, map the lc nickname to conflict.
2906 name_map = strmap_new();
2907 memset(conflict, 0xff, sizeof(conflict));
2908 for (i = 0; i < n_statuses; ++i) {
2909 if (!networkstatus[i]->binds_names)
2910 continue;
2911 SMARTLIST_FOREACH(networkstatus[i]->entries, routerstatus_t *, rs,
2913 const char *other_digest;
2914 if (!rs->is_named)
2915 continue;
2916 other_digest = strmap_get_lc(name_map, rs->nickname);
2917 warned = smartlist_string_isin(warned_conflicts, rs->nickname);
2918 if (!other_digest) {
2919 strmap_set_lc(name_map, rs->nickname, rs->identity_digest);
2920 if (warned)
2921 smartlist_string_remove(warned_conflicts, rs->nickname);
2922 } else if (memcmp(other_digest, rs->identity_digest, DIGEST_LEN) &&
2923 other_digest != conflict) {
2924 if (!warned) {
2925 int should_warn = options->DirPort && options->AuthoritativeDir;
2926 char fp1[HEX_DIGEST_LEN+1];
2927 char fp2[HEX_DIGEST_LEN+1];
2928 base16_encode(fp1, sizeof(fp1), other_digest, DIGEST_LEN);
2929 base16_encode(fp2, sizeof(fp2), rs->identity_digest, DIGEST_LEN);
2930 log_fn(should_warn ? LOG_WARN : LOG_INFO, LD_DIR,
2931 "Naming authorities disagree about which key goes with %s. "
2932 "($%s vs $%s)",
2933 rs->nickname, fp1, fp2);
2934 strmap_set_lc(name_map, rs->nickname, conflict);
2935 smartlist_add(warned_conflicts, tor_strdup(rs->nickname));
2937 } else {
2938 if (warned)
2939 smartlist_string_remove(warned_conflicts, rs->nickname);
2944 result = smartlist_create();
2945 digest_counts = tor_malloc_zero(sizeof(desc_digest_count_t)*n_statuses);
2947 /* Iterate through all of the sorted routerstatus lists in lockstep.
2948 * Invariants:
2949 * - For 0 <= i < n_statuses: index[i] is an index into
2950 * networkstatus[i]->entries, which has size[i] elements.
2951 * - For i1, i2, j such that 0 <= i1 < n_statuses, 0 <= i2 < n_statues, 0 <=
2952 * j < index[i1], networkstatus[i1]->entries[j]->identity_digest <
2953 * networkstatus[i2]->entries[index[i2]]->identity_digest.
2955 * (That is, the indices are always advanced past lower digest before
2956 * higher.)
2958 while (1) {
2959 int n_running=0, n_named=0, n_valid=0, n_listing=0;
2960 int n_v2_dir=0, n_fast=0, n_stable=0, n_exit=0;
2961 int n_desc_digests=0, highest_count=0;
2962 const char *the_name = NULL;
2963 local_routerstatus_t *rs_out, *rs_old;
2964 routerstatus_t *rs, *most_recent;
2965 networkstatus_t *ns;
2966 const char *lowest = NULL;
2968 /* Find out which of the digests appears first. */
2969 for (i = 0; i < n_statuses; ++i) {
2970 if (index[i] < size[i]) {
2971 rs = smartlist_get(networkstatus[i]->entries, index[i]);
2972 if (!lowest || memcmp(rs->identity_digest, lowest, DIGEST_LEN)<0)
2973 lowest = rs->identity_digest;
2976 if (!lowest) {
2977 /* We're out of routers. Great! */
2978 break;
2980 /* Okay. The routers at networkstatus[i]->entries[index[i]] whose digests
2981 * match "lowest" are next in order. Iterate over them, incrementing those
2982 * index[i] as we go. */
2983 for (i = 0; i < n_statuses; ++i) {
2984 if (index[i] >= size[i])
2985 continue;
2986 ns = networkstatus[i];
2987 rs = smartlist_get(ns->entries, index[i]);
2988 if (memcmp(rs->identity_digest, lowest, DIGEST_LEN))
2989 continue;
2990 /* At this point, we know that we're looking at a routersatus with
2991 * identity "lowest".
2993 ++index[i];
2994 ++n_listing;
2995 /* Should we name this router? Only if all the names from naming
2996 * authorities match. */
2997 if (rs->is_named && ns->binds_names) {
2998 if (!the_name)
2999 the_name = rs->nickname;
3000 if (!strcasecmp(rs->nickname, the_name)) {
3001 ++n_named;
3002 } else if (strcmp(the_name,"**mismatch**")) {
3003 char hd[HEX_DIGEST_LEN+1];
3004 base16_encode(hd, HEX_DIGEST_LEN+1, rs->identity_digest, DIGEST_LEN);
3005 if (! smartlist_string_isin(warned_conflicts, hd)) {
3006 warn(LD_DIR, "Naming authorities disagree about nicknames for $%s "
3007 "(\"%s\" vs \"%s\")",
3008 hd, the_name, rs->nickname);
3009 smartlist_add(warned_conflicts, tor_strdup(hd));
3011 the_name = "**mismatch**";
3014 /* Keep a running count of how often which descriptor digests
3015 * appear. */
3016 for (j = 0; j < n_desc_digests; ++j) {
3017 if (!memcmp(rs->descriptor_digest,
3018 digest_counts[j].rs->descriptor_digest, DIGEST_LEN)) {
3019 if (++digest_counts[j].count > highest_count)
3020 highest_count = digest_counts[j].count;
3021 goto found;
3024 digest_counts[n_desc_digests].rs = rs;
3025 digest_counts[n_desc_digests].count = 1;
3026 if (!highest_count)
3027 highest_count = 1;
3028 ++n_desc_digests;
3029 found:
3030 /* Now tally up the easily-tallied flags. */
3031 if (rs->is_valid)
3032 ++n_valid;
3033 if (rs->is_running && ns->is_recent)
3034 ++n_running;
3035 if (rs->is_exit)
3036 ++n_exit;
3037 if (rs->is_fast)
3038 ++n_fast;
3039 if (rs->is_stable)
3040 ++n_stable;
3041 if (rs->is_v2_dir)
3042 ++n_v2_dir;
3044 /* Go over the descriptor digests and figure out which descriptor we
3045 * want. */
3046 most_recent = NULL;
3047 for (i = 0; i < n_desc_digests; ++i) {
3048 /* If any digest appears twice or more, ignore those that don't.*/
3049 if (highest_count >= 2 && digest_counts[i].count < 2)
3050 continue;
3051 if (!most_recent ||
3052 digest_counts[i].rs->published_on > most_recent->published_on)
3053 most_recent = digest_counts[i].rs;
3055 rs_out = tor_malloc_zero(sizeof(local_routerstatus_t));
3056 memcpy(&rs_out->status, most_recent, sizeof(routerstatus_t));
3057 /* Copy status info about this router, if we had any before. */
3058 if ((rs_old = router_get_combined_status_by_digest(lowest))) {
3059 if (!memcmp(rs_out->status.descriptor_digest,
3060 most_recent->descriptor_digest, DIGEST_LEN)) {
3061 rs_out->n_download_failures = rs_old->n_download_failures;
3062 rs_out->next_attempt_at = rs_old->next_attempt_at;
3064 rs_out->name_lookup_warned = rs_old->name_lookup_warned;
3066 smartlist_add(result, rs_out);
3067 debug(LD_DIR, "Router '%s' is listed by %d/%d directories, "
3068 "named by %d/%d, validated by %d/%d, and %d/%d recent directories "
3069 "think it's running.",
3070 rs_out->status.nickname,
3071 n_listing, n_statuses, n_named, n_naming, n_valid, n_statuses,
3072 n_running, n_recent);
3073 rs_out->status.is_named = 0;
3074 if (the_name && strcmp(the_name, "**mismatch**") && n_named > 0) {
3075 const char *d = strmap_get_lc(name_map, the_name);
3076 if (d && d != conflict)
3077 rs_out->status.is_named = 1;
3078 if (smartlist_string_isin(warned_conflicts, rs_out->status.nickname))
3079 smartlist_string_remove(warned_conflicts, rs_out->status.nickname);
3081 if (rs_out->status.is_named)
3082 strlcpy(rs_out->status.nickname, the_name,
3083 sizeof(rs_out->status.nickname));
3084 rs_out->status.is_valid = n_valid > n_statuses/2;
3085 rs_out->status.is_running = n_running > n_recent/2;
3086 rs_out->status.is_exit = n_exit > n_statuses/2;
3087 rs_out->status.is_fast = n_fast > n_statuses/2;
3088 rs_out->status.is_stable = n_stable > n_statuses/2;
3089 rs_out->status.is_v2_dir = n_v2_dir > n_statuses/2;
3091 SMARTLIST_FOREACH(routerstatus_list, local_routerstatus_t *, rs,
3092 local_routerstatus_free(rs));
3093 smartlist_free(routerstatus_list);
3094 routerstatus_list = result;
3096 tor_free(networkstatus);
3097 tor_free(index);
3098 tor_free(size);
3099 tor_free(digest_counts);
3100 strmap_free(name_map, NULL);
3102 networkstatus_list_has_changed = 0;
3103 routerstatus_list_has_changed = 1;
3106 /** Given a list <b>routers</b> of routerinfo_t *, update each routers's
3107 * is_named, is_verified, and is_running fields according to our current
3108 * networkstatus_t documents. */
3109 void
3110 routers_update_status_from_networkstatus(smartlist_t *routers,
3111 int reset_failures)
3113 trusted_dir_server_t *ds;
3114 local_routerstatus_t *rs;
3115 routerstatus_t *rs2;
3116 or_options_t *options = get_options();
3117 int authdir = options->AuthoritativeDir;
3118 int namingdir = options->AuthoritativeDir &&
3119 options->NamingAuthoritativeDir;
3121 if (!routerstatus_list)
3122 return;
3124 SMARTLIST_FOREACH(routers, routerinfo_t *, router,
3126 const char *digest = router->cache_info.identity_digest;
3127 rs = router_get_combined_status_by_digest(digest);
3128 ds = router_get_trusteddirserver_by_digest(digest);
3130 if (!rs)
3131 continue;
3133 if (!namingdir)
3134 router->is_named = rs->status.is_named;
3136 if (!authdir) {
3137 /* If we're an authdir, don't believe others. */
3138 router->is_verified = rs->status.is_valid;
3139 router->is_running = rs->status.is_running;
3140 router->is_fast = rs->status.is_fast;
3141 router->is_stable = rs->status.is_stable;
3143 if (router->is_running && ds) {
3144 ds->n_networkstatus_failures = 0;
3146 if (reset_failures) {
3147 rs->n_download_failures = 0;
3148 rs->next_attempt_at = 0;
3151 /* Note that we have this descriptor. This may be redundant? */
3152 SMARTLIST_FOREACH(networkstatus_list, networkstatus_t *, ns,
3154 rs2 = networkstatus_find_entry(ns, router->cache_info.identity_digest);
3155 if (rs2 && !memcmp(rs2->descriptor_digest,
3156 router->cache_info.signed_descriptor_digest,
3157 DIGEST_LEN))
3158 rs2->need_to_mirror = 0;
3163 /** For every router descriptor we are currently downloading by descriptor
3164 * digest, set result[d] to 1. */
3165 static void
3166 list_pending_descriptor_downloads(digestmap_t *result)
3168 const char *prefix = "d/";
3169 size_t p_len = strlen(prefix);
3170 int i, n_conns;
3171 connection_t **carray;
3172 smartlist_t *tmp = smartlist_create();
3174 tor_assert(result);
3175 get_connection_array(&carray, &n_conns);
3177 for (i = 0; i < n_conns; ++i) {
3178 connection_t *conn = carray[i];
3179 if (conn->type == CONN_TYPE_DIR &&
3180 conn->purpose == DIR_PURPOSE_FETCH_SERVERDESC &&
3181 !conn->marked_for_close) {
3182 if (!strcmpstart(conn->requested_resource, prefix))
3183 dir_split_resource_into_fingerprints(conn->requested_resource+p_len,
3184 tmp, NULL, 1);
3187 SMARTLIST_FOREACH(tmp, char *, d,
3189 digestmap_set(result, d, (void*)1);
3190 tor_free(d);
3192 smartlist_free(tmp);
3195 /** Launch downloads for the all the descriptors whose digests are listed
3196 * as digests[i] for lo <= i < hi. (Lo and hi may be out of range.)
3197 * If <b>source</b> is given, download from <b>source</b>; otherwise,
3198 * download from an appropriate random directory server.
3200 static void
3201 initiate_descriptor_downloads(routerstatus_t *source,
3202 smartlist_t *digests,
3203 int lo, int hi)
3205 int i, n = hi-lo;
3206 char *resource, *cp;
3207 size_t r_len;
3208 if (n <= 0)
3209 return;
3210 if (lo < 0)
3211 lo = 0;
3212 if (hi > smartlist_len(digests))
3213 hi = smartlist_len(digests);
3215 r_len = 8 + (HEX_DIGEST_LEN+1)*n;
3216 cp = resource = tor_malloc(r_len);
3217 memcpy(cp, "d/", 2);
3218 cp += 2;
3219 for (i = lo; i < hi; ++i) {
3220 base16_encode(cp, r_len-(cp-resource),
3221 smartlist_get(digests,i), DIGEST_LEN);
3222 cp += HEX_DIGEST_LEN;
3223 *cp++ = '+';
3225 memcpy(cp-1, ".z", 3);
3227 if (source) {
3228 /* We know which authority we want. */
3229 directory_initiate_command_routerstatus(source,
3230 DIR_PURPOSE_FETCH_SERVERDESC,
3231 0, /* not private */
3232 resource, NULL, 0);
3233 } else {
3234 directory_get_from_dirserver(DIR_PURPOSE_FETCH_SERVERDESC,
3235 resource,
3238 tor_free(resource);
3241 /** Return new list of ID fingerprints for routers that we (as a client) would
3242 * like to download.
3244 static smartlist_t *
3245 router_list_client_downloadable(void)
3247 #define MAX_OLD_SERVER_DOWNLOAD_RATE 2*60*60
3248 #define ESTIMATED_PROPAGATION_TIME 10*60
3249 int n_downloadable = 0;
3250 smartlist_t *downloadable = smartlist_create();
3251 digestmap_t *downloading;
3252 time_t now = time(NULL);
3253 /* these are just used for logging */
3254 int n_not_ready = 0, n_in_progress = 0, n_uptodate = 0,
3255 n_obsolete = 0, n_too_young = 0, n_wouldnt_use = 0;
3257 if (!routerstatus_list)
3258 return downloadable;
3260 downloading = digestmap_new();
3261 list_pending_descriptor_downloads(downloading);
3263 routerstatus_list_update_from_networkstatus(now);
3264 SMARTLIST_FOREACH(routerstatus_list, local_routerstatus_t *, rs,
3266 routerinfo_t *ri;
3267 if (rs->status.published_on + ROUTER_MAX_AGE < now) {
3268 /* This one is too old to consider. */
3269 ++n_obsolete;
3270 } else if (digestmap_get(downloading, rs->status.descriptor_digest)) {
3271 /* We're downloading this one now. */
3272 ++n_in_progress;
3273 } else if (!rs->status.is_running) {
3274 /* If we had this router descriptor, we wouldn't even bother using it. */
3275 ++n_wouldnt_use;
3276 } else if (router_get_by_descriptor_digest(rs->status.descriptor_digest)) {
3277 /* We have the 'best' descriptor for this router. */
3278 ++n_uptodate;
3279 } else if ((ri = router_get_by_digest(rs->status.identity_digest)) &&
3280 ri->cache_info.published_on > rs->status.published_on) {
3281 /* Oddly, we have a descriptor more recent than the 'best' one, but it
3282 was once best. So that's okay. */
3283 ++n_uptodate;
3284 } else if (rs->status.published_on + ESTIMATED_PROPAGATION_TIME > now) {
3285 /* Most caches probably don't have this descriptor yet. */
3286 ++n_too_young;
3287 } else if (rs->next_attempt_at > now) {
3288 /* We failed too recently to try again. */
3289 ++n_not_ready;
3290 } else {
3291 /* Okay, time to try it. */
3292 smartlist_add(downloadable, rs->status.descriptor_digest);
3293 ++n_downloadable;
3297 #if 0
3298 info(LD_DIR,
3299 "%d router descriptors are downloadable. %d are too old to consider. "
3300 "%d are in progress. %d are up-to-date. %d are too young to consider. "
3301 "%d are non-useful. %d failed too recently to retry.",
3302 n_downloadable, n_obsolete, n_in_progress, n_uptodate, n_too_young,
3303 n_wouldnt_use, n_not_ready);
3304 #endif
3306 digestmap_free(downloading, NULL);
3307 return downloadable;
3310 /** Initiate new router downloads as needed.
3312 * We only allow one router descriptor download at a time.
3313 * If we have less than two network-status documents, we ask
3314 * a directory for "all descriptors."
3315 * Otherwise, we ask for all descriptors that we think are different
3316 * from what we have.
3318 static void
3319 update_router_descriptor_client_downloads(time_t now)
3321 #define MAX_DL_PER_REQUEST 128
3322 #define MIN_DL_PER_REQUEST 4
3323 #define MIN_REQUESTS 3
3324 #define MAX_DL_TO_DELAY 16
3325 #define MAX_CLIENT_INTERVAL_WITHOUT_REQUEST 10*60
3326 #define MAX_SERVER_INTERVAL_WITHOUT_REQUEST 1*60
3327 smartlist_t *downloadable = NULL;
3328 int should_delay, n_downloadable;
3329 or_options_t *options = get_options();
3331 if (server_mode(options) && options->DirPort) {
3332 warn(LD_BUG, "Called router_descriptor_client_downloads() on a mirror?");
3335 if (networkstatus_list && smartlist_len(networkstatus_list) < 2) {
3336 /* XXXX Is this redundant? -NM */
3337 info(LD_DIR, "Not enough networkstatus documents to launch requests.");
3340 downloadable = router_list_client_downloadable();
3341 n_downloadable = smartlist_len(downloadable);
3342 if (n_downloadable >= MAX_DL_TO_DELAY) {
3343 debug(LD_DIR,
3344 "There are enough downloadable routerdescs to launch requests.");
3345 should_delay = 0;
3346 } else if (n_downloadable == 0) {
3347 // debug(LD_DIR, "No routerdescs need to be downloaded.");
3348 should_delay = 1;
3349 } else {
3350 should_delay = (last_routerdesc_download_attempted +
3351 MAX_CLIENT_INTERVAL_WITHOUT_REQUEST) > now;
3353 if (should_delay) {
3354 // debug(LD_DIR, "There are not many downloadable routerdescs; "
3355 // "waiting till we have some more.");
3356 } else {
3357 info(LD_DIR, "There are not many downloadable routerdescs, but we've "
3358 "been waiting long enough (%d seconds). Downloading.",
3359 (int)(now-last_routerdesc_download_attempted));
3362 if (! should_delay) {
3363 int i, n_per_request;
3364 n_per_request = (n_downloadable+MIN_REQUESTS-1) / MIN_REQUESTS;
3365 if (n_per_request > MAX_DL_PER_REQUEST)
3366 n_per_request = MAX_DL_PER_REQUEST;
3367 if (n_per_request < MIN_DL_PER_REQUEST)
3368 n_per_request = MIN_DL_PER_REQUEST;
3370 info(LD_DIR, "Launching %d request%s for %d router%s, %d at a time",
3371 (n_downloadable+n_per_request-1)/n_per_request,
3372 n_downloadable>n_per_request?"s":"",
3373 n_downloadable, n_downloadable>1?"s":"", n_per_request);
3374 for (i=0; i < n_downloadable; i += n_per_request) {
3375 initiate_descriptor_downloads(NULL, downloadable, i, i+n_per_request);
3377 last_routerdesc_download_attempted = now;
3379 smartlist_free(downloadable);
3382 /* DOCDOC */
3383 static void
3384 update_router_descriptor_cache_downloads(time_t now)
3386 smartlist_t **downloadable; /* For each authority, what can we dl from it? */
3387 smartlist_t **download_from; /* ... and, what will we dl from it? */
3388 digestmap_t *map; /* Which descs are in progress, or assigned? */
3389 int i, j, n;
3390 int n_download;
3391 or_options_t *options = get_options();
3393 if (!(server_mode(options) && options->DirPort)) {
3394 warn(LD_BUG, "Called update_router_descriptor_cache_downloads() "
3395 "on a non-mirror?");
3398 if (!networkstatus_list || !smartlist_len(networkstatus_list))
3399 return;
3401 map = digestmap_new();
3402 n = smartlist_len(networkstatus_list);
3404 downloadable = tor_malloc_zero(sizeof(smartlist_t*) * n);
3405 download_from = tor_malloc_zero(sizeof(smartlist_t*) * n);
3407 /* Set map[d]=1 for the digest of every descriptor that we are currently
3408 * downloading. */
3409 list_pending_descriptor_downloads(map);
3411 /* For the digest of every descriptor that we don't have, and that we aren't
3412 * downloading, add d to downloadable[i] if the i'th networkstatus knows
3413 * about that descriptor, and we haven't already failed to get that
3414 * descriptor from the corresponding authority.
3416 n_download = 0;
3417 SMARTLIST_FOREACH(networkstatus_list, networkstatus_t *, ns,
3419 smartlist_t *dl = smartlist_create();
3420 downloadable[ns_sl_idx] = dl;
3421 download_from[ns_sl_idx] = smartlist_create();
3422 SMARTLIST_FOREACH(ns->entries, routerstatus_t * , rs,
3424 if (!rs->need_to_mirror)
3425 continue;
3426 if (router_get_by_descriptor_digest(rs->descriptor_digest)) {
3427 warn(LD_BUG, "We have a router descriptor, but need_to_mirror=1.");
3428 rs->need_to_mirror = 0;
3429 continue;
3431 if (options->AuthoritativeDir && dirserv_would_reject_router(rs)) {
3432 rs->need_to_mirror = 0;
3433 continue;
3435 if (digestmap_get(map, rs->descriptor_digest)) {
3436 /* We're downloading it already. */
3437 continue;
3438 } else {
3439 /* We could download it from this guy. */
3440 smartlist_add(dl, rs->descriptor_digest);
3441 ++n_download;
3446 /* At random, assign descriptors to authorities such that:
3447 * - if d is a member of some downloadable[x], d is a member of some
3448 * download_from[y]. (Everything we want to download, we try to download
3449 * from somebody.)
3450 * - If d is a mamber of download_from[y], d is a member of downloadable[y].
3451 * (We only try to download descriptors from authorities who claim to have
3452 * them.)
3453 * - No d is a member of download_from[x] and download_from[y] s.t. x != y.
3454 * (We don't try to download anything from two authorities concurrently.)
3456 while (n_download) {
3457 int which_ns = crypto_rand_int(n);
3458 smartlist_t *dl = downloadable[which_ns];
3459 int idx;
3460 char *d;
3461 tor_assert(dl);
3462 if (!smartlist_len(dl))
3463 continue;
3464 idx = crypto_rand_int(smartlist_len(dl));
3465 d = smartlist_get(dl, idx);
3466 if (! digestmap_get(map, d)) {
3467 smartlist_add(download_from[which_ns], d);
3468 digestmap_set(map, d, (void*) 1);
3470 smartlist_del(dl, idx);
3471 --n_download;
3474 /* Now, we can actually launch our requests. */
3475 for (i=0; i<n; ++i) {
3476 networkstatus_t *ns = smartlist_get(networkstatus_list, i);
3477 trusted_dir_server_t *ds =
3478 router_get_trusteddirserver_by_digest(ns->identity_digest);
3479 smartlist_t *dl = download_from[i];
3480 if (!ds) {
3481 warn(LD_BUG, "Networkstatus with no corresponding authority!");
3482 continue;
3484 if (! smartlist_len(dl))
3485 continue;
3486 info(LD_DIR, "Requesting %d descriptors from authority \"%s\"",
3487 smartlist_len(dl), ds->nickname);
3488 for (j=0; j < smartlist_len(dl); j += MAX_DL_PER_REQUEST) {
3489 initiate_descriptor_downloads(&(ds->fake_status), dl, j,
3490 j+MAX_DL_PER_REQUEST);
3494 for (i=0; i<n; ++i) {
3495 smartlist_free(download_from[i]);
3496 smartlist_free(downloadable[i]);
3498 tor_free(download_from);
3499 tor_free(downloadable);
3500 digestmap_free(map,NULL);
3503 /* DOCDOC */
3504 void
3505 update_router_descriptor_downloads(time_t now)
3507 or_options_t *options = get_options();
3508 if (server_mode(options) && options->DirPort) {
3509 update_router_descriptor_cache_downloads(now);
3510 } else {
3511 update_router_descriptor_client_downloads(now);
3515 /** Return true iff we have enough networkstatus and router information to
3516 * start building circuits. Right now, this means "at least 2 networkstatus
3517 * documents, and at least 1/4 of expected routers." */
3518 //XXX should consider whether we have enough exiting nodes here.
3520 router_have_minimum_dir_info(void)
3522 int tot = 0, num_running = 0;
3523 int n_ns, res, avg;
3524 static int have_enough = 0;
3525 if (!networkstatus_list || !routerlist) {
3526 res = 0;
3527 goto done;
3529 n_ns = smartlist_len(networkstatus_list);
3530 if (n_ns<2) {
3531 res = 0;
3532 goto done;
3534 SMARTLIST_FOREACH(networkstatus_list, networkstatus_t *, ns,
3535 tot += smartlist_len(ns->entries));
3536 avg = tot / n_ns;
3537 SMARTLIST_FOREACH(routerstatus_list, local_routerstatus_t *, rs,
3539 if (rs->status.is_running)
3540 num_running++;
3542 res = smartlist_len(routerlist->routers) >= (avg/4) && num_running > 2;
3543 done:
3544 if (res && !have_enough) {
3545 log(LOG_NOTICE, LD_DIR,
3546 "We now have enough directory information to build circuits.");
3548 if (!res && have_enough) {
3549 log(LOG_NOTICE, LD_DIR,"Our directory information is no longer up-to-date "
3550 "enough to build circuits.%s",
3551 num_running > 2 ? "" : " (Not enough servers seem reachable -- "
3552 "is your network connection down?)");
3554 have_enough = res;
3555 return res;
3558 /** Reset the descriptor download failure count on all routers, so that we
3559 * can retry any long-failed routers immediately.
3561 void
3562 router_reset_descriptor_download_failures(void)
3564 if (!routerstatus_list)
3565 return;
3566 SMARTLIST_FOREACH(routerstatus_list, local_routerstatus_t *, rs,
3568 rs->n_download_failures = 0;
3569 rs->next_attempt_at = 0;
3571 SMARTLIST_FOREACH(networkstatus_list, networkstatus_t *, ns,
3572 SMARTLIST_FOREACH(ns->entries, routerstatus_t *, rs,
3574 if (!router_get_by_descriptor_digest(rs->descriptor_digest))
3575 rs->need_to_mirror = 1;
3576 }));
3577 last_routerdesc_download_attempted = 0;
3580 /** Return true iff the only differences between r1 and r2 are such that
3581 * would not cause a recent (post 0.1.1.6) dirserver to republish.
3584 router_differences_are_cosmetic(routerinfo_t *r1, routerinfo_t *r2)
3586 time_t r1pub, r2pub;
3587 tor_assert(r1 && r2);
3589 /* r1 should be the one that was published first. */
3590 if (r1->cache_info.published_on > r2->cache_info.published_on) {
3591 routerinfo_t *ri_tmp = r2;
3592 r2 = r1;
3593 r1 = ri_tmp;
3596 /* If any key fields differ, they're different. */
3597 if (strcasecmp(r1->address, r2->address) ||
3598 strcasecmp(r1->nickname, r2->nickname) ||
3599 r1->or_port != r2->or_port ||
3600 r1->dir_port != r2->dir_port ||
3601 crypto_pk_cmp_keys(r1->onion_pkey, r2->onion_pkey) ||
3602 crypto_pk_cmp_keys(r1->identity_pkey, r2->identity_pkey) ||
3603 strcasecmp(r1->platform, r2->platform) ||
3604 (r1->contact_info && !r2->contact_info) || /* contact_info is optional */
3605 (!r1->contact_info && r2->contact_info) ||
3606 (r1->contact_info && r2->contact_info &&
3607 strcasecmp(r1->contact_info, r2->contact_info)) ||
3608 r1->is_hibernating != r2->is_hibernating ||
3609 config_cmp_addr_policies(r1->exit_policy, r2->exit_policy))
3610 return 0;
3611 if ((r1->declared_family == NULL) != (r2->declared_family == NULL))
3612 return 0;
3613 if (r1->declared_family && r2->declared_family) {
3614 int i, n;
3615 if (smartlist_len(r1->declared_family)!=smartlist_len(r2->declared_family))
3616 return 0;
3617 n = smartlist_len(r1->declared_family);
3618 for (i=0; i < n; ++i) {
3619 if (strcasecmp(smartlist_get(r1->declared_family, i),
3620 smartlist_get(r2->declared_family, i)))
3621 return 0;
3625 /* Did bandwidth change a lot? */
3626 if ((r1->bandwidthcapacity < r2->bandwidthcapacity/2) ||
3627 (r2->bandwidthcapacity < r1->bandwidthcapacity/2))
3628 return 0;
3630 /* Did more than 12 hours pass? */
3631 if (r1->cache_info.published_on + 12*60*60 < r2->cache_info.published_on)
3632 return 0;
3634 /* Did uptime fail to increase by approximately the amount we would think,
3635 * give or take 30 minutes? */
3636 r1pub = r1->cache_info.published_on;
3637 r2pub = r2->cache_info.published_on;
3638 if (abs(r2->uptime - (r1->uptime + (r2pub - r1pub))))
3639 return 0;
3641 /* Otherwise, the difference is cosmetic. */
3642 return 1;
3645 static void
3646 routerlist_assert_ok(routerlist_t *rl)
3648 digestmap_iter_t *iter;
3649 routerinfo_t *r2;
3650 signed_descriptor_t *sd2;
3651 if (!routerlist)
3652 return;
3653 SMARTLIST_FOREACH(rl->routers, routerinfo_t *, r,
3655 r2 = digestmap_get(rl->identity_map, r->cache_info.identity_digest);
3656 tor_assert(r == r2);
3657 sd2 = digestmap_get(rl->desc_digest_map,
3658 r->cache_info.signed_descriptor_digest);
3659 tor_assert(&(r->cache_info) == sd2);
3661 SMARTLIST_FOREACH(rl->old_routers, signed_descriptor_t *, sd,
3663 r2 = digestmap_get(rl->identity_map, sd->identity_digest);
3664 tor_assert(sd != &(r2->cache_info));
3665 sd2 = digestmap_get(rl->desc_digest_map, sd->signed_descriptor_digest);
3666 tor_assert(sd == sd2);
3668 iter = digestmap_iter_init(rl->identity_map);
3669 while (!digestmap_iter_done(iter)) {
3670 const char *d;
3671 void *_r;
3672 routerinfo_t *r;
3673 digestmap_iter_get(iter, &d, &_r);
3674 r = _r;
3675 tor_assert(!memcmp(r->cache_info.identity_digest, d, DIGEST_LEN));
3676 iter = digestmap_iter_next(rl->identity_map, iter);
3678 iter = digestmap_iter_init(rl->desc_digest_map);
3679 while (!digestmap_iter_done(iter)) {
3680 const char *d;
3681 void *_sd;
3682 signed_descriptor_t *sd;
3683 digestmap_iter_get(iter, &d, &_sd);
3684 sd = _sd;
3685 tor_assert(!memcmp(sd->signed_descriptor_digest, d, DIGEST_LEN));
3686 iter = digestmap_iter_next(rl->desc_digest_map, iter);