router_add_to_routerlist() really needs to free not-added routers.
[tor.git] / src / or / routerlist.c
blobe6303b80f03b0f14d3bd354e476cc4d7648b6ebe
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 routerinfo_free(router);
1390 return -1;
1393 if (authdir) {
1394 if (authdir_wants_to_reject_router(router, msg)) {
1395 routerinfo_free(router);
1396 return -2;
1398 authdir_verified = router->is_verified;
1400 } else {
1401 if (! router->xx_is_recognized && !from_cache) {
1402 log_fn(LOG_WARN, "Dropping unrecognized descriptor for router '%s'",
1403 router->nickname);
1404 rouerinfo_free(router);
1405 return -1;
1410 /* If we have a router with this name, and the identity key is the same,
1411 * choose the newer one. If the identity key has changed, drop the router.
1413 for (i = 0; i < smartlist_len(routerlist->routers); ++i) {
1414 routerinfo_t *old_router = smartlist_get(routerlist->routers, i);
1415 if (!crypto_pk_cmp_keys(router->identity_pkey,old_router->identity_pkey)) {
1416 if (router->published_on <= old_router->published_on) {
1417 /* Same key, but old */
1418 debug(LD_DIR, "Skipping not-new descriptor for router '%s'",
1419 router->nickname);
1420 routerlist_insert_old(routerlist, router);
1421 *msg = "Router descriptor was not new.";
1422 return -1;
1423 } else {
1424 /* Same key, new. */
1425 int unreachable = 0;
1426 debug(LD_DIR, "Replacing entry for router '%s/%s' [%s]",
1427 router->nickname, old_router->nickname,
1428 hex_str(id_digest,DIGEST_LEN));
1429 if (router->addr == old_router->addr &&
1430 router->or_port == old_router->or_port) {
1431 /* these carry over when the address and orport are unchanged.*/
1432 router->last_reachable = old_router->last_reachable;
1433 router->testing_since = old_router->testing_since;
1434 router->num_unreachable_notifications =
1435 old_router->num_unreachable_notifications;
1437 if (authdir &&
1438 dirserv_thinks_router_is_blatantly_unreachable(router, time(NULL))) {
1439 if (router->num_unreachable_notifications >= 3) {
1440 unreachable = 1;
1441 notice(LD_DIR, "Notifying server '%s' that it's unreachable. (ContactInfo '%s', platform '%s').",
1442 router->nickname, router->contact_info ? router->contact_info : "",
1443 router->platform ? router->platform : "");
1444 } else {
1445 info(LD_DIR,"'%s' may be unreachable -- the %d previous descriptors were thought to be unreachable.", router->nickname, router->num_unreachable_notifications);
1446 router->num_unreachable_notifications++;
1449 routerlist_replace(routerlist, old_router, router, i, 1);
1450 if (!from_cache)
1451 router_append_to_journal(router->signed_descriptor,
1452 router->signed_descriptor_len);
1453 directory_set_dirty();
1454 *msg = unreachable ? "Dirserver believes your ORPort is unreachable" :
1455 authdir_verified ? "Verified server updated" :
1456 "Unverified server updated. (Have you sent us your key fingerprint?)";
1457 return unreachable ? 1 : 0;
1459 } else if (!strcasecmp(router->nickname, old_router->nickname)) {
1460 /* nicknames match, keys don't. */
1461 if (router->is_named) {
1462 /* The new verified router replaces the old one; remove the
1463 * old one. And carry on to the end of the list, in case
1464 * there are more old unverified routers with this nickname
1466 /* mark-for-close connections using the old key, so we can
1467 * make new ones with the new key.
1469 connection_t *conn;
1470 while ((conn = connection_get_by_identity_digest(
1471 old_router->identity_digest, CONN_TYPE_OR))) {
1472 // And LD_OR? XXXXNM
1473 info(LD_DIR,"Closing conn to router '%s'; there is now a named router with that name.",
1474 old_router->nickname);
1475 connection_mark_for_close(conn);
1477 routerlist_remove(routerlist, old_router, i--, 0);
1478 } else if (old_router->is_named) {
1479 /* Can't replace a verified router with an unverified one. */
1480 debug(LD_DIR, "Skipping unverified entry for verified router '%s'",
1481 router->nickname);
1482 routerinfo_free(router);
1483 *msg = "Already have named router with same nickname and different key.";
1484 return -2;
1488 /* We haven't seen a router with this name before. Add it to the end of
1489 * the list. */
1490 routerlist_insert(routerlist, router);
1491 if (!from_cache)
1492 router_append_to_journal(router->signed_descriptor,
1493 router->signed_descriptor_len);
1494 directory_set_dirty();
1495 return 0;
1498 #define MAX_DESCRIPTORS_PER_ROUTER 5
1500 /** Remove any routers from the routerlist that are more than <b>age</b>
1501 * seconds old.
1503 void
1504 routerlist_remove_old_routers(int age)
1506 int i;
1507 time_t cutoff;
1508 routerinfo_t *router;
1509 if (!routerlist)
1510 return;
1512 cutoff = time(NULL) - age;
1513 for (i = 0; i < smartlist_len(routerlist->routers); ++i) {
1514 router = smartlist_get(routerlist->routers, i);
1515 if (router->published_on <= cutoff) {
1516 /* Too old. Remove it. */
1517 info(LD_DIR,"Forgetting obsolete (too old) routerinfo for router '%s'", router->nickname);
1518 routerlist_remove(routerlist, router, i--, 1);
1524 static int
1525 _compare_old_routers_by_identity(const void **_a, const void **_b)
1527 int i;
1528 const routerinfo_t *r1 = *_a, *r2 = *_b;
1529 if ((i = memcmp(r1->identity_digest, r2->identity_digest, DIGEST_LEN)))
1530 return i;
1531 return r1->published_on - r2->published_on;
1534 struct duration_idx_t {
1535 int duration;
1536 int idx;
1537 int old;
1540 static int
1541 _compare_duration_idx(const void *_d1, const void *_d2)
1543 const struct duration_idx_t *d1 = _d1;
1544 const struct duration_idx_t *d2 = _d2;
1545 return d1->duration - d2->duration;
1548 /** The range <b>lo</b> through <b>hi</b> inclusive of routerlist->old_routers
1549 * must contain routerinfo_t with the same identity and with publication time
1550 * in ascending order. Remove members from this range until there are no more
1551 * than MAX_DESCRIPTORS_PER_ROUTER remaining. Start by removing the oldest
1552 * members from before <b>cutoff</b>, then remove members which were current
1553 * for the lowest amount of time. The order of members of old_routers at
1554 * indices <b>lo</b> or higher may be changed.
1556 static void
1557 routerlist_remove_old_cached_routers_with_id(time_t cutoff, int lo, int hi)
1559 int i, n = hi-lo+1, n_extra;
1560 int n_rmv = 0;
1561 struct duration_idx_t *lifespans;
1562 uint8_t *rmv;
1563 smartlist_t *lst = routerlist->old_routers;
1564 #if 1
1565 const char *ident;
1566 tor_assert(hi < smartlist_len(lst));
1567 tor_assert(lo <= hi);
1568 ident = ((routerinfo_t*)smartlist_get(lst, lo))->identity_digest;
1569 for (i = lo+1; i <= hi; ++i) {
1570 routerinfo_t *r = smartlist_get(lst, i);
1571 tor_assert(!memcmp(ident, r->identity_digest, DIGEST_LEN));
1573 #endif
1575 /* Check whether we need to do anything at all. */
1576 n_extra = n - MAX_DESCRIPTORS_PER_ROUTER;
1577 if (n_extra <= 0)
1578 return;
1581 lifespans = tor_malloc_zero(sizeof(struct duration_idx_t)*n);
1582 rmv = tor_malloc_zero(sizeof(uint8_t)*n);
1583 /* Set lifespans to contain the lifespan and index of each server. */
1584 /* Set rmv[i-lo]=1 if we're going to remove a server for being too old. */
1585 for (i = lo; i <= hi; ++i) {
1586 routerinfo_t *r = smartlist_get(lst, i);
1587 routerinfo_t *r_next;
1588 lifespans[i].idx = i;
1589 if (i < hi) {
1590 r_next = smartlist_get(lst, i+1);
1591 tor_assert(r->published_on <= r_next->published_on);
1592 lifespans[i].duration = r_next->published_on - r->published_on;
1593 } else {
1594 r_next = NULL;
1595 lifespans[i].duration = INT_MAX;
1597 if (r->published_on < cutoff && n_rmv < n_extra) {
1598 ++n_rmv;
1599 lifespans[i].old = 1;
1600 rmv[i-lo] = 1;
1604 if (n_rmv < n_extra) {
1606 * We aren't removing enough servers for being old. Sort lifespans by
1607 * the duration of liveness, and remove the ones we're not already going to
1608 * remove based on how long they were alive.
1610 qsort(lifespans, n, sizeof(struct duration_idx_t), _compare_duration_idx);
1611 for (i = 0; i < n && n_rmv < n_extra; ++i) {
1612 if (!lifespans[i].old) {
1613 rmv[lifespans[i].idx-lo] = 1;
1614 ++n_rmv;
1619 for (i = hi; i >= lo; ++i) {
1620 if (rmv[i-lo])
1621 routerlist_remove_old(routerlist, smartlist_get(lst, i), i);
1623 tor_free(rmv);
1624 tor_free(lifespans);
1627 void
1628 routerlist_remove_old_cached_routers(void)
1630 int i, hi=-1;
1631 const char *cur_id = NULL;
1632 time_t cutoff;
1633 if (!routerlist)
1634 return;
1636 /* First, check whether we have too many router descriptors, total. We're
1637 * okay with having too many for some given router, so long as the total
1638 * number doesn't much exceed
1640 if (smartlist_len(routerlist->old_routers) <
1641 smartlist_len(routerlist->routers) * (MAX_DESCRIPTORS_PER_ROUTER - 1))
1642 return;
1644 smartlist_sort(routerlist->old_routers, _compare_old_routers_by_identity);
1646 cutoff = time(NULL) - ROUTER_MAX_AGE;
1648 /* Iterate through the list from back to front, so when we remove descriptors
1649 * we don't mess up groups we haven't gotten to. */
1650 for (i = smartlist_len(routerlist->old_routers)-1; i >= 0; --i) {
1651 routerinfo_t *r = smartlist_get(routerlist->old_routers, i);
1652 if (!cur_id) {
1653 cur_id = r->identity_digest;
1654 hi = i;
1656 if (memcmp(cur_id, r->identity_digest, DIGEST_LEN)) {
1657 routerlist_remove_old_cached_routers_with_id(cutoff, i+1, hi);
1658 hi = i;
1661 routerlist_remove_old_cached_routers_with_id(cutoff, 0, hi);
1665 * Code to parse a single router descriptor and insert it into the
1666 * routerlist. Return -1 if the descriptor was ill-formed; 0 if the
1667 * descriptor was well-formed but could not be added; and 1 if the
1668 * descriptor was added.
1670 * If we don't add it and <b>msg</b> is not NULL, then assign to
1671 * *<b>msg</b> a static string describing the reason for refusing the
1672 * descriptor.
1674 * This is used only by the controller.
1677 router_load_single_router(const char *s, const char **msg)
1679 routerinfo_t *ri;
1680 smartlist_t *lst;
1681 tor_assert(msg);
1682 *msg = NULL;
1684 if (!(ri = router_parse_entry_from_string(s, NULL))) {
1685 warn(LD_DIR, "Error parsing router descriptor; dropping.");
1686 *msg = "Couldn't parse router descriptor.";
1687 return -1;
1689 if (router_is_me(ri)) {
1690 warn(LD_DIR, "Router's identity key matches mine; dropping.");
1691 *msg = "Router's identity key matches mine.";
1692 routerinfo_free(ri);
1693 return 0;
1696 lst = smartlist_create();
1697 smartlist_add(lst, ri);
1698 routers_update_status_from_networkstatus(lst, 0, 1);
1700 if (router_add_to_routerlist(ri, msg, 0)<0) {
1701 warn(LD_DIR, "Couldn't add router to list: %s Dropping.",
1702 *msg?*msg:"(No message).");
1703 /* we've already assigned to *msg now, and ri is already freed */
1704 smartlist_free(lst);
1705 return 0;
1706 } else {
1707 control_event_descriptors_changed(lst);
1708 smartlist_free(lst);
1709 debug(LD_DIR, "Added router to list");
1710 return 1;
1714 /** Given a string <b>s</b> containing some routerdescs, parse it and put the
1715 * routers into our directory. If <b>from_cache</b> is false, the routers
1716 * have come from the network: cache them.
1718 * If <b>requested_fingerprints</b> is provided, it must contain a list of
1719 * uppercased identity fingerprints. Do not update any router whose
1720 * fingerprint is not on the list; after updating a router, remove its
1721 * fingerprint from the list.
1723 void
1724 router_load_routers_from_string(const char *s, int from_cache,
1725 smartlist_t *requested_fingerprints)
1727 smartlist_t *routers = smartlist_create(), *changed = smartlist_create();
1728 char fp[HEX_DIGEST_LEN+1];
1729 const char *msg;
1731 router_parse_list_from_string(&s, routers);
1733 routers_update_status_from_networkstatus(routers, !from_cache, from_cache);
1735 SMARTLIST_FOREACH(routers, routerinfo_t *, ri,
1737 base16_encode(fp, sizeof(fp), ri->identity_digest, DIGEST_LEN);
1738 if (requested_fingerprints) {
1739 if (smartlist_string_isin(requested_fingerprints, fp)) {
1740 smartlist_string_remove(requested_fingerprints, fp);
1741 } else {
1742 char *requested =
1743 smartlist_join_strings(requested_fingerprints," ",0,NULL);
1744 warn(LD_DIR, "We received a router descriptor with a fingerprint (%s) that we never requested. (We asked for: %s.) Dropping.", fp, requested);
1745 tor_free(requested);
1746 routerinfo_free(ri);
1747 continue;
1751 if (router_add_to_routerlist(ri, &msg, from_cache) >= 0)
1752 smartlist_add(changed, ri);
1755 if (smartlist_len(changed))
1756 control_event_descriptors_changed(changed);
1758 routerlist_assert_ok(routerlist);
1759 router_rebuild_store(0);
1761 smartlist_free(routers);
1762 smartlist_free(changed);
1765 /** Helper: return a newly allocated string containing the name of the filename
1766 * where we plan to cache <b>ns</b>. */
1767 static char *
1768 networkstatus_get_cache_filename(const networkstatus_t *ns)
1770 const char *datadir = get_options()->DataDirectory;
1771 size_t len = strlen(datadir)+64;
1772 char fp[HEX_DIGEST_LEN+1];
1773 char *fn = tor_malloc(len+1);
1774 base16_encode(fp, HEX_DIGEST_LEN+1, ns->identity_digest, DIGEST_LEN);
1775 tor_snprintf(fn, len, "%s/cached-status/%s",datadir,fp);
1776 return fn;
1779 /** Helper for smartlist_sort: Compare two networkstatus objects by
1780 * publication date. */
1781 static int
1782 _compare_networkstatus_published_on(const void **_a, const void **_b)
1784 const networkstatus_t *a = *_a, *b = *_b;
1785 if (a->published_on < b->published_on)
1786 return -1;
1787 else if (a->published_on > b->published_on)
1788 return 1;
1789 else
1790 return 0;
1793 /** How far in the future do we allow a network-status to get before removing
1794 * it? (seconds) */
1795 #define NETWORKSTATUS_ALLOW_SKEW (48*60*60)
1796 /** Given a string <b>s</b> containing a network status that we received at
1797 * <b>arrived_at</b> from <b>source</b>, try to parse it, see if we want to
1798 * store it, and put it into our cache is necessary.
1800 * If <b>source</b> is NS_FROM_DIR or NS_FROM_CACHE, do not replace our
1801 * own networkstatus_t (if we're a directory server).
1803 * If <b>source</b> is NS_FROM_CACHE, do not write our networkstatus_t to the
1804 * cache.
1806 * If <b>requested_fingerprints</b> is provided, it must contain a list of
1807 * uppercased identity fingerprints. Do not update any networkstatus whose
1808 * fingerprint is not on the list; after updating a networkstatus, remove its
1809 * fingerprint from the list.
1811 * Return 0 on success, -1 on failure.
1813 * Callers should make sure that routers_update_all_from_networkstatus() is
1814 * invoked after this function succeeds.
1817 router_set_networkstatus(const char *s, time_t arrived_at,
1818 networkstatus_source_t source, smartlist_t *requested_fingerprints)
1820 networkstatus_t *ns;
1821 int i, found;
1822 time_t now;
1823 int skewed = 0;
1824 trusted_dir_server_t *trusted_dir;
1825 char fp[HEX_DIGEST_LEN+1];
1826 char published[ISO_TIME_LEN+1];
1828 ns = networkstatus_parse_from_string(s);
1829 if (!ns) {
1830 warn(LD_DIR, "Couldn't parse network status.");
1831 return -1;
1833 if (!(trusted_dir=router_get_trusteddirserver_by_digest(ns->identity_digest))) {
1834 info(LD_DIR, "Network status was signed, but not by an authoritative directory we recognize.");
1835 networkstatus_free(ns);
1836 return -1;
1838 now = time(NULL);
1839 if (arrived_at > now)
1840 arrived_at = now;
1842 ns->received_on = arrived_at;
1844 format_iso_time(published, ns->published_on);
1846 if (ns->published_on > now + NETWORKSTATUS_ALLOW_SKEW) {
1847 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);
1848 skewed = 1;
1851 if (!networkstatus_list)
1852 networkstatus_list = smartlist_create();
1854 if (source == NS_FROM_DIR && router_digest_is_me(ns->identity_digest)) {
1855 /* Don't replace our own networkstatus when we get it from somebody else. */
1856 networkstatus_free(ns);
1857 return 0;
1860 base16_encode(fp, HEX_DIGEST_LEN+1, ns->identity_digest, DIGEST_LEN);
1862 if (requested_fingerprints) {
1863 if (smartlist_string_isin(requested_fingerprints, fp)) {
1864 smartlist_string_remove(requested_fingerprints, fp);
1865 } else {
1866 char *requested = smartlist_join_strings(requested_fingerprints," ",0,NULL);
1867 warn(LD_DIR, "We received a network status with a fingerprint (%s) that we never requested. (We asked for: %s.) Dropping.", fp, requested);
1868 tor_free(requested);
1869 return 0;
1873 if (source != NS_FROM_CACHE)
1874 trusted_dir->n_networkstatus_failures = 0;
1876 found = 0;
1877 for (i=0; i < smartlist_len(networkstatus_list); ++i) {
1878 networkstatus_t *old_ns = smartlist_get(networkstatus_list, i);
1880 if (!memcmp(old_ns->identity_digest, ns->identity_digest, DIGEST_LEN)) {
1881 if (!memcmp(old_ns->networkstatus_digest,
1882 ns->networkstatus_digest, DIGEST_LEN)) {
1883 /* Same one we had before. */
1884 networkstatus_free(ns);
1885 info(LD_DIR,
1886 "Not replacing network-status from %s (published %s); "
1887 "we already have it.",
1888 trusted_dir->description, published);
1889 if (old_ns->received_on < arrived_at) {
1890 if (source != NS_FROM_CACHE) {
1891 char *fn = networkstatus_get_cache_filename(old_ns);
1892 /* We use mtime to tell when it arrived, so update that. */
1893 touch_file(fn);
1894 tor_free(fn);
1896 old_ns->received_on = arrived_at;
1898 return 0;
1899 } else if (old_ns->published_on >= ns->published_on) {
1900 char old_published[ISO_TIME_LEN+1];
1901 format_iso_time(old_published, old_ns->published_on);
1902 info(LD_DIR,
1903 "Not replacing network-status from %s (published %s);"
1904 " we have a newer one (published %s) for this authority.",
1905 trusted_dir->description, published,
1906 old_published);
1907 networkstatus_free(ns);
1908 return 0;
1909 } else {
1910 networkstatus_free(old_ns);
1911 smartlist_set(networkstatus_list, i, ns);
1912 found = 1;
1913 break;
1918 if (!found)
1919 smartlist_add(networkstatus_list, ns);
1921 info(LD_DIR, "Setting networkstatus %s %s (published %s)",
1922 source == NS_FROM_CACHE?"cached from":
1923 (source==NS_FROM_DIR?"downloaded from":"generated for"),
1924 trusted_dir->description, published);
1925 networkstatus_list_has_changed = 1;
1927 smartlist_sort(networkstatus_list, _compare_networkstatus_published_on);
1929 if (source != NS_FROM_CACHE && !skewed) {
1930 char *fn = networkstatus_get_cache_filename(ns);
1931 if (write_str_to_file(fn, s, 0)<0) {
1932 notice(LD_FS, "Couldn't write cached network status to \"%s\"", fn);
1934 tor_free(fn);
1937 networkstatus_list_update_recent(now);
1939 if (get_options()->DirPort && !skewed)
1940 dirserv_set_cached_networkstatus_v2(s,
1941 ns->identity_digest,
1942 ns->published_on);
1944 return 0;
1947 /** How old do we allow a network-status to get before removing it completely? */
1948 #define MAX_NETWORKSTATUS_AGE (10*24*60*60)
1949 /** Remove all very-old network_status_t objects from memory and from the
1950 * disk cache. */
1951 void
1952 networkstatus_list_clean(time_t now)
1954 int i;
1955 if (!networkstatus_list)
1956 return;
1958 for (i = 0; i < smartlist_len(networkstatus_list); ++i) {
1959 networkstatus_t *ns = smartlist_get(networkstatus_list, i);
1960 char *fname = NULL;;
1961 if (ns->published_on + MAX_NETWORKSTATUS_AGE > now)
1962 continue;
1963 /* Okay, this one is too old. Remove it from the list, and delete it
1964 * from the cache. */
1965 smartlist_del(networkstatus_list, i--);
1966 fname = networkstatus_get_cache_filename(ns);
1967 if (file_status(fname) == FN_FILE) {
1968 info(LD_DIR, "Removing too-old networkstatus in %s", fname);
1969 unlink(fname);
1971 tor_free(fname);
1972 if (get_options()->DirPort) {
1973 dirserv_set_cached_networkstatus_v2(NULL, ns->identity_digest, 0);
1975 networkstatus_free(ns);
1979 /** Helper for bsearching a list of routerstatus_t pointers.*/
1980 static int
1981 _compare_digest_to_routerstatus_entry(const void *_key, const void **_member)
1983 const char *key = _key;
1984 const routerstatus_t *rs = *_member;
1985 return memcmp(key, rs->identity_digest, DIGEST_LEN);
1988 /** Return the entry in <b>ns</b> for the identity digest <b>digest</b>, or
1989 * NULL if none was found. */
1990 static routerstatus_t *
1991 networkstatus_find_entry(networkstatus_t *ns, const char *digest)
1993 return smartlist_bsearch(ns->entries, digest,
1994 _compare_digest_to_routerstatus_entry);
1997 /** Return the consensus view of the status of the router whose digest is
1998 * <b>digest</b>, or NULL if we don't know about any such router. */
1999 local_routerstatus_t *
2000 router_get_combined_status_by_digest(const char *digest)
2002 if (!routerstatus_list)
2003 return NULL;
2004 return smartlist_bsearch(routerstatus_list, digest,
2005 _compare_digest_to_routerstatus_entry);
2008 /** DOCDOC */
2009 static int
2010 routerdesc_digest_is_recognized(const char *identity, const char *digest)
2012 routerstatus_t *rs;
2013 if (!networkstatus_list)
2014 return 0;
2016 SMARTLIST_FOREACH(networkstatus_list, networkstatus_t *, ns,
2018 if (!(rs = networkstatus_find_entry(ns, identity)))
2019 continue;
2020 if (!memcmp(rs->descriptor_digest, digest, DIGEST_LEN))
2021 return 1;
2023 return 0;
2026 /* XXXX These should be configurable, perhaps? NM */
2027 #define AUTHORITY_NS_CACHE_INTERVAL 10*60
2028 #define NONAUTHORITY_NS_CACHE_INTERVAL 15*60
2029 /** We are a directory server, and so cache network_status documents.
2030 * Initiate downloads as needed to update them. For authorities, this means
2031 * asking each trusted directory for its network-status. For caches, this
2032 * means asking a random authority for all network-statuses.
2034 static void
2035 update_networkstatus_cache_downloads(time_t now)
2037 int authority = authdir_mode(get_options());
2038 int interval =
2039 authority ? AUTHORITY_NS_CACHE_INTERVAL : NONAUTHORITY_NS_CACHE_INTERVAL;
2041 if (last_networkstatus_download_attempted + interval >= now)
2042 return;
2043 if (!trusted_dir_servers)
2044 return;
2046 last_networkstatus_download_attempted = now;
2048 if (authority) {
2049 /* An authority launches a separate connection for everybody. */
2050 SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, ds,
2052 char resource[HEX_DIGEST_LEN+6];
2053 if (router_digest_is_me(ds->digest))
2054 continue;
2055 if (connection_get_by_type_addr_port_purpose(
2056 CONN_TYPE_DIR, ds->addr, ds->dir_port,
2057 DIR_PURPOSE_FETCH_NETWORKSTATUS)) {
2058 /* We are already fetching this one. */
2059 continue;
2061 strlcpy(resource, "fp/", sizeof(resource));
2062 base16_encode(resource+3, sizeof(resource)-3, ds->digest, DIGEST_LEN);
2063 strlcat(resource, ".z", sizeof(resource));
2064 directory_get_from_dirserver(DIR_PURPOSE_FETCH_NETWORKSTATUS,resource,1);
2066 } else {
2067 /* A non-authority cache launches one connection to a random authority. */
2068 /* (Check whether we're currently fetching network-status objects.) */
2069 if (!connection_get_by_type_purpose(CONN_TYPE_DIR,
2070 DIR_PURPOSE_FETCH_NETWORKSTATUS))
2071 directory_get_from_dirserver(DIR_PURPOSE_FETCH_NETWORKSTATUS,"all.z",1);
2075 /*XXXX Should these be configurable? NM*/
2076 /** How old (in seconds) can a network-status be before we try replacing it? */
2077 #define NETWORKSTATUS_MAX_VALIDITY (48*60*60)
2078 /** How long (in seconds) does a client wait after getting a network status
2079 * before downloading the next in sequence? */
2080 #define NETWORKSTATUS_CLIENT_DL_INTERVAL (30*60)
2081 /* How many times do we allow a networkstatus download to fail before we
2082 * assume that the authority isn't publishing? */
2083 #define NETWORKSTATUS_N_ALLOWABLE_FAILURES 3
2084 /** We are not a directory cache or authority. Update our network-status list
2085 * by launching a new directory fetch for enough network-status documents "as
2086 * necessary". See function comments for implementation details.
2088 static void
2089 update_networkstatus_client_downloads(time_t now)
2091 int n_live = 0, needed = 0, n_running_dirservers, n_dirservers, i;
2092 int most_recent_idx = -1;
2093 trusted_dir_server_t *most_recent = NULL;
2094 time_t most_recent_received = 0;
2095 char *resource, *cp;
2096 size_t resource_len;
2098 if (connection_get_by_type_purpose(CONN_TYPE_DIR,
2099 DIR_PURPOSE_FETCH_NETWORKSTATUS))
2100 return;
2102 /* This is a little tricky. We want to download enough network-status
2103 * objects so that we have at least half of them under
2104 * NETWORKSTATUS_MAX_VALIDITY publication time. We want to download a new
2105 * *one* if the most recent one's publication time is under
2106 * NETWORKSTATUS_CLIENT_DL_INTERVAL.
2108 if (!trusted_dir_servers || !smartlist_len(trusted_dir_servers))
2109 return;
2110 n_dirservers = n_running_dirservers = smartlist_len(trusted_dir_servers);
2111 SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, ds,
2113 networkstatus_t *ns = networkstatus_get_by_digest(ds->digest);
2114 if (!ns)
2115 continue;
2116 if (ds->n_networkstatus_failures > NETWORKSTATUS_N_ALLOWABLE_FAILURES) {
2117 --n_running_dirservers;
2118 continue;
2120 if (ns->published_on > now-NETWORKSTATUS_MAX_VALIDITY)
2121 ++n_live;
2122 if (!most_recent || ns->received_on > most_recent_received) {
2123 most_recent_idx = ds_sl_idx; /* magic variable from FOREACH */
2124 most_recent = ds;
2125 most_recent_received = ns->received_on;
2129 /* Download enough so we have at least half live, but no more than all the
2130 * trusted dirservers we know.
2132 if (n_live < (n_dirservers/2)+1)
2133 needed = (n_dirservers/2)+1-n_live;
2134 if (needed > n_running_dirservers)
2135 needed = n_running_dirservers;
2137 if (needed)
2138 info(LD_DIR, "For %d/%d running directory servers, we have %d live"
2139 " network-status documents. Downloading %d.",
2140 n_running_dirservers, n_dirservers, n_live, needed);
2142 /* Also, download at least 1 every NETWORKSTATUS_CLIENT_DL_INTERVAL. */
2143 if (n_running_dirservers &&
2144 most_recent_received < now-NETWORKSTATUS_CLIENT_DL_INTERVAL && needed < 1) {
2145 info(LD_DIR, "Our most recent network-status document (from %s) "
2146 "is %d seconds old; downloading another.",
2147 most_recent?most_recent->description:"nobody",
2148 (int)(now-most_recent_received));
2149 needed = 1;
2152 if (!needed)
2153 return;
2155 /* If no networkstatus was found, choose a dirserver at random as "most
2156 * recent". */
2157 if (most_recent_idx<0)
2158 most_recent_idx = crypto_rand_int(n_dirservers);
2160 /* Build a request string for all the resources we want. */
2161 resource_len = needed * (HEX_DIGEST_LEN+1) + 6;
2162 resource = tor_malloc(resource_len);
2163 memcpy(resource, "fp/", 3);
2164 cp = resource+3;
2165 for (i = most_recent_idx+1; needed; ++i) {
2166 trusted_dir_server_t *ds;
2167 if (i >= n_dirservers)
2168 i = 0;
2169 ds = smartlist_get(trusted_dir_servers, i);
2170 if (ds->n_networkstatus_failures > NETWORKSTATUS_N_ALLOWABLE_FAILURES)
2171 continue;
2172 base16_encode(cp, HEX_DIGEST_LEN+1, ds->digest, DIGEST_LEN);
2173 cp += HEX_DIGEST_LEN;
2174 --needed;
2175 if (needed)
2176 *cp++ = '+';
2178 memcpy(cp, ".z", 3);
2179 directory_get_from_dirserver(DIR_PURPOSE_FETCH_NETWORKSTATUS, resource, 1);
2180 tor_free(resource);
2183 /*DOCDOC*/
2184 void
2185 update_networkstatus_downloads(time_t now)
2187 or_options_t *options = get_options();
2188 if (server_mode(options) && options->DirPort)
2189 update_networkstatus_cache_downloads(time(NULL));
2190 else
2191 update_networkstatus_client_downloads(time(NULL));
2194 /** Decide whether a given addr:port is definitely accepted,
2195 * definitely rejected, probably accepted, or probably rejected by a
2196 * given policy. If <b>addr</b> is 0, we don't know the IP of the
2197 * target address. If <b>port</b> is 0, we don't know the port of the
2198 * target address.
2200 * For now, the algorithm is pretty simple: we look for definite and
2201 * uncertain matches. The first definite match is what we guess; if
2202 * it was preceded by no uncertain matches of the opposite policy,
2203 * then the guess is definite; otherwise it is probable. (If we
2204 * have a known addr and port, all matches are definite; if we have an
2205 * unknown addr/port, any address/port ranges other than "all" are
2206 * uncertain.)
2208 * We could do better by assuming that some ranges never match typical
2209 * addresses (127.0.0.1, and so on). But we'll try this for now.
2211 addr_policy_result_t
2212 router_compare_addr_to_addr_policy(uint32_t addr, uint16_t port,
2213 addr_policy_t *policy)
2215 int maybe_reject = 0;
2216 int maybe_accept = 0;
2217 int match = 0;
2218 int maybe = 0;
2219 addr_policy_t *tmpe;
2221 for (tmpe=policy; tmpe; tmpe=tmpe->next) {
2222 maybe = 0;
2223 if (!addr) {
2224 /* Address is unknown. */
2225 if ((port >= tmpe->prt_min && port <= tmpe->prt_max) ||
2226 (!port && tmpe->prt_min<=1 && tmpe->prt_max>=65535)) {
2227 /* The port definitely matches. */
2228 if (tmpe->msk == 0) {
2229 match = 1;
2230 } else {
2231 maybe = 1;
2233 } else if (!port) {
2234 /* The port maybe matches. */
2235 maybe = 1;
2237 } else {
2238 /* Address is known */
2239 if ((addr & tmpe->msk) == (tmpe->addr & tmpe->msk)) {
2240 if (port >= tmpe->prt_min && port <= tmpe->prt_max) {
2241 /* Exact match for the policy */
2242 match = 1;
2243 } else if (!port) {
2244 maybe = 1;
2248 if (maybe) {
2249 if (tmpe->policy_type == ADDR_POLICY_REJECT)
2250 maybe_reject = 1;
2251 else
2252 maybe_accept = 1;
2254 if (match) {
2255 if (tmpe->policy_type == ADDR_POLICY_ACCEPT) {
2256 /* If we already hit a clause that might trigger a 'reject', than we
2257 * can't be sure of this certain 'accept'.*/
2258 return maybe_reject ? ADDR_POLICY_PROBABLY_ACCEPTED : ADDR_POLICY_ACCEPTED;
2259 } else {
2260 return maybe_accept ? ADDR_POLICY_PROBABLY_REJECTED : ADDR_POLICY_REJECTED;
2264 /* accept all by default. */
2265 return maybe_reject ? ADDR_POLICY_PROBABLY_ACCEPTED : ADDR_POLICY_ACCEPTED;
2268 /** Return 1 if all running sufficiently-stable routers will reject
2269 * addr:port, return 0 if any might accept it. */
2271 router_exit_policy_all_routers_reject(uint32_t addr, uint16_t port,
2272 int need_uptime)
2274 addr_policy_result_t r;
2275 if (!routerlist) return 1;
2277 SMARTLIST_FOREACH(routerlist->routers, routerinfo_t *, router,
2279 if (router->is_running &&
2280 !router_is_unreliable(router, need_uptime, 0)) {
2281 r = router_compare_addr_to_addr_policy(addr, port, router->exit_policy);
2282 if (r != ADDR_POLICY_REJECTED && r != ADDR_POLICY_PROBABLY_REJECTED)
2283 return 0; /* this one could be ok. good enough. */
2286 return 1; /* all will reject. */
2290 * If <b>policy</b> implicitly allows connections to any port in the
2291 * IP set <b>addr</b>/<b>mask</b>, then set *<b>policy_out</b> to the
2292 * part of the policy that allows it, and return 1. Else return 0.
2294 * A policy allows an IP:Port combination <em>implicitly</em> if
2295 * it is included in a *: pattern, or in a fallback pattern.
2297 static int
2298 policy_includes_addr_mask_implicitly(addr_policy_t *policy,
2299 uint32_t addr, uint32_t mask,
2300 addr_policy_t **policy_out)
2302 uint32_t addr2;
2303 tor_assert(policy_out);
2304 addr &= mask;
2305 addr2 = addr | ~mask;
2306 for (; policy; policy=policy->next) {
2307 /* Does this policy cover all of the address range we're looking at? */
2308 /* Boolean logic time: range X is contained in range Y if, for
2309 * each bit B, all possible values of B in X are values of B in Y.
2310 * In "addr", we have every fixed bit set to its value, and every
2311 * free bit set to 0. In "addr2", we have every fixed bit set to
2312 * its value, and every free bit set to 1. So if addr and addr2 are
2313 * both in the policy, the range is covered by the policy.
2315 uint32_t p_addr = policy->addr & policy->msk;
2316 if (p_addr == (addr & policy->msk) &&
2317 p_addr == (addr2 & policy->msk) &&
2318 (policy->prt_min <= 1 && policy->prt_max == 65535)) {
2319 return 0;
2321 /* Does this policy cover some of the address range we're looking at? */
2322 /* Boolean logic time: range X and range Y intersect if there is
2323 * some z such that z & Xmask == Xaddr and z & Ymask == Yaddr.
2324 * This is FALSE iff there is some bit b where Xmask == yMask == 1
2325 * and Xaddr != Yaddr. So if X intersects with Y iff at every
2326 * place where Xmask&Ymask==1, Xaddr == Yaddr, or equivalently,
2327 * Xaddr&Xmask&Ymask == Yaddr&Xmask&Ymask.
2329 if ((policy->addr & policy->msk & mask) == (addr & policy->msk) &&
2330 policy->policy_type == ADDR_POLICY_ACCEPT) {
2331 *policy_out = policy;
2332 return 1;
2335 *policy_out = NULL;
2336 return 1;
2339 /** If <b>policy</b> implicitly allows connections to any port on
2340 * 127.*, 192.168.*, etc, then warn (if <b>warn</b> is set) and return
2341 * true. Else return false.
2344 exit_policy_implicitly_allows_local_networks(addr_policy_t *policy,
2345 int warn)
2347 addr_policy_t *p;
2348 int r=0,i;
2349 static struct {
2350 uint32_t addr; uint32_t mask; const char *network;
2351 } private_networks[] = {
2352 { 0x7f000000, 0xff000000, "localhost (127.0.0.0/8)" },
2353 { 0x0a000000, 0xff000000, "addresses in private network 10.0.0.0/8" },
2354 { 0xa9fe0000, 0xffff0000, "addresses in private network 169.254.0.0/16" },
2355 { 0xac100000, 0xfff00000, "addresses in private network 172.16.0.0/12" },
2356 { 0xc0a80000, 0xffff0000, "addresses in private network 192.168.0.0/16" },
2357 { 0,0,NULL},
2359 for (i=0; private_networks[i].addr; ++i) {
2360 p = NULL;
2361 /* log_fn(LOG_INFO,"Checking network %s", private_networks[i].network); */
2362 if (policy_includes_addr_mask_implicitly(
2363 policy, private_networks[i].addr, private_networks[i].mask, &p)) {
2364 if (warn)
2365 warn(LD_CONFIG, "Exit policy %s implicitly accepts %s",
2366 p?p->string:"(default)",
2367 private_networks[i].network);
2368 r = 1;
2372 return r;
2375 /** Return true iff <b>router</b> does not permit exit streams.
2378 router_exit_policy_rejects_all(routerinfo_t *router)
2380 return router_compare_addr_to_addr_policy(0, 0, router->exit_policy)
2381 == ADDR_POLICY_REJECTED;
2384 /** Add to the list of authorized directory servers one at
2385 * <b>address</b>:<b>port</b>, with identity key <b>digest</b>. If
2386 * <b>address</b> is NULL, add ourself. */
2387 void
2388 add_trusted_dir_server(const char *nickname, const char *address,
2389 uint16_t port, const char *digest, int supports_v1)
2391 trusted_dir_server_t *ent;
2392 uint32_t a;
2393 char *hostname = NULL;
2394 size_t dlen;
2395 if (!trusted_dir_servers)
2396 trusted_dir_servers = smartlist_create();
2398 if (!address) { /* The address is us; we should guess. */
2399 if (resolve_my_address(get_options(), &a, &hostname) < 0) {
2400 warn(LD_CONFIG, "Couldn't find a suitable address when adding ourself as a trusted directory server.");
2401 return;
2403 } else {
2404 if (tor_lookup_hostname(address, &a)) {
2405 warn(LD_CONFIG, "Unable to lookup address for directory server at %s",
2406 address);
2407 return;
2409 hostname = tor_strdup(address);
2410 a = ntohl(a);
2413 ent = tor_malloc_zero(sizeof(trusted_dir_server_t));
2414 ent->nickname = nickname ? tor_strdup(nickname) : NULL;
2415 ent->address = hostname;
2416 ent->addr = a;
2417 ent->dir_port = port;
2418 ent->is_running = 1;
2419 ent->supports_v1_protocol = supports_v1;
2420 memcpy(ent->digest, digest, DIGEST_LEN);
2422 dlen = 64 + strlen(hostname) + (nickname?strlen(nickname):0);
2423 ent->description = tor_malloc(dlen);
2424 if (nickname)
2425 tor_snprintf(ent->description, dlen, "directory server \"%s\" at %s:%d",
2426 nickname, hostname, (int)port);
2427 else
2428 tor_snprintf(ent->description, dlen, "directory server at %s:%d",
2429 hostname, (int)port);
2431 smartlist_add(trusted_dir_servers, ent);
2434 /** Free storage held in <b>ds</b> */
2435 void
2436 trusted_dir_server_free(trusted_dir_server_t *ds)
2438 tor_free(ds->nickname);
2439 tor_free(ds->description);
2440 tor_free(ds->address);
2441 tor_free(ds);
2444 /** Remove all members from the list of trusted dir servers. */
2445 void
2446 clear_trusted_dir_servers(void)
2448 if (trusted_dir_servers) {
2449 SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, ent,
2450 trusted_dir_server_free(ent));
2451 smartlist_clear(trusted_dir_servers);
2452 } else {
2453 trusted_dir_servers = smartlist_create();
2457 /** Return the network status with a given identity digest. */
2458 networkstatus_t *
2459 networkstatus_get_by_digest(const char *digest)
2461 SMARTLIST_FOREACH(networkstatus_list, networkstatus_t *, ns,
2463 if (!memcmp(ns->identity_digest, digest, DIGEST_LEN))
2464 return ns;
2466 return NULL;
2469 /** If the network-status list has changed since the last time we called this
2470 * function, update the status of every router from the network-status list.
2472 void
2473 routers_update_all_from_networkstatus(void)
2475 #define SELF_OPINION_INTERVAL 90*60
2476 routerinfo_t *me;
2477 time_t now;
2478 if (!routerlist || !networkstatus_list ||
2479 (!networkstatus_list_has_changed && !routerstatus_list_has_changed))
2480 return;
2482 now = time(NULL);
2483 if (networkstatus_list_has_changed)
2484 routerstatus_list_update_from_networkstatus(now);
2486 routers_update_status_from_networkstatus(routerlist->routers, 0, 0);
2488 me = router_get_my_routerinfo();
2489 if (me && !have_warned_about_unverified_status) {
2490 int n_recent = 0, n_listing = 0, n_valid = 0, n_named = 0;
2491 routerstatus_t *rs;
2492 SMARTLIST_FOREACH(networkstatus_list, networkstatus_t *, ns,
2494 if (ns->received_on + SELF_OPINION_INTERVAL < now)
2495 continue;
2496 ++n_recent;
2497 if (!(rs = networkstatus_find_entry(ns, me->identity_digest)))
2498 continue;
2499 ++n_listing;
2500 if (rs->is_valid)
2501 ++n_valid;
2502 if (rs->is_named)
2503 ++n_named;
2506 if (n_recent >= 2 && n_listing >= 2) {
2507 if (n_valid <= n_recent/2) {
2508 warn(LD_GENERAL, "%d/%d recent directory servers list us as invalid. Please consider sending your identity fingerprint to the tor-ops.",
2509 n_recent-n_valid, n_recent);
2510 have_warned_about_unverified_status = 1;
2511 } else if (n_named <= n_recent/2) {
2512 warn(LD_GENERAL, "%d/%d recent directory servers list us as unnamed. Please consider sending your identity fingerprint to the tor-ops.",
2513 n_recent-n_valid, n_recent);
2514 have_warned_about_unverified_status = 1;
2519 helper_nodes_set_status_from_directory();
2521 if (!have_warned_about_old_version) {
2522 int n_recent = 0;
2523 int n_recommended = 0;
2524 int is_server = server_mode(get_options());
2525 version_status_t consensus = VS_RECOMMENDED;
2526 SMARTLIST_FOREACH(networkstatus_list, networkstatus_t *, ns,
2528 version_status_t vs;
2529 if (!ns->recommends_versions ||
2530 ns->received_on + SELF_OPINION_INTERVAL < now )
2531 continue;
2532 vs = tor_version_is_obsolete(
2533 VERSION, is_server ? ns->server_versions : ns->client_versions);
2534 if (vs == VS_RECOMMENDED)
2535 ++n_recommended;
2536 if (n_recent++ == 0) {
2537 consensus = vs;
2538 } else if (consensus != vs) {
2539 consensus = version_status_join(consensus, vs);
2542 if (n_recent > 2 && n_recommended < n_recent/2) {
2543 if (consensus == VS_NEW || consensus == VS_NEW_IN_SERIES) {
2544 if (!have_warned_about_new_version) {
2545 notice(LD_GENERAL, "This version of Tor (%s) is newer than any recommended version%s, according to %d/%d recent network statuses.",
2546 VERSION, consensus == VS_NEW_IN_SERIES ? " in its series" : "",
2547 n_recent-n_recommended, n_recent);
2548 have_warned_about_new_version = 1;
2550 } else {
2551 notice(LD_GENERAL, "This version of Tor (%s) is %s, according to %d/%d recent network statuses.",
2552 VERSION, consensus == VS_OLD ? "obsolete" : "not recommended",
2553 n_recent-n_recommended, n_recent);
2554 have_warned_about_old_version = 1;
2556 } else {
2557 info(LD_GENERAL, "%d/%d recent directories think my version is ok.",
2558 n_recommended, n_recent);
2562 routerstatus_list_has_changed = 0;
2565 /** Allow any network-status newer than this to influence our view of who's
2566 * running. */
2567 #define DEFAULT_RUNNING_INTERVAL 60*60
2568 /** If possible, always allow at least this many network-statuses to influence
2569 * our view of who's running. */
2570 #define MIN_TO_INFLUENCE_RUNNING 3
2572 /** Change the is_recent field of each member of networkstatus_list so that
2573 * all members more recent than DEFAULT_RUNNING_INTERVAL are recent, and
2574 * at least the MIN_TO_INFLUENCE_RUNNING most recent members are resent, and no
2575 * others are recent. Set networkstatus_list_has_changed if anything happeed.
2577 void
2578 networkstatus_list_update_recent(time_t now)
2580 int n_statuses, n_recent, changed, i;
2581 char published[ISO_TIME_LEN+1];
2583 if (!networkstatus_list)
2584 return;
2586 n_statuses = smartlist_len(networkstatus_list);
2587 n_recent = 0;
2588 changed = 0;
2589 for (i=n_statuses-1; i >= 0; --i) {
2590 networkstatus_t *ns = smartlist_get(networkstatus_list, i);
2591 trusted_dir_server_t *ds =
2592 router_get_trusteddirserver_by_digest(ns->identity_digest);
2593 const char *src = ds?ds->description:ns->source_address;
2594 if (n_recent < MIN_TO_INFLUENCE_RUNNING ||
2595 ns->published_on + DEFAULT_RUNNING_INTERVAL > now) {
2596 if (!ns->is_recent) {
2597 format_iso_time(published, ns->published_on);
2598 info(LD_DIR,
2599 "Networkstatus from %s (published %s) is now \"recent\"",
2600 src, published);
2601 changed = 1;
2603 ns->is_recent = 1;
2604 ++n_recent;
2605 } else {
2606 if (ns->is_recent) {
2607 format_iso_time(published, ns->published_on);
2608 info(LD_DIR,
2609 "Networkstatus from %s (published %s) is no longer \"recent\"",
2610 src, published);
2611 changed = 1;
2612 ns->is_recent = 0;
2616 if (changed)
2617 networkstatus_list_has_changed = 1;
2620 /** Update our view of router status (as stored in routerstatus_list) from
2621 * the current set of network status documents (as stored in networkstatus_list).
2622 * Do nothing unless the network status list has changed since the last time
2623 * this function was called.
2625 static void
2626 routerstatus_list_update_from_networkstatus(time_t now)
2628 or_options_t *options = get_options();
2629 int n_trusted, n_statuses, n_recent=0, n_naming=0;
2630 int n_distinct = 0;
2631 int i, warned;
2632 int *index, *size;
2633 networkstatus_t **networkstatus;
2634 smartlist_t *result;
2635 strmap_t *name_map;
2636 char conflict[DIGEST_LEN];
2638 networkstatus_list_update_recent(now);
2640 if (!networkstatus_list_has_changed)
2641 return;
2642 if (!networkstatus_list)
2643 networkstatus_list = smartlist_create();
2644 if (!routerstatus_list)
2645 routerstatus_list = smartlist_create();
2646 if (!trusted_dir_servers)
2647 trusted_dir_servers = smartlist_create();
2648 if (!warned_conflicts)
2649 warned_conflicts = smartlist_create();
2651 n_trusted = smartlist_len(trusted_dir_servers);
2652 n_statuses = smartlist_len(networkstatus_list);
2654 if (n_statuses < (n_trusted/2)+1) {
2655 /* Not enough statuses to adjust status. */
2656 notice(LD_DIR,"Not enough statuses to update router status list. (%d/%d)",
2657 n_statuses, n_trusted);
2658 return;
2661 info(LD_DIR, "Rebuilding router status list.");
2663 index = tor_malloc(sizeof(int)*n_statuses);
2664 size = tor_malloc(sizeof(int)*n_statuses);
2665 networkstatus = tor_malloc(sizeof(networkstatus_t *)*n_statuses);
2666 for (i = 0; i < n_statuses; ++i) {
2667 index[i] = 0;
2668 networkstatus[i] = smartlist_get(networkstatus_list, i);
2669 size[i] = smartlist_len(networkstatus[i]->entries);
2670 if (networkstatus[i]->binds_names)
2671 ++n_naming;
2672 if (networkstatus[i]->is_recent)
2673 ++n_recent;
2676 name_map = strmap_new();
2677 memset(conflict, 0xff, sizeof(conflict));
2678 for (i = 0; i < n_statuses; ++i) {
2679 if (!networkstatus[i]->binds_names)
2680 continue;
2681 SMARTLIST_FOREACH(networkstatus[i]->entries, routerstatus_t *, rs,
2683 const char *other_digest;
2684 if (!rs->is_named)
2685 continue;
2686 other_digest = strmap_get_lc(name_map, rs->nickname);
2687 warned = smartlist_string_isin(warned_conflicts, rs->nickname);
2688 if (!other_digest) {
2689 strmap_set_lc(name_map, rs->nickname, rs->identity_digest);
2690 if (warned)
2691 smartlist_string_remove(warned_conflicts, rs->nickname);
2692 } else if (memcmp(other_digest, rs->identity_digest, DIGEST_LEN) &&
2693 other_digest != conflict) {
2694 if (!warned) {
2695 int should_warn = options->DirPort && options->AuthoritativeDir;
2696 char fp1[HEX_DIGEST_LEN+1];
2697 char fp2[HEX_DIGEST_LEN+1];
2698 base16_encode(fp1, sizeof(fp1), other_digest, DIGEST_LEN);
2699 base16_encode(fp2, sizeof(fp2), rs->identity_digest, DIGEST_LEN);
2700 log_fn(should_warn ? LOG_WARN : LOG_INFO, LD_DIR,
2701 "Naming authorities disagree about which key goes with %s. ($%s vs $%s)",
2702 rs->nickname, fp1, fp2);
2703 strmap_set_lc(name_map, rs->nickname, conflict);
2704 smartlist_add(warned_conflicts, tor_strdup(rs->nickname));
2706 } else {
2707 if (warned)
2708 smartlist_string_remove(warned_conflicts, rs->nickname);
2713 result = smartlist_create();
2715 /* Iterate through all of the sorted routerstatus lists in step.
2716 * Invariants:
2717 * - For 0 <= i < n_statuses: index[i] is an index into
2718 * networkstatus[i]->entries, which has size[i] elements.
2719 * - For i1, i2, j such that 0 <= i1 < n_statuses, 0 <= i2 < n_statues, 0 <=
2720 * j < index[i1], networkstatus[i1]->entries[j]->identity_digest <
2721 * networkstatus[i2]->entries[index[i2]]->identity_digest.
2723 * (That is, the indices are always advanced past lower digest before
2724 * higher.)
2726 while (1) {
2727 int n_running=0, n_named=0, n_valid=0, n_listing=0;
2728 const char *the_name = NULL;
2729 local_routerstatus_t *rs_out, *rs_old;
2730 routerstatus_t *rs, *most_recent;
2731 networkstatus_t *ns;
2732 const char *lowest = NULL;
2733 /* Find out which of the digests appears first. */
2734 for (i = 0; i < n_statuses; ++i) {
2735 if (index[i] < size[i]) {
2736 rs = smartlist_get(networkstatus[i]->entries, index[i]);
2737 if (!lowest || memcmp(rs->identity_digest, lowest, DIGEST_LEN)<0)
2738 lowest = rs->identity_digest;
2741 if (!lowest) {
2742 /* We're out of routers. Great! */
2743 break;
2745 /* Okay. The routers at networkstatus[i]->entries[index[i]] whose digests
2746 * match "lowest" are next in order. Iterate over them, incrementing those
2747 * index[i] as we go. */
2748 ++n_distinct;
2749 most_recent = NULL;
2750 for (i = 0; i < n_statuses; ++i) {
2751 if (index[i] >= size[i])
2752 continue;
2753 ns = networkstatus[i];
2754 rs = smartlist_get(ns->entries, index[i]);
2755 if (memcmp(rs->identity_digest, lowest, DIGEST_LEN))
2756 continue;
2757 ++index[i];
2758 ++n_listing;
2759 if (!most_recent || rs->published_on > most_recent->published_on)
2760 most_recent = rs;
2761 if (rs->is_named && ns->binds_names) {
2762 if (!the_name)
2763 the_name = rs->nickname;
2764 if (!strcasecmp(rs->nickname, the_name)) {
2765 ++n_named;
2766 } else if (strcmp(the_name,"**mismatch**")) {
2767 char hd[HEX_DIGEST_LEN+1];
2768 base16_encode(hd, HEX_DIGEST_LEN+1, rs->identity_digest, DIGEST_LEN);
2769 if (! smartlist_string_isin(warned_conflicts, hd)) {
2770 warn(LD_DIR, "Naming authorities disagree about nicknames for $%s (\"%s\" vs \"%s\")",
2771 hd, the_name, rs->nickname);
2772 smartlist_add(warned_conflicts, tor_strdup(hd));
2774 the_name = "**mismatch**";
2777 if (rs->is_valid)
2778 ++n_valid;
2779 if (rs->is_running && ns->is_recent)
2780 ++n_running;
2782 rs_out = tor_malloc_zero(sizeof(local_routerstatus_t));
2783 memcpy(&rs_out->status, most_recent, sizeof(routerstatus_t));
2784 if ((rs_old = router_get_combined_status_by_digest(lowest))) {
2785 rs_out->n_download_failures = rs_old->n_download_failures;
2786 rs_out->next_attempt_at = rs_old->next_attempt_at;
2787 rs_out->name_lookup_warned = rs_old->name_lookup_warned;
2789 smartlist_add(result, rs_out);
2790 debug(LD_DIR, "Router '%s' is listed by %d/%d directories, "
2791 "named by %d/%d, validated by %d/%d, and %d/%d recent directories "
2792 "think it's running.",
2793 rs_out->status.nickname,
2794 n_listing, n_statuses, n_named, n_naming, n_valid, n_statuses,
2795 n_running, n_recent);
2796 rs_out->status.is_named = 0;
2797 if (the_name && strcmp(the_name, "**mismatch**") && n_named > 0) {
2798 const char *d = strmap_get_lc(name_map, the_name);
2799 if (d && d != conflict)
2800 rs_out->status.is_named = 1;
2801 if (smartlist_string_isin(warned_conflicts, rs_out->status.nickname))
2802 smartlist_string_remove(warned_conflicts, rs_out->status.nickname);
2804 if (rs_out->status.is_named)
2805 strlcpy(rs_out->status.nickname, the_name, sizeof(rs_out->status.nickname));
2806 rs_out->status.is_valid = n_valid > n_statuses/2;
2807 rs_out->status.is_running = n_running > n_recent/2;
2809 SMARTLIST_FOREACH(routerstatus_list, local_routerstatus_t *, rs,
2810 local_routerstatus_free(rs));
2811 smartlist_free(routerstatus_list);
2812 routerstatus_list = result;
2814 tor_free(networkstatus);
2815 tor_free(index);
2816 tor_free(size);
2817 strmap_free(name_map, NULL);
2819 networkstatus_list_has_changed = 0;
2820 routerstatus_list_has_changed = 1;
2823 /** Given a list <b>routers</b> of routerinfo_t *, update each routers's
2824 * is_named, is_verified, and is_running fields according to our current
2825 * networkstatus_t documents. */
2826 void
2827 routers_update_status_from_networkstatus(smartlist_t *routers, int reset_failures, int assume_recognized)
2829 trusted_dir_server_t *ds;
2830 local_routerstatus_t *rs;
2831 or_options_t *options = get_options();
2832 int authdir = options->AuthoritativeDir;
2833 int namingdir = options->AuthoritativeDir &&
2834 options->NamingAuthoritativeDir;
2836 if (!routerstatus_list)
2837 return;
2839 SMARTLIST_FOREACH(routers, routerinfo_t *, router,
2841 rs = router_get_combined_status_by_digest(router->identity_digest);
2842 ds = router_get_trusteddirserver_by_digest(router->identity_digest);
2844 if (!rs)
2845 continue;
2847 if (!namingdir)
2848 router->is_named = rs->status.is_named;
2850 if (!authdir) {
2851 /* If we're an authdir, don't believe others. */
2852 router->is_verified = rs->status.is_valid;
2853 router->is_running = rs->status.is_running;
2855 if (router->is_running && ds) {
2856 ds->n_networkstatus_failures = 0;
2858 if (assume_recognized) {
2859 router->xx_is_recognized = 1;
2860 } else {
2861 if (!router->xx_is_recognized) {
2862 router->xx_is_recognized = routerdesc_digest_is_recognized(
2863 router->identity_digest, router->signed_descriptor_digest);
2865 router->xx_is_extra_new = router->published_on > rs->status.published_on;
2867 if (reset_failures && router->xx_is_recognized) {
2868 rs->n_download_failures = 0;
2869 rs->next_attempt_at = 0;
2874 /** Return new list of ID fingerprints for superseded routers. A router is
2875 * superseded if any network-status has a router with a different digest
2876 * published more recently, or if it is listed in the network-status but not
2877 * in the router list.
2879 static smartlist_t *
2880 router_list_downloadable(void)
2882 #define MAX_OLD_SERVER_DOWNLOAD_RATE 2*60*60
2883 int n_conns, i, n_downloadable = 0;
2884 connection_t **carray;
2885 smartlist_t *superseded = smartlist_create();
2886 smartlist_t *downloading;
2887 time_t now = time(NULL);
2888 int mirror = server_mode(get_options()) && get_options()->DirPort;
2889 /* these are just used for logging */
2890 int n_not_ready = 0, n_in_progress = 0, n_uptodate = 0, n_skip_old = 0,
2891 n_obsolete = 0, xx_n_unrecognized = 0, xx_n_extra_new = 0, xx_n_both = 0,
2892 xx_n_unrec_old = 0;
2894 if (!routerstatus_list)
2895 return superseded;
2897 get_connection_array(&carray, &n_conns);
2899 routerstatus_list_update_from_networkstatus(now);
2901 SMARTLIST_FOREACH(routerstatus_list, local_routerstatus_t *, rs,
2903 if (rs->status.published_on + ROUTER_MAX_AGE < now) {
2904 rs->should_download = 0;
2905 ++n_obsolete;
2906 } if (rs->next_attempt_at < now) {
2907 rs->should_download = 1;
2908 ++n_downloadable;
2909 } else {
2911 char fp[HEX_DIGEST_LEN+1];
2912 base16_encode(fp, HEX_DIGEST_LEN+1, rs->status.identity_digest, DIGEST_LEN);
2913 log_fn(LOG_NOTICE, "Not yet ready to download %s (%d more seconds)", fp,
2914 (int)(rs->next_attempt_at-now));
2916 rs->should_download = 0;
2917 ++n_not_ready;
2921 downloading = smartlist_create();
2922 for (i = 0; i < n_conns; ++i) {
2923 connection_t *conn = carray[i];
2924 if (conn->type == CONN_TYPE_DIR &&
2925 conn->purpose == DIR_PURPOSE_FETCH_SERVERDESC &&
2926 !conn->marked_for_close) {
2927 if (!strcmpstart(conn->requested_resource, "all"))
2928 n_downloadable = 0;
2929 dir_split_resource_into_fingerprints(conn->requested_resource,
2930 downloading, NULL, 1);
2934 if (n_downloadable) {
2935 SMARTLIST_FOREACH(downloading, const char *, d,
2937 local_routerstatus_t *rs;
2938 if ((rs = router_get_combined_status_by_digest(d)) && rs->should_download) {
2939 rs->should_download = 0;
2940 --n_downloadable;
2941 ++n_in_progress;
2945 SMARTLIST_FOREACH(downloading, char *, cp, tor_free(cp));
2946 smartlist_free(downloading);
2947 if (!n_downloadable)
2948 return superseded;
2950 if (routerlist && n_downloadable) {
2951 SMARTLIST_FOREACH(routerlist->routers, routerinfo_t *, ri,
2953 local_routerstatus_t *rs;
2954 if (!(rs = router_get_combined_status_by_digest(ri->identity_digest)) ||
2955 !rs->should_download) {
2956 // log_fn(LOG_NOTICE, "No status for %s", fp);
2957 continue;
2959 if (!ri->xx_is_recognized) {
2960 ++xx_n_unrecognized;
2961 if (ri->xx_is_extra_new)
2962 ++xx_n_both;
2964 if (ri->xx_is_extra_new)
2965 ++xx_n_extra_new;
2967 /* Change this "or" to be an "and" once dirs generate hashes right.
2968 * Remove the version check once older versions are uncommon.
2969 * XXXXX. NM */
2970 if (!memcmp(ri->signed_descriptor_digest, rs->status.descriptor_digest,
2971 DIGEST_LEN) ||
2972 rs->status.published_on <= ri->published_on) {
2973 ++n_uptodate;
2974 rs->should_download = 0;
2975 --n_downloadable;
2976 } else if (!mirror &&
2977 ri->platform &&
2978 !tor_version_as_new_as(ri->platform, "0.1.1.6-alpha") &&
2979 ri->published_on + MAX_OLD_SERVER_DOWNLOAD_RATE > now) {
2980 /* Same digest, or date is up-to-date, or we have a comparatively recent
2981 * server with an old version.
2982 * No need to download it. */
2983 // log_fn(LOG_NOTICE, "Up-to-date status for %s", fp);
2984 ++n_skip_old;
2985 if (!ri->xx_is_recognized)
2986 ++xx_n_unrec_old;
2987 rs->should_download = 0;
2988 --n_downloadable;
2989 } /* else {
2990 char t1[ISO_TIME_LEN+1];
2991 char t2[ISO_TIME_LEN+1];
2992 format_iso_time(t1, rs->satus.published_on);
2993 format_iso_time(t2, ri->published_on);
2994 log_fn(LOG_NOTICE, "Out-of-date status for %s %s (%d %d) [%s %s]", fp,
2995 ri->nickname,
2996 !memcmp(ri->signed_descriptor_digest,rs->status.descriptor_digest,
2997 DIGEST_LEN),
2998 rs->published_on < ri->published_on,
2999 t1, t2);
3000 } */
3004 info(LD_DIR, "%d router descriptors are downloadable; "
3005 "%d are up to date; %d are in progress; "
3006 "%d are not ready to retry; "
3007 "%d are not published recently enough to be worthwhile; "
3008 "%d are running pre-0.1.1.6 Tors and aren't stale enough to replace. "
3009 "%d have unrecognized descriptor hashes; %d are newer than the dirs "
3010 "have told us about; %d are both unrecognized and newer than any "
3011 "publication date in the networkstatus; %d are both "
3012 "unrecognized and running a pre-0.1.1.6 version.",
3013 n_downloadable, n_uptodate, n_in_progress, n_not_ready,
3014 n_obsolete, n_skip_old, xx_n_unrecognized, xx_n_extra_new, xx_n_both,
3015 xx_n_unrec_old);
3017 if (!n_downloadable)
3018 return superseded;
3020 SMARTLIST_FOREACH(routerstatus_list, local_routerstatus_t *, rs,
3022 if (rs->should_download) {
3023 char *fp = tor_malloc(HEX_DIGEST_LEN+1);
3024 base16_encode(fp, HEX_DIGEST_LEN+1, rs->status.identity_digest, DIGEST_LEN);
3025 smartlist_add(superseded, fp);
3029 return superseded;
3032 /** Initiate new router downloads as needed.
3034 * We only allow one router descriptor download at a time.
3035 * If we have less than two network-status documents, we ask
3036 * a directory for "all descriptors."
3037 * Otherwise, we ask for all descriptors that we think are different
3038 * from what we have.
3040 void
3041 update_router_descriptor_downloads(time_t now)
3043 #define MAX_DL_PER_REQUEST 128
3044 #define MIN_DL_PER_REQUEST 4
3045 #define MIN_REQUESTS 3
3046 #define MAX_DL_TO_DELAY 16
3047 #define MAX_CLIENT_INTERVAL_WITHOUT_REQUEST 10*60
3048 #define MAX_SERVER_INTERVAL_WITHOUT_REQUEST 1*60
3049 smartlist_t *downloadable = NULL;
3050 int get_all = 0;
3051 int dirserv = server_mode(get_options()) && get_options()->DirPort;
3052 int should_delay, n_downloadable;
3053 if (!networkstatus_list || smartlist_len(networkstatus_list)<2)
3054 get_all = 1;
3056 if (get_all) {
3057 notice(LD_DIR, "Launching request for all routers");
3058 last_routerdesc_download_attempted = now;
3059 directory_get_from_dirserver(DIR_PURPOSE_FETCH_SERVERDESC,"all.z",1);
3060 return;
3063 downloadable = router_list_downloadable();
3064 n_downloadable = smartlist_len(downloadable);
3065 if (n_downloadable >= MAX_DL_TO_DELAY) {
3066 debug(LD_DIR,
3067 "There are enough downloadable routerdescs to launch requests.");
3068 should_delay = 0;
3069 } else if (n_downloadable == 0) {
3070 debug(LD_DIR, "No routerdescs need to be downloaded.");
3071 should_delay = 1;
3072 } else {
3073 if (dirserv) {
3074 should_delay = (last_routerdesc_download_attempted +
3075 MAX_SERVER_INTERVAL_WITHOUT_REQUEST) > now;
3076 } else {
3077 should_delay = (last_routerdesc_download_attempted +
3078 MAX_CLIENT_INTERVAL_WITHOUT_REQUEST) > now;
3080 if (should_delay)
3081 debug(LD_DIR, "There are not many downloadable routerdescs; waiting till we have some more.");
3082 else
3083 info(LD_DIR, "There are not many downloadable routerdescs, but we've been waiting long enough (%d seconds). Downloading.",
3084 (int)(now-last_routerdesc_download_attempted));
3087 if (! should_delay) {
3088 int i, j, n_per_request=MAX_DL_PER_REQUEST;
3089 size_t r_len = MAX_DL_PER_REQUEST*(HEX_DIGEST_LEN+1)+16;
3090 char *resource = tor_malloc(r_len);
3092 if (! dirserv) {
3093 n_per_request = (n_downloadable+MIN_REQUESTS-1) / MIN_REQUESTS;
3094 if (n_per_request > MAX_DL_PER_REQUEST)
3095 n_per_request = MAX_DL_PER_REQUEST;
3096 if (n_per_request < MIN_DL_PER_REQUEST)
3097 n_per_request = MIN_DL_PER_REQUEST;
3099 info(LD_DIR, "Launching %d request%s for %d router%s, %d at a time",
3100 (n_downloadable+n_per_request-1)/n_per_request,
3101 n_downloadable>n_per_request?"s":"",
3102 n_downloadable, n_downloadable>1?"s":"", n_per_request);
3103 for (i=0; i < n_downloadable; i += n_per_request) {
3104 char *cp = resource;
3105 memcpy(resource, "fp/", 3);
3106 cp = resource + 3;
3107 for (j=i; j < i+n_per_request && j < n_downloadable; ++j) {
3108 memcpy(cp, smartlist_get(downloadable, j), HEX_DIGEST_LEN);
3109 cp += HEX_DIGEST_LEN;
3110 *cp++ = '+';
3112 memcpy(cp-1, ".z", 3);
3113 directory_get_from_dirserver(DIR_PURPOSE_FETCH_SERVERDESC,resource,1);
3115 last_routerdesc_download_attempted = now;
3116 tor_free(resource);
3118 SMARTLIST_FOREACH(downloadable, char *, c, tor_free(c));
3119 smartlist_free(downloadable);
3122 /** Return true iff we have enough networkstatus and router information to
3123 * start building circuits. Right now, this means "at least 2 networkstatus
3124 * documents, and at least 1/4 of expected routers." */
3126 router_have_minimum_dir_info(void)
3128 int tot = 0, avg;
3129 if (!networkstatus_list || smartlist_len(networkstatus_list)<2 ||
3130 !routerlist)
3131 return 0;
3132 SMARTLIST_FOREACH(networkstatus_list, networkstatus_t *, ns,
3133 tot += smartlist_len(ns->entries));
3134 avg = tot / smartlist_len(networkstatus_list);
3135 return smartlist_len(routerlist->routers) > (avg/4);
3138 /** Reset the descriptor download failure count on all routers, so that we
3139 * can retry any long-failed routers immediately.
3141 void
3142 router_reset_descriptor_download_failures(void)
3144 if (!routerstatus_list)
3145 return;
3146 SMARTLIST_FOREACH(routerstatus_list, local_routerstatus_t *, rs,
3148 rs->n_download_failures = 0;
3149 rs->next_attempt_at = 0;
3151 last_routerdesc_download_attempted = 0;
3154 /** Return true iff the only differences between r1 and r2 are such that
3155 * would not cause a recent (post 0.1.1.6) direserver to republish.
3158 router_differences_are_cosmetic(routerinfo_t *r1, routerinfo_t *r2)
3160 tor_assert(r1 && r2);
3162 /* post-0.1.1.6 servers know what they're doing. */
3163 if (tor_version_as_new_as(r1->platform, "0.1.1.6-alpha") ||
3164 tor_version_as_new_as(r2->platform, "0.1.1.6-alpha"))
3165 return 0;
3167 /* r1 should be the one that was published first. */
3168 if (r1->published_on > r2->published_on) {
3169 routerinfo_t *ri_tmp = r2;
3170 r2 = r1;
3171 r1 = ri_tmp;
3174 /* If any key fields differ, they're different. */
3175 if (strcasecmp(r1->address, r2->address) ||
3176 strcasecmp(r1->nickname, r2->nickname) ||
3177 r1->or_port != r2->or_port ||
3178 r1->dir_port != r2->dir_port ||
3179 crypto_pk_cmp_keys(r1->onion_pkey, r2->onion_pkey) ||
3180 crypto_pk_cmp_keys(r1->identity_pkey, r2->identity_pkey) ||
3181 strcasecmp(r1->platform, r2->platform) ||
3182 (r1->contact_info && !r2->contact_info) || /* contact_info is optional */
3183 (!r1->contact_info && r2->contact_info) ||
3184 (r1->contact_info && r2->contact_info && strcasecmp(r1->contact_info, r2->contact_info)) ||
3185 r1->is_hibernating != r2->is_hibernating ||
3186 config_cmp_addr_policies(r1->exit_policy, r2->exit_policy))
3187 return 0;
3188 if ((r1->declared_family == NULL) != (r2->declared_family == NULL))
3189 return 0;
3190 if (r1->declared_family && r2->declared_family) {
3191 int i, n;
3192 if (smartlist_len(r1->declared_family)!=smartlist_len(r2->declared_family))
3193 return 0;
3194 n = smartlist_len(r1->declared_family);
3195 for (i=0; i < n; ++i) {
3196 if (strcasecmp(smartlist_get(r1->declared_family, i),
3197 smartlist_get(r2->declared_family, i)))
3198 return 0;
3202 /* Did bandwidth change a lot? */
3203 if ((r1->bandwidthcapacity < r2->bandwidthcapacity/2) ||
3204 (r2->bandwidthcapacity < r1->bandwidthcapacity/2))
3205 return 0;
3207 /* Did more than 12 hours pass? */
3208 if (r1->published_on + 12*60*60 < r2->published_on)
3209 return 0;
3211 /* Did uptime fail to increase by approximately the amount we would think,
3212 * give or take 30 minutes? */
3213 if (abs(r2->uptime - (r1->uptime + (r2->published_on-r1->published_on)))>30*60)
3214 return 0;
3216 /* Otherwise, the difference is cosmetic. */
3217 return 1;
3220 static void
3221 routerlist_assert_ok(routerlist_t *rl)
3223 digestmap_iter_t *iter;
3224 routerinfo_t *r2;
3225 if (!routerlist)
3226 return;
3227 SMARTLIST_FOREACH(rl->routers, routerinfo_t *, r,
3229 r2 = digestmap_get(rl->identity_map, r->identity_digest);
3230 tor_assert(r == r2);
3231 r2 = digestmap_get(rl->desc_digest_map, r->signed_descriptor_digest);
3232 tor_assert(r == r2);
3234 SMARTLIST_FOREACH(rl->old_routers, routerinfo_t *, r,
3236 r2 = digestmap_get(rl->identity_map, r->identity_digest);
3237 tor_assert(r != r2);
3238 r2 = digestmap_get(rl->desc_digest_map, r->signed_descriptor_digest);
3239 tor_assert(r == r2);
3241 iter = digestmap_iter_init(rl->identity_map);
3242 while (!digestmap_iter_done(iter)) {
3243 const char *d;
3244 void *_r;
3245 routerinfo_t *r;
3246 digestmap_iter_get(iter, &d, &_r);
3247 r = _r;
3248 tor_assert(!memcmp(r->identity_digest, d, DIGEST_LEN));
3249 iter = digestmap_iter_next(rl->identity_map, iter);
3251 iter = digestmap_iter_init(rl->desc_digest_map);
3252 while (!digestmap_iter_done(iter)) {
3253 const char *d;
3254 void *_r;
3255 routerinfo_t *r;
3256 digestmap_iter_get(iter, &d, &_r);
3257 r = _r;
3258 tor_assert(!memcmp(r->signed_descriptor_digest, d, DIGEST_LEN));
3259 iter = digestmap_iter_next(rl->desc_digest_map, iter);