Convert circuituse, command, config, connection, relay, router, test to new logging...
[tor.git] / src / or / routerlist.c
blob3cd9bcd4e3239ff73d80343d046d35c38923ae4f
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 #define NEW_LOG_INTERFACE
16 #include "or.h"
18 /****************************************************************************/
20 /** Global list of a trusted_dir_server_t object for each trusted directory
21 * server. */
22 static smartlist_t *trusted_dir_servers = NULL;
24 /* static function prototypes */
25 static routerinfo_t *router_pick_directory_server_impl(int requireother,
26 int fascistfirewall,
27 int for_v2_directory);
28 static trusted_dir_server_t *router_pick_trusteddirserver_impl(
29 int need_v1_support, int requireother, int fascistfirewall);
30 static void mark_all_trusteddirservers_up(void);
31 static int router_nickname_is_in_list(routerinfo_t *router, const char *list);
32 static int router_nickname_matches(routerinfo_t *router, const char *nickname);
33 static void routerstatus_list_update_from_networkstatus(time_t now);
34 static void local_routerstatus_free(local_routerstatus_t *rs);
35 static void trusted_dir_server_free(trusted_dir_server_t *ds);
36 static void update_networkstatus_cache_downloads(time_t now);
37 static void update_networkstatus_client_downloads(time_t now);
38 static int routerdesc_digest_is_recognized(const char *identity,
39 const char *digest);
40 static void routerlist_assert_ok(routerlist_t *rl);
42 /****************************************************************************/
44 /****
45 * Functions to manage and access our list of known routers. (Note:
46 * dirservers maintain a separate, independent list of known router
47 * descriptors.)
48 ****/
50 /** Global list of all of the routers that we know about. */
51 static routerlist_t *routerlist = NULL;
53 extern int has_fetched_directory; /**< from main.c */
55 /** Global list of all of the current network_status documents that we know
56 * about. This list is kept sorted by published_on. */
57 static smartlist_t *networkstatus_list = NULL;
58 /** Global list of local_routerstatus_t for each router, known or unknown. */
59 static smartlist_t *routerstatus_list = NULL;
60 /** True iff any member of networkstatus_list has changed since the last time
61 * we called routerstatus_list_update_from_networkstatus(). */
62 static int networkstatus_list_has_changed = 0;
63 /** True iff any element of routerstatus_list has changed since the last
64 * time we called routers_update_all_from_networkstatus().*/
65 static int routerstatus_list_has_changed = 0;
66 /** List of strings for nicknames we've already warned about and that are
67 * still unknown / unavailable. */
68 static smartlist_t *warned_nicknames = NULL;
69 /** List of strings for nicknames or fingerprints we've already warned about
70 * and that are still conflicted. */
71 static smartlist_t *warned_conflicts = NULL;
73 /** The last time we tried to download any routerdesc, or 0 for "never". We
74 * use this to rate-limit download attempts when the number of routerdescs to
75 * download is low. */
76 static time_t last_routerdesc_download_attempted = 0;
77 /** The last time we tried to download a networkstatus, or 0 for "never". We
78 * use this to rate-limit download attempts for directory caches (including
79 * mirrors). Clients don't use this now. */
80 static time_t last_networkstatus_download_attempted = 0;
82 /* DOCDOC */
83 static int have_warned_about_unverified_status = 0;
84 static int have_warned_about_old_version = 0;
85 static int have_warned_about_new_version = 0;
87 /** Repopulate our list of network_status_t objects from the list cached on
88 * disk. Return 0 on success, -1 on failure. */
89 int
90 router_reload_networkstatus(void)
92 char filename[512];
93 struct stat st;
94 smartlist_t *entries;
95 char *s;
96 tor_assert(get_options()->DataDirectory);
97 if (!networkstatus_list)
98 networkstatus_list = smartlist_create();
100 tor_snprintf(filename,sizeof(filename),"%s/cached-status",
101 get_options()->DataDirectory);
102 entries = tor_listdir(filename);
103 SMARTLIST_FOREACH(entries, const char *, fn, {
104 char buf[DIGEST_LEN];
105 if (fn[0] == '.') /* skip . and .. */
106 continue;
107 if (strlen(fn) != HEX_DIGEST_LEN ||
108 base16_decode(buf, sizeof(buf), fn, strlen(fn))) {
109 info(LD_DIR,
110 "Skipping cached-status file with unexpected name \"%s\"",fn);
111 continue;
113 tor_snprintf(filename,sizeof(filename),"%s/cached-status/%s",
114 get_options()->DataDirectory, fn);
115 s = read_file_to_str(filename, 0);
116 if (s) {
117 stat(filename, &st);
118 if (router_set_networkstatus(s, st.st_mtime, NS_FROM_CACHE, NULL)<0) {
119 warn(LD_FS, "Couldn't load networkstatus from \"%s\"",filename);
121 tor_free(s);
124 SMARTLIST_FOREACH(entries, char *, fn, tor_free(fn));
125 smartlist_free(entries);
126 networkstatus_list_clean(time(NULL));
127 routers_update_all_from_networkstatus();
128 return 0;
131 /* Router descriptor storage.
133 * Routerdescs are stored in a big file, named "cached-routers". As new
134 * routerdescs arrive, we append them to a journal file named
135 * "cached-routers.new".
137 * From time to time, we replace "cached-routers" with a new file containing
138 * only the live, non-superseded descriptors, and clear cached-routers.new.
140 * On startup, we read both files.
143 /** The size of the router log, in bytes. */
144 static size_t router_journal_len = 0;
145 /** The size of the router store, in bytes. */
146 static size_t router_store_len = 0;
148 /** Helper: return 1 iff the router log is so big we want to rebuild the
149 * store. */
150 static int
151 router_should_rebuild_store(void)
153 if (router_store_len > (1<<16))
154 return router_journal_len > router_store_len / 2;
155 else
156 return router_journal_len > (1<<15);
159 /** Add the <b>len</b>-type router descriptor in <b>s</b> to the router
160 * journal. */
161 static int
162 router_append_to_journal(const char *s, size_t len)
164 or_options_t *options = get_options();
165 size_t fname_len = strlen(options->DataDirectory)+32;
166 char *fname = tor_malloc(len);
168 tor_snprintf(fname, fname_len, "%s/cached-routers.new",
169 options->DataDirectory);
171 if (!len)
172 len = strlen(s);
174 if (append_bytes_to_file(fname, s, len, 0)) {
175 warn(LD_FS, "Unable to store router descriptor");
176 tor_free(fname);
177 return -1;
180 tor_free(fname);
181 router_journal_len += len;
182 return 0;
185 /** If the journal is too long, or if <b>force</b> is true, then atomically
186 * replace the router store with the routers currently in our routerlist, and
187 * clear the journal. Return 0 on success, -1 on failure.
189 static int
190 router_rebuild_store(int force)
192 size_t len = 0;
193 or_options_t *options;
194 size_t fname_len;
195 smartlist_t *chunk_list = NULL;
196 char *fname = NULL;
197 int r = -1;
199 if (!force && !router_should_rebuild_store())
200 return 0;
201 if (!routerlist)
202 return 0;
204 /* Don't save deadweight. */
205 routerlist_remove_old_routers(ROUTER_MAX_AGE);
207 options = get_options();
208 fname_len = strlen(options->DataDirectory)+32;
209 fname = tor_malloc(fname_len);
210 tor_snprintf(fname, fname_len, "%s/cached-routers", options->DataDirectory);
211 chunk_list = smartlist_create();
213 SMARTLIST_FOREACH(routerlist->routers, routerinfo_t *, ri,
215 sized_chunk_t *c;
216 if (!ri->signed_descriptor) {
217 warn(LD_BUG, "Bug! No descriptor stored for router '%s'.",
218 ri->nickname);
219 goto done;
221 c = tor_malloc(sizeof(sized_chunk_t));
222 c->bytes = ri->signed_descriptor;
223 c->len = ri->signed_descriptor_len;
224 smartlist_add(chunk_list, c);
227 if (write_chunks_to_file(fname, chunk_list, 0)<0) {
228 warn(LD_FS, "Error writing router store to disk.");
229 goto done;
232 tor_snprintf(fname, fname_len, "%s/cached-routers.new",
233 options->DataDirectory);
235 write_str_to_file(fname, "", 0);
237 r = 0;
238 router_store_len = len;
239 router_journal_len = 0;
240 done:
241 tor_free(fname);
242 if (chunk_list) {
243 SMARTLIST_FOREACH(chunk_list, sized_chunk_t *, c, tor_free(c));
244 smartlist_free(chunk_list);
246 return r;
249 /* Load all cached router descriptors from the store. Return 0 on success and
250 * -1 on failure.
253 router_reload_router_list(void)
255 or_options_t *options = get_options();
256 size_t fname_len = strlen(options->DataDirectory)+32;
257 char *fname = tor_malloc(fname_len);
258 struct stat st;
259 int j;
261 if (!routerlist)
262 router_get_routerlist();
264 router_journal_len = router_store_len = 0;
266 for (j = 0; j < 2; ++j) {
267 char *contents;
268 tor_snprintf(fname, fname_len,
269 (j==0)?"%s/cached-routers":"%s/cached-routers.new",
270 options->DataDirectory);
271 contents = read_file_to_str(fname, 0);
272 if (contents) {
273 stat(fname, &st);
274 if (j==0)
275 router_store_len = st.st_size;
276 else
277 router_journal_len = st.st_size;
278 router_load_routers_from_string(contents, 1, NULL);
279 tor_free(contents);
282 tor_free(fname);
284 /* Don't cache expired routers. */
285 routerlist_remove_old_routers(ROUTER_MAX_AGE);
287 if (router_journal_len) {
288 /* Always clear the journal on startup.*/
289 router_rebuild_store(1);
291 return 0;
294 /** Set *<b>outp</b> to a smartlist containing a list of
295 * trusted_dir_server_t * for all known trusted dirservers. Callers
296 * must not modify the list or its contents.
298 void
299 router_get_trusted_dir_servers(smartlist_t **outp)
301 if (!trusted_dir_servers)
302 trusted_dir_servers = smartlist_create();
304 *outp = trusted_dir_servers;
307 /** Try to find a running dirserver. If there are no running dirservers
308 * in our routerlist and <b>retry_if_no_servers</b> is non-zero,
309 * set all the authoritative ones as running again, and pick one;
310 * if there are then no dirservers at all in our routerlist,
311 * reload the routerlist and try one last time. If for_runningrouters is
312 * true, then only pick a dirserver that can answer runningrouters queries
313 * (that is, a trusted dirserver, or one running 0.0.9rc5-cvs or later).
314 * Other args are as in router_pick_directory_server_impl().
316 routerinfo_t *
317 router_pick_directory_server(int requireother,
318 int fascistfirewall,
319 int for_v2_directory,
320 int retry_if_no_servers)
322 routerinfo_t *choice;
324 if (!routerlist)
325 return NULL;
327 choice = router_pick_directory_server_impl(requireother, fascistfirewall,
328 for_v2_directory);
329 if (choice || !retry_if_no_servers)
330 return choice;
332 info(LD_DIR,"No reachable router entries for dirservers. Trying them all again.");
333 /* mark all authdirservers as up again */
334 mark_all_trusteddirservers_up();
335 /* try again */
336 choice = router_pick_directory_server_impl(requireother, fascistfirewall,
337 for_v2_directory);
338 if (choice)
339 return choice;
341 info(LD_DIR,"Still no %s router entries. Reloading and trying again.",
342 firewall_is_fascist() ? "reachable" : "known");
343 has_fetched_directory=0; /* reset it */
344 if (router_reload_router_list()) {
345 return NULL;
347 /* give it one last try */
348 choice = router_pick_directory_server_impl(requireother, 0,
349 for_v2_directory);
350 return choice;
353 trusted_dir_server_t *
354 router_get_trusteddirserver_by_digest(const char *digest)
356 if (!trusted_dir_servers)
357 return NULL;
359 SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, ds,
361 if (!memcmp(ds->digest, digest, DIGEST_LEN))
362 return ds;
365 return NULL;
368 /** Try to find a running trusted dirserver. If there are no running
369 * trusted dirservers and <b>retry_if_no_servers</b> is non-zero,
370 * set them all as running again, and try again.
371 * Other args are as in router_pick_trusteddirserver_impl().
373 trusted_dir_server_t *
374 router_pick_trusteddirserver(int need_v1_support,
375 int requireother,
376 int fascistfirewall,
377 int retry_if_no_servers)
379 trusted_dir_server_t *choice;
381 choice = router_pick_trusteddirserver_impl(need_v1_support,
382 requireother, fascistfirewall);
383 if (choice || !retry_if_no_servers)
384 return choice;
386 info(LD_DIR,"No trusted dirservers are reachable. Trying them all again.");
387 mark_all_trusteddirservers_up();
388 return router_pick_trusteddirserver_impl(need_v1_support,
389 requireother, fascistfirewall);
392 /** Pick a random running verified directory server/mirror from our
393 * routerlist.
394 * If <b>fascistfirewall</b> and we're not using a proxy,
395 * make sure the port we pick is allowed by options-\>firewallports.
396 * If <b>requireother</b>, it cannot be us. If <b>for_v2_directory</b>,
397 * choose a directory server new enough to support the v2 directory
398 * functionality.
400 static routerinfo_t *
401 router_pick_directory_server_impl(int requireother, int fascistfirewall,
402 int for_v2_directory)
404 routerinfo_t *result;
405 smartlist_t *sl;
407 if (!routerlist)
408 return NULL;
410 if (get_options()->HttpProxy)
411 fascistfirewall = 0;
413 /* Find all the running dirservers we know about. */
414 sl = smartlist_create();
415 SMARTLIST_FOREACH(routerlist->routers, routerinfo_t *, router,
417 if (!router->is_running || !router->dir_port || !router->is_verified)
418 continue;
419 if (requireother && router_is_me(router))
420 continue;
421 if (fascistfirewall) {
422 if (!fascist_firewall_allows_address(router->addr, router->dir_port))
423 continue;
425 /* Before 0.1.1.6-alpha, only trusted dirservers served status info.
426 * Before 0.1.1.7-alpha, retrieving nonexistent server IDs could bork
427 * the directory server.
429 if (for_v2_directory &&
430 !(tor_version_as_new_as(router->platform,"0.1.1.7-alpha") ||
431 router_digest_is_trusted_dir(router->identity_digest)))
432 continue;
433 smartlist_add(sl, router);
436 result = smartlist_choose(sl);
437 smartlist_free(sl);
438 return result;
441 /** Choose randomly from among the trusted dirservers that are up.
442 * If <b>fascistfirewall</b> and we're not using a proxy,
443 * make sure the port we pick is allowed by options-\>firewallports.
444 * If <b>requireother</b>, it cannot be us. If <b>need_v1_support</b>, choose
445 * a trusted authority for the v1 directory system.
447 static trusted_dir_server_t *
448 router_pick_trusteddirserver_impl(int need_v1_support,
449 int requireother, int fascistfirewall)
451 smartlist_t *sl;
452 routerinfo_t *me;
453 trusted_dir_server_t *ds;
454 sl = smartlist_create();
455 me = router_get_my_routerinfo();
457 if (!trusted_dir_servers)
458 return NULL;
460 if (get_options()->HttpProxy)
461 fascistfirewall = 0;
463 SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, d,
465 if (!d->is_running) continue;
466 if (need_v1_support && !d->supports_v1_protocol)
467 continue;
468 if (requireother && me &&
469 !memcmp(me->identity_digest, d->digest, DIGEST_LEN))
470 continue;
471 if (fascistfirewall) {
472 if (!fascist_firewall_allows_address(d->addr, d->dir_port))
473 continue;
475 smartlist_add(sl, d);
478 ds = smartlist_choose(sl);
479 smartlist_free(sl);
480 return ds;
483 /** Go through and mark the authoritative dirservers as up. */
484 static void
485 mark_all_trusteddirservers_up(void)
487 if (routerlist) {
488 SMARTLIST_FOREACH(routerlist->routers, routerinfo_t *, router,
489 if (router_digest_is_trusted_dir(router->identity_digest) &&
490 router->dir_port > 0) {
491 router->is_running = 1;
494 if (trusted_dir_servers) {
495 SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, dir,
497 dir->is_running = 1;
498 dir->n_networkstatus_failures = 0;
501 last_networkstatus_download_attempted = 0;
504 /** Reset all internal variables used to count failed downloads of network
505 * status objects. */
506 void
507 router_reset_status_download_failures(void)
509 mark_all_trusteddirservers_up();
512 /** Return 0 if \\exists an authoritative dirserver that's currently
513 * thought to be running, else return 1.
516 all_trusted_directory_servers_down(void)
518 if (!trusted_dir_servers)
519 return 1;
520 SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, dir,
521 if (dir->is_running) return 0);
522 return 1;
525 /** Add all the family of <b>router</b> to the smartlist <b>sl</b>.
526 * This is used to make sure we don't pick siblings in a single path.
528 void
529 routerlist_add_family(smartlist_t *sl, routerinfo_t *router)
531 routerinfo_t *r;
532 config_line_t *cl;
534 if (!router->declared_family)
535 return;
537 /* Add every r such that router declares familyness with r, and r
538 * declares familyhood with router. */
539 SMARTLIST_FOREACH(router->declared_family, const char *, n,
541 if (!(r = router_get_by_nickname(n, 0)))
542 continue;
543 if (!r->declared_family)
544 continue;
545 SMARTLIST_FOREACH(r->declared_family, const char *, n2,
547 if (router_nickname_matches(router, n2))
548 smartlist_add(sl, r);
552 /* If the user declared any families locally, honor those too. */
553 for (cl = get_options()->NodeFamilies; cl; cl = cl->next) {
554 if (router_nickname_is_in_list(router, cl->value)) {
555 add_nickname_list_to_smartlist(sl, cl->value, 1, 1);
560 /** Given a comma-and-whitespace separated list of nicknames, see which
561 * nicknames in <b>list</b> name routers in our routerlist that are
562 * currently running. Add the routerinfos for those routers to <b>sl</b>.
564 void
565 add_nickname_list_to_smartlist(smartlist_t *sl, const char *list, int warn_if_down, int warn_if_unnamed)
567 routerinfo_t *router;
568 smartlist_t *nickname_list;
570 if (!list)
571 return; /* nothing to do */
572 tor_assert(sl);
574 nickname_list = smartlist_create();
575 if (!warned_nicknames)
576 warned_nicknames = smartlist_create();
578 smartlist_split_string(nickname_list, list, ",",
579 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
581 SMARTLIST_FOREACH(nickname_list, const char *, nick, {
582 int warned;
583 if (!is_legal_nickname_or_hexdigest(nick)) {
584 warn(LD_CONFIG, "Nickname %s is misformed; skipping", nick);
585 continue;
587 router = router_get_by_nickname(nick, warn_if_unnamed);
588 warned = smartlist_string_isin(warned_nicknames, nick);
589 if (router) {
590 if (router->is_running) {
591 smartlist_add(sl,router);
592 if (warned)
593 smartlist_string_remove(warned_nicknames, nick);
594 } else {
595 if (!warned) {
596 log_fn(warn_if_down ? LOG_WARN : LOG_DEBUG, LD_CONFIG,
597 "Nickname list includes '%s' which is known but down.",nick);
598 smartlist_add(warned_nicknames, tor_strdup(nick));
601 } else {
602 if (!warned) {
603 log_fn(has_fetched_directory ? LOG_WARN : LOG_INFO, LD_CONFIG,
604 "Nickname list includes '%s' which isn't a known router.",nick);
605 smartlist_add(warned_nicknames, tor_strdup(nick));
609 SMARTLIST_FOREACH(nickname_list, char *, nick, tor_free(nick));
610 smartlist_free(nickname_list);
613 /** Return 1 iff any member of the comma-separated list <b>list</b> is an
614 * acceptable nickname or hexdigest for <b>router</b>. Else return 0.
616 static int
617 router_nickname_is_in_list(routerinfo_t *router, const char *list)
619 smartlist_t *nickname_list;
620 int v = 0;
622 if (!list)
623 return 0; /* definitely not */
624 tor_assert(router);
626 nickname_list = smartlist_create();
627 smartlist_split_string(nickname_list, list, ",",
628 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
629 SMARTLIST_FOREACH(nickname_list, const char *, cp,
630 if (router_nickname_matches(router, cp)) {v=1;break;});
631 SMARTLIST_FOREACH(nickname_list, char *, cp, tor_free(cp));
632 smartlist_free(nickname_list);
633 return v;
636 /** Add every router from our routerlist that is currently running to
637 * <b>sl</b>.
639 static void
640 router_add_running_routers_to_smartlist(smartlist_t *sl, int allow_unverified,
641 int need_uptime, int need_capacity)
643 if (!routerlist)
644 return;
646 SMARTLIST_FOREACH(routerlist->routers, routerinfo_t *, router,
648 if (router->is_running &&
649 (router->is_verified ||
650 (allow_unverified &&
651 !router_is_unreliable(router, need_uptime, need_capacity)))) {
652 /* If it's running, and either it's verified or we're ok picking
653 * unverified routers and this one is suitable.
655 smartlist_add(sl, router);
660 /** Look through the routerlist until we find a router that has my key.
661 Return it. */
662 routerinfo_t *
663 routerlist_find_my_routerinfo(void)
665 if (!routerlist)
666 return NULL;
668 SMARTLIST_FOREACH(routerlist->routers, routerinfo_t *, router,
670 if (router_is_me(router))
671 return router;
673 return NULL;
676 /** Find a router that's up, that has this IP address, and
677 * that allows exit to this address:port, or return NULL if there
678 * isn't a good one.
680 routerinfo_t *
681 router_find_exact_exit_enclave(const char *address, uint16_t port)
683 uint32_t addr;
684 struct in_addr in;
686 if (!tor_inet_aton(address, &in))
687 return NULL; /* it's not an IP already */
688 addr = ntohl(in.s_addr);
690 SMARTLIST_FOREACH(routerlist->routers, routerinfo_t *, router,
692 if (router->is_running &&
693 router->addr == addr &&
694 router_compare_addr_to_addr_policy(addr, port, router->exit_policy) ==
695 ADDR_POLICY_ACCEPTED)
696 return router;
698 return NULL;
701 /** Return 1 if <b>router</b> is not suitable for these parameters, else 0.
702 * If <b>need_uptime</b> is non-zero, we require a minimum uptime.
703 * If <b>need_capacity</b> is non-zero, we require a minimum advertised
704 * bandwidth.
707 router_is_unreliable(routerinfo_t *router, int need_uptime, int need_capacity)
709 if (need_uptime && router->uptime < ROUTER_REQUIRED_MIN_UPTIME)
710 return 1;
711 if (need_capacity && router->bandwidthcapacity < ROUTER_REQUIRED_MIN_BANDWIDTH)
712 return 1;
713 return 0;
716 /** Remove from routerlist <b>sl</b> all routers who have a low uptime. */
717 static void
718 routerlist_sl_remove_unreliable_routers(smartlist_t *sl)
720 int i;
721 routerinfo_t *router;
723 for (i = 0; i < smartlist_len(sl); ++i) {
724 router = smartlist_get(sl, i);
725 if (router_is_unreliable(router, 1, 0)) {
726 // log(LOG_DEBUG, "Router '%s' has insufficient uptime; deleting.",
727 // router->nickname);
728 smartlist_del(sl, i--);
733 #define MAX_BELIEVABLE_BANDWIDTH 2000000 /* 2 MB/sec */
735 /** Choose a random element of router list <b>sl</b>, weighted by
736 * the advertised bandwidth of each router.
738 routerinfo_t *
739 routerlist_sl_choose_by_bandwidth(smartlist_t *sl)
741 int i;
742 routerinfo_t *router;
743 smartlist_t *bandwidths;
744 uint32_t this_bw, tmp, total_bw=0, rand_bw;
745 uint32_t *p;
747 /* First count the total bandwidth weight, and make a smartlist
748 * of each value. */
749 bandwidths = smartlist_create();
750 for (i = 0; i < smartlist_len(sl); ++i) {
751 router = smartlist_get(sl, i);
752 this_bw = (router->bandwidthcapacity < router->bandwidthrate) ?
753 router->bandwidthcapacity : router->bandwidthrate;
754 /* if they claim something huge, don't believe it */
755 if (this_bw > MAX_BELIEVABLE_BANDWIDTH)
756 this_bw = MAX_BELIEVABLE_BANDWIDTH;
757 p = tor_malloc(sizeof(uint32_t));
758 *p = this_bw;
759 smartlist_add(bandwidths, p);
760 total_bw += this_bw;
762 if (!total_bw) {
763 SMARTLIST_FOREACH(bandwidths, uint32_t*, p, tor_free(p));
764 smartlist_free(bandwidths);
765 return smartlist_choose(sl);
767 /* Second, choose a random value from the bandwidth weights. */
768 rand_bw = crypto_rand_int(total_bw);
769 /* Last, count through sl until we get to the element we picked */
770 tmp = 0;
771 for (i=0; ; i++) {
772 tor_assert(i < smartlist_len(sl));
773 p = smartlist_get(bandwidths, i);
774 tmp += *p;
775 if (tmp >= rand_bw)
776 break;
778 SMARTLIST_FOREACH(bandwidths, uint32_t*, p, tor_free(p));
779 smartlist_free(bandwidths);
780 return (routerinfo_t *)smartlist_get(sl, i);
783 /** Return a random running router from the routerlist. If any node
784 * named in <b>preferred</b> is available, pick one of those. Never
785 * pick a node named in <b>excluded</b>, or whose routerinfo is in
786 * <b>excludedsmartlist</b>, even if they are the only nodes
787 * available. If <b>strict</b> is true, never pick any node besides
788 * those in <b>preferred</b>.
789 * If <b>need_uptime</b> is non-zero, don't return a router with less
790 * than a minimum uptime.
791 * If <b>need_capacity</b> is non-zero, weight your choice by the
792 * advertised capacity of each router.
794 routerinfo_t *
795 router_choose_random_node(const char *preferred,
796 const char *excluded,
797 smartlist_t *excludedsmartlist,
798 int need_uptime, int need_capacity,
799 int allow_unverified, int strict)
801 smartlist_t *sl, *excludednodes;
802 routerinfo_t *choice;
804 excludednodes = smartlist_create();
805 add_nickname_list_to_smartlist(excludednodes,excluded,0,1);
807 /* Try the preferred nodes first. Ignore need_uptime and need_capacity,
808 * since the user explicitly asked for these nodes. */
809 sl = smartlist_create();
810 add_nickname_list_to_smartlist(sl,preferred,1,1);
811 smartlist_subtract(sl,excludednodes);
812 if (excludedsmartlist)
813 smartlist_subtract(sl,excludedsmartlist);
814 choice = smartlist_choose(sl);
815 smartlist_free(sl);
816 if (!choice && !strict) {
817 /* Then give up on our preferred choices: any node
818 * will do that has the required attributes. */
819 sl = smartlist_create();
820 router_add_running_routers_to_smartlist(sl, allow_unverified,
821 need_uptime, need_capacity);
822 smartlist_subtract(sl,excludednodes);
823 if (excludedsmartlist)
824 smartlist_subtract(sl,excludedsmartlist);
825 if (need_uptime)
826 routerlist_sl_remove_unreliable_routers(sl);
827 if (need_capacity)
828 choice = routerlist_sl_choose_by_bandwidth(sl);
829 else
830 choice = smartlist_choose(sl);
831 smartlist_free(sl);
833 smartlist_free(excludednodes);
834 if (!choice)
835 warn(LD_CIRC,"No available nodes when trying to choose node. Failing.");
836 return choice;
839 /** Return true iff the digest of <b>router</b>'s identity key,
840 * encoded in hexadecimal, matches <b>hexdigest</b> (which is
841 * optionally prefixed with a single dollar sign). Return false if
842 * <b>hexdigest</b> is malformed, or it doesn't match. */
843 static INLINE int
844 router_hex_digest_matches(routerinfo_t *router, const char *hexdigest)
846 char digest[DIGEST_LEN];
847 tor_assert(hexdigest);
848 if (hexdigest[0] == '$')
849 ++hexdigest;
851 if (strlen(hexdigest) != HEX_DIGEST_LEN ||
852 base16_decode(digest, DIGEST_LEN, hexdigest, HEX_DIGEST_LEN)<0)
853 return 0;
854 return (!memcmp(digest, router->identity_digest, DIGEST_LEN));
857 /** Return true if <b>router</b>'s nickname matches <b>nickname</b>
858 * (case-insensitive), or if <b>router's</b> identity key digest
859 * matches a hexadecimal value stored in <b>nickname</b>. Return
860 * false otherwise. */
861 static int
862 router_nickname_matches(routerinfo_t *router, const char *nickname)
864 if (nickname[0]!='$' && !strcasecmp(router->nickname, nickname))
865 return 1;
866 return router_hex_digest_matches(router, nickname);
869 /** Return the router in our routerlist whose (case-insensitive)
870 * nickname or (case-sensitive) hexadecimal key digest is
871 * <b>nickname</b>. Return NULL if no such router is known.
873 routerinfo_t *
874 router_get_by_nickname(const char *nickname, int warn_if_unnamed)
876 int maybedigest;
877 char digest[DIGEST_LEN];
878 routerinfo_t *best_match=NULL;
879 int n_matches = 0;
881 tor_assert(nickname);
882 if (!routerlist)
883 return NULL;
884 if (nickname[0] == '$')
885 return router_get_by_hexdigest(nickname);
886 if (server_mode(get_options()) &&
887 !strcasecmp(nickname, get_options()->Nickname))
888 return router_get_my_routerinfo();
890 maybedigest = (strlen(nickname) == HEX_DIGEST_LEN) &&
891 (base16_decode(digest,DIGEST_LEN,nickname,HEX_DIGEST_LEN) == 0);
893 SMARTLIST_FOREACH(routerlist->routers, routerinfo_t *, router,
895 if (!strcasecmp(router->nickname, nickname)) {
896 if (router->is_named)
897 return router;
898 else {
899 ++n_matches;
900 best_match = router;
902 } else if (maybedigest &&
903 !memcmp(digest, router->identity_digest, DIGEST_LEN)) {
904 return router;
908 if (best_match) {
909 if (warn_if_unnamed && n_matches > 1) {
910 smartlist_t *fps = smartlist_create();
911 int any_unwarned = 0;
912 SMARTLIST_FOREACH(routerlist->routers, routerinfo_t *, router,
914 local_routerstatus_t *rs;
915 char *desc;
916 size_t dlen;
917 char fp[HEX_DIGEST_LEN+1];
918 if (strcasecmp(router->nickname, nickname))
919 continue;
920 rs=router_get_combined_status_by_digest(router->identity_digest);
921 if (!rs->name_lookup_warned) {
922 rs->name_lookup_warned = 1;
923 any_unwarned = 1;
925 base16_encode(fp, sizeof(fp), router->identity_digest, DIGEST_LEN);
926 dlen = 32 + HEX_DIGEST_LEN + strlen(router->address);
927 desc = tor_malloc(dlen);
928 tor_snprintf(desc, dlen, "\"$%s\" for the one at %s:%d",
929 fp, router->address, router->or_port);
930 smartlist_add(fps, desc);
932 if (any_unwarned) {
933 char *alternatives = smartlist_join_strings(fps, "; ",0,NULL);
934 warn(LD_CONFIG, "There are multiple matches for the nickname \"%s\","
935 " but none is listed as named by the directory authories. "
936 "Choosing one arbitrarily. If you meant one in particular, "
937 "you should say %s.", nickname, alternatives);
938 tor_free(alternatives);
940 SMARTLIST_FOREACH(fps, char *, cp, tor_free(cp));
941 smartlist_free(fps);
942 } else if (warn_if_unnamed) {
943 local_routerstatus_t *rs =
944 router_get_combined_status_by_digest(best_match->identity_digest);
945 if (rs && !rs->name_lookup_warned) {
946 char fp[HEX_DIGEST_LEN+1];
947 base16_encode(fp, sizeof(fp), best_match->identity_digest, DIGEST_LEN);
948 warn(LD_CONFIG, "You specified a server \"%s\" by name, but the "
949 "directory authorities do not have a listing for this name. "
950 "To make sure you get the same server in the future, refer to "
951 "it by key, as \"$%s\".", nickname, fp);
952 rs->name_lookup_warned = 1;
955 return best_match;
958 return NULL;
961 /** Return true iff <b>digest</b> is the digest of the identity key of
962 * a trusted directory. */
964 router_digest_is_trusted_dir(const char *digest)
966 if (!trusted_dir_servers)
967 return 0;
968 SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, ent,
969 if (!memcmp(digest, ent->digest, DIGEST_LEN)) return 1);
970 return 0;
973 /** Return the router in our routerlist whose hexadecimal key digest
974 * is <b>hexdigest</b>. Return NULL if no such router is known. */
975 routerinfo_t *
976 router_get_by_hexdigest(const char *hexdigest)
978 char digest[DIGEST_LEN];
980 tor_assert(hexdigest);
981 if (!routerlist)
982 return NULL;
983 if (hexdigest[0]=='$')
984 ++hexdigest;
985 if (strlen(hexdigest) != HEX_DIGEST_LEN ||
986 base16_decode(digest,DIGEST_LEN,hexdigest,HEX_DIGEST_LEN) < 0)
987 return NULL;
989 return router_get_by_digest(digest);
992 /** Return the router in our routerlist whose 20-byte key digest
993 * is <b>digest</b>. Return NULL if no such router is known. */
994 routerinfo_t *
995 router_get_by_digest(const char *digest)
997 tor_assert(digest);
999 if (!routerlist) return NULL;
1001 // routerlist_assert_ok(routerlist);
1003 return digestmap_get(routerlist->identity_map, digest);
1006 /** Return the router in our routerlist whose 20-byte descriptor
1007 * is <b>digest</b>. Return NULL if no such router is known. */
1008 routerinfo_t *
1009 router_get_by_descriptor_digest(const char *digest)
1011 tor_assert(digest);
1013 if (!routerlist) return NULL;
1015 SMARTLIST_FOREACH(routerlist->routers, routerinfo_t*, router,
1017 if (0 == memcmp(router->signed_descriptor_digest, digest, DIGEST_LEN))
1018 return router;
1021 return NULL;
1024 /** Return the current list of all known routers. */
1025 routerlist_t *
1026 router_get_routerlist(void)
1028 if (!routerlist) {
1029 routerlist = tor_malloc_zero(sizeof(routerlist_t));
1030 routerlist->routers = smartlist_create();
1031 routerlist->identity_map = digestmap_new();
1033 return routerlist;
1036 /** Free all storage held by <b>router</b>. */
1037 void
1038 routerinfo_free(routerinfo_t *router)
1040 if (!router)
1041 return;
1043 tor_free(router->signed_descriptor);
1044 tor_free(router->address);
1045 tor_free(router->nickname);
1046 tor_free(router->platform);
1047 tor_free(router->contact_info);
1048 if (router->onion_pkey)
1049 crypto_free_pk_env(router->onion_pkey);
1050 if (router->identity_pkey)
1051 crypto_free_pk_env(router->identity_pkey);
1052 if (router->declared_family) {
1053 SMARTLIST_FOREACH(router->declared_family, char *, s, tor_free(s));
1054 smartlist_free(router->declared_family);
1056 addr_policy_free(router->exit_policy);
1057 tor_free(router);
1060 /** Allocate a fresh copy of <b>router</b> */
1061 routerinfo_t *
1062 routerinfo_copy(const routerinfo_t *router)
1064 routerinfo_t *r;
1065 addr_policy_t **e, *tmp;
1067 r = tor_malloc(sizeof(routerinfo_t));
1068 memcpy(r, router, sizeof(routerinfo_t));
1070 r->address = tor_strdup(r->address);
1071 r->nickname = tor_strdup(r->nickname);
1072 r->platform = tor_strdup(r->platform);
1073 if (r->signed_descriptor)
1074 r->signed_descriptor = tor_strdup(r->signed_descriptor);
1075 if (r->onion_pkey)
1076 r->onion_pkey = crypto_pk_dup_key(r->onion_pkey);
1077 if (r->identity_pkey)
1078 r->identity_pkey = crypto_pk_dup_key(r->identity_pkey);
1079 e = &r->exit_policy;
1080 while (*e) {
1081 tmp = tor_malloc(sizeof(addr_policy_t));
1082 memcpy(tmp,*e,sizeof(addr_policy_t));
1083 *e = tmp;
1084 (*e)->string = tor_strdup((*e)->string);
1085 e = & ((*e)->next);
1087 if (r->declared_family) {
1088 r->declared_family = smartlist_create();
1089 SMARTLIST_FOREACH(router->declared_family, const char *, s,
1090 smartlist_add(r->declared_family, tor_strdup(s)));
1092 return r;
1095 /** Free all storage held by a routerlist <b>rl</b> */
1096 void
1097 routerlist_free(routerlist_t *rl)
1099 tor_assert(rl);
1100 digestmap_free(rl->identity_map, NULL);
1101 SMARTLIST_FOREACH(rl->routers, routerinfo_t *, r,
1102 routerinfo_free(r));
1103 smartlist_free(rl->routers);
1104 tor_free(rl);
1107 /** Insert an item <b>ri</b> into the routerlist <b>rl</b>, updating indices
1108 * as needed. */
1109 static void
1110 routerlist_insert(routerlist_t *rl, routerinfo_t *ri)
1112 digestmap_set(rl->identity_map, ri->identity_digest, ri);
1113 smartlist_add(rl->routers, ri);
1114 // routerlist_assert_ok(rl);
1117 /** Remove an item <b>ri</b> into the routerlist <b>rl</b>, updating indices
1118 * as needed. If <b>idx</b> is nonnegative and smartlist_get(rl-&gt;routers,
1119 * idx) == ri, we don't need to do a linear search over the list to decide
1120 * which to remove. We fill the gap rl-&gt;routers with a later element in
1121 * the list, if any exists. ri_old is not freed.*/
1122 void
1123 routerlist_remove(routerlist_t *rl, routerinfo_t *ri, int idx)
1125 routerinfo_t *ri_tmp;
1126 if (idx < 0 || smartlist_get(rl->routers, idx) != ri) {
1127 idx = -1;
1128 SMARTLIST_FOREACH(rl->routers, routerinfo_t *, r,
1129 if (r == ri) {
1130 idx = r_sl_idx;
1131 break;
1133 if (idx < 0)
1134 return;
1136 smartlist_del(rl->routers, idx);
1137 ri_tmp = digestmap_remove(rl->identity_map, ri->identity_digest);
1138 tor_assert(ri_tmp == ri);
1139 // routerlist_assert_ok(rl);
1142 /** Remove <b>ri_old</b> from the routerlist <b>rl</b>, and replace it with
1143 * <b>ri_new</b>, updating all index info. If <b>idx</b> is nonnegative and
1144 * smartlist_get(rl-&gt;routers, idx) == ri, we don't need to do a linear
1145 * search over the list to decide which to remove. We put ri_new in the same
1146 * index as ri_old, if possible. ri_old is not freed.*/
1147 static void
1148 routerlist_replace(routerlist_t *rl, routerinfo_t *ri_old,
1149 routerinfo_t *ri_new, int idx)
1151 if (idx < 0 || smartlist_get(rl->routers, idx) != ri_old) {
1152 idx = -1;
1153 SMARTLIST_FOREACH(rl->routers, routerinfo_t *, r,
1154 if (r == ri_old) {
1155 idx = r_sl_idx;
1156 break;
1159 if (idx >= 0) {
1160 smartlist_set(rl->routers, idx, ri_new);
1161 } else {
1162 smartlist_add(rl->routers, ri_new);
1164 if (memcmp(ri_old->identity_digest, ri_new->identity_digest, DIGEST_LEN)) {
1165 /* digests don't match; digestmap_set won't replace */
1166 digestmap_remove(rl->identity_map, ri_old->identity_digest);
1168 digestmap_set(rl->identity_map, ri_new->identity_digest, ri_new);
1171 /** Free all memory held by the rouerlist module */
1172 void
1173 routerlist_free_all(void)
1175 if (routerlist)
1176 routerlist_free(routerlist);
1177 routerlist = NULL;
1178 if (warned_nicknames) {
1179 SMARTLIST_FOREACH(warned_nicknames, char *, cp, tor_free(cp));
1180 smartlist_free(warned_nicknames);
1181 warned_nicknames = NULL;
1183 if (warned_conflicts) {
1184 SMARTLIST_FOREACH(warned_conflicts, char *, cp, tor_free(cp));
1185 smartlist_free(warned_conflicts);
1186 warned_conflicts = NULL;
1188 if (trusted_dir_servers) {
1189 SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, ds,
1190 trusted_dir_server_free(ds));
1191 smartlist_free(trusted_dir_servers);
1192 trusted_dir_servers = NULL;
1194 if (networkstatus_list) {
1195 SMARTLIST_FOREACH(networkstatus_list, networkstatus_t *, ns,
1196 networkstatus_free(ns));
1197 smartlist_free(networkstatus_list);
1198 networkstatus_list = NULL;
1200 if (routerstatus_list) {
1201 SMARTLIST_FOREACH(routerstatus_list, local_routerstatus_t *, rs,
1202 local_routerstatus_free(rs));
1203 smartlist_free(routerstatus_list);
1204 routerstatus_list = NULL;
1208 /** Free all storage held by the routerstatus object <b>rs</b>. */
1209 void
1210 routerstatus_free(routerstatus_t *rs)
1212 tor_free(rs);
1215 /** Free all storage held by the local_routerstatus object <b>rs</b>. */
1216 static void
1217 local_routerstatus_free(local_routerstatus_t *rs)
1219 tor_free(rs);
1222 /** Free all storage held by the networkstatus object <b>ns</b>. */
1223 void
1224 networkstatus_free(networkstatus_t *ns)
1226 tor_free(ns->source_address);
1227 tor_free(ns->contact);
1228 if (ns->signing_key)
1229 crypto_free_pk_env(ns->signing_key);
1230 tor_free(ns->client_versions);
1231 tor_free(ns->server_versions);
1232 if (ns->entries) {
1233 SMARTLIST_FOREACH(ns->entries, routerstatus_t *, rs, routerstatus_free(rs));
1234 smartlist_free(ns->entries);
1236 tor_free(ns);
1239 /** Forget that we have issued any router-related warnings, so that we'll
1240 * warn again if we see the same errors. */
1241 void
1242 routerlist_reset_warnings(void)
1244 if (!warned_nicknames)
1245 warned_nicknames = smartlist_create();
1246 SMARTLIST_FOREACH(warned_nicknames, char *, cp, tor_free(cp));
1247 smartlist_clear(warned_nicknames); /* now the list is empty. */
1249 if (!warned_conflicts)
1250 warned_conflicts = smartlist_create();
1251 SMARTLIST_FOREACH(warned_conflicts, char *, cp, tor_free(cp));
1252 smartlist_clear(warned_conflicts); /* now the list is empty. */
1254 SMARTLIST_FOREACH(routerstatus_list, local_routerstatus_t *, rs,
1255 rs->name_lookup_warned = 0);
1257 have_warned_about_unverified_status = 0;
1258 have_warned_about_old_version = 0;
1259 have_warned_about_new_version = 0;
1262 /** Mark the router with ID <b>digest</b> as non-running in our routerlist. */
1263 void
1264 router_mark_as_down(const char *digest)
1266 routerinfo_t *router;
1267 tor_assert(digest);
1269 SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, d,
1270 if (!memcmp(d->digest, digest, DIGEST_LEN))
1271 d->is_running = 0);
1273 router = router_get_by_digest(digest);
1274 if (!router) /* we don't seem to know about him in the first place */
1275 return;
1276 debug(LD_DIR,"Marking router '%s' as down.",router->nickname);
1277 if (router_is_me(router) && !we_are_hibernating())
1278 warn(LD_NET, "We just marked ourself as down. Are your external addresses reachable?");
1279 router->is_running = 0;
1282 /** Add <b>router</b> to the routerlist, if we don't already have it. Replace
1283 * older entries (if any) with the same key. Note: Callers should not hold
1284 * their pointers to <b>router</b> if this function fails; <b>router</b>
1285 * will either be inserted into the routerlist or freed.
1287 * Returns >= 0 if the router was added; less than 0 if it was not.
1289 * If we're returning non-zero, then assign to *<b>msg</b> a static string
1290 * describing the reason for not liking the routerinfo.
1292 * If the return value is less than -1, there was a problem with the
1293 * routerinfo. If the return value is equal to -1, then the routerinfo was
1294 * fine, but out-of-date. If the return value is equal to 1, the
1295 * routerinfo was accepted, but we should notify the generator of the
1296 * descriptor using the message *<b>msg</b>.
1298 * This function should be called *after*
1299 * routers_update_status_from_networkstatus; subsequenctly, you should call
1300 * router_rebuild_store and control_event_descriptors_changed.
1302 * XXXX never replace your own descriptor.
1305 router_add_to_routerlist(routerinfo_t *router, const char **msg,
1306 int from_cache)
1308 int i;
1309 char id_digest[DIGEST_LEN];
1310 int authdir = get_options()->AuthoritativeDir;
1311 int authdir_verified = 0;
1313 tor_assert(msg);
1315 if (!routerlist)
1316 router_get_routerlist();
1318 crypto_pk_get_digest(router->identity_pkey, id_digest);
1320 if (authdir) {
1321 if (authdir_wants_to_reject_router(router, msg))
1322 return -2;
1323 authdir_verified = router->is_verified;
1325 } else {
1326 if (! router->xx_is_recognized) {
1327 log_fn(LOG_WARN, "Dropping unrecognized descriptor for router '%s'",
1328 router->nickname);
1329 return -1;
1334 /* If we have a router with this name, and the identity key is the same,
1335 * choose the newer one. If the identity key has changed, drop the router.
1337 for (i = 0; i < smartlist_len(routerlist->routers); ++i) {
1338 routerinfo_t *old_router = smartlist_get(routerlist->routers, i);
1339 if (!crypto_pk_cmp_keys(router->identity_pkey,old_router->identity_pkey)) {
1340 if (router->published_on <= old_router->published_on) {
1341 /* Same key, but old */
1342 debug(LD_DIR, "Skipping not-new descriptor for router '%s'",
1343 router->nickname);
1344 routerinfo_free(router);
1345 *msg = "Router descriptor was not new.";
1346 return -1;
1347 } else {
1348 /* Same key, new. */
1349 int unreachable = 0;
1350 debug(LD_DIR, "Replacing entry for router '%s/%s' [%s]",
1351 router->nickname, old_router->nickname,
1352 hex_str(id_digest,DIGEST_LEN));
1353 if (router->addr == old_router->addr &&
1354 router->or_port == old_router->or_port) {
1355 /* these carry over when the address and orport are unchanged.*/
1356 router->last_reachable = old_router->last_reachable;
1357 router->testing_since = old_router->testing_since;
1358 router->num_unreachable_notifications =
1359 old_router->num_unreachable_notifications;
1361 if (authdir &&
1362 dirserv_thinks_router_is_blatantly_unreachable(router, time(NULL))) {
1363 if (router->num_unreachable_notifications >= 3) {
1364 unreachable = 1;
1365 notice(LD_DIR, "Notifying server '%s' that it's unreachable. (ContactInfo '%s', platform '%s').",
1366 router->nickname, router->contact_info ? router->contact_info : "",
1367 router->platform ? router->platform : "");
1368 } else {
1369 info(LD_DIR,"'%s' may be unreachable -- the %d previous descriptors were thought to be unreachable.", router->nickname, router->num_unreachable_notifications);
1370 router->num_unreachable_notifications++;
1373 routerlist_replace(routerlist, old_router, router, i);
1374 routerinfo_free(old_router);
1375 if (!from_cache)
1376 router_append_to_journal(router->signed_descriptor,
1377 router->signed_descriptor_len);
1378 directory_set_dirty();
1379 *msg = unreachable ? "Dirserver believes your ORPort is unreachable" :
1380 authdir_verified ? "Verified server updated" :
1381 "Unverified server updated. (Have you sent us your key fingerprint?)";
1382 return unreachable ? 1 : 0;
1384 } else if (!strcasecmp(router->nickname, old_router->nickname)) {
1385 /* nicknames match, keys don't. */
1386 if (router->is_named) {
1387 /* The new verified router replaces the old one; remove the
1388 * old one. And carry on to the end of the list, in case
1389 * there are more old unverified routers with this nickname
1391 /* mark-for-close connections using the old key, so we can
1392 * make new ones with the new key.
1394 connection_t *conn;
1395 while ((conn = connection_get_by_identity_digest(
1396 old_router->identity_digest, CONN_TYPE_OR))) {
1397 // And LD_OR? XXXXNM
1398 info(LD_DIR,"Closing conn to router '%s'; there is now a named router with that name.",
1399 old_router->nickname);
1400 connection_mark_for_close(conn);
1402 routerlist_remove(routerlist, old_router, i--);
1403 routerinfo_free(old_router);
1404 } else if (old_router->is_named) {
1405 /* Can't replace a verified router with an unverified one. */
1406 debug(LD_DIR, "Skipping unverified entry for verified router '%s'",
1407 router->nickname);
1408 routerinfo_free(router);
1409 *msg = "Already have named router with same nickname and different key.";
1410 return -2;
1414 /* We haven't seen a router with this name before. Add it to the end of
1415 * the list. */
1416 routerlist_insert(routerlist, router);
1417 if (!from_cache)
1418 router_append_to_journal(router->signed_descriptor,
1419 router->signed_descriptor_len);
1420 directory_set_dirty();
1421 return 0;
1424 /** Remove any routers from the routerlist that are more than <b>age</b>
1425 * seconds old.
1427 void
1428 routerlist_remove_old_routers(int age)
1430 int i;
1431 time_t cutoff;
1432 routerinfo_t *router;
1433 if (!routerlist)
1434 return;
1436 cutoff = time(NULL) - age;
1437 for (i = 0; i < smartlist_len(routerlist->routers); ++i) {
1438 router = smartlist_get(routerlist->routers, i);
1439 if (router->published_on <= cutoff) {
1440 /* Too old. Remove it. */
1441 info(LD_DIR,"Forgetting obsolete (too old) routerinfo for router '%s'", router->nickname);
1442 routerlist_remove(routerlist, router, i--);
1443 routerinfo_free(router);
1449 * Code to parse a single router descriptor and insert it into the
1450 * routerlist. Return -1 if the descriptor was ill-formed; 0 if the
1451 * descriptor was well-formed but could not be added; and 1 if the
1452 * descriptor was added.
1454 * If we don't add it and <b>msg</b> is not NULL, then assign to
1455 * *<b>msg</b> a static string describing the reason for refusing the
1456 * descriptor.
1458 * This is used only by the controller.
1461 router_load_single_router(const char *s, const char **msg)
1463 routerinfo_t *ri;
1464 smartlist_t *lst;
1465 tor_assert(msg);
1466 *msg = NULL;
1468 if (!(ri = router_parse_entry_from_string(s, NULL))) {
1469 warn(LD_DIR, "Error parsing router descriptor; dropping.");
1470 *msg = "Couldn't parse router descriptor.";
1471 return -1;
1473 if (router_is_me(ri)) {
1474 warn(LD_DIR, "Router's identity key matches mine; dropping.");
1475 *msg = "Router's identity key matches mine.";
1476 routerinfo_free(ri);
1477 return 0;
1480 lst = smartlist_create();
1481 smartlist_add(lst, ri);
1482 routers_update_status_from_networkstatus(lst, 0, 1);
1484 if (router_add_to_routerlist(ri, msg, 0)<0) {
1485 warn(LD_DIR, "Couldn't add router to list: %s Dropping.",
1486 *msg?*msg:"(No message).");
1487 /* we've already assigned to *msg now, and ri is already freed */
1488 smartlist_free(lst);
1489 return 0;
1490 } else {
1491 control_event_descriptors_changed(lst);
1492 smartlist_free(lst);
1493 debug(LD_DIR, "Added router to list");
1494 return 1;
1498 /** Given a string <b>s</b> containing some routerdescs, parse it and put the
1499 * routers into our directory. If <b>from_cache</b> is false, the routers
1500 * have come from the network: cache them.
1502 * If <b>requested_fingerprints</b> is provided, it must contain a list of
1503 * uppercased identity fingerprints. Do not update any router whose
1504 * fingerprint is not on the list; after updating a router, remove its
1505 * fingerprint from the list.
1507 void
1508 router_load_routers_from_string(const char *s, int from_cache,
1509 smartlist_t *requested_fingerprints)
1511 smartlist_t *routers = smartlist_create(), *changed = smartlist_create();
1512 char fp[HEX_DIGEST_LEN+1];
1513 const char *msg;
1515 router_parse_list_from_string(&s, routers);
1517 routers_update_status_from_networkstatus(routers, !from_cache, from_cache);
1519 SMARTLIST_FOREACH(routers, routerinfo_t *, ri,
1521 base16_encode(fp, sizeof(fp), ri->identity_digest, DIGEST_LEN);
1522 if (requested_fingerprints) {
1523 if (smartlist_string_isin(requested_fingerprints, fp)) {
1524 smartlist_string_remove(requested_fingerprints, fp);
1525 } else {
1526 char *requested =
1527 smartlist_join_strings(requested_fingerprints," ",0,NULL);
1528 warn(LD_DIR, "We received a router descriptor with a fingerprint (%s) that we never requested. (We asked for: %s.) Dropping.", fp, requested);
1529 tor_free(requested);
1530 routerinfo_free(ri);
1531 continue;
1535 if (router_add_to_routerlist(ri, &msg, from_cache) >= 0)
1536 smartlist_add(changed, ri);
1539 if (smartlist_len(changed))
1540 control_event_descriptors_changed(changed);
1542 routerlist_assert_ok(routerlist);
1543 router_rebuild_store(0);
1545 smartlist_free(routers);
1546 smartlist_free(changed);
1549 /** Helper: return a newly allocated string containing the name of the filename
1550 * where we plan to cache <b>ns</b>. */
1551 static char *
1552 networkstatus_get_cache_filename(const networkstatus_t *ns)
1554 const char *datadir = get_options()->DataDirectory;
1555 size_t len = strlen(datadir)+64;
1556 char fp[HEX_DIGEST_LEN+1];
1557 char *fn = tor_malloc(len+1);
1558 base16_encode(fp, HEX_DIGEST_LEN+1, ns->identity_digest, DIGEST_LEN);
1559 tor_snprintf(fn, len, "%s/cached-status/%s",datadir,fp);
1560 return fn;
1563 /** Helper for smartlist_sort: Compare two networkstatus objects by
1564 * publication date. */
1565 static int
1566 _compare_networkstatus_published_on(const void **_a, const void **_b)
1568 const networkstatus_t *a = *_a, *b = *_b;
1569 if (a->published_on < b->published_on)
1570 return -1;
1571 else if (a->published_on > b->published_on)
1572 return 1;
1573 else
1574 return 0;
1577 /** How far in the future do we allow a network-status to get before removing
1578 * it? (seconds) */
1579 #define NETWORKSTATUS_ALLOW_SKEW (48*60*60)
1580 /** Given a string <b>s</b> containing a network status that we received at
1581 * <b>arrived_at</b> from <b>source</b>, try to parse it, see if we want to
1582 * store it, and put it into our cache is necessary.
1584 * If <b>source</b> is NS_FROM_DIR or NS_FROM_CACHE, do not replace our
1585 * own networkstatus_t (if we're a directory server).
1587 * If <b>source</b> is NS_FROM_CACHE, do not write our networkstatus_t to the
1588 * cache.
1590 * If <b>requested_fingerprints</b> is provided, it must contain a list of
1591 * uppercased identity fingerprints. Do not update any networkstatus whose
1592 * fingerprint is not on the list; after updating a networkstatus, remove its
1593 * fingerprint from the list.
1595 * Return 0 on success, -1 on failure.
1597 * Callers should make sure that routers_update_all_from_networkstatus() is
1598 * invoked after this function succeeds.
1601 router_set_networkstatus(const char *s, time_t arrived_at,
1602 networkstatus_source_t source, smartlist_t *requested_fingerprints)
1604 networkstatus_t *ns;
1605 int i, found;
1606 time_t now;
1607 int skewed = 0;
1608 trusted_dir_server_t *trusted_dir;
1609 char fp[HEX_DIGEST_LEN+1];
1610 char published[ISO_TIME_LEN+1];
1612 ns = networkstatus_parse_from_string(s);
1613 if (!ns) {
1614 warn(LD_DIR, "Couldn't parse network status.");
1615 return -1;
1617 if (!(trusted_dir=router_get_trusteddirserver_by_digest(ns->identity_digest))) {
1618 info(LD_DIR, "Network status was signed, but not by an authoritative directory we recognize.");
1619 networkstatus_free(ns);
1620 return -1;
1622 now = time(NULL);
1623 if (arrived_at > now)
1624 arrived_at = now;
1626 ns->received_on = arrived_at;
1628 format_iso_time(published, ns->published_on);
1630 if (ns->published_on > now + NETWORKSTATUS_ALLOW_SKEW) {
1631 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);
1632 skewed = 1;
1635 if (!networkstatus_list)
1636 networkstatus_list = smartlist_create();
1638 if (source == NS_FROM_DIR && router_digest_is_me(ns->identity_digest)) {
1639 /* Don't replace our own networkstatus when we get it from somebody else. */
1640 networkstatus_free(ns);
1641 return 0;
1644 base16_encode(fp, HEX_DIGEST_LEN+1, ns->identity_digest, DIGEST_LEN);
1646 if (requested_fingerprints) {
1647 if (smartlist_string_isin(requested_fingerprints, fp)) {
1648 smartlist_string_remove(requested_fingerprints, fp);
1649 } else {
1650 char *requested = smartlist_join_strings(requested_fingerprints," ",0,NULL);
1651 warn(LD_DIR, "We received a network status with a fingerprint (%s) that we never requested. (We asked for: %s.) Dropping.", fp, requested);
1652 tor_free(requested);
1653 return 0;
1657 if (source != NS_FROM_CACHE)
1658 trusted_dir->n_networkstatus_failures = 0;
1660 found = 0;
1661 for (i=0; i < smartlist_len(networkstatus_list); ++i) {
1662 networkstatus_t *old_ns = smartlist_get(networkstatus_list, i);
1664 if (!memcmp(old_ns->identity_digest, ns->identity_digest, DIGEST_LEN)) {
1665 if (!memcmp(old_ns->networkstatus_digest,
1666 ns->networkstatus_digest, DIGEST_LEN)) {
1667 /* Same one we had before. */
1668 networkstatus_free(ns);
1669 info(LD_DIR,
1670 "Not replacing network-status from %s (published %s); "
1671 "we already have it.",
1672 trusted_dir->description, published);
1673 if (old_ns->received_on < arrived_at) {
1674 if (source != NS_FROM_CACHE) {
1675 char *fn = networkstatus_get_cache_filename(old_ns);
1676 /* We use mtime to tell when it arrived, so update that. */
1677 touch_file(fn);
1678 tor_free(fn);
1680 old_ns->received_on = arrived_at;
1682 return 0;
1683 } else if (old_ns->published_on >= ns->published_on) {
1684 char old_published[ISO_TIME_LEN+1];
1685 format_iso_time(old_published, old_ns->published_on);
1686 info(LD_DIR,
1687 "Not replacing network-status from %s (published %s);"
1688 " we have a newer one (published %s) for this authority.",
1689 trusted_dir->description, published,
1690 old_published);
1691 networkstatus_free(ns);
1692 return 0;
1693 } else {
1694 networkstatus_free(old_ns);
1695 smartlist_set(networkstatus_list, i, ns);
1696 found = 1;
1697 break;
1702 if (!found)
1703 smartlist_add(networkstatus_list, ns);
1705 info(LD_DIR, "Setting networkstatus %s %s (published %s)",
1706 source == NS_FROM_CACHE?"cached from":
1707 (source==NS_FROM_DIR?"downloaded from":"generated for"),
1708 trusted_dir->description, published);
1709 networkstatus_list_has_changed = 1;
1711 smartlist_sort(networkstatus_list, _compare_networkstatus_published_on);
1713 if (source != NS_FROM_CACHE && !skewed) {
1714 char *fn = networkstatus_get_cache_filename(ns);
1715 if (write_str_to_file(fn, s, 0)<0) {
1716 notice(LD_FS, "Couldn't write cached network status to \"%s\"", fn);
1718 tor_free(fn);
1721 networkstatus_list_update_recent(now);
1723 if (get_options()->DirPort && !skewed)
1724 dirserv_set_cached_networkstatus_v2(s,
1725 ns->identity_digest,
1726 ns->published_on);
1728 return 0;
1731 /** How old do we allow a network-status to get before removing it completely? */
1732 #define MAX_NETWORKSTATUS_AGE (10*24*60*60)
1733 /** Remove all very-old network_status_t objects from memory and from the
1734 * disk cache. */
1735 void
1736 networkstatus_list_clean(time_t now)
1738 int i;
1739 if (!networkstatus_list)
1740 return;
1742 for (i = 0; i < smartlist_len(networkstatus_list); ++i) {
1743 networkstatus_t *ns = smartlist_get(networkstatus_list, i);
1744 char *fname = NULL;;
1745 if (ns->published_on + MAX_NETWORKSTATUS_AGE > now)
1746 continue;
1747 /* Okay, this one is too old. Remove it from the list, and delete it
1748 * from the cache. */
1749 smartlist_del(networkstatus_list, i--);
1750 fname = networkstatus_get_cache_filename(ns);
1751 if (file_status(fname) == FN_FILE) {
1752 info(LD_DIR, "Removing too-old networkstatus in %s", fname);
1753 unlink(fname);
1755 tor_free(fname);
1756 if (get_options()->DirPort) {
1757 dirserv_set_cached_networkstatus_v2(NULL, ns->identity_digest, 0);
1759 networkstatus_free(ns);
1763 /** Helper for bsearching a list of routerstatus_t pointers.*/
1764 static int
1765 _compare_digest_to_routerstatus_entry(const void *_key, const void **_member)
1767 const char *key = _key;
1768 const routerstatus_t *rs = *_member;
1769 return memcmp(key, rs->identity_digest, DIGEST_LEN);
1772 /** Return the entry in <b>ns</b> for the identity digest <b>digest</b>, or
1773 * NULL if none was found. */
1774 static routerstatus_t *
1775 networkstatus_find_entry(networkstatus_t *ns, const char *digest)
1777 return smartlist_bsearch(ns->entries, digest,
1778 _compare_digest_to_routerstatus_entry);
1781 /** Return the consensus view of the status of the router whose digest is
1782 * <b>digest</b>, or NULL if we don't know about any such router. */
1783 local_routerstatus_t *
1784 router_get_combined_status_by_digest(const char *digest)
1786 if (!routerstatus_list)
1787 return NULL;
1788 return smartlist_bsearch(routerstatus_list, digest,
1789 _compare_digest_to_routerstatus_entry);
1792 /** DOCDOC */
1793 static int
1794 routerdesc_digest_is_recognized(const char *identity, const char *digest)
1796 routerstatus_t *rs;
1797 if (!networkstatus_list)
1798 return 0;
1800 SMARTLIST_FOREACH(networkstatus_list, networkstatus_t *, ns,
1802 if (!(rs = networkstatus_find_entry(ns, identity)))
1803 continue;
1804 if (!memcmp(rs->descriptor_digest, digest, DIGEST_LEN))
1805 return 1;
1807 return 0;
1810 /* XXXX These should be configurable, perhaps? NM */
1811 #define AUTHORITY_NS_CACHE_INTERVAL 10*60
1812 #define NONAUTHORITY_NS_CACHE_INTERVAL 15*60
1813 /** We are a directory server, and so cache network_status documents.
1814 * Initiate downloads as needed to update them. For authorities, this means
1815 * asking each trusted directory for its network-status. For caches, this
1816 * means asking a random authority for all network-statuses.
1818 static void
1819 update_networkstatus_cache_downloads(time_t now)
1821 int authority = authdir_mode(get_options());
1822 int interval =
1823 authority ? AUTHORITY_NS_CACHE_INTERVAL : NONAUTHORITY_NS_CACHE_INTERVAL;
1825 if (last_networkstatus_download_attempted + interval >= now)
1826 return;
1827 if (!trusted_dir_servers)
1828 return;
1830 last_networkstatus_download_attempted = now;
1832 if (authority) {
1833 /* An authority launches a separate connection for everybody. */
1834 SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, ds,
1836 char resource[HEX_DIGEST_LEN+6];
1837 if (router_digest_is_me(ds->digest))
1838 continue;
1839 if (connection_get_by_type_addr_port_purpose(
1840 CONN_TYPE_DIR, ds->addr, ds->dir_port,
1841 DIR_PURPOSE_FETCH_NETWORKSTATUS)) {
1842 /* We are already fetching this one. */
1843 continue;
1845 strlcpy(resource, "fp/", sizeof(resource));
1846 base16_encode(resource+3, sizeof(resource)-3, ds->digest, DIGEST_LEN);
1847 strlcat(resource, ".z", sizeof(resource));
1848 directory_get_from_dirserver(DIR_PURPOSE_FETCH_NETWORKSTATUS,resource,1);
1850 } else {
1851 /* A non-authority cache launches one connection to a random authority. */
1852 /* (Check whether we're currently fetching network-status objects.) */
1853 if (!connection_get_by_type_purpose(CONN_TYPE_DIR,
1854 DIR_PURPOSE_FETCH_NETWORKSTATUS))
1855 directory_get_from_dirserver(DIR_PURPOSE_FETCH_NETWORKSTATUS,"all.z",1);
1859 /*XXXX Should these be configurable? NM*/
1860 /** How old (in seconds) can a network-status be before we try replacing it? */
1861 #define NETWORKSTATUS_MAX_VALIDITY (48*60*60)
1862 /** How long (in seconds) does a client wait after getting a network status
1863 * before downloading the next in sequence? */
1864 #define NETWORKSTATUS_CLIENT_DL_INTERVAL (30*60)
1865 /* How many times do we allow a networkstatus download to fail before we
1866 * assume that the authority isn't publishing? */
1867 #define NETWORKSTATUS_N_ALLOWABLE_FAILURES 3
1868 /** We are not a directory cache or authority. Update our network-status list
1869 * by launching a new directory fetch for enough network-status documents "as
1870 * necessary". See function comments for implementation details.
1872 static void
1873 update_networkstatus_client_downloads(time_t now)
1875 int n_live = 0, needed = 0, n_running_dirservers, n_dirservers, i;
1876 int most_recent_idx = -1;
1877 trusted_dir_server_t *most_recent = NULL;
1878 time_t most_recent_received = 0;
1879 char *resource, *cp;
1880 size_t resource_len;
1882 if (connection_get_by_type_purpose(CONN_TYPE_DIR,
1883 DIR_PURPOSE_FETCH_NETWORKSTATUS))
1884 return;
1886 /* This is a little tricky. We want to download enough network-status
1887 * objects so that we have at least half of them under
1888 * NETWORKSTATUS_MAX_VALIDITY publication time. We want to download a new
1889 * *one* if the most recent one's publication time is under
1890 * NETWORKSTATUS_CLIENT_DL_INTERVAL.
1892 if (!trusted_dir_servers || !smartlist_len(trusted_dir_servers))
1893 return;
1894 n_dirservers = n_running_dirservers = smartlist_len(trusted_dir_servers);
1895 SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, ds,
1897 networkstatus_t *ns = networkstatus_get_by_digest(ds->digest);
1898 if (!ns)
1899 continue;
1900 if (ds->n_networkstatus_failures > NETWORKSTATUS_N_ALLOWABLE_FAILURES) {
1901 --n_running_dirservers;
1902 continue;
1904 if (ns->published_on > now-NETWORKSTATUS_MAX_VALIDITY)
1905 ++n_live;
1906 if (!most_recent || ns->received_on > most_recent_received) {
1907 most_recent_idx = ds_sl_idx; /* magic variable from FOREACH */
1908 most_recent = ds;
1909 most_recent_received = ns->received_on;
1913 /* Download enough so we have at least half live, but no more than all the
1914 * trusted dirservers we know.
1916 if (n_live < (n_dirservers/2)+1)
1917 needed = (n_dirservers/2)+1-n_live;
1918 if (needed > n_running_dirservers)
1919 needed = n_running_dirservers;
1921 if (needed)
1922 info(LD_DIR, "For %d/%d running directory servers, we have %d live"
1923 " network-status documents. Downloading %d.",
1924 n_running_dirservers, n_dirservers, n_live, needed);
1926 /* Also, download at least 1 every NETWORKSTATUS_CLIENT_DL_INTERVAL. */
1927 if (n_running_dirservers &&
1928 most_recent_received < now-NETWORKSTATUS_CLIENT_DL_INTERVAL && needed < 1) {
1929 info(LD_DIR, "Our most recent network-status document (from %s) "
1930 "is %d seconds old; downloading another.",
1931 most_recent?most_recent->description:"nobody",
1932 (int)(now-most_recent_received));
1933 needed = 1;
1936 if (!needed)
1937 return;
1939 /* If no networkstatus was found, choose a dirserver at random as "most
1940 * recent". */
1941 if (most_recent_idx<0)
1942 most_recent_idx = crypto_rand_int(n_dirservers);
1944 /* Build a request string for all the resources we want. */
1945 resource_len = needed * (HEX_DIGEST_LEN+1) + 6;
1946 resource = tor_malloc(resource_len);
1947 memcpy(resource, "fp/", 3);
1948 cp = resource+3;
1949 for (i = most_recent_idx+1; needed; ++i) {
1950 trusted_dir_server_t *ds;
1951 if (i >= n_dirservers)
1952 i = 0;
1953 ds = smartlist_get(trusted_dir_servers, i);
1954 if (ds->n_networkstatus_failures > NETWORKSTATUS_N_ALLOWABLE_FAILURES)
1955 continue;
1956 base16_encode(cp, HEX_DIGEST_LEN+1, ds->digest, DIGEST_LEN);
1957 cp += HEX_DIGEST_LEN;
1958 --needed;
1959 if (needed)
1960 *cp++ = '+';
1962 memcpy(cp, ".z", 3);
1963 directory_get_from_dirserver(DIR_PURPOSE_FETCH_NETWORKSTATUS, resource, 1);
1964 tor_free(resource);
1967 /*DOCDOC*/
1968 void
1969 update_networkstatus_downloads(time_t now)
1971 or_options_t *options = get_options();
1972 if (server_mode(options) && options->DirPort)
1973 update_networkstatus_cache_downloads(time(NULL));
1974 else
1975 update_networkstatus_client_downloads(time(NULL));
1978 /** Decide whether a given addr:port is definitely accepted,
1979 * definitely rejected, probably accepted, or probably rejected by a
1980 * given policy. If <b>addr</b> is 0, we don't know the IP of the
1981 * target address. If <b>port</b> is 0, we don't know the port of the
1982 * target address.
1984 * For now, the algorithm is pretty simple: we look for definite and
1985 * uncertain matches. The first definite match is what we guess; if
1986 * it was preceded by no uncertain matches of the opposite policy,
1987 * then the guess is definite; otherwise it is probable. (If we
1988 * have a known addr and port, all matches are definite; if we have an
1989 * unknown addr/port, any address/port ranges other than "all" are
1990 * uncertain.)
1992 * We could do better by assuming that some ranges never match typical
1993 * addresses (127.0.0.1, and so on). But we'll try this for now.
1995 addr_policy_result_t
1996 router_compare_addr_to_addr_policy(uint32_t addr, uint16_t port,
1997 addr_policy_t *policy)
1999 int maybe_reject = 0;
2000 int maybe_accept = 0;
2001 int match = 0;
2002 int maybe = 0;
2003 addr_policy_t *tmpe;
2005 for (tmpe=policy; tmpe; tmpe=tmpe->next) {
2006 maybe = 0;
2007 if (!addr) {
2008 /* Address is unknown. */
2009 if ((port >= tmpe->prt_min && port <= tmpe->prt_max) ||
2010 (!port && tmpe->prt_min<=1 && tmpe->prt_max>=65535)) {
2011 /* The port definitely matches. */
2012 if (tmpe->msk == 0) {
2013 match = 1;
2014 } else {
2015 maybe = 1;
2017 } else if (!port) {
2018 /* The port maybe matches. */
2019 maybe = 1;
2021 } else {
2022 /* Address is known */
2023 if ((addr & tmpe->msk) == (tmpe->addr & tmpe->msk)) {
2024 if (port >= tmpe->prt_min && port <= tmpe->prt_max) {
2025 /* Exact match for the policy */
2026 match = 1;
2027 } else if (!port) {
2028 maybe = 1;
2032 if (maybe) {
2033 if (tmpe->policy_type == ADDR_POLICY_REJECT)
2034 maybe_reject = 1;
2035 else
2036 maybe_accept = 1;
2038 if (match) {
2039 if (tmpe->policy_type == ADDR_POLICY_ACCEPT) {
2040 /* If we already hit a clause that might trigger a 'reject', than we
2041 * can't be sure of this certain 'accept'.*/
2042 return maybe_reject ? ADDR_POLICY_PROBABLY_ACCEPTED : ADDR_POLICY_ACCEPTED;
2043 } else {
2044 return maybe_accept ? ADDR_POLICY_PROBABLY_REJECTED : ADDR_POLICY_REJECTED;
2048 /* accept all by default. */
2049 return maybe_reject ? ADDR_POLICY_PROBABLY_ACCEPTED : ADDR_POLICY_ACCEPTED;
2052 /** Return 1 if all running sufficiently-stable routers will reject
2053 * addr:port, return 0 if any might accept it. */
2055 router_exit_policy_all_routers_reject(uint32_t addr, uint16_t port,
2056 int need_uptime)
2058 addr_policy_result_t r;
2059 if (!routerlist) return 1;
2061 SMARTLIST_FOREACH(routerlist->routers, routerinfo_t *, router,
2063 if (router->is_running &&
2064 !router_is_unreliable(router, need_uptime, 0)) {
2065 r = router_compare_addr_to_addr_policy(addr, port, router->exit_policy);
2066 if (r != ADDR_POLICY_REJECTED && r != ADDR_POLICY_PROBABLY_REJECTED)
2067 return 0; /* this one could be ok. good enough. */
2070 return 1; /* all will reject. */
2074 * If <b>policy</b> implicitly allows connections to any port in the
2075 * IP set <b>addr</b>/<b>mask</b>, then set *<b>policy_out</b> to the
2076 * part of the policy that allows it, and return 1. Else return 0.
2078 * A policy allows an IP:Port combination <em>implicitly</em> if
2079 * it is included in a *: pattern, or in a fallback pattern.
2081 static int
2082 policy_includes_addr_mask_implicitly(addr_policy_t *policy,
2083 uint32_t addr, uint32_t mask,
2084 addr_policy_t **policy_out)
2086 uint32_t addr2;
2087 tor_assert(policy_out);
2088 addr &= mask;
2089 addr2 = addr | ~mask;
2090 for (; policy; policy=policy->next) {
2091 /* Does this policy cover all of the address range we're looking at? */
2092 /* Boolean logic time: range X is contained in range Y if, for
2093 * each bit B, all possible values of B in X are values of B in Y.
2094 * In "addr", we have every fixed bit set to its value, and every
2095 * free bit set to 0. In "addr2", we have every fixed bit set to
2096 * its value, and every free bit set to 1. So if addr and addr2 are
2097 * both in the policy, the range is covered by the policy.
2099 uint32_t p_addr = policy->addr & policy->msk;
2100 if (p_addr == (addr & policy->msk) &&
2101 p_addr == (addr2 & policy->msk) &&
2102 (policy->prt_min <= 1 && policy->prt_max == 65535)) {
2103 return 0;
2105 /* Does this policy cover some of the address range we're looking at? */
2106 /* Boolean logic time: range X and range Y intersect if there is
2107 * some z such that z & Xmask == Xaddr and z & Ymask == Yaddr.
2108 * This is FALSE iff there is some bit b where Xmask == yMask == 1
2109 * and Xaddr != Yaddr. So if X intersects with Y iff at every
2110 * place where Xmask&Ymask==1, Xaddr == Yaddr, or equivalently,
2111 * Xaddr&Xmask&Ymask == Yaddr&Xmask&Ymask.
2113 if ((policy->addr & policy->msk & mask) == (addr & policy->msk) &&
2114 policy->policy_type == ADDR_POLICY_ACCEPT) {
2115 *policy_out = policy;
2116 return 1;
2119 *policy_out = NULL;
2120 return 1;
2123 /** If <b>policy</b> implicitly allows connections to any port on
2124 * 127.*, 192.168.*, etc, then warn (if <b>warn</b> is set) and return
2125 * true. Else return false.
2128 exit_policy_implicitly_allows_local_networks(addr_policy_t *policy,
2129 int warn)
2131 addr_policy_t *p;
2132 int r=0,i;
2133 static struct {
2134 uint32_t addr; uint32_t mask; const char *network;
2135 } private_networks[] = {
2136 { 0x7f000000, 0xff000000, "localhost (127.0.0.0/8)" },
2137 { 0x0a000000, 0xff000000, "addresses in private network 10.0.0.0/8" },
2138 { 0xa9fe0000, 0xffff0000, "addresses in private network 169.254.0.0/16" },
2139 { 0xac100000, 0xfff00000, "addresses in private network 172.16.0.0/12" },
2140 { 0xc0a80000, 0xffff0000, "addresses in private network 192.168.0.0/16" },
2141 { 0,0,NULL},
2143 for (i=0; private_networks[i].addr; ++i) {
2144 p = NULL;
2145 /* log_fn(LOG_INFO,"Checking network %s", private_networks[i].network); */
2146 if (policy_includes_addr_mask_implicitly(
2147 policy, private_networks[i].addr, private_networks[i].mask, &p)) {
2148 if (warn)
2149 warn(LD_CONFIG, "Exit policy %s implicitly accepts %s",
2150 p?p->string:"(default)",
2151 private_networks[i].network);
2152 r = 1;
2156 return r;
2159 /** Return true iff <b>router</b> does not permit exit streams.
2162 router_exit_policy_rejects_all(routerinfo_t *router)
2164 return router_compare_addr_to_addr_policy(0, 0, router->exit_policy)
2165 == ADDR_POLICY_REJECTED;
2168 /** Add to the list of authorized directory servers one at
2169 * <b>address</b>:<b>port</b>, with identity key <b>digest</b>. If
2170 * <b>address</b> is NULL, add ourself. */
2171 void
2172 add_trusted_dir_server(const char *nickname, const char *address,
2173 uint16_t port, const char *digest, int supports_v1)
2175 trusted_dir_server_t *ent;
2176 uint32_t a;
2177 char *hostname = NULL;
2178 size_t dlen;
2179 if (!trusted_dir_servers)
2180 trusted_dir_servers = smartlist_create();
2182 if (!address) { /* The address is us; we should guess. */
2183 if (resolve_my_address(get_options(), &a, &hostname) < 0) {
2184 warn(LD_CONFIG, "Couldn't find a suitable address when adding ourself as a trusted directory server.");
2185 return;
2187 } else {
2188 if (tor_lookup_hostname(address, &a)) {
2189 warn(LD_CONFIG, "Unable to lookup address for directory server at %s",
2190 address);
2191 return;
2193 hostname = tor_strdup(address);
2194 a = ntohl(a);
2197 ent = tor_malloc_zero(sizeof(trusted_dir_server_t));
2198 ent->nickname = nickname ? tor_strdup(nickname) : NULL;
2199 ent->address = hostname;
2200 ent->addr = a;
2201 ent->dir_port = port;
2202 ent->is_running = 1;
2203 ent->supports_v1_protocol = supports_v1;
2204 memcpy(ent->digest, digest, DIGEST_LEN);
2206 dlen = 64 + strlen(hostname) + (nickname?strlen(nickname):0);
2207 ent->description = tor_malloc(dlen);
2208 if (nickname)
2209 tor_snprintf(ent->description, dlen, "directory server \"%s\" at %s:%d",
2210 nickname, hostname, (int)port);
2211 else
2212 tor_snprintf(ent->description, dlen, "directory server at %s:%d",
2213 hostname, (int)port);
2215 smartlist_add(trusted_dir_servers, ent);
2218 /** Free storage held in <b>ds</b> */
2219 void
2220 trusted_dir_server_free(trusted_dir_server_t *ds)
2222 tor_free(ds->nickname);
2223 tor_free(ds->description);
2224 tor_free(ds->address);
2225 tor_free(ds);
2228 /** Remove all members from the list of trusted dir servers. */
2229 void
2230 clear_trusted_dir_servers(void)
2232 if (trusted_dir_servers) {
2233 SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, ent,
2234 trusted_dir_server_free(ent));
2235 smartlist_clear(trusted_dir_servers);
2236 } else {
2237 trusted_dir_servers = smartlist_create();
2241 /** Return the network status with a given identity digest. */
2242 networkstatus_t *
2243 networkstatus_get_by_digest(const char *digest)
2245 SMARTLIST_FOREACH(networkstatus_list, networkstatus_t *, ns,
2247 if (!memcmp(ns->identity_digest, digest, DIGEST_LEN))
2248 return ns;
2250 return NULL;
2253 /** If the network-status list has changed since the last time we called this
2254 * function, update the status of every router from the network-status list.
2256 void
2257 routers_update_all_from_networkstatus(void)
2259 #define SELF_OPINION_INTERVAL 90*60
2260 routerinfo_t *me;
2261 time_t now;
2262 if (!routerlist || !networkstatus_list ||
2263 (!networkstatus_list_has_changed && !routerstatus_list_has_changed))
2264 return;
2266 now = time(NULL);
2267 if (networkstatus_list_has_changed)
2268 routerstatus_list_update_from_networkstatus(now);
2270 routers_update_status_from_networkstatus(routerlist->routers, 0, 0);
2272 me = router_get_my_routerinfo();
2273 if (me && !have_warned_about_unverified_status) {
2274 int n_recent = 0, n_listing = 0, n_valid = 0, n_named = 0;
2275 routerstatus_t *rs;
2276 SMARTLIST_FOREACH(networkstatus_list, networkstatus_t *, ns,
2278 if (ns->received_on + SELF_OPINION_INTERVAL < now)
2279 continue;
2280 ++n_recent;
2281 if (!(rs = networkstatus_find_entry(ns, me->identity_digest)))
2282 continue;
2283 ++n_listing;
2284 if (rs->is_valid)
2285 ++n_valid;
2286 if (rs->is_named)
2287 ++n_named;
2290 if (n_recent >= 2 && n_listing >= 2) {
2291 if (n_valid <= n_recent/2) {
2292 warn(LD_GENERAL, "%d/%d recent directory servers list us as invalid. Please consider sending your identity fingerprint to the tor-ops.",
2293 n_recent-n_valid, n_recent);
2294 have_warned_about_unverified_status = 1;
2295 } else if (n_named <= n_recent/2) {
2296 warn(LD_GENERAL, "%d/%d recent directory servers list us as unnamed. Please consider sending your identity fingerprint to the tor-ops.",
2297 n_recent-n_valid, n_recent);
2298 have_warned_about_unverified_status = 1;
2303 helper_nodes_set_status_from_directory();
2305 if (!have_warned_about_old_version) {
2306 int n_recent = 0;
2307 int n_recommended = 0;
2308 int is_server = server_mode(get_options());
2309 version_status_t consensus = VS_RECOMMENDED;
2310 SMARTLIST_FOREACH(networkstatus_list, networkstatus_t *, ns,
2312 version_status_t vs;
2313 if (!ns->recommends_versions ||
2314 ns->received_on + SELF_OPINION_INTERVAL < now )
2315 continue;
2316 vs = tor_version_is_obsolete(
2317 VERSION, is_server ? ns->server_versions : ns->client_versions);
2318 if (vs == VS_RECOMMENDED)
2319 ++n_recommended;
2320 if (n_recent++ == 0) {
2321 consensus = vs;
2322 } else if (consensus != vs) {
2323 consensus = version_status_join(consensus, vs);
2326 if (n_recent > 2 && n_recommended < n_recent/2) {
2327 if (consensus == VS_NEW || consensus == VS_NEW_IN_SERIES) {
2328 if (!have_warned_about_new_version) {
2329 notice(LD_GENERAL, "This version of Tor (%s) is newer than any recommended version%s, according to %d/%d recent network statuses.",
2330 VERSION, consensus == VS_NEW_IN_SERIES ? " in its series" : "",
2331 n_recent-n_recommended, n_recent);
2332 have_warned_about_new_version = 1;
2334 } else {
2335 notice(LD_GENERAL, "This version of Tor (%s) is %s, according to %d/%d recent network statuses.",
2336 VERSION, consensus == VS_OLD ? "obsolete" : "not recommended",
2337 n_recent-n_recommended, n_recent);
2338 have_warned_about_old_version = 1;
2340 } else {
2341 info(LD_GENERAL, "%d/%d recent directories think my version is ok.",
2342 n_recommended, n_recent);
2346 routerstatus_list_has_changed = 0;
2349 /** Allow any network-status newer than this to influence our view of who's
2350 * running. */
2351 #define DEFAULT_RUNNING_INTERVAL 60*60
2352 /** If possible, always allow at least this many network-statuses to influence
2353 * our view of who's running. */
2354 #define MIN_TO_INFLUENCE_RUNNING 3
2356 /** Change the is_recent field of each member of networkstatus_list so that
2357 * all members more recent than DEFAULT_RUNNING_INTERVAL are recent, and
2358 * at least the MIN_TO_INFLUENCE_RUNNING most recent members are resent, and no
2359 * others are recent. Set networkstatus_list_has_changed if anything happeed.
2361 void
2362 networkstatus_list_update_recent(time_t now)
2364 int n_statuses, n_recent, changed, i;
2365 char published[ISO_TIME_LEN+1];
2367 if (!networkstatus_list)
2368 return;
2370 n_statuses = smartlist_len(networkstatus_list);
2371 n_recent = 0;
2372 changed = 0;
2373 for (i=n_statuses-1; i >= 0; --i) {
2374 networkstatus_t *ns = smartlist_get(networkstatus_list, i);
2375 trusted_dir_server_t *ds =
2376 router_get_trusteddirserver_by_digest(ns->identity_digest);
2377 const char *src = ds?ds->description:ns->source_address;
2378 if (n_recent < MIN_TO_INFLUENCE_RUNNING ||
2379 ns->published_on + DEFAULT_RUNNING_INTERVAL > now) {
2380 if (!ns->is_recent) {
2381 format_iso_time(published, ns->published_on);
2382 info(LD_DIR,
2383 "Networkstatus from %s (published %s) is now \"recent\"",
2384 src, published);
2385 changed = 1;
2387 ns->is_recent = 1;
2388 ++n_recent;
2389 } else {
2390 if (ns->is_recent) {
2391 format_iso_time(published, ns->published_on);
2392 info(LD_DIR,
2393 "Networkstatus from %s (published %s) is no longer \"recent\"",
2394 src, published);
2395 changed = 1;
2396 ns->is_recent = 0;
2400 if (changed)
2401 networkstatus_list_has_changed = 1;
2404 /** Update our view of router status (as stored in routerstatus_list) from
2405 * the current set of network status documents (as stored in networkstatus_list).
2406 * Do nothing unless the network status list has changed since the last time
2407 * this function was called.
2409 static void
2410 routerstatus_list_update_from_networkstatus(time_t now)
2412 or_options_t *options = get_options();
2413 int n_trusted, n_statuses, n_recent=0, n_naming=0;
2414 int n_distinct = 0;
2415 int i, warned;
2416 int *index, *size;
2417 networkstatus_t **networkstatus;
2418 smartlist_t *result;
2419 strmap_t *name_map;
2420 char conflict[DIGEST_LEN];
2422 networkstatus_list_update_recent(now);
2424 if (!networkstatus_list_has_changed)
2425 return;
2426 if (!networkstatus_list)
2427 networkstatus_list = smartlist_create();
2428 if (!routerstatus_list)
2429 routerstatus_list = smartlist_create();
2430 if (!trusted_dir_servers)
2431 trusted_dir_servers = smartlist_create();
2432 if (!warned_conflicts)
2433 warned_conflicts = smartlist_create();
2435 n_trusted = smartlist_len(trusted_dir_servers);
2436 n_statuses = smartlist_len(networkstatus_list);
2438 if (n_statuses < (n_trusted/2)+1) {
2439 /* Not enough statuses to adjust status. */
2440 notice(LD_DIR,"Not enough statuses to update router status list. (%d/%d)",
2441 n_statuses, n_trusted);
2442 return;
2445 info(LD_DIR, "Rebuilding router status list.");
2447 index = tor_malloc(sizeof(int)*n_statuses);
2448 size = tor_malloc(sizeof(int)*n_statuses);
2449 networkstatus = tor_malloc(sizeof(networkstatus_t *)*n_statuses);
2450 for (i = 0; i < n_statuses; ++i) {
2451 index[i] = 0;
2452 networkstatus[i] = smartlist_get(networkstatus_list, i);
2453 size[i] = smartlist_len(networkstatus[i]->entries);
2454 if (networkstatus[i]->binds_names)
2455 ++n_naming;
2456 if (networkstatus[i]->is_recent)
2457 ++n_recent;
2460 name_map = strmap_new();
2461 memset(conflict, 0xff, sizeof(conflict));
2462 for (i = 0; i < n_statuses; ++i) {
2463 if (!networkstatus[i]->binds_names)
2464 continue;
2465 SMARTLIST_FOREACH(networkstatus[i]->entries, routerstatus_t *, rs,
2467 const char *other_digest;
2468 if (!rs->is_named)
2469 continue;
2470 other_digest = strmap_get_lc(name_map, rs->nickname);
2471 warned = smartlist_string_isin(warned_conflicts, rs->nickname);
2472 if (!other_digest) {
2473 strmap_set_lc(name_map, rs->nickname, rs->identity_digest);
2474 if (warned)
2475 smartlist_string_remove(warned_conflicts, rs->nickname);
2476 } else if (memcmp(other_digest, rs->identity_digest, DIGEST_LEN) &&
2477 other_digest != conflict) {
2478 if (!warned) {
2479 int should_warn = options->DirPort && options->AuthoritativeDir;
2480 char fp1[HEX_DIGEST_LEN+1];
2481 char fp2[HEX_DIGEST_LEN+1];
2482 base16_encode(fp1, sizeof(fp1), other_digest, DIGEST_LEN);
2483 base16_encode(fp2, sizeof(fp2), rs->identity_digest, DIGEST_LEN);
2484 log_fn(should_warn ? LOG_WARN : LOG_INFO, LD_DIR,
2485 "Naming authorities disagree about which key goes with %s. ($%s vs $%s)",
2486 rs->nickname, fp1, fp2);
2487 strmap_set_lc(name_map, rs->nickname, conflict);
2488 smartlist_add(warned_conflicts, tor_strdup(rs->nickname));
2490 } else {
2491 if (warned)
2492 smartlist_string_remove(warned_conflicts, rs->nickname);
2497 result = smartlist_create();
2499 /* Iterate through all of the sorted routerstatus lists in step.
2500 * Invariants:
2501 * - For 0 <= i < n_statuses: index[i] is an index into
2502 * networkstatus[i]->entries, which has size[i] elements.
2503 * - For i1, i2, j such that 0 <= i1 < n_statuses, 0 <= i2 < n_statues, 0 <=
2504 * j < index[i1], networkstatus[i1]->entries[j]->identity_digest <
2505 * networkstatus[i2]->entries[index[i2]]->identity_digest.
2507 * (That is, the indices are always advanced past lower digest before
2508 * higher.)
2510 while (1) {
2511 int n_running=0, n_named=0, n_valid=0, n_listing=0;
2512 const char *the_name = NULL;
2513 local_routerstatus_t *rs_out, *rs_old;
2514 routerstatus_t *rs, *most_recent;
2515 networkstatus_t *ns;
2516 const char *lowest = NULL;
2517 /* Find out which of the digests appears first. */
2518 for (i = 0; i < n_statuses; ++i) {
2519 if (index[i] < size[i]) {
2520 rs = smartlist_get(networkstatus[i]->entries, index[i]);
2521 if (!lowest || memcmp(rs->identity_digest, lowest, DIGEST_LEN)<0)
2522 lowest = rs->identity_digest;
2525 if (!lowest) {
2526 /* We're out of routers. Great! */
2527 break;
2529 /* Okay. The routers at networkstatus[i]->entries[index[i]] whose digests
2530 * match "lowest" are next in order. Iterate over them, incrementing those
2531 * index[i] as we go. */
2532 ++n_distinct;
2533 most_recent = NULL;
2534 for (i = 0; i < n_statuses; ++i) {
2535 if (index[i] >= size[i])
2536 continue;
2537 ns = networkstatus[i];
2538 rs = smartlist_get(ns->entries, index[i]);
2539 if (memcmp(rs->identity_digest, lowest, DIGEST_LEN))
2540 continue;
2541 ++index[i];
2542 ++n_listing;
2543 if (!most_recent || rs->published_on > most_recent->published_on)
2544 most_recent = rs;
2545 if (rs->is_named && ns->binds_names) {
2546 if (!the_name)
2547 the_name = rs->nickname;
2548 if (!strcasecmp(rs->nickname, the_name)) {
2549 ++n_named;
2550 } else if (strcmp(the_name,"**mismatch**")) {
2551 char hd[HEX_DIGEST_LEN+1];
2552 base16_encode(hd, HEX_DIGEST_LEN+1, rs->identity_digest, DIGEST_LEN);
2553 if (! smartlist_string_isin(warned_conflicts, hd)) {
2554 warn(LD_DIR, "Naming authorities disagree about nicknames for $%s (\"%s\" vs \"%s\")",
2555 hd, the_name, rs->nickname);
2556 smartlist_add(warned_conflicts, tor_strdup(hd));
2558 the_name = "**mismatch**";
2561 if (rs->is_valid)
2562 ++n_valid;
2563 if (rs->is_running && ns->is_recent)
2564 ++n_running;
2566 rs_out = tor_malloc_zero(sizeof(local_routerstatus_t));
2567 memcpy(&rs_out->status, most_recent, sizeof(routerstatus_t));
2568 if ((rs_old = router_get_combined_status_by_digest(lowest))) {
2569 rs_out->n_download_failures = rs_old->n_download_failures;
2570 rs_out->next_attempt_at = rs_old->next_attempt_at;
2571 rs_out->name_lookup_warned = rs_old->name_lookup_warned;
2573 smartlist_add(result, rs_out);
2574 debug(LD_DIR, "Router '%s' is listed by %d/%d directories, "
2575 "named by %d/%d, validated by %d/%d, and %d/%d recent directories "
2576 "think it's running.",
2577 rs_out->status.nickname,
2578 n_listing, n_statuses, n_named, n_naming, n_valid, n_statuses,
2579 n_running, n_recent);
2580 rs_out->status.is_named = 0;
2581 if (the_name && strcmp(the_name, "**mismatch**") && n_named > 0) {
2582 const char *d = strmap_get_lc(name_map, the_name);
2583 if (d && d != conflict)
2584 rs_out->status.is_named = 1;
2585 if (smartlist_string_isin(warned_conflicts, rs_out->status.nickname))
2586 smartlist_string_remove(warned_conflicts, rs_out->status.nickname);
2588 if (rs_out->status.is_named)
2589 strlcpy(rs_out->status.nickname, the_name, sizeof(rs_out->status.nickname));
2590 rs_out->status.is_valid = n_valid > n_statuses/2;
2591 rs_out->status.is_running = n_running > n_recent/2;
2593 SMARTLIST_FOREACH(routerstatus_list, local_routerstatus_t *, rs,
2594 local_routerstatus_free(rs));
2595 smartlist_free(routerstatus_list);
2596 routerstatus_list = result;
2598 tor_free(networkstatus);
2599 tor_free(index);
2600 tor_free(size);
2601 strmap_free(name_map, NULL);
2603 networkstatus_list_has_changed = 0;
2604 routerstatus_list_has_changed = 1;
2607 /** Given a list <b>routers</b> of routerinfo_t *, update each routers's
2608 * is_named, is_verified, and is_running fields according to our current
2609 * networkstatus_t documents. */
2610 void
2611 routers_update_status_from_networkstatus(smartlist_t *routers, int reset_failures, int assume_recognized)
2613 trusted_dir_server_t *ds;
2614 local_routerstatus_t *rs;
2615 or_options_t *options = get_options();
2616 int authdir = options->AuthoritativeDir;
2617 int namingdir = options->AuthoritativeDir &&
2618 options->NamingAuthoritativeDir;
2620 if (!routerstatus_list)
2621 return;
2623 SMARTLIST_FOREACH(routers, routerinfo_t *, router,
2625 rs = router_get_combined_status_by_digest(router->identity_digest);
2626 ds = router_get_trusteddirserver_by_digest(router->identity_digest);
2628 if (!rs)
2629 continue;
2631 if (!namingdir)
2632 router->is_named = rs->status.is_named;
2634 if (!authdir) {
2635 /* If we're an authdir, don't believe others. */
2636 router->is_verified = rs->status.is_valid;
2637 router->is_running = rs->status.is_running;
2639 if (router->is_running && ds) {
2640 ds->n_networkstatus_failures = 0;
2642 if (assume_recognized) {
2643 router->xx_is_recognized = 1;
2644 } else {
2645 if (!router->xx_is_recognized) {
2646 router->xx_is_recognized = routerdesc_digest_is_recognized(
2647 router->identity_digest, router->signed_descriptor_digest);
2649 router->xx_is_extra_new = router->published_on > rs->status.published_on;
2651 if (reset_failures && router->xx_is_recognized) {
2652 rs->n_download_failures = 0;
2653 rs->next_attempt_at = 0;
2658 /** Return new list of ID fingerprints for superseded routers. A router is
2659 * superseded if any network-status has a router with a different digest
2660 * published more recently, or if it is listed in the network-status but not
2661 * in the router list.
2663 static smartlist_t *
2664 router_list_downloadable(void)
2666 #define MAX_OLD_SERVER_DOWNLOAD_RATE 2*60*60
2667 int n_conns, i, n_downloadable = 0;
2668 connection_t **carray;
2669 smartlist_t *superseded = smartlist_create();
2670 smartlist_t *downloading;
2671 time_t now = time(NULL);
2672 int mirror = server_mode(get_options()) && get_options()->DirPort;
2673 /* these are just used for logging */
2674 int n_not_ready = 0, n_in_progress = 0, n_uptodate = 0, n_skip_old = 0,
2675 n_obsolete = 0, xx_n_unrecognized = 0, xx_n_extra_new = 0, xx_n_both = 0,
2676 xx_n_unrec_old = 0;
2678 if (!routerstatus_list)
2679 return superseded;
2681 get_connection_array(&carray, &n_conns);
2683 routerstatus_list_update_from_networkstatus(now);
2685 SMARTLIST_FOREACH(routerstatus_list, local_routerstatus_t *, rs,
2687 if (rs->status.published_on + ROUTER_MAX_AGE < now) {
2688 rs->should_download = 0;
2689 ++n_obsolete;
2690 } if (rs->next_attempt_at < now) {
2691 rs->should_download = 1;
2692 ++n_downloadable;
2693 } else {
2695 char fp[HEX_DIGEST_LEN+1];
2696 base16_encode(fp, HEX_DIGEST_LEN+1, rs->status.identity_digest, DIGEST_LEN);
2697 log_fn(LOG_NOTICE, "Not yet ready to download %s (%d more seconds)", fp,
2698 (int)(rs->next_attempt_at-now));
2700 rs->should_download = 0;
2701 ++n_not_ready;
2705 downloading = smartlist_create();
2706 for (i = 0; i < n_conns; ++i) {
2707 connection_t *conn = carray[i];
2708 if (conn->type == CONN_TYPE_DIR &&
2709 conn->purpose == DIR_PURPOSE_FETCH_SERVERDESC &&
2710 !conn->marked_for_close) {
2711 if (!strcmpstart(conn->requested_resource, "all"))
2712 n_downloadable = 0;
2713 dir_split_resource_into_fingerprints(conn->requested_resource,
2714 downloading, NULL, 1);
2719 log_fn(LOG_NOTICE, "%d downloads already in progress",
2720 smartlist_len(downloading));
2721 smartlist_sort_strings(downloading);
2723 if (n_downloadable) {
2724 SMARTLIST_FOREACH(downloading, const char *, d,
2726 local_routerstatus_t *rs;
2727 if ((rs = router_get_combined_status_by_digest(d)) && rs->should_download) {
2728 rs->should_download = 0;
2729 --n_downloadable;
2730 ++n_in_progress;
2731 // log_fn(LOG_NOTICE, "%s is in-progress; not fetching", dl);
2735 SMARTLIST_FOREACH(downloading, char *, cp, tor_free(cp));
2736 smartlist_free(downloading);
2737 if (!n_downloadable)
2738 return superseded;
2740 if (routerlist && n_downloadable) {
2741 SMARTLIST_FOREACH(routerlist->routers, routerinfo_t *, ri,
2743 local_routerstatus_t *rs;
2744 if (!(rs = router_get_combined_status_by_digest(ri->identity_digest)) ||
2745 !rs->should_download) {
2746 // log_fn(LOG_NOTICE, "No status for %s", fp);
2747 continue;
2749 if (!ri->xx_is_recognized) {
2750 ++xx_n_unrecognized;
2751 if (ri->xx_is_extra_new)
2752 ++xx_n_both;
2754 if (ri->xx_is_extra_new)
2755 ++xx_n_extra_new;
2757 /* Change this "or" to be an "and" once dirs generate hashes right.
2758 * Remove the version check once older versions are uncommon.
2759 * XXXXX. NM */
2760 if (!memcmp(ri->signed_descriptor_digest, rs->status.descriptor_digest,
2761 DIGEST_LEN) ||
2762 rs->status.published_on <= ri->published_on) {
2763 ++n_uptodate;
2764 rs->should_download = 0;
2765 --n_downloadable;
2766 } else if (!mirror &&
2767 ri->platform &&
2768 !tor_version_as_new_as(ri->platform, "0.1.1.6-alpha") &&
2769 ri->published_on + MAX_OLD_SERVER_DOWNLOAD_RATE > now) {
2770 /* Same digest, or date is up-to-date, or we have a comparatively recent
2771 * server with an old version.
2772 * No need to download it. */
2773 // log_fn(LOG_NOTICE, "Up-to-date status for %s", fp);
2774 ++n_skip_old;
2775 if (!ri->xx_is_recognized)
2776 ++xx_n_unrec_old;
2777 rs->should_download = 0;
2778 --n_downloadable;
2779 } /* else {
2780 char t1[ISO_TIME_LEN+1];
2781 char t2[ISO_TIME_LEN+1];
2782 format_iso_time(t1, rs->satus.published_on);
2783 format_iso_time(t2, ri->published_on);
2784 log_fn(LOG_NOTICE, "Out-of-date status for %s %s (%d %d) [%s %s]", fp,
2785 ri->nickname,
2786 !memcmp(ri->signed_descriptor_digest,rs->status.descriptor_digest,
2787 DIGEST_LEN),
2788 rs->published_on < ri->published_on,
2789 t1, t2);
2790 } */
2794 info(LD_DIR, "%d router descriptors are downloadable; "
2795 "%d are up to date; %d are in progress; "
2796 "%d are not ready to retry; "
2797 "%d are not published recently enough to be worthwhile; "
2798 "%d are running pre-0.1.1.6 Tors and aren't stale enough to replace. "
2799 "%d have unrecognized descriptor hashes; %d are newer than the dirs "
2800 "have told us about; %d are both unrecognized and newer than any "
2801 "publication date in the networkstatus; %d are both "
2802 "unrecognized and running a pre-0.1.1.6 version.",
2803 n_downloadable, n_uptodate, n_in_progress, n_not_ready,
2804 n_obsolete, n_skip_old, xx_n_unrecognized, xx_n_extra_new, xx_n_both,
2805 xx_n_unrec_old);
2807 if (!n_downloadable)
2808 return superseded;
2810 SMARTLIST_FOREACH(routerstatus_list, local_routerstatus_t *, rs,
2812 if (rs->should_download) {
2813 char *fp = tor_malloc(HEX_DIGEST_LEN+1);
2814 base16_encode(fp, HEX_DIGEST_LEN+1, rs->status.identity_digest, DIGEST_LEN);
2815 smartlist_add(superseded, fp);
2819 return superseded;
2822 /** Initiate new router downloads as needed.
2824 * We only allow one router descriptor download at a time.
2825 * If we have less than two network-status documents, we ask
2826 * a directory for "all descriptors."
2827 * Otherwise, we ask for all descriptors that we think are different
2828 * from what we have.
2830 void
2831 update_router_descriptor_downloads(time_t now)
2833 #define MAX_DL_PER_REQUEST 128
2834 #define MIN_DL_PER_REQUEST 4
2835 #define MIN_REQUESTS 3
2836 #define MAX_DL_TO_DELAY 16
2837 #define MAX_CLIENT_INTERVAL_WITHOUT_REQUEST 10*60
2838 #define MAX_SERVER_INTERVAL_WITHOUT_REQUEST 1*60
2839 smartlist_t *downloadable = NULL;
2840 int get_all = 0;
2841 int dirserv = server_mode(get_options()) && get_options()->DirPort;
2842 int should_delay, n_downloadable;
2843 if (!networkstatus_list || smartlist_len(networkstatus_list)<2)
2844 get_all = 1;
2846 if (get_all) {
2847 notice(LD_DIR, "Launching request for all routers");
2848 last_routerdesc_download_attempted = now;
2849 directory_get_from_dirserver(DIR_PURPOSE_FETCH_SERVERDESC,"all.z",1);
2850 return;
2853 downloadable = router_list_downloadable();
2854 n_downloadable = smartlist_len(downloadable);
2855 if (n_downloadable >= MAX_DL_TO_DELAY) {
2856 debug(LD_DIR,
2857 "There are enough downloadable routerdescs to launch requests.");
2858 should_delay = 0;
2859 } else if (n_downloadable == 0) {
2860 debug(LD_DIR, "No routerdescs need to be downloaded.");
2861 should_delay = 1;
2862 } else {
2863 if (dirserv) {
2864 should_delay = (last_routerdesc_download_attempted +
2865 MAX_SERVER_INTERVAL_WITHOUT_REQUEST) > now;
2866 } else {
2867 should_delay = (last_routerdesc_download_attempted +
2868 MAX_CLIENT_INTERVAL_WITHOUT_REQUEST) > now;
2870 if (should_delay)
2871 debug(LD_DIR, "There are not many downloadable routerdescs; waiting till we have some more.");
2872 else
2873 info(LD_DIR, "There are not many downloadable routerdescs, but we've been waiting long enough (%d seconds). Downloading.",
2874 (int)(now-last_routerdesc_download_attempted));
2877 if (! should_delay) {
2878 int i, j, n_per_request=MAX_DL_PER_REQUEST;
2879 size_t r_len = MAX_DL_PER_REQUEST*(HEX_DIGEST_LEN+1)+16;
2880 char *resource = tor_malloc(r_len);
2882 if (! dirserv) {
2883 n_per_request = (n_downloadable+MIN_REQUESTS-1) / MIN_REQUESTS;
2884 if (n_per_request > MAX_DL_PER_REQUEST)
2885 n_per_request = MAX_DL_PER_REQUEST;
2886 if (n_per_request < MIN_DL_PER_REQUEST)
2887 n_per_request = MIN_DL_PER_REQUEST;
2889 info(LD_DIR, "Launching %d request%s for %d router%s, %d at a time",
2890 (n_downloadable+n_per_request-1)/n_per_request,
2891 n_downloadable>n_per_request?"s":"",
2892 n_downloadable, n_downloadable>1?"s":"", n_per_request);
2893 for (i=0; i < n_downloadable; i += n_per_request) {
2894 char *cp = resource;
2895 memcpy(resource, "fp/", 3);
2896 cp = resource + 3;
2897 for (j=i; j < i+n_per_request && j < n_downloadable; ++j) {
2898 memcpy(cp, smartlist_get(downloadable, j), HEX_DIGEST_LEN);
2899 cp += HEX_DIGEST_LEN;
2900 *cp++ = '+';
2902 memcpy(cp-1, ".z", 3);
2903 directory_get_from_dirserver(DIR_PURPOSE_FETCH_SERVERDESC,resource,1);
2905 last_routerdesc_download_attempted = now;
2906 tor_free(resource);
2908 SMARTLIST_FOREACH(downloadable, char *, c, tor_free(c));
2909 smartlist_free(downloadable);
2912 /** Return true iff we have enough networkstatus and router information to
2913 * start building circuits. Right now, this means "at least 2 networkstatus
2914 * documents, and at least 1/4 of expected routers." */
2916 router_have_minimum_dir_info(void)
2918 int tot = 0, avg;
2919 if (!networkstatus_list || smartlist_len(networkstatus_list)<2 ||
2920 !routerlist)
2921 return 0;
2922 SMARTLIST_FOREACH(networkstatus_list, networkstatus_t *, ns,
2923 tot += smartlist_len(ns->entries));
2924 avg = tot / smartlist_len(networkstatus_list);
2925 return smartlist_len(routerlist->routers) > (avg/4);
2928 /** Reset the descriptor download failure count on all routers, so that we
2929 * can retry any long-failed routers immediately.
2931 void
2932 router_reset_descriptor_download_failures(void)
2934 if (!routerstatus_list)
2935 return;
2936 SMARTLIST_FOREACH(routerstatus_list, local_routerstatus_t *, rs,
2938 rs->n_download_failures = 0;
2939 rs->next_attempt_at = 0;
2941 last_routerdesc_download_attempted = 0;
2944 /** Return true iff the only differences between r1 and r2 are such that
2945 * would not cause a recent (post 0.1.1.6) direserver to republish.
2948 router_differences_are_cosmetic(routerinfo_t *r1, routerinfo_t *r2)
2950 tor_assert(r1 && r2);
2952 /* post-0.1.1.6 servers know what they're doing. */
2953 if (tor_version_as_new_as(r1->platform, "0.1.1.6-alpha") ||
2954 tor_version_as_new_as(r2->platform, "0.1.1.6-alpha"))
2955 return 0;
2957 /* r1 should be the one that was published first. */
2958 if (r1->published_on > r2->published_on) {
2959 routerinfo_t *ri_tmp = r2;
2960 r2 = r1;
2961 r1 = ri_tmp;
2964 /* If any key fields differ, they're different. */
2965 if (strcasecmp(r1->address, r2->address) ||
2966 strcasecmp(r1->nickname, r2->nickname) ||
2967 r1->or_port != r2->or_port ||
2968 r1->dir_port != r2->dir_port ||
2969 crypto_pk_cmp_keys(r1->onion_pkey, r2->onion_pkey) ||
2970 crypto_pk_cmp_keys(r1->identity_pkey, r2->identity_pkey) ||
2971 strcasecmp(r1->platform, r2->platform) ||
2972 (r1->contact_info && !r2->contact_info) || /* contact_info is optional */
2973 (!r1->contact_info && r2->contact_info) ||
2974 (r1->contact_info && r2->contact_info && strcasecmp(r1->contact_info, r2->contact_info)) ||
2975 r1->is_hibernating != r2->is_hibernating ||
2976 config_cmp_addr_policies(r1->exit_policy, r2->exit_policy))
2977 return 0;
2978 if ((r1->declared_family == NULL) != (r2->declared_family == NULL))
2979 return 0;
2980 if (r1->declared_family && r2->declared_family) {
2981 int i, n;
2982 if (smartlist_len(r1->declared_family)!=smartlist_len(r2->declared_family))
2983 return 0;
2984 n = smartlist_len(r1->declared_family);
2985 for (i=0; i < n; ++i) {
2986 if (strcasecmp(smartlist_get(r1->declared_family, i),
2987 smartlist_get(r2->declared_family, i)))
2988 return 0;
2992 /* Did bandwidth change a lot? */
2993 if ((r1->bandwidthcapacity < r2->bandwidthcapacity/2) ||
2994 (r2->bandwidthcapacity < r1->bandwidthcapacity/2))
2995 return 0;
2997 /* Did more than 12 hours pass? */
2998 if (r1->published_on + 12*60*60 < r2->published_on)
2999 return 0;
3001 /* Did uptime fail to increase by approximately the amount we would think,
3002 * give or take 30 minutes? */
3003 if (abs(r2->uptime - (r1->uptime + (r2->published_on-r1->published_on)))>30*60)
3004 return 0;
3006 /* Otherwise, the difference is cosmetic. */
3007 return 1;
3010 static void
3011 routerlist_assert_ok(routerlist_t *rl)
3013 digestmap_iter_t *iter;
3014 if (!routerlist)
3015 return;
3016 SMARTLIST_FOREACH(rl->routers, routerinfo_t *, r,
3018 routerinfo_t *r2 = digestmap_get(rl->identity_map,
3019 r->identity_digest);
3020 tor_assert(r == r2);
3022 iter = digestmap_iter_init(rl->identity_map);
3023 while (!digestmap_iter_done(iter)) {
3024 const char *d;
3025 void *_r;
3026 routerinfo_t *r;
3027 digestmap_iter_get(iter, &d, &_r);
3028 r = _r;
3029 tor_assert(!memcmp(r->identity_digest, d, DIGEST_LEN));
3030 iter = digestmap_iter_next(rl->identity_map, iter);