Fix an annoying rep violation bug
[tor.git] / src / or / routerlist.c
blobeb12a890fe92e57ade2e2e34e84db541bdb4c891
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[] = "$Id$";
8 /**
9 * \file routerlist.c
10 * \brief Code to
11 * maintain and access the global list of routerinfos for known
12 * servers.
13 **/
15 #include "or.h"
17 /****************************************************************************/
19 /** Global list of a trusted_dir_server_t object for each trusted directory
20 * server. */
21 static smartlist_t *trusted_dir_servers = NULL;
23 /* static function prototypes */
24 static routerinfo_t *router_pick_directory_server_impl(int requireother,
25 int fascistfirewall,
26 int for_v2_directory);
27 static trusted_dir_server_t *router_pick_trusteddirserver_impl(
28 int need_v1_support, int requireother, int fascistfirewall);
29 static void mark_all_trusteddirservers_up(void);
30 static int router_nickname_is_in_list(routerinfo_t *router, const char *list);
31 static int router_nickname_matches(routerinfo_t *router, const char *nickname);
32 static void routerstatus_list_update_from_networkstatus(time_t now);
33 static void local_routerstatus_free(local_routerstatus_t *rs);
34 static void trusted_dir_server_free(trusted_dir_server_t *ds);
35 static void update_networkstatus_cache_downloads(time_t now);
36 static void update_networkstatus_client_downloads(time_t now);
37 static int routerdesc_digest_is_recognized(const char *identity,
38 const char *digest);
39 static void routerlist_assert_ok(routerlist_t *rl);
41 /****************************************************************************/
43 /****
44 * Functions to manage and access our list of known routers. (Note:
45 * dirservers maintain a separate, independent list of known router
46 * descriptors.)
47 ****/
49 /** Global list of all of the routers that we know about. */
50 static routerlist_t *routerlist = NULL;
52 extern int has_fetched_directory; /**< from main.c */
54 /** Global list of all of the current network_status documents that we know
55 * about. This list is kept sorted by published_on. */
56 static smartlist_t *networkstatus_list = NULL;
57 /** Global list of local_routerstatus_t for each router, known or unknown. */
58 static smartlist_t *routerstatus_list = NULL;
59 /** True iff any member of networkstatus_list has changed since the last time
60 * we called routerstatus_list_update_from_networkstatus(). */
61 static int networkstatus_list_has_changed = 0;
62 /** True iff any element of routerstatus_list has changed since the last
63 * time we called routers_update_all_from_networkstatus().*/
64 static int routerstatus_list_has_changed = 0;
65 /** List of strings for nicknames we've already warned about and that are
66 * still unknown / unavailable. */
67 static smartlist_t *warned_nicknames = NULL;
68 /** List of strings for nicknames or fingerprints we've already warned about
69 * and that are still conflicted. */
70 static smartlist_t *warned_conflicts = NULL;
72 /** The last time we tried to download any routerdesc, or 0 for "never". We
73 * use this to rate-limit download attempts when the number of routerdescs to
74 * download is low. */
75 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 (fn[0] == '.') /* skip . and .. */
105 continue;
106 if (strlen(fn) != HEX_DIGEST_LEN ||
107 base16_decode(buf, sizeof(buf), fn, strlen(fn))) {
108 info(LD_DIR,
109 "Skipping cached-status file with unexpected name \"%s\"",fn);
110 continue;
112 tor_snprintf(filename,sizeof(filename),"%s/cached-status/%s",
113 get_options()->DataDirectory, fn);
114 s = read_file_to_str(filename, 0);
115 if (s) {
116 stat(filename, &st);
117 if (router_set_networkstatus(s, st.st_mtime, NS_FROM_CACHE, NULL)<0) {
118 warn(LD_FS, "Couldn't load networkstatus from \"%s\"",filename);
120 tor_free(s);
123 SMARTLIST_FOREACH(entries, char *, fn, tor_free(fn));
124 smartlist_free(entries);
125 networkstatus_list_clean(time(NULL));
126 routers_update_all_from_networkstatus();
127 return 0;
130 /* Router descriptor storage.
132 * Routerdescs are stored in a big file, named "cached-routers". As new
133 * routerdescs arrive, we append them to a journal file named
134 * "cached-routers.new".
136 * From time to time, we replace "cached-routers" with a new file containing
137 * only the live, non-superseded descriptors, and clear cached-routers.new.
139 * On startup, we read both files.
142 /** The size of the router log, in bytes. */
143 static size_t router_journal_len = 0;
144 /** The size of the router store, in bytes. */
145 static size_t router_store_len = 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 else
155 return router_journal_len > (1<<15);
158 /** Add the <b>len</b>-type router descriptor in <b>s</b> to the router
159 * journal. */
160 static int
161 router_append_to_journal(const char *s, size_t len)
163 or_options_t *options = get_options();
164 size_t fname_len = strlen(options->DataDirectory)+32;
165 char *fname = tor_malloc(len);
167 tor_snprintf(fname, fname_len, "%s/cached-routers.new",
168 options->DataDirectory);
170 if (!len)
171 len = strlen(s);
173 if (append_bytes_to_file(fname, s, len, 0)) {
174 warn(LD_FS, "Unable to store router descriptor");
175 tor_free(fname);
176 return -1;
179 tor_free(fname);
180 router_journal_len += len;
181 return 0;
184 /** If the journal is too long, or if <b>force</b> is true, then atomically
185 * replace the router store with the routers currently in our routerlist, and
186 * clear the journal. Return 0 on success, -1 on failure.
188 static int
189 router_rebuild_store(int force)
191 size_t len = 0;
192 or_options_t *options;
193 size_t fname_len;
194 smartlist_t *chunk_list = NULL;
195 char *fname = NULL;
196 int r = -1, i;
198 if (!force && !router_should_rebuild_store())
199 return 0;
200 if (!routerlist)
201 return 0;
203 /* Don't save deadweight. */
204 routerlist_remove_old_routers(ROUTER_MAX_AGE);
206 options = get_options();
207 fname_len = strlen(options->DataDirectory)+32;
208 fname = tor_malloc(fname_len);
209 tor_snprintf(fname, fname_len, "%s/cached-routers", options->DataDirectory);
210 chunk_list = smartlist_create();
212 for (i = 0; i < 2; ++i) {
213 smartlist_t *lst = (i == 0) ? routerlist->old_routers : routerlist->routers;
214 SMARTLIST_FOREACH(lst, routerinfo_t *, ri,
216 sized_chunk_t *c;
217 if (!ri->signed_descriptor) {
218 warn(LD_BUG, "Bug! No descriptor stored for router '%s'.",
219 ri->nickname);
220 goto done;
222 c = tor_malloc(sizeof(sized_chunk_t));
223 c->bytes = ri->signed_descriptor;
224 c->len = ri->signed_descriptor_len;
225 smartlist_add(chunk_list, c);
228 if (write_chunks_to_file(fname, chunk_list, 0)<0) {
229 warn(LD_FS, "Error writing router store to disk.");
230 goto done;
233 tor_snprintf(fname, fname_len, "%s/cached-routers.new",
234 options->DataDirectory);
236 write_str_to_file(fname, "", 0);
238 r = 0;
239 router_store_len = len;
240 router_journal_len = 0;
241 done:
242 tor_free(fname);
243 if (chunk_list) {
244 SMARTLIST_FOREACH(chunk_list, sized_chunk_t *, c, tor_free(c));
245 smartlist_free(chunk_list);
247 return r;
250 /* Load all cached router descriptors from the store. Return 0 on success and
251 * -1 on failure.
254 router_reload_router_list(void)
256 or_options_t *options = get_options();
257 size_t fname_len = strlen(options->DataDirectory)+32;
258 char *fname = tor_malloc(fname_len);
259 struct stat st;
260 int j;
262 if (!routerlist)
263 router_get_routerlist();
265 router_journal_len = router_store_len = 0;
267 for (j = 0; j < 2; ++j) {
268 char *contents;
269 tor_snprintf(fname, fname_len,
270 (j==0)?"%s/cached-routers":"%s/cached-routers.new",
271 options->DataDirectory);
272 contents = read_file_to_str(fname, 0);
273 if (contents) {
274 stat(fname, &st);
275 if (j==0)
276 router_store_len = st.st_size;
277 else
278 router_journal_len = st.st_size;
279 router_load_routers_from_string(contents, 1, NULL);
280 tor_free(contents);
283 tor_free(fname);
285 /* Don't cache expired routers. */
286 routerlist_remove_old_routers(ROUTER_MAX_AGE);
288 if (router_journal_len) {
289 /* Always clear the journal on startup.*/
290 router_rebuild_store(1);
292 return 0;
295 /** Set *<b>outp</b> to a smartlist containing a list of
296 * trusted_dir_server_t * for all known trusted dirservers. Callers
297 * must not modify the list or its contents.
299 void
300 router_get_trusted_dir_servers(smartlist_t **outp)
302 if (!trusted_dir_servers)
303 trusted_dir_servers = smartlist_create();
305 *outp = trusted_dir_servers;
308 /** Try to find a running dirserver. If there are no running dirservers
309 * in our routerlist and <b>retry_if_no_servers</b> is non-zero,
310 * set all the authoritative ones as running again, and pick one;
311 * if there are then no dirservers at all in our routerlist,
312 * reload the routerlist and try one last time. If for_runningrouters is
313 * true, then only pick a dirserver that can answer runningrouters queries
314 * (that is, a trusted dirserver, or one running 0.0.9rc5-cvs or later).
315 * Other args are as in router_pick_directory_server_impl().
317 routerinfo_t *
318 router_pick_directory_server(int requireother,
319 int fascistfirewall,
320 int for_v2_directory,
321 int retry_if_no_servers)
323 routerinfo_t *choice;
325 if (!routerlist)
326 return NULL;
328 choice = router_pick_directory_server_impl(requireother, fascistfirewall,
329 for_v2_directory);
330 if (choice || !retry_if_no_servers)
331 return choice;
333 info(LD_DIR,"No reachable router entries for dirservers. Trying them all again.");
334 /* mark all authdirservers as up again */
335 mark_all_trusteddirservers_up();
336 /* try again */
337 choice = router_pick_directory_server_impl(requireother, fascistfirewall,
338 for_v2_directory);
339 if (choice)
340 return choice;
342 info(LD_DIR,"Still no %s router entries. Reloading and trying again.",
343 firewall_is_fascist() ? "reachable" : "known");
344 has_fetched_directory=0; /* reset it */
345 if (router_reload_router_list()) {
346 return NULL;
348 /* give it one last try */
349 choice = router_pick_directory_server_impl(requireother, 0,
350 for_v2_directory);
351 return choice;
354 trusted_dir_server_t *
355 router_get_trusteddirserver_by_digest(const char *digest)
357 if (!trusted_dir_servers)
358 return NULL;
360 SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, ds,
362 if (!memcmp(ds->digest, digest, DIGEST_LEN))
363 return ds;
366 return NULL;
369 /** Try to find a running trusted dirserver. If there are no running
370 * trusted dirservers and <b>retry_if_no_servers</b> is non-zero,
371 * set them all as running again, and try again.
372 * Other args are as in router_pick_trusteddirserver_impl().
374 trusted_dir_server_t *
375 router_pick_trusteddirserver(int need_v1_support,
376 int requireother,
377 int fascistfirewall,
378 int retry_if_no_servers)
380 trusted_dir_server_t *choice;
382 choice = router_pick_trusteddirserver_impl(need_v1_support,
383 requireother, fascistfirewall);
384 if (choice || !retry_if_no_servers)
385 return choice;
387 info(LD_DIR,"No trusted dirservers are reachable. Trying them all again.");
388 mark_all_trusteddirservers_up();
389 return router_pick_trusteddirserver_impl(need_v1_support,
390 requireother, fascistfirewall);
393 /** Pick a random running verified directory server/mirror from our
394 * routerlist.
395 * If <b>fascistfirewall</b> and we're not using a proxy,
396 * make sure the port we pick is allowed by options-\>firewallports.
397 * If <b>requireother</b>, it cannot be us. If <b>for_v2_directory</b>,
398 * choose a directory server new enough to support the v2 directory
399 * functionality.
401 static routerinfo_t *
402 router_pick_directory_server_impl(int requireother, int fascistfirewall,
403 int for_v2_directory)
405 routerinfo_t *result;
406 smartlist_t *sl;
408 if (!routerlist)
409 return NULL;
411 if (get_options()->HttpProxy)
412 fascistfirewall = 0;
414 /* Find all the running dirservers we know about. */
415 sl = smartlist_create();
416 SMARTLIST_FOREACH(routerlist->routers, routerinfo_t *, router,
418 if (!router->is_running || !router->dir_port || !router->is_verified)
419 continue;
420 if (requireother && router_is_me(router))
421 continue;
422 if (fascistfirewall) {
423 if (!fascist_firewall_allows_address(router->addr, router->dir_port))
424 continue;
426 /* Before 0.1.1.6-alpha, only trusted dirservers served status info.
427 * Before 0.1.1.7-alpha, retrieving nonexistent server IDs could bork
428 * the directory server.
430 if (for_v2_directory &&
431 !(tor_version_as_new_as(router->platform,"0.1.1.7-alpha") ||
432 router_digest_is_trusted_dir(router->identity_digest)))
433 continue;
434 smartlist_add(sl, router);
437 result = smartlist_choose(sl);
438 smartlist_free(sl);
439 return result;
442 /** Choose randomly from among the trusted dirservers that are up.
443 * If <b>fascistfirewall</b> and we're not using a proxy,
444 * make sure the port we pick is allowed by options-\>firewallports.
445 * If <b>requireother</b>, it cannot be us. If <b>need_v1_support</b>, choose
446 * a trusted authority for the v1 directory system.
448 static trusted_dir_server_t *
449 router_pick_trusteddirserver_impl(int need_v1_support,
450 int requireother, int fascistfirewall)
452 smartlist_t *sl;
453 routerinfo_t *me;
454 trusted_dir_server_t *ds;
455 sl = smartlist_create();
456 me = router_get_my_routerinfo();
458 if (!trusted_dir_servers)
459 return NULL;
461 if (get_options()->HttpProxy)
462 fascistfirewall = 0;
464 SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, d,
466 if (!d->is_running) continue;
467 if (need_v1_support && !d->supports_v1_protocol)
468 continue;
469 if (requireother && me &&
470 !memcmp(me->identity_digest, d->digest, DIGEST_LEN))
471 continue;
472 if (fascistfirewall) {
473 if (!fascist_firewall_allows_address(d->addr, d->dir_port))
474 continue;
476 smartlist_add(sl, d);
479 ds = smartlist_choose(sl);
480 smartlist_free(sl);
481 return ds;
484 /** Go through and mark the authoritative dirservers as up. */
485 static void
486 mark_all_trusteddirservers_up(void)
488 if (routerlist) {
489 SMARTLIST_FOREACH(routerlist->routers, routerinfo_t *, router,
490 if (router_digest_is_trusted_dir(router->identity_digest) &&
491 router->dir_port > 0) {
492 router->is_running = 1;
495 if (trusted_dir_servers) {
496 SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, dir,
498 dir->is_running = 1;
499 dir->n_networkstatus_failures = 0;
502 last_networkstatus_download_attempted = 0;
505 /** Reset all internal variables used to count failed downloads of network
506 * status objects. */
507 void
508 router_reset_status_download_failures(void)
510 mark_all_trusteddirservers_up();
513 /** Return 0 if \\exists an authoritative dirserver that's currently
514 * thought to be running, else return 1.
517 all_trusted_directory_servers_down(void)
519 if (!trusted_dir_servers)
520 return 1;
521 SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, dir,
522 if (dir->is_running) return 0);
523 return 1;
526 /** Add all the family of <b>router</b> to the smartlist <b>sl</b>.
527 * This is used to make sure we don't pick siblings in a single path.
529 void
530 routerlist_add_family(smartlist_t *sl, routerinfo_t *router)
532 routerinfo_t *r;
533 config_line_t *cl;
535 if (!router->declared_family)
536 return;
538 /* Add every r such that router declares familyness with r, and r
539 * declares familyhood with router. */
540 SMARTLIST_FOREACH(router->declared_family, const char *, n,
542 if (!(r = router_get_by_nickname(n, 0)))
543 continue;
544 if (!r->declared_family)
545 continue;
546 SMARTLIST_FOREACH(r->declared_family, const char *, n2,
548 if (router_nickname_matches(router, n2))
549 smartlist_add(sl, r);
553 /* If the user declared any families locally, honor those too. */
554 for (cl = get_options()->NodeFamilies; cl; cl = cl->next) {
555 if (router_nickname_is_in_list(router, cl->value)) {
556 add_nickname_list_to_smartlist(sl, cl->value, 1, 1);
561 /** Given a comma-and-whitespace separated list of nicknames, see which
562 * nicknames in <b>list</b> name routers in our routerlist that are
563 * currently running. Add the routerinfos for those routers to <b>sl</b>.
565 void
566 add_nickname_list_to_smartlist(smartlist_t *sl, const char *list, int warn_if_down, int warn_if_unnamed)
568 routerinfo_t *router;
569 smartlist_t *nickname_list;
571 if (!list)
572 return; /* nothing to do */
573 tor_assert(sl);
575 nickname_list = smartlist_create();
576 if (!warned_nicknames)
577 warned_nicknames = smartlist_create();
579 smartlist_split_string(nickname_list, list, ",",
580 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
582 SMARTLIST_FOREACH(nickname_list, const char *, nick, {
583 int warned;
584 if (!is_legal_nickname_or_hexdigest(nick)) {
585 warn(LD_CONFIG, "Nickname %s is misformed; skipping", nick);
586 continue;
588 router = router_get_by_nickname(nick, warn_if_unnamed);
589 warned = smartlist_string_isin(warned_nicknames, nick);
590 if (router) {
591 if (router->is_running) {
592 smartlist_add(sl,router);
593 if (warned)
594 smartlist_string_remove(warned_nicknames, nick);
595 } else {
596 if (!warned) {
597 log_fn(warn_if_down ? LOG_WARN : LOG_DEBUG, LD_CONFIG,
598 "Nickname list includes '%s' which is known but down.",nick);
599 smartlist_add(warned_nicknames, tor_strdup(nick));
602 } else {
603 if (!warned) {
604 log_fn(has_fetched_directory ? LOG_WARN : LOG_INFO, LD_CONFIG,
605 "Nickname list includes '%s' which isn't a known router.",nick);
606 smartlist_add(warned_nicknames, tor_strdup(nick));
610 SMARTLIST_FOREACH(nickname_list, char *, nick, tor_free(nick));
611 smartlist_free(nickname_list);
614 /** Return 1 iff any member of the comma-separated list <b>list</b> is an
615 * acceptable nickname or hexdigest for <b>router</b>. Else return 0.
617 static int
618 router_nickname_is_in_list(routerinfo_t *router, const char *list)
620 smartlist_t *nickname_list;
621 int v = 0;
623 if (!list)
624 return 0; /* definitely not */
625 tor_assert(router);
627 nickname_list = smartlist_create();
628 smartlist_split_string(nickname_list, list, ",",
629 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
630 SMARTLIST_FOREACH(nickname_list, const char *, cp,
631 if (router_nickname_matches(router, cp)) {v=1;break;});
632 SMARTLIST_FOREACH(nickname_list, char *, cp, tor_free(cp));
633 smartlist_free(nickname_list);
634 return v;
637 /** Add every router from our routerlist that is currently running to
638 * <b>sl</b>.
640 static void
641 router_add_running_routers_to_smartlist(smartlist_t *sl, int allow_unverified,
642 int need_uptime, int need_capacity)
644 if (!routerlist)
645 return;
647 SMARTLIST_FOREACH(routerlist->routers, routerinfo_t *, router,
649 if (router->is_running &&
650 (router->is_verified ||
651 (allow_unverified &&
652 !router_is_unreliable(router, need_uptime, need_capacity)))) {
653 /* If it's running, and either it's verified or we're ok picking
654 * unverified routers and this one is suitable.
656 smartlist_add(sl, router);
661 /** Look through the routerlist until we find a router that has my key.
662 Return it. */
663 routerinfo_t *
664 routerlist_find_my_routerinfo(void)
666 if (!routerlist)
667 return NULL;
669 SMARTLIST_FOREACH(routerlist->routers, routerinfo_t *, router,
671 if (router_is_me(router))
672 return router;
674 return NULL;
677 /** Find a router that's up, that has this IP address, and
678 * that allows exit to this address:port, or return NULL if there
679 * isn't a good one.
681 routerinfo_t *
682 router_find_exact_exit_enclave(const char *address, uint16_t port)
684 uint32_t addr;
685 struct in_addr in;
687 if (!tor_inet_aton(address, &in))
688 return NULL; /* it's not an IP already */
689 addr = ntohl(in.s_addr);
691 SMARTLIST_FOREACH(routerlist->routers, routerinfo_t *, router,
693 if (router->is_running &&
694 router->addr == addr &&
695 router_compare_addr_to_addr_policy(addr, port, router->exit_policy) ==
696 ADDR_POLICY_ACCEPTED)
697 return router;
699 return NULL;
702 /** Return 1 if <b>router</b> is not suitable for these parameters, else 0.
703 * If <b>need_uptime</b> is non-zero, we require a minimum uptime.
704 * If <b>need_capacity</b> is non-zero, we require a minimum advertised
705 * bandwidth.
708 router_is_unreliable(routerinfo_t *router, int need_uptime, int need_capacity)
710 if (need_uptime && router->uptime < ROUTER_REQUIRED_MIN_UPTIME)
711 return 1;
712 if (need_capacity && router->bandwidthcapacity < ROUTER_REQUIRED_MIN_BANDWIDTH)
713 return 1;
714 return 0;
717 /** Remove from routerlist <b>sl</b> all routers who have a low uptime. */
718 static void
719 routerlist_sl_remove_unreliable_routers(smartlist_t *sl)
721 int i;
722 routerinfo_t *router;
724 for (i = 0; i < smartlist_len(sl); ++i) {
725 router = smartlist_get(sl, i);
726 if (router_is_unreliable(router, 1, 0)) {
727 // log(LOG_DEBUG, "Router '%s' has insufficient uptime; deleting.",
728 // router->nickname);
729 smartlist_del(sl, i--);
734 #define MAX_BELIEVABLE_BANDWIDTH 2000000 /* 2 MB/sec */
736 /** Choose a random element of router list <b>sl</b>, weighted by
737 * the advertised bandwidth of each router.
739 routerinfo_t *
740 routerlist_sl_choose_by_bandwidth(smartlist_t *sl)
742 int i;
743 routerinfo_t *router;
744 smartlist_t *bandwidths;
745 uint32_t this_bw, tmp, total_bw=0, rand_bw;
746 uint32_t *p;
748 /* First count the total bandwidth weight, and make a smartlist
749 * of each value. */
750 bandwidths = smartlist_create();
751 for (i = 0; i < smartlist_len(sl); ++i) {
752 router = smartlist_get(sl, i);
753 this_bw = (router->bandwidthcapacity < router->bandwidthrate) ?
754 router->bandwidthcapacity : router->bandwidthrate;
755 /* if they claim something huge, don't believe it */
756 if (this_bw > MAX_BELIEVABLE_BANDWIDTH)
757 this_bw = MAX_BELIEVABLE_BANDWIDTH;
758 p = tor_malloc(sizeof(uint32_t));
759 *p = this_bw;
760 smartlist_add(bandwidths, p);
761 total_bw += this_bw;
763 if (!total_bw) {
764 SMARTLIST_FOREACH(bandwidths, uint32_t*, p, tor_free(p));
765 smartlist_free(bandwidths);
766 return smartlist_choose(sl);
768 /* Second, choose a random value from the bandwidth weights. */
769 rand_bw = crypto_rand_int(total_bw);
770 /* Last, count through sl until we get to the element we picked */
771 tmp = 0;
772 for (i=0; ; i++) {
773 tor_assert(i < smartlist_len(sl));
774 p = smartlist_get(bandwidths, i);
775 tmp += *p;
776 if (tmp >= rand_bw)
777 break;
779 SMARTLIST_FOREACH(bandwidths, uint32_t*, p, tor_free(p));
780 smartlist_free(bandwidths);
781 return (routerinfo_t *)smartlist_get(sl, i);
784 /** Return a random running router from the routerlist. If any node
785 * named in <b>preferred</b> is available, pick one of those. Never
786 * pick a node named in <b>excluded</b>, or whose routerinfo is in
787 * <b>excludedsmartlist</b>, even if they are the only nodes
788 * available. If <b>strict</b> is true, never pick any node besides
789 * those in <b>preferred</b>.
790 * If <b>need_uptime</b> is non-zero, don't return a router with less
791 * than a minimum uptime.
792 * If <b>need_capacity</b> is non-zero, weight your choice by the
793 * advertised capacity of each router.
795 routerinfo_t *
796 router_choose_random_node(const char *preferred,
797 const char *excluded,
798 smartlist_t *excludedsmartlist,
799 int need_uptime, int need_capacity,
800 int allow_unverified, int strict)
802 smartlist_t *sl, *excludednodes;
803 routerinfo_t *choice;
805 excludednodes = smartlist_create();
806 add_nickname_list_to_smartlist(excludednodes,excluded,0,1);
808 /* Try the preferred nodes first. Ignore need_uptime and need_capacity,
809 * since the user explicitly asked for these nodes. */
810 sl = smartlist_create();
811 add_nickname_list_to_smartlist(sl,preferred,1,1);
812 smartlist_subtract(sl,excludednodes);
813 if (excludedsmartlist)
814 smartlist_subtract(sl,excludedsmartlist);
815 choice = smartlist_choose(sl);
816 smartlist_free(sl);
817 if (!choice && !strict) {
818 /* Then give up on our preferred choices: any node
819 * will do that has the required attributes. */
820 sl = smartlist_create();
821 router_add_running_routers_to_smartlist(sl, allow_unverified,
822 need_uptime, need_capacity);
823 smartlist_subtract(sl,excludednodes);
824 if (excludedsmartlist)
825 smartlist_subtract(sl,excludedsmartlist);
826 if (need_uptime)
827 routerlist_sl_remove_unreliable_routers(sl);
828 if (need_capacity)
829 choice = routerlist_sl_choose_by_bandwidth(sl);
830 else
831 choice = smartlist_choose(sl);
832 smartlist_free(sl);
834 smartlist_free(excludednodes);
835 if (!choice)
836 warn(LD_CIRC,"No available nodes when trying to choose node. Failing.");
837 return choice;
840 /** Return true iff the digest of <b>router</b>'s identity key,
841 * encoded in hexadecimal, matches <b>hexdigest</b> (which is
842 * optionally prefixed with a single dollar sign). Return false if
843 * <b>hexdigest</b> is malformed, or it doesn't match. */
844 static INLINE int
845 router_hex_digest_matches(routerinfo_t *router, const char *hexdigest)
847 char digest[DIGEST_LEN];
848 tor_assert(hexdigest);
849 if (hexdigest[0] == '$')
850 ++hexdigest;
852 if (strlen(hexdigest) != HEX_DIGEST_LEN ||
853 base16_decode(digest, DIGEST_LEN, hexdigest, HEX_DIGEST_LEN)<0)
854 return 0;
855 return (!memcmp(digest, router->identity_digest, DIGEST_LEN));
858 /** Return true if <b>router</b>'s nickname matches <b>nickname</b>
859 * (case-insensitive), or if <b>router's</b> identity key digest
860 * matches a hexadecimal value stored in <b>nickname</b>. Return
861 * false otherwise. */
862 static int
863 router_nickname_matches(routerinfo_t *router, const char *nickname)
865 if (nickname[0]!='$' && !strcasecmp(router->nickname, nickname))
866 return 1;
867 return router_hex_digest_matches(router, nickname);
870 /** Return the router in our routerlist whose (case-insensitive)
871 * nickname or (case-sensitive) hexadecimal key digest is
872 * <b>nickname</b>. Return NULL if no such router is known.
874 routerinfo_t *
875 router_get_by_nickname(const char *nickname, int warn_if_unnamed)
877 int maybedigest;
878 char digest[DIGEST_LEN];
879 routerinfo_t *best_match=NULL;
880 int n_matches = 0;
882 tor_assert(nickname);
883 if (!routerlist)
884 return NULL;
885 if (nickname[0] == '$')
886 return router_get_by_hexdigest(nickname);
887 if (server_mode(get_options()) &&
888 !strcasecmp(nickname, get_options()->Nickname))
889 return router_get_my_routerinfo();
891 maybedigest = (strlen(nickname) == HEX_DIGEST_LEN) &&
892 (base16_decode(digest,DIGEST_LEN,nickname,HEX_DIGEST_LEN) == 0);
894 SMARTLIST_FOREACH(routerlist->routers, routerinfo_t *, router,
896 if (!strcasecmp(router->nickname, nickname)) {
897 if (router->is_named)
898 return router;
899 else {
900 ++n_matches;
901 best_match = router;
903 } else if (maybedigest &&
904 !memcmp(digest, router->identity_digest, DIGEST_LEN)) {
905 return router;
909 if (best_match) {
910 if (warn_if_unnamed && n_matches > 1) {
911 smartlist_t *fps = smartlist_create();
912 int any_unwarned = 0;
913 SMARTLIST_FOREACH(routerlist->routers, routerinfo_t *, router,
915 local_routerstatus_t *rs;
916 char *desc;
917 size_t dlen;
918 char fp[HEX_DIGEST_LEN+1];
919 if (strcasecmp(router->nickname, nickname))
920 continue;
921 rs=router_get_combined_status_by_digest(router->identity_digest);
922 if (!rs->name_lookup_warned) {
923 rs->name_lookup_warned = 1;
924 any_unwarned = 1;
926 base16_encode(fp, sizeof(fp), router->identity_digest, DIGEST_LEN);
927 dlen = 32 + HEX_DIGEST_LEN + strlen(router->address);
928 desc = tor_malloc(dlen);
929 tor_snprintf(desc, dlen, "\"$%s\" for the one at %s:%d",
930 fp, router->address, router->or_port);
931 smartlist_add(fps, desc);
933 if (any_unwarned) {
934 char *alternatives = smartlist_join_strings(fps, "; ",0,NULL);
935 warn(LD_CONFIG, "There are multiple matches for the nickname \"%s\","
936 " but none is listed as named by the directory authories. "
937 "Choosing one arbitrarily. If you meant one in particular, "
938 "you should say %s.", nickname, alternatives);
939 tor_free(alternatives);
941 SMARTLIST_FOREACH(fps, char *, cp, tor_free(cp));
942 smartlist_free(fps);
943 } else if (warn_if_unnamed) {
944 local_routerstatus_t *rs =
945 router_get_combined_status_by_digest(best_match->identity_digest);
946 if (rs && !rs->name_lookup_warned) {
947 char fp[HEX_DIGEST_LEN+1];
948 base16_encode(fp, sizeof(fp), best_match->identity_digest, DIGEST_LEN);
949 warn(LD_CONFIG, "You specified a server \"%s\" by name, but the "
950 "directory authorities do not have a listing for this name. "
951 "To make sure you get the same server in the future, refer to "
952 "it by key, as \"$%s\".", nickname, fp);
953 rs->name_lookup_warned = 1;
956 return best_match;
959 return NULL;
962 /** Return true iff <b>digest</b> is the digest of the identity key of
963 * a trusted directory. */
965 router_digest_is_trusted_dir(const char *digest)
967 if (!trusted_dir_servers)
968 return 0;
969 SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, ent,
970 if (!memcmp(digest, ent->digest, DIGEST_LEN)) return 1);
971 return 0;
974 /** Return the router in our routerlist whose hexadecimal key digest
975 * is <b>hexdigest</b>. Return NULL if no such router is known. */
976 routerinfo_t *
977 router_get_by_hexdigest(const char *hexdigest)
979 char digest[DIGEST_LEN];
981 tor_assert(hexdigest);
982 if (!routerlist)
983 return NULL;
984 if (hexdigest[0]=='$')
985 ++hexdigest;
986 if (strlen(hexdigest) != HEX_DIGEST_LEN ||
987 base16_decode(digest,DIGEST_LEN,hexdigest,HEX_DIGEST_LEN) < 0)
988 return NULL;
990 return router_get_by_digest(digest);
993 /** Return the router in our routerlist whose 20-byte key digest
994 * is <b>digest</b>. Return NULL if no such router is known. */
995 routerinfo_t *
996 router_get_by_digest(const char *digest)
998 tor_assert(digest);
1000 if (!routerlist) return NULL;
1002 // routerlist_assert_ok(routerlist);
1004 return digestmap_get(routerlist->identity_map, digest);
1007 /** Return the router in our routerlist whose 20-byte descriptor
1008 * is <b>digest</b>. Return NULL if no such router is known. */
1009 routerinfo_t *
1010 router_get_by_descriptor_digest(const char *digest)
1012 tor_assert(digest);
1014 if (!routerlist) return NULL;
1016 SMARTLIST_FOREACH(routerlist->routers, routerinfo_t*, router,
1018 if (0 == memcmp(router->signed_descriptor_digest, digest, DIGEST_LEN))
1019 return router;
1022 return NULL;
1025 /** Return the current list of all known routers. */
1026 routerlist_t *
1027 router_get_routerlist(void)
1029 if (!routerlist) {
1030 routerlist = tor_malloc_zero(sizeof(routerlist_t));
1031 routerlist->routers = smartlist_create();
1032 routerlist->old_routers = smartlist_create();
1033 routerlist->identity_map = digestmap_new();
1034 routerlist->desc_digest_map = digestmap_new();
1036 return routerlist;
1039 /** Free all storage held by <b>router</b>. */
1040 void
1041 routerinfo_free(routerinfo_t *router)
1043 if (!router)
1044 return;
1046 tor_free(router->signed_descriptor);
1047 tor_free(router->address);
1048 tor_free(router->nickname);
1049 tor_free(router->platform);
1050 tor_free(router->contact_info);
1051 if (router->onion_pkey)
1052 crypto_free_pk_env(router->onion_pkey);
1053 if (router->identity_pkey)
1054 crypto_free_pk_env(router->identity_pkey);
1055 if (router->declared_family) {
1056 SMARTLIST_FOREACH(router->declared_family, char *, s, tor_free(s));
1057 smartlist_free(router->declared_family);
1059 addr_policy_free(router->exit_policy);
1060 tor_free(router);
1063 /** Allocate a fresh copy of <b>router</b> */
1064 routerinfo_t *
1065 routerinfo_copy(const routerinfo_t *router)
1067 routerinfo_t *r;
1068 addr_policy_t **e, *tmp;
1070 r = tor_malloc(sizeof(routerinfo_t));
1071 memcpy(r, router, sizeof(routerinfo_t));
1073 r->address = tor_strdup(r->address);
1074 r->nickname = tor_strdup(r->nickname);
1075 r->platform = tor_strdup(r->platform);
1076 if (r->signed_descriptor)
1077 r->signed_descriptor = tor_strdup(r->signed_descriptor);
1078 if (r->onion_pkey)
1079 r->onion_pkey = crypto_pk_dup_key(r->onion_pkey);
1080 if (r->identity_pkey)
1081 r->identity_pkey = crypto_pk_dup_key(r->identity_pkey);
1082 e = &r->exit_policy;
1083 while (*e) {
1084 tmp = tor_malloc(sizeof(addr_policy_t));
1085 memcpy(tmp,*e,sizeof(addr_policy_t));
1086 *e = tmp;
1087 (*e)->string = tor_strdup((*e)->string);
1088 e = & ((*e)->next);
1090 if (r->declared_family) {
1091 r->declared_family = smartlist_create();
1092 SMARTLIST_FOREACH(router->declared_family, const char *, s,
1093 smartlist_add(r->declared_family, tor_strdup(s)));
1095 return r;
1098 /** Free all storage held by a routerlist <b>rl</b> */
1099 void
1100 routerlist_free(routerlist_t *rl)
1102 tor_assert(rl);
1103 digestmap_free(rl->identity_map, NULL);
1104 digestmap_free(rl->desc_digest_map, NULL);
1105 SMARTLIST_FOREACH(rl->routers, routerinfo_t *, r,
1106 routerinfo_free(r));
1107 SMARTLIST_FOREACH(rl->old_routers, routerinfo_t *, r,
1108 routerinfo_free(r));
1109 smartlist_free(rl->routers);
1110 smartlist_free(rl->old_routers);
1111 tor_free(rl);
1114 static INLINE int
1115 _routerlist_find_elt(smartlist_t *sl, routerinfo_t *ri, int idx)
1117 if (idx < 0 || smartlist_get(sl, idx) != ri) {
1118 idx = -1;
1119 SMARTLIST_FOREACH(sl, routerinfo_t *, r,
1120 if (r == ri) {
1121 idx = r_sl_idx;
1122 break;
1125 return idx;
1128 /** Insert an item <b>ri</b> into the routerlist <b>rl</b>, updating indices
1129 * as needed. */
1130 static void
1131 routerlist_insert(routerlist_t *rl, routerinfo_t *ri)
1133 digestmap_set(rl->identity_map, ri->identity_digest, ri);
1134 digestmap_set(rl->desc_digest_map, ri->signed_descriptor_digest, ri);
1135 smartlist_add(rl->routers, ri);
1136 // routerlist_assert_ok(rl);
1139 static void
1140 routerlist_insert_old(routerlist_t *rl, routerinfo_t *ri)
1142 if (get_options()->DirPort) {
1143 digestmap_set(rl->desc_digest_map, ri->signed_descriptor_digest, ri);
1144 smartlist_add(rl->old_routers, ri);
1145 } else {
1146 routerinfo_free(ri);
1148 // routerlist_assert_ok(rl);
1151 /** Remove an item <b>ri</b> into the routerlist <b>rl</b>, updating indices
1152 * as needed. If <b>idx</b> is nonnegative and smartlist_get(rl-&gt;routers,
1153 * idx) == ri, we don't need to do a linear search over the list to decide
1154 * which to remove. We fill the gap rl-&gt;routers with a later element in
1155 * the list, if any exists. ri is freed..*/
1156 void
1157 routerlist_remove(routerlist_t *rl, routerinfo_t *ri, int idx, int make_old)
1159 routerinfo_t *ri_tmp;
1160 idx = _routerlist_find_elt(rl->routers, ri, idx);
1161 if (idx < 0)
1162 return;
1163 smartlist_del(rl->routers, idx);
1164 ri_tmp = digestmap_remove(rl->identity_map, ri->identity_digest);
1165 tor_assert(ri_tmp == ri);
1166 if (make_old && get_options()->DirPort) {
1167 smartlist_add(rl->old_routers, ri);
1168 } else {
1169 ri_tmp = digestmap_remove(rl->desc_digest_map,
1170 ri->signed_descriptor_digest);
1171 tor_assert(ri_tmp == ri);
1172 routerinfo_free(ri);
1174 // routerlist_assert_ok(rl);
1177 void
1178 routerlist_remove_old(routerlist_t *rl, routerinfo_t *ri, int idx)
1180 routerinfo_t *ri_tmp;
1181 idx = _routerlist_find_elt(rl->old_routers, ri, idx);
1182 if (idx < 0)
1183 return;
1184 smartlist_del(rl->old_routers, idx);
1185 ri_tmp = digestmap_remove(rl->desc_digest_map,
1186 ri->signed_descriptor_digest);
1187 tor_assert(ri_tmp == ri);
1188 routerinfo_free(ri);
1189 // routerlist_assert_ok(rl);
1192 /** Remove <b>ri_old</b> from the routerlist <b>rl</b>, and replace it with
1193 * <b>ri_new</b>, updating all index info. If <b>idx</b> is nonnegative and
1194 * smartlist_get(rl-&gt;routers, idx) == ri, we don't need to do a linear
1195 * search over the list to decide which to remove. We put ri_new in the same
1196 * index as ri_old, if possible. ri is freed as appropriate */
1197 static void
1198 routerlist_replace(routerlist_t *rl, routerinfo_t *ri_old,
1199 routerinfo_t *ri_new, int idx, int make_old)
1201 tor_assert(ri_old != ri_new);
1202 idx = _routerlist_find_elt(rl->routers, ri_old, idx);
1203 if (idx >= 0) {
1204 smartlist_set(rl->routers, idx, ri_new);
1205 } else {
1206 warn(LD_BUG, "Appending entry from routerlist_replace.");
1207 routerlist_insert(rl, ri_new);
1208 return;
1210 if (memcmp(ri_old->identity_digest, ri_new->identity_digest, DIGEST_LEN)) {
1211 /* digests don't match; digestmap_set won't replace */
1212 digestmap_remove(rl->identity_map, ri_old->identity_digest);
1214 digestmap_set(rl->identity_map, ri_new->identity_digest, ri_new);
1215 digestmap_set(rl->desc_digest_map, ri_new->signed_descriptor_digest, ri_new);
1217 if (make_old && get_options()->DirPort) {
1218 smartlist_add(rl->old_routers, ri_old);
1219 } else {
1220 if (memcmp(ri_old->signed_descriptor_digest,
1221 ri_new->signed_descriptor_digest,
1222 DIGEST_LEN)) {
1223 /* digests don't match; digestmap_set didn't replace */
1224 digestmap_remove(rl->desc_digest_map, ri_old->signed_descriptor_digest);
1226 routerinfo_free(ri_old);
1228 // routerlist_assert_ok(rl);
1231 /** Free all memory held by the rouerlist module */
1232 void
1233 routerlist_free_all(void)
1235 if (routerlist)
1236 routerlist_free(routerlist);
1237 routerlist = NULL;
1238 if (warned_nicknames) {
1239 SMARTLIST_FOREACH(warned_nicknames, char *, cp, tor_free(cp));
1240 smartlist_free(warned_nicknames);
1241 warned_nicknames = NULL;
1243 if (warned_conflicts) {
1244 SMARTLIST_FOREACH(warned_conflicts, char *, cp, tor_free(cp));
1245 smartlist_free(warned_conflicts);
1246 warned_conflicts = NULL;
1248 if (trusted_dir_servers) {
1249 SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, ds,
1250 trusted_dir_server_free(ds));
1251 smartlist_free(trusted_dir_servers);
1252 trusted_dir_servers = NULL;
1254 if (networkstatus_list) {
1255 SMARTLIST_FOREACH(networkstatus_list, networkstatus_t *, ns,
1256 networkstatus_free(ns));
1257 smartlist_free(networkstatus_list);
1258 networkstatus_list = NULL;
1260 if (routerstatus_list) {
1261 SMARTLIST_FOREACH(routerstatus_list, local_routerstatus_t *, rs,
1262 local_routerstatus_free(rs));
1263 smartlist_free(routerstatus_list);
1264 routerstatus_list = NULL;
1268 /** Free all storage held by the routerstatus object <b>rs</b>. */
1269 void
1270 routerstatus_free(routerstatus_t *rs)
1272 tor_free(rs);
1275 /** Free all storage held by the local_routerstatus object <b>rs</b>. */
1276 static void
1277 local_routerstatus_free(local_routerstatus_t *rs)
1279 tor_free(rs);
1282 /** Free all storage held by the networkstatus object <b>ns</b>. */
1283 void
1284 networkstatus_free(networkstatus_t *ns)
1286 tor_free(ns->source_address);
1287 tor_free(ns->contact);
1288 if (ns->signing_key)
1289 crypto_free_pk_env(ns->signing_key);
1290 tor_free(ns->client_versions);
1291 tor_free(ns->server_versions);
1292 if (ns->entries) {
1293 SMARTLIST_FOREACH(ns->entries, routerstatus_t *, rs, routerstatus_free(rs));
1294 smartlist_free(ns->entries);
1296 tor_free(ns);
1299 /** Forget that we have issued any router-related warnings, so that we'll
1300 * warn again if we see the same errors. */
1301 void
1302 routerlist_reset_warnings(void)
1304 if (!warned_nicknames)
1305 warned_nicknames = smartlist_create();
1306 SMARTLIST_FOREACH(warned_nicknames, char *, cp, tor_free(cp));
1307 smartlist_clear(warned_nicknames); /* now the list is empty. */
1309 if (!warned_conflicts)
1310 warned_conflicts = smartlist_create();
1311 SMARTLIST_FOREACH(warned_conflicts, char *, cp, tor_free(cp));
1312 smartlist_clear(warned_conflicts); /* now the list is empty. */
1314 SMARTLIST_FOREACH(routerstatus_list, local_routerstatus_t *, rs,
1315 rs->name_lookup_warned = 0);
1317 have_warned_about_unverified_status = 0;
1318 have_warned_about_old_version = 0;
1319 have_warned_about_new_version = 0;
1322 /** Mark the router with ID <b>digest</b> as non-running in our routerlist. */
1323 void
1324 router_mark_as_down(const char *digest)
1326 routerinfo_t *router;
1327 tor_assert(digest);
1329 SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, d,
1330 if (!memcmp(d->digest, digest, DIGEST_LEN))
1331 d->is_running = 0);
1333 router = router_get_by_digest(digest);
1334 if (!router) /* we don't seem to know about him in the first place */
1335 return;
1336 debug(LD_DIR,"Marking router '%s' as down.",router->nickname);
1337 if (router_is_me(router) && !we_are_hibernating())
1338 warn(LD_NET, "We just marked ourself as down. Are your external addresses reachable?");
1339 router->is_running = 0;
1342 /** Add <b>router</b> to the routerlist, if we don't already have it. Replace
1343 * older entries (if any) with the same key. Note: Callers should not hold
1344 * their pointers to <b>router</b> if this function fails; <b>router</b>
1345 * will either be inserted into the routerlist or freed.
1347 * Returns >= 0 if the router was added; less than 0 if it was not.
1349 * If we're returning non-zero, then assign to *<b>msg</b> a static string
1350 * describing the reason for not liking the routerinfo.
1352 * If the return value is less than -1, there was a problem with the
1353 * routerinfo. If the return value is equal to -1, then the routerinfo was
1354 * fine, but out-of-date. If the return value is equal to 1, the
1355 * routerinfo was accepted, but we should notify the generator of the
1356 * descriptor using the message *<b>msg</b>.
1358 * This function should be called *after*
1359 * routers_update_status_from_networkstatus; subsequenctly, you should call
1360 * router_rebuild_store and control_event_descriptors_changed.
1362 * XXXX never replace your own descriptor.
1365 router_add_to_routerlist(routerinfo_t *router, const char **msg,
1366 int from_cache)
1368 int i;
1369 char id_digest[DIGEST_LEN];
1370 int authdir = get_options()->AuthoritativeDir;
1371 int authdir_verified = 0;
1373 tor_assert(msg);
1375 if (!routerlist)
1376 router_get_routerlist();
1378 /* XXXX NM If this assert doesn't trigger, we should remove the id_digest
1379 * local. */
1380 crypto_pk_get_digest(router->identity_pkey, id_digest);
1381 tor_assert(!memcmp(id_digest, router->identity_digest, DIGEST_LEN));
1383 /* Make sure that we haven't already got this exact descriptor. */
1384 if (digestmap_get(routerlist->desc_digest_map,
1385 router->signed_descriptor_digest)) {
1386 info(LD_DIR, "Dropping descriptor that we already have for router '%s'",
1387 router->nickname);
1388 *msg = "Router descriptor was not new.";
1389 return -1;
1392 if (authdir) {
1393 if (authdir_wants_to_reject_router(router, msg))
1394 return -2;
1395 authdir_verified = router->is_verified;
1397 } else {
1398 if (! router->xx_is_recognized && !from_cache) {
1399 log_fn(LOG_WARN, "Dropping unrecognized descriptor for router '%s'",
1400 router->nickname);
1401 return -1;
1406 /* If we have a router with this name, and the identity key is the same,
1407 * choose the newer one. If the identity key has changed, drop the router.
1409 for (i = 0; i < smartlist_len(routerlist->routers); ++i) {
1410 routerinfo_t *old_router = smartlist_get(routerlist->routers, i);
1411 if (!crypto_pk_cmp_keys(router->identity_pkey,old_router->identity_pkey)) {
1412 if (router->published_on <= old_router->published_on) {
1413 /* Same key, but old */
1414 debug(LD_DIR, "Skipping not-new descriptor for router '%s'",
1415 router->nickname);
1416 routerlist_insert_old(routerlist, router);
1417 *msg = "Router descriptor was not new.";
1418 return -1;
1419 } else {
1420 /* Same key, new. */
1421 int unreachable = 0;
1422 debug(LD_DIR, "Replacing entry for router '%s/%s' [%s]",
1423 router->nickname, old_router->nickname,
1424 hex_str(id_digest,DIGEST_LEN));
1425 if (router->addr == old_router->addr &&
1426 router->or_port == old_router->or_port) {
1427 /* these carry over when the address and orport are unchanged.*/
1428 router->last_reachable = old_router->last_reachable;
1429 router->testing_since = old_router->testing_since;
1430 router->num_unreachable_notifications =
1431 old_router->num_unreachable_notifications;
1433 if (authdir &&
1434 dirserv_thinks_router_is_blatantly_unreachable(router, time(NULL))) {
1435 if (router->num_unreachable_notifications >= 3) {
1436 unreachable = 1;
1437 notice(LD_DIR, "Notifying server '%s' that it's unreachable. (ContactInfo '%s', platform '%s').",
1438 router->nickname, router->contact_info ? router->contact_info : "",
1439 router->platform ? router->platform : "");
1440 } else {
1441 info(LD_DIR,"'%s' may be unreachable -- the %d previous descriptors were thought to be unreachable.", router->nickname, router->num_unreachable_notifications);
1442 router->num_unreachable_notifications++;
1445 routerlist_replace(routerlist, old_router, router, i, 1);
1446 if (!from_cache)
1447 router_append_to_journal(router->signed_descriptor,
1448 router->signed_descriptor_len);
1449 directory_set_dirty();
1450 *msg = unreachable ? "Dirserver believes your ORPort is unreachable" :
1451 authdir_verified ? "Verified server updated" :
1452 "Unverified server updated. (Have you sent us your key fingerprint?)";
1453 return unreachable ? 1 : 0;
1455 } else if (!strcasecmp(router->nickname, old_router->nickname)) {
1456 /* nicknames match, keys don't. */
1457 if (router->is_named) {
1458 /* The new verified router replaces the old one; remove the
1459 * old one. And carry on to the end of the list, in case
1460 * there are more old unverified routers with this nickname
1462 /* mark-for-close connections using the old key, so we can
1463 * make new ones with the new key.
1465 connection_t *conn;
1466 while ((conn = connection_get_by_identity_digest(
1467 old_router->identity_digest, CONN_TYPE_OR))) {
1468 // And LD_OR? XXXXNM
1469 info(LD_DIR,"Closing conn to router '%s'; there is now a named router with that name.",
1470 old_router->nickname);
1471 connection_mark_for_close(conn);
1473 routerlist_remove(routerlist, old_router, i--, 0);
1474 } else if (old_router->is_named) {
1475 /* Can't replace a verified router with an unverified one. */
1476 debug(LD_DIR, "Skipping unverified entry for verified router '%s'",
1477 router->nickname);
1478 routerinfo_free(router);
1479 *msg = "Already have named router with same nickname and different key.";
1480 return -2;
1484 /* We haven't seen a router with this name before. Add it to the end of
1485 * the list. */
1486 routerlist_insert(routerlist, router);
1487 if (!from_cache)
1488 router_append_to_journal(router->signed_descriptor,
1489 router->signed_descriptor_len);
1490 directory_set_dirty();
1491 return 0;
1494 #define MAX_DESCRIPTORS_PER_ROUTER 5
1496 /** Remove any routers from the routerlist that are more than <b>age</b>
1497 * seconds old.
1499 void
1500 routerlist_remove_old_routers(int age)
1502 int i;
1503 time_t cutoff;
1504 routerinfo_t *router;
1505 if (!routerlist)
1506 return;
1508 cutoff = time(NULL) - age;
1509 for (i = 0; i < smartlist_len(routerlist->routers); ++i) {
1510 router = smartlist_get(routerlist->routers, i);
1511 if (router->published_on <= cutoff) {
1512 /* Too old. Remove it. */
1513 info(LD_DIR,"Forgetting obsolete (too old) routerinfo for router '%s'", router->nickname);
1514 routerlist_remove(routerlist, router, i--, 1);
1520 static int
1521 _compare_old_routers_by_identity(const void **_a, const void **_b)
1523 int i;
1524 const routerinfo_t *r1 = *_a, *r2 = *_b;
1525 if ((i = memcmp(r1->identity_digest, r2->identity_digest, DIGEST_LEN)))
1526 return i;
1527 return r1->published_on - r2->published_on;
1530 struct duration_idx_t {
1531 int duration;
1532 int idx;
1533 int old;
1536 static int
1537 _compare_duration_idx(const void *_d1, const void *_d2)
1539 const struct duration_idx_t *d1 = _d1;
1540 const struct duration_idx_t *d2 = _d2;
1541 return d1->duration - d2->duration;
1544 /** The range <b>lo</b> through <b>hi</b> inclusive of routerlist->old_routers
1545 * must contain routerinfo_t with the same identity and with publication time
1546 * in ascending order. Remove members from this range until there are no more
1547 * than MAX_DESCRIPTORS_PER_ROUTER remaining. Start by removing the oldest
1548 * members from before <b>cutoff</b>, then remove members which were current
1549 * for the lowest amount of time. The order of members of old_routers at
1550 * indices <b>lo</b> or higher may be changed.
1552 static void
1553 routerlist_remove_old_cached_routers_with_id(time_t cutoff, int lo, int hi)
1555 int i, n = hi-lo+1, n_extra;
1556 int n_rmv = 0;
1557 struct duration_idx_t *lifespans;
1558 uint8_t *rmv;
1559 smartlist_t *lst = routerlist->old_routers;
1560 #if 1
1561 const char *ident;
1562 tor_assert(hi < smartlist_len(lst));
1563 tor_assert(lo <= hi);
1564 ident = ((routerinfo_t*)smartlist_get(lst, lo))->identity_digest;
1565 for (i = lo+1; i <= hi; ++i) {
1566 routerinfo_t *r = smartlist_get(lst, i);
1567 tor_assert(!memcmp(ident, r->identity_digest, DIGEST_LEN));
1569 #endif
1571 /* Check whether we need to do anything at all. */
1572 n_extra = n - MAX_DESCRIPTORS_PER_ROUTER;
1573 if (n_extra <= 0)
1574 return;
1577 lifespans = tor_malloc_zero(sizeof(struct duration_idx_t)*n);
1578 rmv = tor_malloc_zero(sizeof(uint8_t)*n);
1579 /* Set lifespans to contain the lifespan and index of each server. */
1580 /* Set rmv[i-lo]=1 if we're going to remove a server for being too old. */
1581 for (i = lo; i <= hi; ++i) {
1582 routerinfo_t *r = smartlist_get(lst, i);
1583 routerinfo_t *r_next;
1584 lifespans[i].idx = i;
1585 if (i < hi) {
1586 r_next = smartlist_get(lst, i+1);
1587 tor_assert(r->published_on <= r_next->published_on);
1588 lifespans[i].duration = r_next->published_on - r->published_on;
1589 } else {
1590 r_next = NULL;
1591 lifespans[i].duration = INT_MAX;
1593 if (r->published_on < cutoff && n_rmv < n_extra) {
1594 ++n_rmv;
1595 lifespans[i].old = 1;
1596 rmv[i-lo] = 1;
1600 if (n_rmv < n_extra) {
1602 * We aren't removing enough servers for being old. Sort lifespans by
1603 * the duration of liveness, and remove the ones we're not already going to
1604 * remove based on how long they were alive.
1606 qsort(lifespans, n, sizeof(struct duration_idx_t), _compare_duration_idx);
1607 for (i = 0; i < n && n_rmv < n_extra; ++i) {
1608 if (!lifespans[i].old) {
1609 rmv[lifespans[i].idx-lo] = 1;
1610 ++n_rmv;
1615 for (i = hi; i >= lo; ++i) {
1616 if (rmv[i-lo])
1617 routerlist_remove_old(routerlist, smartlist_get(lst, i), i);
1619 tor_free(rmv);
1620 tor_free(lifespans);
1623 void
1624 routerlist_remove_old_cached_routers(void)
1626 int i, hi=-1;
1627 const char *cur_id = NULL;
1628 time_t cutoff;
1629 if (!routerlist)
1630 return;
1632 /* First, check whether we have too many router descriptors, total. We're
1633 * okay with having too many for some given router, so long as the total
1634 * number doesn't much exceed
1636 if (smartlist_len(routerlist->old_routers) <
1637 smartlist_len(routerlist->routers) * (MAX_DESCRIPTORS_PER_ROUTER - 1))
1638 return;
1640 smartlist_sort(routerlist->old_routers, _compare_old_routers_by_identity);
1642 cutoff = time(NULL) - ROUTER_MAX_AGE;
1644 /* Iterate through the list from back to front, so when we remove descriptors
1645 * we don't mess up groups we haven't gotten to. */
1646 for (i = smartlist_len(routerlist->old_routers)-1; i >= 0; --i) {
1647 routerinfo_t *r = smartlist_get(routerlist->old_routers, i);
1648 if (!cur_id) {
1649 cur_id = r->identity_digest;
1650 hi = i;
1652 if (memcmp(cur_id, r->identity_digest, DIGEST_LEN)) {
1653 routerlist_remove_old_cached_routers_with_id(cutoff, i+1, hi);
1654 hi = i;
1657 routerlist_remove_old_cached_routers_with_id(cutoff, 0, hi);
1661 * Code to parse a single router descriptor and insert it into the
1662 * routerlist. Return -1 if the descriptor was ill-formed; 0 if the
1663 * descriptor was well-formed but could not be added; and 1 if the
1664 * descriptor was added.
1666 * If we don't add it and <b>msg</b> is not NULL, then assign to
1667 * *<b>msg</b> a static string describing the reason for refusing the
1668 * descriptor.
1670 * This is used only by the controller.
1673 router_load_single_router(const char *s, const char **msg)
1675 routerinfo_t *ri;
1676 smartlist_t *lst;
1677 tor_assert(msg);
1678 *msg = NULL;
1680 if (!(ri = router_parse_entry_from_string(s, NULL))) {
1681 warn(LD_DIR, "Error parsing router descriptor; dropping.");
1682 *msg = "Couldn't parse router descriptor.";
1683 return -1;
1685 if (router_is_me(ri)) {
1686 warn(LD_DIR, "Router's identity key matches mine; dropping.");
1687 *msg = "Router's identity key matches mine.";
1688 routerinfo_free(ri);
1689 return 0;
1692 lst = smartlist_create();
1693 smartlist_add(lst, ri);
1694 routers_update_status_from_networkstatus(lst, 0, 1);
1696 if (router_add_to_routerlist(ri, msg, 0)<0) {
1697 warn(LD_DIR, "Couldn't add router to list: %s Dropping.",
1698 *msg?*msg:"(No message).");
1699 /* we've already assigned to *msg now, and ri is already freed */
1700 smartlist_free(lst);
1701 return 0;
1702 } else {
1703 control_event_descriptors_changed(lst);
1704 smartlist_free(lst);
1705 debug(LD_DIR, "Added router to list");
1706 return 1;
1710 /** Given a string <b>s</b> containing some routerdescs, parse it and put the
1711 * routers into our directory. If <b>from_cache</b> is false, the routers
1712 * have come from the network: cache them.
1714 * If <b>requested_fingerprints</b> is provided, it must contain a list of
1715 * uppercased identity fingerprints. Do not update any router whose
1716 * fingerprint is not on the list; after updating a router, remove its
1717 * fingerprint from the list.
1719 void
1720 router_load_routers_from_string(const char *s, int from_cache,
1721 smartlist_t *requested_fingerprints)
1723 smartlist_t *routers = smartlist_create(), *changed = smartlist_create();
1724 char fp[HEX_DIGEST_LEN+1];
1725 const char *msg;
1727 router_parse_list_from_string(&s, routers);
1729 routers_update_status_from_networkstatus(routers, !from_cache, from_cache);
1731 SMARTLIST_FOREACH(routers, routerinfo_t *, ri,
1733 base16_encode(fp, sizeof(fp), ri->identity_digest, DIGEST_LEN);
1734 if (requested_fingerprints) {
1735 if (smartlist_string_isin(requested_fingerprints, fp)) {
1736 smartlist_string_remove(requested_fingerprints, fp);
1737 } else {
1738 char *requested =
1739 smartlist_join_strings(requested_fingerprints," ",0,NULL);
1740 warn(LD_DIR, "We received a router descriptor with a fingerprint (%s) that we never requested. (We asked for: %s.) Dropping.", fp, requested);
1741 tor_free(requested);
1742 routerinfo_free(ri);
1743 continue;
1747 if (router_add_to_routerlist(ri, &msg, from_cache) >= 0)
1748 smartlist_add(changed, ri);
1751 if (smartlist_len(changed))
1752 control_event_descriptors_changed(changed);
1754 routerlist_assert_ok(routerlist);
1755 router_rebuild_store(0);
1757 smartlist_free(routers);
1758 smartlist_free(changed);
1761 /** Helper: return a newly allocated string containing the name of the filename
1762 * where we plan to cache <b>ns</b>. */
1763 static char *
1764 networkstatus_get_cache_filename(const networkstatus_t *ns)
1766 const char *datadir = get_options()->DataDirectory;
1767 size_t len = strlen(datadir)+64;
1768 char fp[HEX_DIGEST_LEN+1];
1769 char *fn = tor_malloc(len+1);
1770 base16_encode(fp, HEX_DIGEST_LEN+1, ns->identity_digest, DIGEST_LEN);
1771 tor_snprintf(fn, len, "%s/cached-status/%s",datadir,fp);
1772 return fn;
1775 /** Helper for smartlist_sort: Compare two networkstatus objects by
1776 * publication date. */
1777 static int
1778 _compare_networkstatus_published_on(const void **_a, const void **_b)
1780 const networkstatus_t *a = *_a, *b = *_b;
1781 if (a->published_on < b->published_on)
1782 return -1;
1783 else if (a->published_on > b->published_on)
1784 return 1;
1785 else
1786 return 0;
1789 /** How far in the future do we allow a network-status to get before removing
1790 * it? (seconds) */
1791 #define NETWORKSTATUS_ALLOW_SKEW (48*60*60)
1792 /** Given a string <b>s</b> containing a network status that we received at
1793 * <b>arrived_at</b> from <b>source</b>, try to parse it, see if we want to
1794 * store it, and put it into our cache is necessary.
1796 * If <b>source</b> is NS_FROM_DIR or NS_FROM_CACHE, do not replace our
1797 * own networkstatus_t (if we're a directory server).
1799 * If <b>source</b> is NS_FROM_CACHE, do not write our networkstatus_t to the
1800 * cache.
1802 * If <b>requested_fingerprints</b> is provided, it must contain a list of
1803 * uppercased identity fingerprints. Do not update any networkstatus whose
1804 * fingerprint is not on the list; after updating a networkstatus, remove its
1805 * fingerprint from the list.
1807 * Return 0 on success, -1 on failure.
1809 * Callers should make sure that routers_update_all_from_networkstatus() is
1810 * invoked after this function succeeds.
1813 router_set_networkstatus(const char *s, time_t arrived_at,
1814 networkstatus_source_t source, smartlist_t *requested_fingerprints)
1816 networkstatus_t *ns;
1817 int i, found;
1818 time_t now;
1819 int skewed = 0;
1820 trusted_dir_server_t *trusted_dir;
1821 char fp[HEX_DIGEST_LEN+1];
1822 char published[ISO_TIME_LEN+1];
1824 ns = networkstatus_parse_from_string(s);
1825 if (!ns) {
1826 warn(LD_DIR, "Couldn't parse network status.");
1827 return -1;
1829 if (!(trusted_dir=router_get_trusteddirserver_by_digest(ns->identity_digest))) {
1830 info(LD_DIR, "Network status was signed, but not by an authoritative directory we recognize.");
1831 networkstatus_free(ns);
1832 return -1;
1834 now = time(NULL);
1835 if (arrived_at > now)
1836 arrived_at = now;
1838 ns->received_on = arrived_at;
1840 format_iso_time(published, ns->published_on);
1842 if (ns->published_on > now + NETWORKSTATUS_ALLOW_SKEW) {
1843 warn(LD_GENERAL, "Network status from %s was published in the future (%s GMT). Somebody is skewed here: check your clock. Not caching.", trusted_dir->description, published);
1844 skewed = 1;
1847 if (!networkstatus_list)
1848 networkstatus_list = smartlist_create();
1850 if (source == NS_FROM_DIR && router_digest_is_me(ns->identity_digest)) {
1851 /* Don't replace our own networkstatus when we get it from somebody else. */
1852 networkstatus_free(ns);
1853 return 0;
1856 base16_encode(fp, HEX_DIGEST_LEN+1, ns->identity_digest, DIGEST_LEN);
1858 if (requested_fingerprints) {
1859 if (smartlist_string_isin(requested_fingerprints, fp)) {
1860 smartlist_string_remove(requested_fingerprints, fp);
1861 } else {
1862 char *requested = smartlist_join_strings(requested_fingerprints," ",0,NULL);
1863 warn(LD_DIR, "We received a network status with a fingerprint (%s) that we never requested. (We asked for: %s.) Dropping.", fp, requested);
1864 tor_free(requested);
1865 return 0;
1869 if (source != NS_FROM_CACHE)
1870 trusted_dir->n_networkstatus_failures = 0;
1872 found = 0;
1873 for (i=0; i < smartlist_len(networkstatus_list); ++i) {
1874 networkstatus_t *old_ns = smartlist_get(networkstatus_list, i);
1876 if (!memcmp(old_ns->identity_digest, ns->identity_digest, DIGEST_LEN)) {
1877 if (!memcmp(old_ns->networkstatus_digest,
1878 ns->networkstatus_digest, DIGEST_LEN)) {
1879 /* Same one we had before. */
1880 networkstatus_free(ns);
1881 info(LD_DIR,
1882 "Not replacing network-status from %s (published %s); "
1883 "we already have it.",
1884 trusted_dir->description, published);
1885 if (old_ns->received_on < arrived_at) {
1886 if (source != NS_FROM_CACHE) {
1887 char *fn = networkstatus_get_cache_filename(old_ns);
1888 /* We use mtime to tell when it arrived, so update that. */
1889 touch_file(fn);
1890 tor_free(fn);
1892 old_ns->received_on = arrived_at;
1894 return 0;
1895 } else if (old_ns->published_on >= ns->published_on) {
1896 char old_published[ISO_TIME_LEN+1];
1897 format_iso_time(old_published, old_ns->published_on);
1898 info(LD_DIR,
1899 "Not replacing network-status from %s (published %s);"
1900 " we have a newer one (published %s) for this authority.",
1901 trusted_dir->description, published,
1902 old_published);
1903 networkstatus_free(ns);
1904 return 0;
1905 } else {
1906 networkstatus_free(old_ns);
1907 smartlist_set(networkstatus_list, i, ns);
1908 found = 1;
1909 break;
1914 if (!found)
1915 smartlist_add(networkstatus_list, ns);
1917 info(LD_DIR, "Setting networkstatus %s %s (published %s)",
1918 source == NS_FROM_CACHE?"cached from":
1919 (source==NS_FROM_DIR?"downloaded from":"generated for"),
1920 trusted_dir->description, published);
1921 networkstatus_list_has_changed = 1;
1923 smartlist_sort(networkstatus_list, _compare_networkstatus_published_on);
1925 if (source != NS_FROM_CACHE && !skewed) {
1926 char *fn = networkstatus_get_cache_filename(ns);
1927 if (write_str_to_file(fn, s, 0)<0) {
1928 notice(LD_FS, "Couldn't write cached network status to \"%s\"", fn);
1930 tor_free(fn);
1933 networkstatus_list_update_recent(now);
1935 if (get_options()->DirPort && !skewed)
1936 dirserv_set_cached_networkstatus_v2(s,
1937 ns->identity_digest,
1938 ns->published_on);
1940 return 0;
1943 /** How old do we allow a network-status to get before removing it completely? */
1944 #define MAX_NETWORKSTATUS_AGE (10*24*60*60)
1945 /** Remove all very-old network_status_t objects from memory and from the
1946 * disk cache. */
1947 void
1948 networkstatus_list_clean(time_t now)
1950 int i;
1951 if (!networkstatus_list)
1952 return;
1954 for (i = 0; i < smartlist_len(networkstatus_list); ++i) {
1955 networkstatus_t *ns = smartlist_get(networkstatus_list, i);
1956 char *fname = NULL;;
1957 if (ns->published_on + MAX_NETWORKSTATUS_AGE > now)
1958 continue;
1959 /* Okay, this one is too old. Remove it from the list, and delete it
1960 * from the cache. */
1961 smartlist_del(networkstatus_list, i--);
1962 fname = networkstatus_get_cache_filename(ns);
1963 if (file_status(fname) == FN_FILE) {
1964 info(LD_DIR, "Removing too-old networkstatus in %s", fname);
1965 unlink(fname);
1967 tor_free(fname);
1968 if (get_options()->DirPort) {
1969 dirserv_set_cached_networkstatus_v2(NULL, ns->identity_digest, 0);
1971 networkstatus_free(ns);
1975 /** Helper for bsearching a list of routerstatus_t pointers.*/
1976 static int
1977 _compare_digest_to_routerstatus_entry(const void *_key, const void **_member)
1979 const char *key = _key;
1980 const routerstatus_t *rs = *_member;
1981 return memcmp(key, rs->identity_digest, DIGEST_LEN);
1984 /** Return the entry in <b>ns</b> for the identity digest <b>digest</b>, or
1985 * NULL if none was found. */
1986 static routerstatus_t *
1987 networkstatus_find_entry(networkstatus_t *ns, const char *digest)
1989 return smartlist_bsearch(ns->entries, digest,
1990 _compare_digest_to_routerstatus_entry);
1993 /** Return the consensus view of the status of the router whose digest is
1994 * <b>digest</b>, or NULL if we don't know about any such router. */
1995 local_routerstatus_t *
1996 router_get_combined_status_by_digest(const char *digest)
1998 if (!routerstatus_list)
1999 return NULL;
2000 return smartlist_bsearch(routerstatus_list, digest,
2001 _compare_digest_to_routerstatus_entry);
2004 /** DOCDOC */
2005 static int
2006 routerdesc_digest_is_recognized(const char *identity, const char *digest)
2008 routerstatus_t *rs;
2009 if (!networkstatus_list)
2010 return 0;
2012 SMARTLIST_FOREACH(networkstatus_list, networkstatus_t *, ns,
2014 if (!(rs = networkstatus_find_entry(ns, identity)))
2015 continue;
2016 if (!memcmp(rs->descriptor_digest, digest, DIGEST_LEN))
2017 return 1;
2019 return 0;
2022 /* XXXX These should be configurable, perhaps? NM */
2023 #define AUTHORITY_NS_CACHE_INTERVAL 10*60
2024 #define NONAUTHORITY_NS_CACHE_INTERVAL 15*60
2025 /** We are a directory server, and so cache network_status documents.
2026 * Initiate downloads as needed to update them. For authorities, this means
2027 * asking each trusted directory for its network-status. For caches, this
2028 * means asking a random authority for all network-statuses.
2030 static void
2031 update_networkstatus_cache_downloads(time_t now)
2033 int authority = authdir_mode(get_options());
2034 int interval =
2035 authority ? AUTHORITY_NS_CACHE_INTERVAL : NONAUTHORITY_NS_CACHE_INTERVAL;
2037 if (last_networkstatus_download_attempted + interval >= now)
2038 return;
2039 if (!trusted_dir_servers)
2040 return;
2042 last_networkstatus_download_attempted = now;
2044 if (authority) {
2045 /* An authority launches a separate connection for everybody. */
2046 SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, ds,
2048 char resource[HEX_DIGEST_LEN+6];
2049 if (router_digest_is_me(ds->digest))
2050 continue;
2051 if (connection_get_by_type_addr_port_purpose(
2052 CONN_TYPE_DIR, ds->addr, ds->dir_port,
2053 DIR_PURPOSE_FETCH_NETWORKSTATUS)) {
2054 /* We are already fetching this one. */
2055 continue;
2057 strlcpy(resource, "fp/", sizeof(resource));
2058 base16_encode(resource+3, sizeof(resource)-3, ds->digest, DIGEST_LEN);
2059 strlcat(resource, ".z", sizeof(resource));
2060 directory_get_from_dirserver(DIR_PURPOSE_FETCH_NETWORKSTATUS,resource,1);
2062 } else {
2063 /* A non-authority cache launches one connection to a random authority. */
2064 /* (Check whether we're currently fetching network-status objects.) */
2065 if (!connection_get_by_type_purpose(CONN_TYPE_DIR,
2066 DIR_PURPOSE_FETCH_NETWORKSTATUS))
2067 directory_get_from_dirserver(DIR_PURPOSE_FETCH_NETWORKSTATUS,"all.z",1);
2071 /*XXXX Should these be configurable? NM*/
2072 /** How old (in seconds) can a network-status be before we try replacing it? */
2073 #define NETWORKSTATUS_MAX_VALIDITY (48*60*60)
2074 /** How long (in seconds) does a client wait after getting a network status
2075 * before downloading the next in sequence? */
2076 #define NETWORKSTATUS_CLIENT_DL_INTERVAL (30*60)
2077 /* How many times do we allow a networkstatus download to fail before we
2078 * assume that the authority isn't publishing? */
2079 #define NETWORKSTATUS_N_ALLOWABLE_FAILURES 3
2080 /** We are not a directory cache or authority. Update our network-status list
2081 * by launching a new directory fetch for enough network-status documents "as
2082 * necessary". See function comments for implementation details.
2084 static void
2085 update_networkstatus_client_downloads(time_t now)
2087 int n_live = 0, needed = 0, n_running_dirservers, n_dirservers, i;
2088 int most_recent_idx = -1;
2089 trusted_dir_server_t *most_recent = NULL;
2090 time_t most_recent_received = 0;
2091 char *resource, *cp;
2092 size_t resource_len;
2094 if (connection_get_by_type_purpose(CONN_TYPE_DIR,
2095 DIR_PURPOSE_FETCH_NETWORKSTATUS))
2096 return;
2098 /* This is a little tricky. We want to download enough network-status
2099 * objects so that we have at least half of them under
2100 * NETWORKSTATUS_MAX_VALIDITY publication time. We want to download a new
2101 * *one* if the most recent one's publication time is under
2102 * NETWORKSTATUS_CLIENT_DL_INTERVAL.
2104 if (!trusted_dir_servers || !smartlist_len(trusted_dir_servers))
2105 return;
2106 n_dirservers = n_running_dirservers = smartlist_len(trusted_dir_servers);
2107 SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, ds,
2109 networkstatus_t *ns = networkstatus_get_by_digest(ds->digest);
2110 if (!ns)
2111 continue;
2112 if (ds->n_networkstatus_failures > NETWORKSTATUS_N_ALLOWABLE_FAILURES) {
2113 --n_running_dirservers;
2114 continue;
2116 if (ns->published_on > now-NETWORKSTATUS_MAX_VALIDITY)
2117 ++n_live;
2118 if (!most_recent || ns->received_on > most_recent_received) {
2119 most_recent_idx = ds_sl_idx; /* magic variable from FOREACH */
2120 most_recent = ds;
2121 most_recent_received = ns->received_on;
2125 /* Download enough so we have at least half live, but no more than all the
2126 * trusted dirservers we know.
2128 if (n_live < (n_dirservers/2)+1)
2129 needed = (n_dirservers/2)+1-n_live;
2130 if (needed > n_running_dirservers)
2131 needed = n_running_dirservers;
2133 if (needed)
2134 info(LD_DIR, "For %d/%d running directory servers, we have %d live"
2135 " network-status documents. Downloading %d.",
2136 n_running_dirservers, n_dirservers, n_live, needed);
2138 /* Also, download at least 1 every NETWORKSTATUS_CLIENT_DL_INTERVAL. */
2139 if (n_running_dirservers &&
2140 most_recent_received < now-NETWORKSTATUS_CLIENT_DL_INTERVAL && needed < 1) {
2141 info(LD_DIR, "Our most recent network-status document (from %s) "
2142 "is %d seconds old; downloading another.",
2143 most_recent?most_recent->description:"nobody",
2144 (int)(now-most_recent_received));
2145 needed = 1;
2148 if (!needed)
2149 return;
2151 /* If no networkstatus was found, choose a dirserver at random as "most
2152 * recent". */
2153 if (most_recent_idx<0)
2154 most_recent_idx = crypto_rand_int(n_dirservers);
2156 /* Build a request string for all the resources we want. */
2157 resource_len = needed * (HEX_DIGEST_LEN+1) + 6;
2158 resource = tor_malloc(resource_len);
2159 memcpy(resource, "fp/", 3);
2160 cp = resource+3;
2161 for (i = most_recent_idx+1; needed; ++i) {
2162 trusted_dir_server_t *ds;
2163 if (i >= n_dirservers)
2164 i = 0;
2165 ds = smartlist_get(trusted_dir_servers, i);
2166 if (ds->n_networkstatus_failures > NETWORKSTATUS_N_ALLOWABLE_FAILURES)
2167 continue;
2168 base16_encode(cp, HEX_DIGEST_LEN+1, ds->digest, DIGEST_LEN);
2169 cp += HEX_DIGEST_LEN;
2170 --needed;
2171 if (needed)
2172 *cp++ = '+';
2174 memcpy(cp, ".z", 3);
2175 directory_get_from_dirserver(DIR_PURPOSE_FETCH_NETWORKSTATUS, resource, 1);
2176 tor_free(resource);
2179 /*DOCDOC*/
2180 void
2181 update_networkstatus_downloads(time_t now)
2183 or_options_t *options = get_options();
2184 if (server_mode(options) && options->DirPort)
2185 update_networkstatus_cache_downloads(time(NULL));
2186 else
2187 update_networkstatus_client_downloads(time(NULL));
2190 /** Decide whether a given addr:port is definitely accepted,
2191 * definitely rejected, probably accepted, or probably rejected by a
2192 * given policy. If <b>addr</b> is 0, we don't know the IP of the
2193 * target address. If <b>port</b> is 0, we don't know the port of the
2194 * target address.
2196 * For now, the algorithm is pretty simple: we look for definite and
2197 * uncertain matches. The first definite match is what we guess; if
2198 * it was preceded by no uncertain matches of the opposite policy,
2199 * then the guess is definite; otherwise it is probable. (If we
2200 * have a known addr and port, all matches are definite; if we have an
2201 * unknown addr/port, any address/port ranges other than "all" are
2202 * uncertain.)
2204 * We could do better by assuming that some ranges never match typical
2205 * addresses (127.0.0.1, and so on). But we'll try this for now.
2207 addr_policy_result_t
2208 router_compare_addr_to_addr_policy(uint32_t addr, uint16_t port,
2209 addr_policy_t *policy)
2211 int maybe_reject = 0;
2212 int maybe_accept = 0;
2213 int match = 0;
2214 int maybe = 0;
2215 addr_policy_t *tmpe;
2217 for (tmpe=policy; tmpe; tmpe=tmpe->next) {
2218 maybe = 0;
2219 if (!addr) {
2220 /* Address is unknown. */
2221 if ((port >= tmpe->prt_min && port <= tmpe->prt_max) ||
2222 (!port && tmpe->prt_min<=1 && tmpe->prt_max>=65535)) {
2223 /* The port definitely matches. */
2224 if (tmpe->msk == 0) {
2225 match = 1;
2226 } else {
2227 maybe = 1;
2229 } else if (!port) {
2230 /* The port maybe matches. */
2231 maybe = 1;
2233 } else {
2234 /* Address is known */
2235 if ((addr & tmpe->msk) == (tmpe->addr & tmpe->msk)) {
2236 if (port >= tmpe->prt_min && port <= tmpe->prt_max) {
2237 /* Exact match for the policy */
2238 match = 1;
2239 } else if (!port) {
2240 maybe = 1;
2244 if (maybe) {
2245 if (tmpe->policy_type == ADDR_POLICY_REJECT)
2246 maybe_reject = 1;
2247 else
2248 maybe_accept = 1;
2250 if (match) {
2251 if (tmpe->policy_type == ADDR_POLICY_ACCEPT) {
2252 /* If we already hit a clause that might trigger a 'reject', than we
2253 * can't be sure of this certain 'accept'.*/
2254 return maybe_reject ? ADDR_POLICY_PROBABLY_ACCEPTED : ADDR_POLICY_ACCEPTED;
2255 } else {
2256 return maybe_accept ? ADDR_POLICY_PROBABLY_REJECTED : ADDR_POLICY_REJECTED;
2260 /* accept all by default. */
2261 return maybe_reject ? ADDR_POLICY_PROBABLY_ACCEPTED : ADDR_POLICY_ACCEPTED;
2264 /** Return 1 if all running sufficiently-stable routers will reject
2265 * addr:port, return 0 if any might accept it. */
2267 router_exit_policy_all_routers_reject(uint32_t addr, uint16_t port,
2268 int need_uptime)
2270 addr_policy_result_t r;
2271 if (!routerlist) return 1;
2273 SMARTLIST_FOREACH(routerlist->routers, routerinfo_t *, router,
2275 if (router->is_running &&
2276 !router_is_unreliable(router, need_uptime, 0)) {
2277 r = router_compare_addr_to_addr_policy(addr, port, router->exit_policy);
2278 if (r != ADDR_POLICY_REJECTED && r != ADDR_POLICY_PROBABLY_REJECTED)
2279 return 0; /* this one could be ok. good enough. */
2282 return 1; /* all will reject. */
2286 * If <b>policy</b> implicitly allows connections to any port in the
2287 * IP set <b>addr</b>/<b>mask</b>, then set *<b>policy_out</b> to the
2288 * part of the policy that allows it, and return 1. Else return 0.
2290 * A policy allows an IP:Port combination <em>implicitly</em> if
2291 * it is included in a *: pattern, or in a fallback pattern.
2293 static int
2294 policy_includes_addr_mask_implicitly(addr_policy_t *policy,
2295 uint32_t addr, uint32_t mask,
2296 addr_policy_t **policy_out)
2298 uint32_t addr2;
2299 tor_assert(policy_out);
2300 addr &= mask;
2301 addr2 = addr | ~mask;
2302 for (; policy; policy=policy->next) {
2303 /* Does this policy cover all of the address range we're looking at? */
2304 /* Boolean logic time: range X is contained in range Y if, for
2305 * each bit B, all possible values of B in X are values of B in Y.
2306 * In "addr", we have every fixed bit set to its value, and every
2307 * free bit set to 0. In "addr2", we have every fixed bit set to
2308 * its value, and every free bit set to 1. So if addr and addr2 are
2309 * both in the policy, the range is covered by the policy.
2311 uint32_t p_addr = policy->addr & policy->msk;
2312 if (p_addr == (addr & policy->msk) &&
2313 p_addr == (addr2 & policy->msk) &&
2314 (policy->prt_min <= 1 && policy->prt_max == 65535)) {
2315 return 0;
2317 /* Does this policy cover some of the address range we're looking at? */
2318 /* Boolean logic time: range X and range Y intersect if there is
2319 * some z such that z & Xmask == Xaddr and z & Ymask == Yaddr.
2320 * This is FALSE iff there is some bit b where Xmask == yMask == 1
2321 * and Xaddr != Yaddr. So if X intersects with Y iff at every
2322 * place where Xmask&Ymask==1, Xaddr == Yaddr, or equivalently,
2323 * Xaddr&Xmask&Ymask == Yaddr&Xmask&Ymask.
2325 if ((policy->addr & policy->msk & mask) == (addr & policy->msk) &&
2326 policy->policy_type == ADDR_POLICY_ACCEPT) {
2327 *policy_out = policy;
2328 return 1;
2331 *policy_out = NULL;
2332 return 1;
2335 /** If <b>policy</b> implicitly allows connections to any port on
2336 * 127.*, 192.168.*, etc, then warn (if <b>warn</b> is set) and return
2337 * true. Else return false.
2340 exit_policy_implicitly_allows_local_networks(addr_policy_t *policy,
2341 int warn)
2343 addr_policy_t *p;
2344 int r=0,i;
2345 static struct {
2346 uint32_t addr; uint32_t mask; const char *network;
2347 } private_networks[] = {
2348 { 0x7f000000, 0xff000000, "localhost (127.0.0.0/8)" },
2349 { 0x0a000000, 0xff000000, "addresses in private network 10.0.0.0/8" },
2350 { 0xa9fe0000, 0xffff0000, "addresses in private network 169.254.0.0/16" },
2351 { 0xac100000, 0xfff00000, "addresses in private network 172.16.0.0/12" },
2352 { 0xc0a80000, 0xffff0000, "addresses in private network 192.168.0.0/16" },
2353 { 0,0,NULL},
2355 for (i=0; private_networks[i].addr; ++i) {
2356 p = NULL;
2357 /* log_fn(LOG_INFO,"Checking network %s", private_networks[i].network); */
2358 if (policy_includes_addr_mask_implicitly(
2359 policy, private_networks[i].addr, private_networks[i].mask, &p)) {
2360 if (warn)
2361 warn(LD_CONFIG, "Exit policy %s implicitly accepts %s",
2362 p?p->string:"(default)",
2363 private_networks[i].network);
2364 r = 1;
2368 return r;
2371 /** Return true iff <b>router</b> does not permit exit streams.
2374 router_exit_policy_rejects_all(routerinfo_t *router)
2376 return router_compare_addr_to_addr_policy(0, 0, router->exit_policy)
2377 == ADDR_POLICY_REJECTED;
2380 /** Add to the list of authorized directory servers one at
2381 * <b>address</b>:<b>port</b>, with identity key <b>digest</b>. If
2382 * <b>address</b> is NULL, add ourself. */
2383 void
2384 add_trusted_dir_server(const char *nickname, const char *address,
2385 uint16_t port, const char *digest, int supports_v1)
2387 trusted_dir_server_t *ent;
2388 uint32_t a;
2389 char *hostname = NULL;
2390 size_t dlen;
2391 if (!trusted_dir_servers)
2392 trusted_dir_servers = smartlist_create();
2394 if (!address) { /* The address is us; we should guess. */
2395 if (resolve_my_address(get_options(), &a, &hostname) < 0) {
2396 warn(LD_CONFIG, "Couldn't find a suitable address when adding ourself as a trusted directory server.");
2397 return;
2399 } else {
2400 if (tor_lookup_hostname(address, &a)) {
2401 warn(LD_CONFIG, "Unable to lookup address for directory server at %s",
2402 address);
2403 return;
2405 hostname = tor_strdup(address);
2406 a = ntohl(a);
2409 ent = tor_malloc_zero(sizeof(trusted_dir_server_t));
2410 ent->nickname = nickname ? tor_strdup(nickname) : NULL;
2411 ent->address = hostname;
2412 ent->addr = a;
2413 ent->dir_port = port;
2414 ent->is_running = 1;
2415 ent->supports_v1_protocol = supports_v1;
2416 memcpy(ent->digest, digest, DIGEST_LEN);
2418 dlen = 64 + strlen(hostname) + (nickname?strlen(nickname):0);
2419 ent->description = tor_malloc(dlen);
2420 if (nickname)
2421 tor_snprintf(ent->description, dlen, "directory server \"%s\" at %s:%d",
2422 nickname, hostname, (int)port);
2423 else
2424 tor_snprintf(ent->description, dlen, "directory server at %s:%d",
2425 hostname, (int)port);
2427 smartlist_add(trusted_dir_servers, ent);
2430 /** Free storage held in <b>ds</b> */
2431 void
2432 trusted_dir_server_free(trusted_dir_server_t *ds)
2434 tor_free(ds->nickname);
2435 tor_free(ds->description);
2436 tor_free(ds->address);
2437 tor_free(ds);
2440 /** Remove all members from the list of trusted dir servers. */
2441 void
2442 clear_trusted_dir_servers(void)
2444 if (trusted_dir_servers) {
2445 SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, ent,
2446 trusted_dir_server_free(ent));
2447 smartlist_clear(trusted_dir_servers);
2448 } else {
2449 trusted_dir_servers = smartlist_create();
2453 /** Return the network status with a given identity digest. */
2454 networkstatus_t *
2455 networkstatus_get_by_digest(const char *digest)
2457 SMARTLIST_FOREACH(networkstatus_list, networkstatus_t *, ns,
2459 if (!memcmp(ns->identity_digest, digest, DIGEST_LEN))
2460 return ns;
2462 return NULL;
2465 /** If the network-status list has changed since the last time we called this
2466 * function, update the status of every router from the network-status list.
2468 void
2469 routers_update_all_from_networkstatus(void)
2471 #define SELF_OPINION_INTERVAL 90*60
2472 routerinfo_t *me;
2473 time_t now;
2474 if (!routerlist || !networkstatus_list ||
2475 (!networkstatus_list_has_changed && !routerstatus_list_has_changed))
2476 return;
2478 now = time(NULL);
2479 if (networkstatus_list_has_changed)
2480 routerstatus_list_update_from_networkstatus(now);
2482 routers_update_status_from_networkstatus(routerlist->routers, 0, 0);
2484 me = router_get_my_routerinfo();
2485 if (me && !have_warned_about_unverified_status) {
2486 int n_recent = 0, n_listing = 0, n_valid = 0, n_named = 0;
2487 routerstatus_t *rs;
2488 SMARTLIST_FOREACH(networkstatus_list, networkstatus_t *, ns,
2490 if (ns->received_on + SELF_OPINION_INTERVAL < now)
2491 continue;
2492 ++n_recent;
2493 if (!(rs = networkstatus_find_entry(ns, me->identity_digest)))
2494 continue;
2495 ++n_listing;
2496 if (rs->is_valid)
2497 ++n_valid;
2498 if (rs->is_named)
2499 ++n_named;
2502 if (n_recent >= 2 && n_listing >= 2) {
2503 if (n_valid <= n_recent/2) {
2504 warn(LD_GENERAL, "%d/%d recent directory servers list us as invalid. Please consider sending your identity fingerprint to the tor-ops.",
2505 n_recent-n_valid, n_recent);
2506 have_warned_about_unverified_status = 1;
2507 } else if (n_named <= n_recent/2) {
2508 warn(LD_GENERAL, "%d/%d recent directory servers list us as unnamed. Please consider sending your identity fingerprint to the tor-ops.",
2509 n_recent-n_valid, n_recent);
2510 have_warned_about_unverified_status = 1;
2515 helper_nodes_set_status_from_directory();
2517 if (!have_warned_about_old_version) {
2518 int n_recent = 0;
2519 int n_recommended = 0;
2520 int is_server = server_mode(get_options());
2521 version_status_t consensus = VS_RECOMMENDED;
2522 SMARTLIST_FOREACH(networkstatus_list, networkstatus_t *, ns,
2524 version_status_t vs;
2525 if (!ns->recommends_versions ||
2526 ns->received_on + SELF_OPINION_INTERVAL < now )
2527 continue;
2528 vs = tor_version_is_obsolete(
2529 VERSION, is_server ? ns->server_versions : ns->client_versions);
2530 if (vs == VS_RECOMMENDED)
2531 ++n_recommended;
2532 if (n_recent++ == 0) {
2533 consensus = vs;
2534 } else if (consensus != vs) {
2535 consensus = version_status_join(consensus, vs);
2538 if (n_recent > 2 && n_recommended < n_recent/2) {
2539 if (consensus == VS_NEW || consensus == VS_NEW_IN_SERIES) {
2540 if (!have_warned_about_new_version) {
2541 notice(LD_GENERAL, "This version of Tor (%s) is newer than any recommended version%s, according to %d/%d recent network statuses.",
2542 VERSION, consensus == VS_NEW_IN_SERIES ? " in its series" : "",
2543 n_recent-n_recommended, n_recent);
2544 have_warned_about_new_version = 1;
2546 } else {
2547 notice(LD_GENERAL, "This version of Tor (%s) is %s, according to %d/%d recent network statuses.",
2548 VERSION, consensus == VS_OLD ? "obsolete" : "not recommended",
2549 n_recent-n_recommended, n_recent);
2550 have_warned_about_old_version = 1;
2552 } else {
2553 info(LD_GENERAL, "%d/%d recent directories think my version is ok.",
2554 n_recommended, n_recent);
2558 routerstatus_list_has_changed = 0;
2561 /** Allow any network-status newer than this to influence our view of who's
2562 * running. */
2563 #define DEFAULT_RUNNING_INTERVAL 60*60
2564 /** If possible, always allow at least this many network-statuses to influence
2565 * our view of who's running. */
2566 #define MIN_TO_INFLUENCE_RUNNING 3
2568 /** Change the is_recent field of each member of networkstatus_list so that
2569 * all members more recent than DEFAULT_RUNNING_INTERVAL are recent, and
2570 * at least the MIN_TO_INFLUENCE_RUNNING most recent members are resent, and no
2571 * others are recent. Set networkstatus_list_has_changed if anything happeed.
2573 void
2574 networkstatus_list_update_recent(time_t now)
2576 int n_statuses, n_recent, changed, i;
2577 char published[ISO_TIME_LEN+1];
2579 if (!networkstatus_list)
2580 return;
2582 n_statuses = smartlist_len(networkstatus_list);
2583 n_recent = 0;
2584 changed = 0;
2585 for (i=n_statuses-1; i >= 0; --i) {
2586 networkstatus_t *ns = smartlist_get(networkstatus_list, i);
2587 trusted_dir_server_t *ds =
2588 router_get_trusteddirserver_by_digest(ns->identity_digest);
2589 const char *src = ds?ds->description:ns->source_address;
2590 if (n_recent < MIN_TO_INFLUENCE_RUNNING ||
2591 ns->published_on + DEFAULT_RUNNING_INTERVAL > now) {
2592 if (!ns->is_recent) {
2593 format_iso_time(published, ns->published_on);
2594 info(LD_DIR,
2595 "Networkstatus from %s (published %s) is now \"recent\"",
2596 src, published);
2597 changed = 1;
2599 ns->is_recent = 1;
2600 ++n_recent;
2601 } else {
2602 if (ns->is_recent) {
2603 format_iso_time(published, ns->published_on);
2604 info(LD_DIR,
2605 "Networkstatus from %s (published %s) is no longer \"recent\"",
2606 src, published);
2607 changed = 1;
2608 ns->is_recent = 0;
2612 if (changed)
2613 networkstatus_list_has_changed = 1;
2616 /** Update our view of router status (as stored in routerstatus_list) from
2617 * the current set of network status documents (as stored in networkstatus_list).
2618 * Do nothing unless the network status list has changed since the last time
2619 * this function was called.
2621 static void
2622 routerstatus_list_update_from_networkstatus(time_t now)
2624 or_options_t *options = get_options();
2625 int n_trusted, n_statuses, n_recent=0, n_naming=0;
2626 int n_distinct = 0;
2627 int i, warned;
2628 int *index, *size;
2629 networkstatus_t **networkstatus;
2630 smartlist_t *result;
2631 strmap_t *name_map;
2632 char conflict[DIGEST_LEN];
2634 networkstatus_list_update_recent(now);
2636 if (!networkstatus_list_has_changed)
2637 return;
2638 if (!networkstatus_list)
2639 networkstatus_list = smartlist_create();
2640 if (!routerstatus_list)
2641 routerstatus_list = smartlist_create();
2642 if (!trusted_dir_servers)
2643 trusted_dir_servers = smartlist_create();
2644 if (!warned_conflicts)
2645 warned_conflicts = smartlist_create();
2647 n_trusted = smartlist_len(trusted_dir_servers);
2648 n_statuses = smartlist_len(networkstatus_list);
2650 if (n_statuses < (n_trusted/2)+1) {
2651 /* Not enough statuses to adjust status. */
2652 notice(LD_DIR,"Not enough statuses to update router status list. (%d/%d)",
2653 n_statuses, n_trusted);
2654 return;
2657 info(LD_DIR, "Rebuilding router status list.");
2659 index = tor_malloc(sizeof(int)*n_statuses);
2660 size = tor_malloc(sizeof(int)*n_statuses);
2661 networkstatus = tor_malloc(sizeof(networkstatus_t *)*n_statuses);
2662 for (i = 0; i < n_statuses; ++i) {
2663 index[i] = 0;
2664 networkstatus[i] = smartlist_get(networkstatus_list, i);
2665 size[i] = smartlist_len(networkstatus[i]->entries);
2666 if (networkstatus[i]->binds_names)
2667 ++n_naming;
2668 if (networkstatus[i]->is_recent)
2669 ++n_recent;
2672 name_map = strmap_new();
2673 memset(conflict, 0xff, sizeof(conflict));
2674 for (i = 0; i < n_statuses; ++i) {
2675 if (!networkstatus[i]->binds_names)
2676 continue;
2677 SMARTLIST_FOREACH(networkstatus[i]->entries, routerstatus_t *, rs,
2679 const char *other_digest;
2680 if (!rs->is_named)
2681 continue;
2682 other_digest = strmap_get_lc(name_map, rs->nickname);
2683 warned = smartlist_string_isin(warned_conflicts, rs->nickname);
2684 if (!other_digest) {
2685 strmap_set_lc(name_map, rs->nickname, rs->identity_digest);
2686 if (warned)
2687 smartlist_string_remove(warned_conflicts, rs->nickname);
2688 } else if (memcmp(other_digest, rs->identity_digest, DIGEST_LEN) &&
2689 other_digest != conflict) {
2690 if (!warned) {
2691 int should_warn = options->DirPort && options->AuthoritativeDir;
2692 char fp1[HEX_DIGEST_LEN+1];
2693 char fp2[HEX_DIGEST_LEN+1];
2694 base16_encode(fp1, sizeof(fp1), other_digest, DIGEST_LEN);
2695 base16_encode(fp2, sizeof(fp2), rs->identity_digest, DIGEST_LEN);
2696 log_fn(should_warn ? LOG_WARN : LOG_INFO, LD_DIR,
2697 "Naming authorities disagree about which key goes with %s. ($%s vs $%s)",
2698 rs->nickname, fp1, fp2);
2699 strmap_set_lc(name_map, rs->nickname, conflict);
2700 smartlist_add(warned_conflicts, tor_strdup(rs->nickname));
2702 } else {
2703 if (warned)
2704 smartlist_string_remove(warned_conflicts, rs->nickname);
2709 result = smartlist_create();
2711 /* Iterate through all of the sorted routerstatus lists in step.
2712 * Invariants:
2713 * - For 0 <= i < n_statuses: index[i] is an index into
2714 * networkstatus[i]->entries, which has size[i] elements.
2715 * - For i1, i2, j such that 0 <= i1 < n_statuses, 0 <= i2 < n_statues, 0 <=
2716 * j < index[i1], networkstatus[i1]->entries[j]->identity_digest <
2717 * networkstatus[i2]->entries[index[i2]]->identity_digest.
2719 * (That is, the indices are always advanced past lower digest before
2720 * higher.)
2722 while (1) {
2723 int n_running=0, n_named=0, n_valid=0, n_listing=0;
2724 const char *the_name = NULL;
2725 local_routerstatus_t *rs_out, *rs_old;
2726 routerstatus_t *rs, *most_recent;
2727 networkstatus_t *ns;
2728 const char *lowest = NULL;
2729 /* Find out which of the digests appears first. */
2730 for (i = 0; i < n_statuses; ++i) {
2731 if (index[i] < size[i]) {
2732 rs = smartlist_get(networkstatus[i]->entries, index[i]);
2733 if (!lowest || memcmp(rs->identity_digest, lowest, DIGEST_LEN)<0)
2734 lowest = rs->identity_digest;
2737 if (!lowest) {
2738 /* We're out of routers. Great! */
2739 break;
2741 /* Okay. The routers at networkstatus[i]->entries[index[i]] whose digests
2742 * match "lowest" are next in order. Iterate over them, incrementing those
2743 * index[i] as we go. */
2744 ++n_distinct;
2745 most_recent = NULL;
2746 for (i = 0; i < n_statuses; ++i) {
2747 if (index[i] >= size[i])
2748 continue;
2749 ns = networkstatus[i];
2750 rs = smartlist_get(ns->entries, index[i]);
2751 if (memcmp(rs->identity_digest, lowest, DIGEST_LEN))
2752 continue;
2753 ++index[i];
2754 ++n_listing;
2755 if (!most_recent || rs->published_on > most_recent->published_on)
2756 most_recent = rs;
2757 if (rs->is_named && ns->binds_names) {
2758 if (!the_name)
2759 the_name = rs->nickname;
2760 if (!strcasecmp(rs->nickname, the_name)) {
2761 ++n_named;
2762 } else if (strcmp(the_name,"**mismatch**")) {
2763 char hd[HEX_DIGEST_LEN+1];
2764 base16_encode(hd, HEX_DIGEST_LEN+1, rs->identity_digest, DIGEST_LEN);
2765 if (! smartlist_string_isin(warned_conflicts, hd)) {
2766 warn(LD_DIR, "Naming authorities disagree about nicknames for $%s (\"%s\" vs \"%s\")",
2767 hd, the_name, rs->nickname);
2768 smartlist_add(warned_conflicts, tor_strdup(hd));
2770 the_name = "**mismatch**";
2773 if (rs->is_valid)
2774 ++n_valid;
2775 if (rs->is_running && ns->is_recent)
2776 ++n_running;
2778 rs_out = tor_malloc_zero(sizeof(local_routerstatus_t));
2779 memcpy(&rs_out->status, most_recent, sizeof(routerstatus_t));
2780 if ((rs_old = router_get_combined_status_by_digest(lowest))) {
2781 rs_out->n_download_failures = rs_old->n_download_failures;
2782 rs_out->next_attempt_at = rs_old->next_attempt_at;
2783 rs_out->name_lookup_warned = rs_old->name_lookup_warned;
2785 smartlist_add(result, rs_out);
2786 debug(LD_DIR, "Router '%s' is listed by %d/%d directories, "
2787 "named by %d/%d, validated by %d/%d, and %d/%d recent directories "
2788 "think it's running.",
2789 rs_out->status.nickname,
2790 n_listing, n_statuses, n_named, n_naming, n_valid, n_statuses,
2791 n_running, n_recent);
2792 rs_out->status.is_named = 0;
2793 if (the_name && strcmp(the_name, "**mismatch**") && n_named > 0) {
2794 const char *d = strmap_get_lc(name_map, the_name);
2795 if (d && d != conflict)
2796 rs_out->status.is_named = 1;
2797 if (smartlist_string_isin(warned_conflicts, rs_out->status.nickname))
2798 smartlist_string_remove(warned_conflicts, rs_out->status.nickname);
2800 if (rs_out->status.is_named)
2801 strlcpy(rs_out->status.nickname, the_name, sizeof(rs_out->status.nickname));
2802 rs_out->status.is_valid = n_valid > n_statuses/2;
2803 rs_out->status.is_running = n_running > n_recent/2;
2805 SMARTLIST_FOREACH(routerstatus_list, local_routerstatus_t *, rs,
2806 local_routerstatus_free(rs));
2807 smartlist_free(routerstatus_list);
2808 routerstatus_list = result;
2810 tor_free(networkstatus);
2811 tor_free(index);
2812 tor_free(size);
2813 strmap_free(name_map, NULL);
2815 networkstatus_list_has_changed = 0;
2816 routerstatus_list_has_changed = 1;
2819 /** Given a list <b>routers</b> of routerinfo_t *, update each routers's
2820 * is_named, is_verified, and is_running fields according to our current
2821 * networkstatus_t documents. */
2822 void
2823 routers_update_status_from_networkstatus(smartlist_t *routers, int reset_failures, int assume_recognized)
2825 trusted_dir_server_t *ds;
2826 local_routerstatus_t *rs;
2827 or_options_t *options = get_options();
2828 int authdir = options->AuthoritativeDir;
2829 int namingdir = options->AuthoritativeDir &&
2830 options->NamingAuthoritativeDir;
2832 if (!routerstatus_list)
2833 return;
2835 SMARTLIST_FOREACH(routers, routerinfo_t *, router,
2837 rs = router_get_combined_status_by_digest(router->identity_digest);
2838 ds = router_get_trusteddirserver_by_digest(router->identity_digest);
2840 if (!rs)
2841 continue;
2843 if (!namingdir)
2844 router->is_named = rs->status.is_named;
2846 if (!authdir) {
2847 /* If we're an authdir, don't believe others. */
2848 router->is_verified = rs->status.is_valid;
2849 router->is_running = rs->status.is_running;
2851 if (router->is_running && ds) {
2852 ds->n_networkstatus_failures = 0;
2854 if (assume_recognized) {
2855 router->xx_is_recognized = 1;
2856 } else {
2857 if (!router->xx_is_recognized) {
2858 router->xx_is_recognized = routerdesc_digest_is_recognized(
2859 router->identity_digest, router->signed_descriptor_digest);
2861 router->xx_is_extra_new = router->published_on > rs->status.published_on;
2863 if (reset_failures && router->xx_is_recognized) {
2864 rs->n_download_failures = 0;
2865 rs->next_attempt_at = 0;
2870 /** Return new list of ID fingerprints for superseded routers. A router is
2871 * superseded if any network-status has a router with a different digest
2872 * published more recently, or if it is listed in the network-status but not
2873 * in the router list.
2875 static smartlist_t *
2876 router_list_downloadable(void)
2878 #define MAX_OLD_SERVER_DOWNLOAD_RATE 2*60*60
2879 int n_conns, i, n_downloadable = 0;
2880 connection_t **carray;
2881 smartlist_t *superseded = smartlist_create();
2882 smartlist_t *downloading;
2883 time_t now = time(NULL);
2884 int mirror = server_mode(get_options()) && get_options()->DirPort;
2885 /* these are just used for logging */
2886 int n_not_ready = 0, n_in_progress = 0, n_uptodate = 0, n_skip_old = 0,
2887 n_obsolete = 0, xx_n_unrecognized = 0, xx_n_extra_new = 0, xx_n_both = 0,
2888 xx_n_unrec_old = 0;
2890 if (!routerstatus_list)
2891 return superseded;
2893 get_connection_array(&carray, &n_conns);
2895 routerstatus_list_update_from_networkstatus(now);
2897 SMARTLIST_FOREACH(routerstatus_list, local_routerstatus_t *, rs,
2899 if (rs->status.published_on + ROUTER_MAX_AGE < now) {
2900 rs->should_download = 0;
2901 ++n_obsolete;
2902 } if (rs->next_attempt_at < now) {
2903 rs->should_download = 1;
2904 ++n_downloadable;
2905 } else {
2907 char fp[HEX_DIGEST_LEN+1];
2908 base16_encode(fp, HEX_DIGEST_LEN+1, rs->status.identity_digest, DIGEST_LEN);
2909 log_fn(LOG_NOTICE, "Not yet ready to download %s (%d more seconds)", fp,
2910 (int)(rs->next_attempt_at-now));
2912 rs->should_download = 0;
2913 ++n_not_ready;
2917 downloading = smartlist_create();
2918 for (i = 0; i < n_conns; ++i) {
2919 connection_t *conn = carray[i];
2920 if (conn->type == CONN_TYPE_DIR &&
2921 conn->purpose == DIR_PURPOSE_FETCH_SERVERDESC &&
2922 !conn->marked_for_close) {
2923 if (!strcmpstart(conn->requested_resource, "all"))
2924 n_downloadable = 0;
2925 dir_split_resource_into_fingerprints(conn->requested_resource,
2926 downloading, NULL, 1);
2930 if (n_downloadable) {
2931 SMARTLIST_FOREACH(downloading, const char *, d,
2933 local_routerstatus_t *rs;
2934 if ((rs = router_get_combined_status_by_digest(d)) && rs->should_download) {
2935 rs->should_download = 0;
2936 --n_downloadable;
2937 ++n_in_progress;
2941 SMARTLIST_FOREACH(downloading, char *, cp, tor_free(cp));
2942 smartlist_free(downloading);
2943 if (!n_downloadable)
2944 return superseded;
2946 if (routerlist && n_downloadable) {
2947 SMARTLIST_FOREACH(routerlist->routers, routerinfo_t *, ri,
2949 local_routerstatus_t *rs;
2950 if (!(rs = router_get_combined_status_by_digest(ri->identity_digest)) ||
2951 !rs->should_download) {
2952 // log_fn(LOG_NOTICE, "No status for %s", fp);
2953 continue;
2955 if (!ri->xx_is_recognized) {
2956 ++xx_n_unrecognized;
2957 if (ri->xx_is_extra_new)
2958 ++xx_n_both;
2960 if (ri->xx_is_extra_new)
2961 ++xx_n_extra_new;
2963 /* Change this "or" to be an "and" once dirs generate hashes right.
2964 * Remove the version check once older versions are uncommon.
2965 * XXXXX. NM */
2966 if (!memcmp(ri->signed_descriptor_digest, rs->status.descriptor_digest,
2967 DIGEST_LEN) ||
2968 rs->status.published_on <= ri->published_on) {
2969 ++n_uptodate;
2970 rs->should_download = 0;
2971 --n_downloadable;
2972 } else if (!mirror &&
2973 ri->platform &&
2974 !tor_version_as_new_as(ri->platform, "0.1.1.6-alpha") &&
2975 ri->published_on + MAX_OLD_SERVER_DOWNLOAD_RATE > now) {
2976 /* Same digest, or date is up-to-date, or we have a comparatively recent
2977 * server with an old version.
2978 * No need to download it. */
2979 // log_fn(LOG_NOTICE, "Up-to-date status for %s", fp);
2980 ++n_skip_old;
2981 if (!ri->xx_is_recognized)
2982 ++xx_n_unrec_old;
2983 rs->should_download = 0;
2984 --n_downloadable;
2985 } /* else {
2986 char t1[ISO_TIME_LEN+1];
2987 char t2[ISO_TIME_LEN+1];
2988 format_iso_time(t1, rs->satus.published_on);
2989 format_iso_time(t2, ri->published_on);
2990 log_fn(LOG_NOTICE, "Out-of-date status for %s %s (%d %d) [%s %s]", fp,
2991 ri->nickname,
2992 !memcmp(ri->signed_descriptor_digest,rs->status.descriptor_digest,
2993 DIGEST_LEN),
2994 rs->published_on < ri->published_on,
2995 t1, t2);
2996 } */
3000 info(LD_DIR, "%d router descriptors are downloadable; "
3001 "%d are up to date; %d are in progress; "
3002 "%d are not ready to retry; "
3003 "%d are not published recently enough to be worthwhile; "
3004 "%d are running pre-0.1.1.6 Tors and aren't stale enough to replace. "
3005 "%d have unrecognized descriptor hashes; %d are newer than the dirs "
3006 "have told us about; %d are both unrecognized and newer than any "
3007 "publication date in the networkstatus; %d are both "
3008 "unrecognized and running a pre-0.1.1.6 version.",
3009 n_downloadable, n_uptodate, n_in_progress, n_not_ready,
3010 n_obsolete, n_skip_old, xx_n_unrecognized, xx_n_extra_new, xx_n_both,
3011 xx_n_unrec_old);
3013 if (!n_downloadable)
3014 return superseded;
3016 SMARTLIST_FOREACH(routerstatus_list, local_routerstatus_t *, rs,
3018 if (rs->should_download) {
3019 char *fp = tor_malloc(HEX_DIGEST_LEN+1);
3020 base16_encode(fp, HEX_DIGEST_LEN+1, rs->status.identity_digest, DIGEST_LEN);
3021 smartlist_add(superseded, fp);
3025 return superseded;
3028 /** Initiate new router downloads as needed.
3030 * We only allow one router descriptor download at a time.
3031 * If we have less than two network-status documents, we ask
3032 * a directory for "all descriptors."
3033 * Otherwise, we ask for all descriptors that we think are different
3034 * from what we have.
3036 void
3037 update_router_descriptor_downloads(time_t now)
3039 #define MAX_DL_PER_REQUEST 128
3040 #define MIN_DL_PER_REQUEST 4
3041 #define MIN_REQUESTS 3
3042 #define MAX_DL_TO_DELAY 16
3043 #define MAX_CLIENT_INTERVAL_WITHOUT_REQUEST 10*60
3044 #define MAX_SERVER_INTERVAL_WITHOUT_REQUEST 1*60
3045 smartlist_t *downloadable = NULL;
3046 int get_all = 0;
3047 int dirserv = server_mode(get_options()) && get_options()->DirPort;
3048 int should_delay, n_downloadable;
3049 if (!networkstatus_list || smartlist_len(networkstatus_list)<2)
3050 get_all = 1;
3052 if (get_all) {
3053 notice(LD_DIR, "Launching request for all routers");
3054 last_routerdesc_download_attempted = now;
3055 directory_get_from_dirserver(DIR_PURPOSE_FETCH_SERVERDESC,"all.z",1);
3056 return;
3059 downloadable = router_list_downloadable();
3060 n_downloadable = smartlist_len(downloadable);
3061 if (n_downloadable >= MAX_DL_TO_DELAY) {
3062 debug(LD_DIR,
3063 "There are enough downloadable routerdescs to launch requests.");
3064 should_delay = 0;
3065 } else if (n_downloadable == 0) {
3066 debug(LD_DIR, "No routerdescs need to be downloaded.");
3067 should_delay = 1;
3068 } else {
3069 if (dirserv) {
3070 should_delay = (last_routerdesc_download_attempted +
3071 MAX_SERVER_INTERVAL_WITHOUT_REQUEST) > now;
3072 } else {
3073 should_delay = (last_routerdesc_download_attempted +
3074 MAX_CLIENT_INTERVAL_WITHOUT_REQUEST) > now;
3076 if (should_delay)
3077 debug(LD_DIR, "There are not many downloadable routerdescs; waiting till we have some more.");
3078 else
3079 info(LD_DIR, "There are not many downloadable routerdescs, but we've been waiting long enough (%d seconds). Downloading.",
3080 (int)(now-last_routerdesc_download_attempted));
3083 if (! should_delay) {
3084 int i, j, n_per_request=MAX_DL_PER_REQUEST;
3085 size_t r_len = MAX_DL_PER_REQUEST*(HEX_DIGEST_LEN+1)+16;
3086 char *resource = tor_malloc(r_len);
3088 if (! dirserv) {
3089 n_per_request = (n_downloadable+MIN_REQUESTS-1) / MIN_REQUESTS;
3090 if (n_per_request > MAX_DL_PER_REQUEST)
3091 n_per_request = MAX_DL_PER_REQUEST;
3092 if (n_per_request < MIN_DL_PER_REQUEST)
3093 n_per_request = MIN_DL_PER_REQUEST;
3095 info(LD_DIR, "Launching %d request%s for %d router%s, %d at a time",
3096 (n_downloadable+n_per_request-1)/n_per_request,
3097 n_downloadable>n_per_request?"s":"",
3098 n_downloadable, n_downloadable>1?"s":"", n_per_request);
3099 for (i=0; i < n_downloadable; i += n_per_request) {
3100 char *cp = resource;
3101 memcpy(resource, "fp/", 3);
3102 cp = resource + 3;
3103 for (j=i; j < i+n_per_request && j < n_downloadable; ++j) {
3104 memcpy(cp, smartlist_get(downloadable, j), HEX_DIGEST_LEN);
3105 cp += HEX_DIGEST_LEN;
3106 *cp++ = '+';
3108 memcpy(cp-1, ".z", 3);
3109 directory_get_from_dirserver(DIR_PURPOSE_FETCH_SERVERDESC,resource,1);
3111 last_routerdesc_download_attempted = now;
3112 tor_free(resource);
3114 SMARTLIST_FOREACH(downloadable, char *, c, tor_free(c));
3115 smartlist_free(downloadable);
3118 /** Return true iff we have enough networkstatus and router information to
3119 * start building circuits. Right now, this means "at least 2 networkstatus
3120 * documents, and at least 1/4 of expected routers." */
3122 router_have_minimum_dir_info(void)
3124 int tot = 0, avg;
3125 if (!networkstatus_list || smartlist_len(networkstatus_list)<2 ||
3126 !routerlist)
3127 return 0;
3128 SMARTLIST_FOREACH(networkstatus_list, networkstatus_t *, ns,
3129 tot += smartlist_len(ns->entries));
3130 avg = tot / smartlist_len(networkstatus_list);
3131 return smartlist_len(routerlist->routers) > (avg/4);
3134 /** Reset the descriptor download failure count on all routers, so that we
3135 * can retry any long-failed routers immediately.
3137 void
3138 router_reset_descriptor_download_failures(void)
3140 if (!routerstatus_list)
3141 return;
3142 SMARTLIST_FOREACH(routerstatus_list, local_routerstatus_t *, rs,
3144 rs->n_download_failures = 0;
3145 rs->next_attempt_at = 0;
3147 last_routerdesc_download_attempted = 0;
3150 /** Return true iff the only differences between r1 and r2 are such that
3151 * would not cause a recent (post 0.1.1.6) direserver to republish.
3154 router_differences_are_cosmetic(routerinfo_t *r1, routerinfo_t *r2)
3156 tor_assert(r1 && r2);
3158 /* post-0.1.1.6 servers know what they're doing. */
3159 if (tor_version_as_new_as(r1->platform, "0.1.1.6-alpha") ||
3160 tor_version_as_new_as(r2->platform, "0.1.1.6-alpha"))
3161 return 0;
3163 /* r1 should be the one that was published first. */
3164 if (r1->published_on > r2->published_on) {
3165 routerinfo_t *ri_tmp = r2;
3166 r2 = r1;
3167 r1 = ri_tmp;
3170 /* If any key fields differ, they're different. */
3171 if (strcasecmp(r1->address, r2->address) ||
3172 strcasecmp(r1->nickname, r2->nickname) ||
3173 r1->or_port != r2->or_port ||
3174 r1->dir_port != r2->dir_port ||
3175 crypto_pk_cmp_keys(r1->onion_pkey, r2->onion_pkey) ||
3176 crypto_pk_cmp_keys(r1->identity_pkey, r2->identity_pkey) ||
3177 strcasecmp(r1->platform, r2->platform) ||
3178 (r1->contact_info && !r2->contact_info) || /* contact_info is optional */
3179 (!r1->contact_info && r2->contact_info) ||
3180 (r1->contact_info && r2->contact_info && strcasecmp(r1->contact_info, r2->contact_info)) ||
3181 r1->is_hibernating != r2->is_hibernating ||
3182 config_cmp_addr_policies(r1->exit_policy, r2->exit_policy))
3183 return 0;
3184 if ((r1->declared_family == NULL) != (r2->declared_family == NULL))
3185 return 0;
3186 if (r1->declared_family && r2->declared_family) {
3187 int i, n;
3188 if (smartlist_len(r1->declared_family)!=smartlist_len(r2->declared_family))
3189 return 0;
3190 n = smartlist_len(r1->declared_family);
3191 for (i=0; i < n; ++i) {
3192 if (strcasecmp(smartlist_get(r1->declared_family, i),
3193 smartlist_get(r2->declared_family, i)))
3194 return 0;
3198 /* Did bandwidth change a lot? */
3199 if ((r1->bandwidthcapacity < r2->bandwidthcapacity/2) ||
3200 (r2->bandwidthcapacity < r1->bandwidthcapacity/2))
3201 return 0;
3203 /* Did more than 12 hours pass? */
3204 if (r1->published_on + 12*60*60 < r2->published_on)
3205 return 0;
3207 /* Did uptime fail to increase by approximately the amount we would think,
3208 * give or take 30 minutes? */
3209 if (abs(r2->uptime - (r1->uptime + (r2->published_on-r1->published_on)))>30*60)
3210 return 0;
3212 /* Otherwise, the difference is cosmetic. */
3213 return 1;
3216 static void
3217 routerlist_assert_ok(routerlist_t *rl)
3219 digestmap_iter_t *iter;
3220 routerinfo_t *r2;
3221 if (!routerlist)
3222 return;
3223 SMARTLIST_FOREACH(rl->routers, routerinfo_t *, r,
3225 r2 = digestmap_get(rl->identity_map, r->identity_digest);
3226 tor_assert(r == r2);
3227 r2 = digestmap_get(rl->desc_digest_map, r->signed_descriptor_digest);
3228 tor_assert(r == r2);
3230 SMARTLIST_FOREACH(rl->old_routers, routerinfo_t *, r,
3232 r2 = digestmap_get(rl->identity_map, r->identity_digest);
3233 tor_assert(r != r2);
3234 r2 = digestmap_get(rl->desc_digest_map, r->signed_descriptor_digest);
3235 tor_assert(r == r2);
3237 iter = digestmap_iter_init(rl->identity_map);
3238 while (!digestmap_iter_done(iter)) {
3239 const char *d;
3240 void *_r;
3241 routerinfo_t *r;
3242 digestmap_iter_get(iter, &d, &_r);
3243 r = _r;
3244 tor_assert(!memcmp(r->identity_digest, d, DIGEST_LEN));
3245 iter = digestmap_iter_next(rl->identity_map, iter);
3247 iter = digestmap_iter_init(rl->desc_digest_map);
3248 while (!digestmap_iter_done(iter)) {
3249 const char *d;
3250 void *_r;
3251 routerinfo_t *r;
3252 digestmap_iter_get(iter, &d, &_r);
3253 r = _r;
3254 tor_assert(!memcmp(r->signed_descriptor_digest, d, DIGEST_LEN));
3255 iter = digestmap_iter_next(rl->desc_digest_map, iter);